Line data Source code
1 : /**
2 : * The one shape every billing read has: capture the scope, issue a validated
3 : * request, and refuse to attribute the answer to a scope that has since taken
4 : * over. Only the route, the decoder, and the projection into a snapshot differ
5 : * between reads, so only those live in the readers.
6 : *
7 : * What the skeleton owns is what a reader therefore cannot get wrong on its
8 : * own: one shared request per scope and route, a caller's signal releasing
9 : * only that caller, the publish fence that reports a late answer as
10 : * `SUPERSEDED`, and the denial that drops a published snapshot unless it
11 : * predates a change the host reported.
12 : */
13 : import type {
14 : BillingRequest,
15 : BillingResult,
16 : BillingTransport
17 : } from './billingContracts'
18 : import type {
19 : BillingScope,
20 : BillingScopeContext,
21 : BillingScopeSource
22 : } from './billingScope'
23 : import { createBillingScopeTracker } from './billingScope'
24 : import type { ParsedBillingBody, ValidatedBillingResponse } from './sharedRead'
25 : import {
26 : matchesScopedRead,
27 : readValidatedBillingResponse,
28 : releaseOnAbort
29 : } from './sharedRead'
30 :
31 : /** Every reader's read options carry at least the caller's release signal. */
32 : export interface ScopedReadOptions {
33 : readonly signal?: AbortSignal
34 : }
35 :
36 : export interface ScopedReaderDefinition<
37 : TData,
38 : TSnapshot,
39 : TOptions extends ScopedReadOptions
40 : > {
41 : readonly transport: BillingTransport
42 : /** Where the core learns which user, workspace, and role it runs as. */
43 : readonly scopeSource: BillingScopeSource
44 : /**
45 : * The route to request, as a function for a read whose query varies per
46 : * call. The resolved route joins the scope in identifying an in-flight
47 : * read, so two callers asking for different pages each get their own answer
48 : * rather than the first one's.
49 : */
50 : readonly route: string | ((options: TOptions | undefined) => string)
51 : readonly parse: (body: unknown) => ParsedBillingBody<TData>
52 : /**
53 : * The reader's own reading of a validated response. Returning a failure is
54 : * how a reader refuses an answer its decoder alone cannot reject.
55 : */
56 : readonly project: (
57 : response: ValidatedBillingResponse<TData>,
58 : scope: BillingScope
59 : ) => BillingResult<TSnapshot>
60 : /** The request budget, for a read that bounds itself or lets its caller. */
61 : readonly timeoutMs?: (options: TOptions | undefined) => number | undefined
62 : /**
63 : * The published snapshot this call may be served from instead of asking.
64 : * Absent for a reader that always requests.
65 : */
66 : readonly cached?: (
67 : snapshot: TSnapshot | undefined,
68 : scope: BillingScope,
69 : options: TOptions | undefined
70 : ) => TSnapshot | undefined
71 : /**
72 : * What to publish once the read settles in scope, given whether the host
73 : * fenced the request while it was in flight. `undefined` publishes nothing,
74 : * and the callers waiting on the request are still served what it read.
75 : */
76 : readonly publish?: (
77 : value: TSnapshot,
78 : fenced: boolean
79 : ) => TSnapshot | undefined
80 : }
81 :
82 : export interface ScopedReader<TSnapshot, TOptions extends ScopedReadOptions> {
83 : readonly read: (options?: TOptions) => Promise<BillingResult<TSnapshot>>
84 : readonly getSnapshot: () => TSnapshot | undefined
85 : /** Replaces what `getSnapshot` publishes; `undefined` drops it. */
86 : readonly setSnapshot: (snapshot: TSnapshot | undefined) => void
87 : /**
88 : * Marks a request already in flight as predating a change the host is
89 : * reporting, leaving `publish` to decide what its answer is still worth.
90 : * `detach` also frees the shared slot, so the read that follows issues its
91 : * own request rather than joining the one that predates the change.
92 : */
93 : readonly fenceInFlight: (options?: { readonly detach?: boolean }) => void
94 : readonly dispose: () => void
95 : }
96 :
97 : interface InFlightRead<TSnapshot> {
98 : readonly context: BillingScopeContext
99 : readonly route: string
100 : readonly promise: Promise<BillingResult<TSnapshot>>
101 : /**
102 : * Lives outside the attempt so the read body can consult it without
103 : * referencing the object that holds its own promise.
104 : */
105 : readonly pending: { fenced: boolean }
106 : }
107 :
108 0 : function publishAsRead<TSnapshot>(value: TSnapshot): TSnapshot {
109 0 : return value
110 : }
111 :
112 0 : export function createScopedReader<
113 : TData,
114 : TSnapshot,
115 : TOptions extends ScopedReadOptions
116 : >(
117 : definition: ScopedReaderDefinition<TData, TSnapshot, TOptions>
118 : ): ScopedReader<TSnapshot, TOptions> {
119 0 : const {
120 : transport,
121 : scopeSource,
122 : route,
123 : parse,
124 : project,
125 : timeoutMs,
126 : cached,
127 : publish = publishAsRead
128 : } = definition
129 :
130 0 : const resolveRoute: (options: TOptions | undefined) => string =
131 : typeof route === 'string' ? () => route : route
132 :
133 0 : let snapshot: TSnapshot | undefined
134 0 : let inFlight: InFlightRead<TSnapshot> | undefined
135 0 : const lifetime = { disposed: false }
136 0 : const scopeTracker = createBillingScopeTracker(scopeSource, () => {
137 0 : snapshot = undefined
138 0 : inFlight = undefined
139 : })
140 :
141 0 : async function request(
142 : scope: BillingScope,
143 : options: TOptions | undefined,
144 : resolvedRoute: string
145 : ): Promise<BillingResult<TSnapshot>> {
146 0 : const budget = timeoutMs?.(options)
147 0 : const billingRequest: BillingRequest = {
148 : method: 'GET',
149 : route: resolvedRoute,
150 : ...(budget === undefined ? {} : { timeoutMs: budget })
151 : }
152 0 : const response = await readValidatedBillingResponse(
153 : transport,
154 : billingRequest,
155 : parse
156 : )
157 0 : if (response.status === 'error') return response
158 :
159 0 : return project(response.value, scope)
160 : }
161 :
162 0 : function publishSettled(
163 : value: TSnapshot,
164 : fenced: boolean
165 : ): BillingResult<TSnapshot> {
166 0 : const published = publish(value, fenced)
167 0 : if (published !== undefined) snapshot = published
168 0 : return { status: 'ok', value: published ?? value }
169 : }
170 :
171 0 : async function settle(
172 : context: BillingScopeContext,
173 : pending: { fenced: boolean },
174 : options: TOptions | undefined,
175 : resolvedRoute: string
176 : ): Promise<BillingResult<TSnapshot>> {
177 0 : const result = await request(context.scope, options, resolvedRoute)
178 : // The publish guard. Between issuing the request and settling it the host
179 : // may have changed workspace or signed out, so an answer cached now would
180 : // be attributed to whoever is signed in next, and a failure says nothing
181 : // about the scope that has since taken over.
182 0 : if (lifetime.disposed || !scopeTracker.isCurrent(context)) {
183 0 : return { status: 'error', code: 'SUPERSEDED' }
184 : }
185 :
186 0 : if (result.status !== 'ok') {
187 : // A denial that predates a fence is no evidence about what a later read
188 : // published, and clearing on it would drop a fresh answer for a stale
189 : // refusal.
190 0 : if (result.code === 'ACCESS_DENIED' && !pending.fenced) {
191 0 : snapshot = undefined
192 : }
193 0 : return result
194 : }
195 :
196 0 : return publishSettled(result.value, pending.fenced)
197 : }
198 :
199 0 : async function read(options?: TOptions): Promise<BillingResult<TSnapshot>> {
200 0 : if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' }
201 :
202 0 : const context = scopeTracker.capture()
203 0 : if (context === undefined) {
204 0 : return { status: 'error', code: 'NOT_AUTHENTICATED' }
205 : }
206 :
207 0 : const served = cached?.(snapshot, context.scope, options)
208 0 : if (served !== undefined) return { status: 'ok', value: served }
209 :
210 : // Resolved once, then used both to issue the request and to identify it,
211 : // so the answer a joining caller is served is the one its own route asked
212 : // for.
213 0 : const resolvedRoute = resolveRoute(options)
214 :
215 : // A caller arriving mid-flight joins only a read of the same scope and
216 : // route, rather than issuing a second identical request. A caller for a
217 : // different scope starts its own, and the older one can no longer
218 : // publish. A caller for a different route on the same scope also starts
219 : // its own and takes the slot, so the displaced read still settles and
220 : // publishes — the snapshot carries which page it is — but nobody can join
221 : // it any more. One slot is enough for a feed read one page at a time.
222 0 : if (
223 : matchesScopedRead(inFlight, context) &&
224 : inFlight.route === resolvedRoute
225 : ) {
226 0 : return releaseOnAbort(inFlight.promise, options?.signal)
227 : }
228 :
229 : // No caller signal reaches the shared request: it is bounded by its own
230 : // timeout, and one caller walking away must not fail the readers still
231 : // waiting on it. Each caller's signal releases only that caller, below.
232 0 : const pending = { fenced: false }
233 0 : const attempt: InFlightRead<TSnapshot> = {
234 : context,
235 : route: resolvedRoute,
236 : promise: settle(context, pending, options, resolvedRoute),
237 : pending
238 : }
239 :
240 0 : inFlight = attempt
241 : // The slot is released when the request settles, not when this caller
242 : // stops waiting, so an abandoned read still serves whoever joined it.
243 0 : const release = () => {
244 0 : if (inFlight === attempt) inFlight = undefined
245 : }
246 0 : attempt.promise.then(release, release)
247 :
248 0 : return releaseOnAbort(attempt.promise, options?.signal)
249 : }
250 :
251 0 : return {
252 : read,
253 : getSnapshot: () => snapshot,
254 : setSnapshot: (next) => {
255 0 : snapshot = next
256 : },
257 : fenceInFlight: (fenceOptions) => {
258 0 : if (inFlight === undefined) return
259 0 : inFlight.pending.fenced = true
260 0 : if (fenceOptions?.detach === true) inFlight = undefined
261 : },
262 : dispose: () => {
263 0 : lifetime.disposed = true
264 0 : snapshot = undefined
265 0 : inFlight = undefined
266 0 : scopeTracker.dispose()
267 : }
268 : }
269 : }
|