Line data Source code
1 : /**
2 : * The contracts the billing core shares with its hosts. Dependency-neutral
3 : * by design, the same way `sessionContracts` is: the transport and the typed
4 : * operations depend on this module, never back on each other.
5 : *
6 : * Billing reports failures as coded results rather than thrown errors. The
7 : * codes carry no text; the copy that belongs to each code is owned by the
8 : * billing core and localized by the host. Two server values cross this
9 : * boundary. `serverCode` is a machine identifier and never copy: a command
10 : * matches it against its own closed set, and a host stores it where it
11 : * already keeps `WorkspaceApiError.code`. Its brand makes it unforgeable:
12 : * only the response decoder mints one, and `unwrapServerCode` names the one
13 : * sanctioned widening. `serverMessage` is the sentence the server wrote for
14 : * the customer, carried so a host can show it the way the legacy client does;
15 : * nothing in the core branches on it.
16 : */
17 : import type { SessionClient } from '#/core/session'
18 :
19 : /**
20 : * The session members the billing core reaches for. A host's client is typed
21 : * for its own user, and the identity seam is contravariant in that user, so
22 : * requiring the full client would reject every host whose user is more
23 : * specific than the base.
24 : */
25 : export type BillingSession = Pick<
26 : SessionClient,
27 : 'getSnapshot' | 'subscribe' | 'ensureFresh' | 'remint'
28 : >
29 :
30 : /**
31 : * The failure buckets a billing request can produce, extracted from what the
32 : * cloud app's `workspaceApi` callers actually distinguish today.
33 : * REQUEST_FAILED is the transient bucket: 5xx, a network failure, an abort,
34 : * and a timeout are one failure for a caller, exactly as they are in the
35 : * session client's `TOKEN_EXCHANGE_FAILED`.
36 : */
37 : export type BillingErrorCode =
38 : /** Nobody is signed in, or the identity could not produce a token. */
39 : | 'NOT_AUTHENTICATED'
40 : /** A 401 that survived the one re-mint retry, or a 403. */
41 : | 'ACCESS_DENIED'
42 : | 'NOT_FOUND'
43 : /** A business-level 409 — never a missing customer, which self-heals. */
44 : | 'CONFLICT'
45 : /** The identity or workspace changed while the request was in flight. */
46 : | 'SUPERSEDED'
47 : | 'REQUEST_FAILED'
48 : /** A 2xx whose body does not match the generated contract. */
49 : | 'MALFORMED_RESPONSE'
50 : /**
51 : * The server already had an operation of this kind pending that this
52 : * attempt did not issue. Refusing is the only honest answer: the status
53 : * response names no plan, so joining it would settle whatever the earlier
54 : * attempt chose and report it as this caller's success. The command
55 : * usually declines before it sends anything; a subscription command also
56 : * reports it when the server refuses with `SUBSCRIPTION_CHANGE_IN_PROGRESS`.
57 : */
58 : | 'OPERATION_ALREADY_PENDING'
59 :
60 : declare const billingServerCodeBrand: unique symbol
61 :
62 : /**
63 : * An unbounded server string that is only ever a machine identifier. Nothing
64 : * outside `readBillingErrorCode` mints one, so a command cannot invent a code
65 : * to match. The value stays a `string` underneath: `matchesServerCode` and
66 : * `unwrapServerCode` name the sanctioned uses rather than making the string
67 : * unreadable.
68 : */
69 : export type BillingServerCode = string & {
70 : readonly [billingServerCodeBrand]: true
71 : }
72 :
73 : export type BillingFailure = {
74 : readonly status: 'error'
75 : readonly code: BillingErrorCode
76 : /** Set only when the failure came from an HTTP response. */
77 : readonly httpStatus?: number
78 : /**
79 : * The coded `code` of a generated `ErrorResponse` body, when the server
80 : * sent one. It is the only server value a command branches on. Compare it
81 : * through `matchesServerCode`, and widen it through `unwrapServerCode` at
82 : * a host's error-store boundary. Never render it.
83 : */
84 : readonly serverCode?: BillingServerCode
85 : /**
86 : * The `message` of that same `ErrorResponse`, present when the server sent
87 : * a non-empty one. This is what a host shows the customer; the legacy
88 : * client shows the same string.
89 : */
90 : readonly serverMessage?: string
91 : /** The response's `Retry-After`, when it was a whole number of seconds. */
92 : readonly retryAfterSeconds?: number
93 : }
94 :
95 : /** Whether a failure carries the server code a command names. */
96 0 : export function matchesServerCode(
97 : failure: Pick<BillingFailure, 'serverCode'>,
98 : code: string
99 : ): boolean {
100 0 : return failure.serverCode === code
101 : }
102 :
103 : /** Server codes for a purchase the server refuses for now; its `serverMessage` is the copy to show. */
104 2356 : export const PURCHASE_REFUSAL_SERVER_CODES: readonly string[] = [
105 : 'TOPUP_RATE_LIMITED',
106 : 'TOPUP_PURCHASES_PAUSED'
107 : ]
108 :
109 : /** Whether the server refused this purchase for now, with a sentence written for the customer. */
110 : export function isPurchaseRefusal(
111 : failure: Pick<BillingFailure, 'serverCode'>
112 : ): boolean {
113 : return PURCHASE_REFUSAL_SERVER_CODES.some((code) =>
114 : matchesServerCode(failure, code)
115 : )
116 : }
117 :
118 : /**
119 : * The one widening back to `string`, for a host storing the code beside the
120 : * codes it already keeps. Rendering it is still a contract violation.
121 : */
122 0 : export function unwrapServerCode(code: BillingServerCode): string {
123 0 : return code
124 : }
125 :
126 : export type BillingResult<T> =
127 : | { readonly status: 'ok'; readonly value: T }
128 : | BillingFailure
129 :
130 : interface BillingRequestBase {
131 : /** Route below the host's billing base, e.g. `/billing/topup`. */
132 : readonly route: string
133 : /**
134 : * Present on a write whose replay the backend deduplicates. It is also
135 : * what makes a 401 retry safe: see `createSessionBillingTransport`.
136 : */
137 : readonly idempotencyKey?: string
138 : readonly signal?: AbortSignal
139 : /** Total budget for session minting, retries, and reading the response. */
140 : readonly timeoutMs?: number
141 : }
142 :
143 : export type BillingRequest = BillingRequestBase &
144 : (
145 : | { readonly method: 'GET'; readonly body?: never }
146 : | { readonly method: 'POST' | 'PUT'; readonly body?: unknown }
147 : )
148 :
149 : export interface BillingHttpResponse {
150 : readonly httpStatus: number
151 : readonly body: unknown
152 : /** True when a 401 could not be retried because the write was not replayable. */
153 : readonly authenticationRetrySkipped?: true
154 : /**
155 : * True when the transport holds no credential of its own to re-prove with,
156 : * so a 401 is the host's session ending rather than a refusal.
157 : */
158 : readonly authenticationNotRenewable?: true
159 : /**
160 : * Response header reader. The capability revision a mutation reports
161 : * (`X-Capability-Revision`) reaches the capabilities cache through this,
162 : * mirroring the cloud app's `attachCapabilityRevisionInterceptor`. It is
163 : * absent whenever CORS is bypassed, so every reader treats a missing
164 : * header as "no revision reported" rather than assuming presence.
165 : */
166 : readonly header: (name: string) => string | null
167 : }
168 :
169 : /**
170 : * One request, credentials included. An HTTP answer of any status is an `ok`
171 : * result — only a failure that produced no response at all (no session,
172 : * network, abort, timeout) is an `error`, so the typed operations above it
173 : * own the status-to-code mapping in one place.
174 : */
175 : export type BillingTransport = (
176 : request: BillingRequest
177 : ) => Promise<BillingResult<BillingHttpResponse>>
|