Line data Source code
1 : /**
2 : * Joining a caller to a shared in-flight read without letting either one
3 : * decide the other's fate.
4 : *
5 : * Deduplication and cancellation pull in opposite directions: if the request
6 : * carries the first caller's signal, that caller aborting fails every reader
7 : * that joined it, and a joiner aborting does nothing at all. So the shared
8 : * request carries no caller signal — it is bounded by its own timeout — and
9 : * each caller's signal releases only that caller's wait.
10 : *
11 : * This is the semantic `SessionClient.ensureFresh` already documents for its
12 : * shared mint: concurrent callers share one request, and a later caller's
13 : * signal releases that caller with a transient failure without cancelling the
14 : * work the others are still waiting on.
15 : */
16 : import type {
17 : BillingHttpResponse,
18 : BillingRequest,
19 : BillingResult,
20 : BillingTransport
21 : } from './billingContracts'
22 : import type { BillingScopeContext } from './billingScope'
23 : import { sameBillingScope } from './billingScope'
24 : import {
25 : readBillingErrorCode,
26 : readBillingErrorMessage
27 : } from './billingErrorBody'
28 : import { codeForHttpStatus } from './httpStatus'
29 :
30 : /**
31 : * An abandoned wait is transient, the same bucket the transport reports an
32 : * abort under: the caller stopped waiting, which says nothing about whether
33 : * the read would have succeeded.
34 : */
35 2356 : const ABANDONED = {
36 : status: 'error',
37 : code: 'REQUEST_FAILED'
38 : } as const satisfies BillingResult<never>
39 :
40 : export type ParsedBillingBody<T> =
41 : | { readonly success: true; readonly data: T }
42 : | { readonly success: false }
43 :
44 : export interface ValidatedBillingResponse<T> {
45 : readonly data: T
46 : readonly body: unknown
47 : readonly httpStatus: number
48 : }
49 :
50 0 : export function matchesScopedRead<
51 : T extends { readonly context: BillingScopeContext }
52 : >(read: T | undefined, context: BillingScopeContext): read is T {
53 0 : return (
54 : read !== undefined &&
55 : read.context.generation === context.generation &&
56 : sameBillingScope(read.context.scope, context.scope)
57 : )
58 : }
59 :
60 0 : function readRetryAfterSeconds(
61 : response: Pick<BillingHttpResponse, 'header'>
62 : ): number | undefined {
63 0 : const value = response.header('Retry-After')?.trim()
64 0 : return value && /^\d+$/.test(value) ? Number(value) : undefined
65 : }
66 :
67 0 : export async function readValidatedBillingResponse<T>(
68 : transport: BillingTransport,
69 : request: BillingRequest,
70 : parse: (body: unknown) => ParsedBillingBody<T>
71 : ): Promise<BillingResult<ValidatedBillingResponse<T>>> {
72 0 : const response = await transport(request)
73 0 : if (response.status === 'error') return response
74 :
75 0 : const { httpStatus, body } = response.value
76 0 : if (httpStatus < 200 || httpStatus >= 300) {
77 0 : const serverCode = readBillingErrorCode(body)
78 0 : const serverMessage = readBillingErrorMessage(body)
79 0 : const retryAfterSeconds = readRetryAfterSeconds(response.value)
80 0 : return {
81 : status: 'error',
82 : code: codeForHttpStatus(response.value),
83 : httpStatus,
84 : ...(serverCode === undefined ? {} : { serverCode }),
85 : ...(serverMessage === undefined ? {} : { serverMessage }),
86 : ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds })
87 : }
88 : }
89 :
90 0 : const parsed = parse(body)
91 0 : if (!parsed.success) {
92 0 : return { status: 'error', code: 'MALFORMED_RESPONSE', httpStatus }
93 : }
94 :
95 0 : return { status: 'ok', value: { data: parsed.data, body, httpStatus } }
96 : }
97 :
98 0 : export function releaseOnAbort<T>(
99 : shared: Promise<BillingResult<T>>,
100 : signal: AbortSignal | undefined
101 : ): Promise<BillingResult<T>> {
102 0 : if (signal === undefined) return shared.catch(() => ABANDONED)
103 : // An 'abort' listener never fires for a signal that is already aborted, so
104 : // a caller who cancelled before joining would otherwise wait for the full
105 : // shared read.
106 0 : if (signal.aborted) {
107 0 : void shared.catch(() => {})
108 0 : return Promise.resolve(ABANDONED)
109 : }
110 :
111 0 : return new Promise<BillingResult<T>>((resolve) => {
112 0 : const onAbort = () => resolve(ABANDONED)
113 0 : signal.addEventListener('abort', onAbort, { once: true })
114 0 : shared.then(
115 : (value) => {
116 0 : signal.removeEventListener('abort', onAbort)
117 0 : resolve(value)
118 : },
119 : () => {
120 0 : signal.removeEventListener('abort', onAbort)
121 0 : resolve(ABANDONED)
122 : }
123 : )
124 : })
125 : }
|