Line data Source code
1 : /**
2 : * What every billing transport does identically, regardless of how the
3 : * request is credentialed: hold one timeout budget over the whole exchange,
4 : * send the request, and shape any answer into a `BillingHttpResponse`.
5 : *
6 : * Only the credential differs between transports, so only the credential
7 : * lives in them; keeping the budget and the response shaping here is what
8 : * lets a bearer-token host and a cookie host report the same failures.
9 : */
10 : import type {
11 : BillingHttpResponse,
12 : BillingRequest,
13 : BillingResult
14 : } from './billingContracts'
15 :
16 2356 : export const DEFAULT_BILLING_TIMEOUT_MS = 30_000
17 :
18 0 : export function startRequestBudget(
19 : callerSignal: AbortSignal | undefined,
20 : timeoutMs: number
21 : ) {
22 0 : const controller = new AbortController()
23 0 : const abort = () => controller.abort()
24 0 : if (callerSignal?.aborted === true) {
25 0 : controller.abort()
26 : } else {
27 0 : callerSignal?.addEventListener('abort', abort, { once: true })
28 : }
29 0 : const timeout = setTimeout(abort, timeoutMs)
30 0 : return {
31 : signal: controller.signal,
32 : close: () => {
33 0 : clearTimeout(timeout)
34 0 : callerSignal?.removeEventListener('abort', abort)
35 : }
36 : }
37 : }
38 :
39 : export interface BillingExchange {
40 : readonly fetchImpl: typeof fetch
41 : readonly url: string
42 : readonly signal: AbortSignal
43 : /** Merged over the headers the request itself implies. */
44 : readonly headers?: Record<string, string>
45 : readonly credentials?: RequestCredentials
46 : }
47 :
48 0 : export async function exchangeBillingRequest(
49 : request: BillingRequest,
50 : exchange: BillingExchange
51 : ): Promise<BillingResult<BillingHttpResponse>> {
52 : // Called detached: the browser's fetch refuses any receiver but its global.
53 0 : const { fetchImpl, url, signal, headers, credentials } = exchange
54 0 : let response: Response
55 0 : try {
56 0 : response = await fetchImpl(url, {
57 : method: request.method,
58 : headers: {
59 : 'Content-Type': 'application/json',
60 : ...(request.idempotencyKey === undefined
61 : ? {}
62 : : { 'Idempotency-Key': request.idempotencyKey }),
63 : ...headers
64 : },
65 : ...(request.method === 'GET' || request.body === undefined
66 : ? {}
67 : : { body: JSON.stringify(request.body) }),
68 : ...(credentials === undefined ? {} : { credentials }),
69 : signal
70 : })
71 : } catch {
72 0 : return { status: 'error', code: 'REQUEST_FAILED' }
73 : }
74 :
75 0 : return shapeResponse(response, signal)
76 : }
77 :
78 0 : async function shapeResponse(
79 : response: Response,
80 : signal: AbortSignal
81 : ): Promise<BillingResult<BillingHttpResponse>> {
82 0 : const header = (name: string) => response.headers.get(name)
83 0 : try {
84 0 : return {
85 : status: 'ok',
86 : value: {
87 : httpStatus: response.status,
88 : body: await readBody(response),
89 : header
90 : }
91 : }
92 : } catch {
93 0 : if (signal.aborted) {
94 0 : return { status: 'error', code: 'REQUEST_FAILED' }
95 : }
96 0 : return {
97 : status: 'ok',
98 : value: { httpStatus: response.status, body: undefined, header }
99 : }
100 : }
101 : }
102 :
103 : /** A body that is absent, empty, or not JSON reaches callers as undefined. */
104 0 : async function readBody(response: Response): Promise<unknown> {
105 0 : const text = await response.text()
106 0 : if (text === '') return undefined
107 0 : try {
108 0 : return JSON.parse(text)
109 : } catch {
110 0 : return undefined
111 : }
112 : }
|