diff --git a/packages/account/src/core/billing/__fixtures__/billingTestFixtures.ts b/packages/account/src/core/billing/__fixtures__/billingTestFixtures.ts new file mode 100644 index 00000000000..e2aae66250b --- /dev/null +++ b/packages/account/src/core/billing/__fixtures__/billingTestFixtures.ts @@ -0,0 +1,78 @@ +/** + * The session and transport fakes every billing reader suite builds on. A + * suite keeps what only it needs — its payloads, and the session transitions + * it drives — so that only the shared contract lives here. + */ +import { vi } from 'vitest' + +import type { SessionClient, SessionSnapshot } from '../../session.js' +import type { AccountCredential } from '../../sessionContracts.js' +import type { + BillingHttpResponse, + BillingRequest, + BillingResult, + BillingTransport +} from '../billingContracts.js' + +export function credential( + overrides: Partial = {} +): AccountCredential { + return { + token: 'workspace-jwt', + expiresAt: Date.now() + 60 * 60 * 1000, + uid: 'uid-1', + workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: ['workspace:read'], + ...overrides + } +} + +export function authenticated(session: AccountCredential): SessionSnapshot { + return { + phase: 'authenticated', + user: { uid: session.uid, getIdToken: async () => 'id-token' }, + session + } +} + +/** + * The two members a reader is allowed to reach for. Anything else is left + * undefined at runtime rather than quietly answered, so reaching past them + * fails the test that does it. + */ +export type SessionFake = Pick + +export function httpOk( + body: unknown, + headers: Record = {} +): BillingResult { + return { + status: 'ok', + value: { + httpStatus: 200, + body, + header: (name) => headers[name] ?? null + } + } +} + +export function httpStatus(status: number): BillingResult { + return { + status: 'ok', + value: { httpStatus: status, body: {}, header: () => null } + } +} + +/** A transport that answers each call from the queue, then repeats the last. */ +export function fakeTransport(answers: BillingResult[]) { + const calls: BillingRequest[] = [] + let index = 0 + const transport: BillingTransport = vi.fn(async (request) => { + calls.push(request) + const answer = answers[Math.min(index, answers.length - 1)] + index++ + return answer + }) + return { transport, calls } +} diff --git a/packages/account/src/core/billing/capabilities.test.ts b/packages/account/src/core/billing/capabilities.test.ts index eae4070e578..c27eb6b22c9 100644 --- a/packages/account/src/core/billing/capabilities.test.ts +++ b/packages/account/src/core/billing/capabilities.test.ts @@ -1,56 +1,22 @@ import { describe, expect, it, vi } from 'vitest' -import type { SessionClient, SessionSnapshot } from '../session.js' +import type { SessionSnapshot } from '../session.js' import type { AccountCredential } from '../sessionContracts.js' import { sessionBillingScopeSource } from './billingScope.js' -import type { - BillingHttpResponse, - BillingRequest, - BillingResult, - BillingSession, - BillingTransport -} from './billingContracts.js' +import type { BillingSession, BillingTransport } from './billingContracts.js' import { CAPABILITY_REVISION_HEADER, createCapabilitiesReader, readCapabilityRevision } from './capabilities.js' import { createSessionBillingTransport } from './transport.js' - -function credential( - overrides: Partial = {} -): AccountCredential { - return { - token: 'workspace-jwt', - expiresAt: Date.now() + 60 * 60 * 1000, - uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - permissions: ['workspace:read'], - ...overrides - } -} - -function authenticated(session: AccountCredential): SessionSnapshot { - return { - phase: 'authenticated', - user: { uid: session.uid, getIdToken: async () => 'id-token' }, - session - } -} - -const SIGNED_OUT: SessionSnapshot = { - phase: 'signed-out', - user: null, - session: undefined -} - -/** - * The two members a reader is allowed to reach for. Anything else is left - * undefined at runtime rather than quietly answered, so reaching past them - * fails the test that does it. - */ -type SessionFake = Pick +import { + authenticated, + credential, + fakeTransport, + httpOk +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' function fakeSession(initial: SessionSnapshot = authenticated(credential())) { let snapshot = initial @@ -99,48 +65,6 @@ function capabilitiesBody(overrides: Record = {}) { } } -function httpOk( - body: unknown, - headers: Record = {} -): BillingResult { - return { - status: 'ok', - value: { - httpStatus: 200, - body, - header: (name) => headers[name] ?? null - } - } -} - -function httpStatus( - status: number, - body: unknown = {} -): BillingResult { - return { - status: 'ok', - value: { httpStatus: status, body, header: () => null } - } -} - -/** A transport that answers each call from the queue, then repeats the last. */ -function fakeTransport(answers: BillingResult[]) { - const calls: BillingRequest[] = [] - let index = 0 - const transport: BillingTransport = vi.fn(async (request) => { - calls.push(request) - const answer = answers[Math.min(index, answers.length - 1)] - index++ - return answer - }) - return { transport, calls } -} - -interface SupersedeContext { - readonly host: ReturnType - readonly reader: ReturnType -} - describe('createCapabilitiesReader', () => { it('decodes the server answer and reports the resolved scope', async () => { const { scopeSource } = fakeSession() @@ -174,22 +98,6 @@ describe('createCapabilitiesReader', () => { }) describe('deduplication', () => { - it('serves concurrent readers of one scope from a single request', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(capabilitiesBody())]) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - const [first, second, third] = await Promise.all([ - reader.read(), - reader.read(), - reader.read() - ]) - - expect(transport).toHaveBeenCalledTimes(1) - expect(first).toEqual(second) - expect(second).toEqual(third) - }) - it('does not join a read belonging to another scope', async () => { const host = fakeSession() const { transport } = fakeTransport([ @@ -228,74 +136,6 @@ describe('createCapabilitiesReader', () => { expect(transport).toHaveBeenCalledTimes(1) }) - it('releases a joining caller that aborts, without disturbing the shared read', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(capabilitiesBody()) - }) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - const first = reader.read() - const joiner = new AbortController() - const second = reader.read({ signal: joiner.signal }) - joiner.abort() - - expect(await second).toEqual({ - status: 'error', - code: 'REQUEST_FAILED' - }) - - release() - // The joiner walking away must not cancel the request the first caller - // is still waiting on. - const result = await first - expect(result.status).toBe('ok') - expect(reader.getSnapshot()).toBeDefined() - }) - - it('keeps joined callers alive when the initiating caller aborts', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(capabilitiesBody()) - }) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - const initiator = new AbortController() - const first = reader.read({ signal: initiator.signal }) - const second = reader.read() - initiator.abort() - - expect(await first).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - - release() - // The initiator's signal belongs to the initiator, not to the shared - // request: whoever joined it still gets the answer. - const result = await second - expect(result.status).toBe('ok') - if (result.status !== 'ok') return - expect(result.value.revision).toBe(42) - }) - - it('releases a caller whose signal was already aborted', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(capabilitiesBody())]) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - const result = await reader.read({ signal: AbortSignal.abort() }) - - expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - }) - it('refetches when the caller forces a refresh', async () => { const { scopeSource } = fakeSession() const { transport } = fakeTransport([httpOk(capabilitiesBody())]) @@ -380,77 +220,6 @@ describe('createCapabilitiesReader', () => { }) describe('scope safety', () => { - it('reports SUPERSEDED and caches nothing when the workspace changed in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(capabilitiesBody()) - }) - const reader = createCapabilitiesReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - release() - const result = await pending - - expect(result).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('reports SUPERSEDED and caches nothing when the host signed out in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(capabilitiesBody()) - }) - const reader = createCapabilitiesReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo(SIGNED_OUT) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('drops a cached snapshot when the host changes workspace', async () => { - const host = fakeSession() - const { transport } = fakeTransport([httpOk(capabilitiesBody())]) - const reader = createCapabilitiesReader({ - transport, - scopeSource: host.scopeSource - }) - - await reader.read() - expect(reader.getSnapshot()).toBeDefined() - - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - - expect(reader.getSnapshot()).toBeUndefined() - }) - it('drops owner capabilities when the role changes in place', async () => { const host = fakeSession() const { transport } = fakeTransport([httpOk(capabilitiesBody())]) @@ -516,58 +285,9 @@ describe('createCapabilitiesReader', () => { }) expect(reader.getSnapshot()).toBeUndefined() }) - - it('reports NOT_AUTHENTICATED without asking when nobody is signed in', async () => { - const { scopeSource } = fakeSession(SIGNED_OUT) - const { transport } = fakeTransport([httpOk(capabilitiesBody())]) - - const result = await createCapabilitiesReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code: 'NOT_AUTHENTICATED' }) - expect(transport).not.toHaveBeenCalled() - }) }) describe('failures', () => { - it.for([ - [401, 'ACCESS_DENIED'], - [403, 'ACCESS_DENIED'], - [404, 'NOT_FOUND'], - [409, 'CONFLICT'], - [500, 'REQUEST_FAILED'], - [503, 'REQUEST_FAILED'] - ] as const)('maps %i to %s', async ([status, code]) => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpStatus(status)]) - - const result = await createCapabilitiesReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code, httpStatus: status }) - }) - - it('reports a 2xx body that does not match the contract as malformed', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk({ capabilities: { can_top_up: 'yes' } }) - ]) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'MALFORMED_RESPONSE', - httpStatus: 200 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - it('passes a transport failure through without inventing a status', async () => { const { scopeSource } = fakeSession() const { transport } = fakeTransport([ @@ -581,66 +301,6 @@ describe('createCapabilitiesReader', () => { expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) }) - - it.for([ - [ - 'the workspace changes', - ({ host }: SupersedeContext) => - host.moveTo( - authenticated( - credential({ - workspace: { id: 'ws-2', name: 'Team', type: 'team' } - }) - ) - ) - ], - [ - 'the reader is disposed', - ({ reader }: SupersedeContext) => reader.dispose() - ] - ] as const)( - 'reports SUPERSEDED when a failure lands after %s', - async ([, supersede]) => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpStatus(500) - }) - const reader = createCapabilitiesReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - supersede({ host, reader }) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - } - ) - - it('drops a prior snapshot when the server denies the current actor', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk(capabilitiesBody()), - httpStatus(403) - ]) - const reader = createCapabilitiesReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read({ forceRefresh: true }) - - expect(result).toEqual({ - status: 'error', - code: 'ACCESS_DENIED', - httpStatus: 403 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) }) describe('denial reasons', () => { @@ -794,33 +454,6 @@ describe('createCapabilitiesReader', () => { expect(transport).toHaveBeenCalledTimes(2) }) }) - - it('clears account data and rejects an in-flight result after dispose', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls === 2) await gate - return httpOk(capabilitiesBody()) - }) - const reader = createCapabilitiesReader({ - transport, - scopeSource - }) - - await reader.read() - const pending = reader.read({ forceRefresh: true }) - reader.dispose() - - expect(reader.getSnapshot()).toBeUndefined() - release() - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) }) /** diff --git a/packages/account/src/core/billing/capabilities.ts b/packages/account/src/core/billing/capabilities.ts index b6c155b2736..b3637d69936 100644 --- a/packages/account/src/core/billing/capabilities.ts +++ b/packages/account/src/core/billing/capabilities.ts @@ -20,19 +20,12 @@ import { import { z } from 'zod' import type { BillingResult, BillingTransport } from './billingContracts.js' -import type { - BillingScope, - BillingScopeContext, - BillingScopeSource -} from './billingScope.js' -import { createBillingScopeTracker, sameBillingScope } from './billingScope.js' +import type { BillingScope, BillingScopeSource } from './billingScope.js' +import { sameBillingScope } from './billingScope.js' import type { CapabilityDenials } from './capabilityDenials.js' import { decodeCapabilityDenials } from './capabilityDenials.js' -import { - matchesScopedRead, - readValidatedBillingResponse, - releaseOnAbort -} from './sharedRead.js' +import { createScopedReader } from './scopedReader.js' +import type { ValidatedBillingResponse } from './sharedRead.js' export const CAPABILITIES_ROUTE = '/billing/capabilities' @@ -71,6 +64,8 @@ const CapabilitiesBodySchema = z.object({ rollout_defaults_applied: zBillingCapabilityRolloutDefaults }) +type CapabilitiesBody = z.infer + export type CapabilityScope = BillingScope export interface CapabilitiesSnapshot { @@ -160,40 +155,16 @@ function snapshotAfterInvalidation( return invalidated ? { ...snapshot, freshUntil: 0 } : snapshot } -interface InFlightRead { - readonly context: BillingScopeContext - readonly promise: Promise> - readonly pending: { invalidated: boolean } -} - export function createCapabilitiesReader( options: CapabilitiesReaderOptions ): CapabilitiesReader { const { transport, scopeSource, now = Date.now } = options - let snapshot: CapabilitiesSnapshot | undefined - let inFlight: InFlightRead | undefined - const lifetime = { disposed: false } - const scopeTracker = createBillingScopeTracker(scopeSource, () => { - snapshot = undefined - inFlight = undefined - }) - - const requestCapabilities = async ( + function projectCapabilities( + response: ValidatedBillingResponse, scope: CapabilityScope - ): Promise> => { - const response = await readValidatedBillingResponse( - transport, - { - method: 'GET', - route: CAPABILITIES_ROUTE, - timeoutMs: CAPABILITIES_TIMEOUT_MS - }, - (body) => CapabilitiesBodySchema.safeParse(body) - ) - if (response.status === 'error') return response - - const { data, body, httpStatus } = response.value + ): BillingResult { + const { data, body, httpStatus } = response // Capabilities resolve per (user, workspace), so both halves have to // match. Checking only the workspace would accept another member's answer @@ -228,90 +199,37 @@ export function createCapabilitiesReader( } } - const read = async ( - readOptions?: CapabilitiesReadOptions - ): Promise> => { - if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } - - const context = scopeTracker.capture() - if (context === undefined) { - return { status: 'error', code: 'NOT_AUTHENTICATED' } - } - const { scope } = context - - const currentSnapshot = freshSnapshot( - snapshot, - scope, - readOptions?.forceRefresh === true, - now() - ) - if (currentSnapshot !== undefined) { - return { status: 'ok', value: currentSnapshot } - } - - // One read per scope. A caller arriving mid-flight for the same scope - // joins rather than issuing a second identical request; a caller for a - // different scope starts its own, and the older one can no longer publish. - if (matchesScopedRead(inFlight, context)) { - return releaseOnAbort(inFlight.promise, readOptions?.signal) - } - - // The invalidation flag lives outside the attempt so the read body can - // consult it without referencing the object that holds its own promise. - const pending = { invalidated: false } - // No caller signal reaches the shared request: it is bounded by its own - // timeout, and one caller walking away must not fail the readers still - // waiting on it. Each caller's signal releases only that caller, below. - const promise = (async (): Promise> => { - const result = await requestCapabilities(scope) - // The publish guard. Between issuing the request and settling it the - // host may have changed workspace or signed out, so a snapshot cached - // now would be attributed to whoever is signed in next, and a failure - // says nothing about the scope that has since taken over. - if (lifetime.disposed || !scopeTracker.isCurrent(context)) { - return { status: 'error', code: 'SUPERSEDED' } - } - - if (result.status !== 'ok') { - if (result.code === 'ACCESS_DENIED') snapshot = undefined - return result - } - - // A mutation committed while this read was in flight, and the revision - // the read returns cannot rule out having missed it: the server mints - // that number when it serializes, not when it read. The value is still - // the best available, so it is published — as already stale, so the - // next read refetches instead of serving it. - snapshot = snapshotAfterInvalidation(result.value, pending.invalidated) - return { status: 'ok', value: snapshot } - })() - - const attempt: InFlightRead = { context, promise, pending } - inFlight = attempt - // The slot is released when the request settles, not when this caller - // stops waiting, so an abandoned read still serves whoever joined it. - const release = () => { - if (inFlight === attempt) inFlight = undefined - } - promise.then(release, release) - - return releaseOnAbort(promise, readOptions?.signal) - } + const reader = createScopedReader< + CapabilitiesBody, + CapabilitiesSnapshot, + CapabilitiesReadOptions + >({ + transport, + scopeSource, + route: CAPABILITIES_ROUTE, + parse: (body) => CapabilitiesBodySchema.safeParse(body), + timeoutMs: () => CAPABILITIES_TIMEOUT_MS, + cached: (snapshot, scope, readOptions) => + freshSnapshot(snapshot, scope, readOptions?.forceRefresh === true, now()), + project: projectCapabilities, + // A mutation committed while this read was in flight, and the revision the + // read returns cannot rule out having missed it: the server mints that + // number when it serializes, not when it read. The value is still the best + // available, so it is published — as already stale, so the next read + // refetches instead of serving it. + publish: snapshotAfterInvalidation + }) return { - read, - getSnapshot: () => snapshot, + read: reader.read, + getSnapshot: reader.getSnapshot, invalidate: (revision?: number) => { - if (inFlight !== undefined) inFlight.pending.invalidated = true + reader.fenceInFlight() + const snapshot = reader.getSnapshot() if (snapshot === undefined) return if (revision !== undefined && snapshot.revision === revision) return - snapshot = { ...snapshot, freshUntil: 0 } + reader.setSnapshot({ ...snapshot, freshUntil: 0 }) }, - dispose: () => { - lifetime.disposed = true - snapshot = undefined - inFlight = undefined - scopeTracker.dispose() - } + dispose: reader.dispose } } diff --git a/packages/account/src/core/billing/credits.test.ts b/packages/account/src/core/billing/credits.test.ts index f0640f39434..1bada8854ad 100644 --- a/packages/account/src/core/billing/credits.test.ts +++ b/packages/account/src/core/billing/credits.test.ts @@ -1,63 +1,26 @@ -import { describe, expect, it, vi } from 'vitest' +/** + * What only the credits read does. The scope fence, the shared request, and + * the publish rules it inherits are proved once in `scopedReader.test.ts`. + */ +import { describe, expect, it } from 'vitest' -import type { SessionClient, SessionSnapshot } from '../session.js' -import type { AccountCredential } from '../sessionContracts.js' +import type { SessionSnapshot } from '../session.js' import { sessionBillingScopeSource } from './billingScope.js' -import type { - BillingHttpResponse, - BillingRequest, - BillingResult, - BillingTransport -} from './billingContracts.js' import { createCreditsReader } from './credits.js' - -function credential( - overrides: Partial = {} -): AccountCredential { - return { - token: 'workspace-jwt', - expiresAt: Date.now() + 60 * 60 * 1000, - uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - permissions: ['workspace:read'], - ...overrides - } -} - -function authenticated(session: AccountCredential): SessionSnapshot { - return { - phase: 'authenticated', - user: { uid: session.uid, getIdToken: async () => 'id-token' }, - session - } -} - -const SIGNED_OUT: SessionSnapshot = { - phase: 'signed-out', - user: null, - session: undefined -} - -type SessionFake = Pick - -function fakeSession(initial: SessionSnapshot = authenticated(credential())) { - let snapshot = initial - const listeners = new Set<(next: SessionSnapshot) => void>() +import { + authenticated, + credential, + fakeTransport, + httpOk +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' + +function fakeSession(snapshot: SessionSnapshot = authenticated(credential())) { const fake: SessionFake = { getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - } - } - return { - scopeSource: sessionBillingScopeSource(fake), - moveTo(next: SessionSnapshot) { - snapshot = next - for (const listener of [...listeners]) listener(snapshot) - } + subscribe: () => () => {} } + return { scopeSource: sessionBillingScopeSource(fake) } } const BALANCE = { @@ -68,40 +31,6 @@ const BALANCE = { effective_balance_micros: 12_000_000 } -function httpOk(body: unknown): BillingResult { - return { - status: 'ok', - value: { httpStatus: 200, body, header: () => null } - } -} - -function httpStatus( - status: number, - body: unknown = {} -): BillingResult { - return { - status: 'ok', - value: { httpStatus: status, body, header: () => null } - } -} - -function fakeTransport(answers: BillingResult[]) { - const calls: BillingRequest[] = [] - let index = 0 - const transport: BillingTransport = vi.fn(async (request) => { - calls.push(request) - const answer = answers[Math.min(index, answers.length - 1)] - index++ - return answer - }) - return { transport, calls } -} - -interface SupersedeContext { - readonly host: ReturnType - readonly reader: ReturnType -} - describe('createCreditsReader', () => { it('reads the balance from the billing balance route', async () => { const { scopeSource } = fakeSession() @@ -149,336 +78,4 @@ describe('createCreditsReader', () => { expect(result.value.balance.amount_micros).toBe(0) expect(result.value.balance.prepaid_balance_micros).toBeUndefined() }) - - describe('deduplication', () => { - it('serves concurrent readers of one scope from a single request', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(BALANCE)]) - const reader = createCreditsReader({ transport, scopeSource }) - - const [first, second] = await Promise.all([reader.read(), reader.read()]) - - expect(transport).toHaveBeenCalledTimes(1) - expect(first).toEqual(second) - }) - - it('releases a joining caller that aborts, without disturbing the shared read', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(BALANCE) - }) - const reader = createCreditsReader({ transport, scopeSource }) - - const first = reader.read() - const joiner = new AbortController() - const second = reader.read({ signal: joiner.signal }) - joiner.abort() - - expect(await second).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - - release() - const result = await first - expect(result.status).toBe('ok') - expect(reader.getSnapshot()).toBeDefined() - }) - - it('keeps joined callers alive when the initiating caller aborts', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(BALANCE) - }) - const reader = createCreditsReader({ transport, scopeSource }) - - const initiator = new AbortController() - const first = reader.read({ signal: initiator.signal }) - const second = reader.read() - initiator.abort() - - expect(await first).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - - release() - const result = await second - expect(result.status).toBe('ok') - if (result.status !== 'ok') return - expect(result.value.balance.amount_micros).toBe(12_500_000) - }) - - it('requests again on a later read rather than serving the cache', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(BALANCE)]) - const reader = createCreditsReader({ transport, scopeSource }) - - await reader.read() - await reader.read() - - // A balance moves on every run and carries no server-declared lifetime, - // so there is no window over which serving a cached one is correct. - expect(transport).toHaveBeenCalledTimes(2) - }) - - it('prevents an older read from publishing after a scope round trip', async () => { - const host = fakeSession() - const releases: Array<(balance: typeof BALANCE) => void> = [] - const transport: BillingTransport = vi.fn( - () => - new Promise>((resolve) => { - releases.push((balance) => resolve(httpOk(balance))) - }) - ) - const reader = createCreditsReader({ - transport, - scopeSource: host.scopeSource - }) - - const firstA = reader.read() - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - const readB = reader.read() - host.moveTo(authenticated(credential())) - const latestA = reader.read() - - releases[2]({ ...BALANCE, amount_micros: 99 }) - await latestA - releases[0]({ ...BALANCE, amount_micros: 10 }) - releases[1]({ ...BALANCE, amount_micros: 20 }) - - expect(await firstA).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(await readB).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()?.balance.amount_micros).toBe(99) - }) - }) - - describe('scope safety', () => { - it('reports SUPERSEDED and caches nothing when the workspace changed in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(BALANCE) - }) - const reader = createCreditsReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('reports SUPERSEDED and caches nothing when the host signed out in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(BALANCE) - }) - const reader = createCreditsReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo(SIGNED_OUT) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('drops a published balance when the host changes workspace', async () => { - const host = fakeSession() - const { transport } = fakeTransport([httpOk(BALANCE)]) - const reader = createCreditsReader({ - transport, - scopeSource: host.scopeSource - }) - - await reader.read() - expect(reader.getSnapshot()).toBeDefined() - - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - - // Showing one workspace's credits under another's name is the failure - // this guards; a stale balance is worse than none. - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('reports NOT_AUTHENTICATED without asking when nobody is signed in', async () => { - const { scopeSource } = fakeSession(SIGNED_OUT) - const { transport } = fakeTransport([httpOk(BALANCE)]) - - const result = await createCreditsReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code: 'NOT_AUTHENTICATED' }) - expect(transport).not.toHaveBeenCalled() - }) - }) - - describe('failures', () => { - it.for([ - [401, 'ACCESS_DENIED'], - [403, 'ACCESS_DENIED'], - [404, 'NOT_FOUND'], - [500, 'REQUEST_FAILED'] - ] as const)('maps %i to %s', async ([status, code]) => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpStatus(status)]) - - const result = await createCreditsReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code, httpStatus: status }) - }) - - it('reports a 2xx body that does not match the contract as malformed', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk({ amount_micros: 'a lot', currency: 'USD' }) - ]) - const reader = createCreditsReader({ transport, scopeSource }) - - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'MALFORMED_RESPONSE', - httpStatus: 200 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('keeps the last good balance when a later read fails', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk(BALANCE), - { status: 'error', code: 'REQUEST_FAILED' } - ]) - const reader = createCreditsReader({ transport, scopeSource }) - - await reader.read() - const second = await reader.read() - - // The cache exists to survive a failure, not to skip a read: a transient - // outage leaves the figure stale rather than blanking it. - expect(second).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - expect(reader.getSnapshot()?.balance.amount_micros).toBe(12_500_000) - }) - - it.for([ - [ - 'the workspace changes', - ({ host }: SupersedeContext) => - host.moveTo( - authenticated( - credential({ - workspace: { id: 'ws-2', name: 'Team', type: 'team' } - }) - ) - ) - ], - [ - 'the reader is disposed', - ({ reader }: SupersedeContext) => reader.dispose() - ] - ] as const)( - 'reports SUPERSEDED when a failure lands after %s', - async ([, supersede]) => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpStatus(500) - }) - const reader = createCreditsReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - supersede({ host, reader }) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - } - ) - - it('drops the last good balance when a later read is denied', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(BALANCE), httpStatus(401)]) - const reader = createCreditsReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'ACCESS_DENIED', - httpStatus: 401 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - }) - - it('clears account data and rejects an in-flight result after dispose', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls === 2) await gate - return httpOk(BALANCE) - }) - const reader = createCreditsReader({ transport, scopeSource }) - - await reader.read() - const pending = reader.read() - reader.dispose() - - expect(reader.getSnapshot()).toBeUndefined() - release() - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) }) diff --git a/packages/account/src/core/billing/credits.ts b/packages/account/src/core/billing/credits.ts index 3994a00b01c..3eab1c226b6 100644 --- a/packages/account/src/core/billing/credits.ts +++ b/packages/account/src/core/billing/credits.ts @@ -10,17 +10,8 @@ import { zBillingBalanceResponse } from '@comfyorg/ingest-types/zod' import type { z } from 'zod' import type { BillingResult, BillingTransport } from './billingContracts.js' -import type { - BillingScope, - BillingScopeContext, - BillingScopeSource -} from './billingScope.js' -import { createBillingScopeTracker } from './billingScope.js' -import { - matchesScopedRead, - readValidatedBillingResponse, - releaseOnAbort -} from './sharedRead.js' +import type { BillingScope, BillingScopeSource } from './billingScope.js' +import { createScopedReader } from './scopedReader.js' export const CREDITS_ROUTE = '/billing/balance' @@ -61,98 +52,29 @@ export interface CreditsReaderOptions { readonly now?: () => number } -interface InFlightRead { - readonly context: BillingScopeContext - readonly promise: Promise> -} - export function createCreditsReader( options: CreditsReaderOptions ): CreditsReader { const { transport, scopeSource, now = Date.now } = options - let snapshot: CreditsSnapshot | undefined - let inFlight: InFlightRead | undefined - const lifetime = { disposed: false } - const scopeTracker = createBillingScopeTracker(scopeSource, () => { - snapshot = undefined - inFlight = undefined - }) - - const requestBalance = async ( - scope: CreditsScope - ): Promise> => { - const response = await readValidatedBillingResponse( - transport, - { method: 'GET', route: CREDITS_ROUTE }, - (body) => zBillingBalanceResponse.safeParse(body) - ) - if (response.status === 'error') return response - - return { + const reader = createScopedReader< + BillingBalance, + CreditsSnapshot, + CreditsReadOptions + >({ + transport, + scopeSource, + route: CREDITS_ROUTE, + parse: (body) => zBillingBalanceResponse.safeParse(body), + project: ({ data }, scope) => ({ status: 'ok', - value: { balance: response.value.data, scope, readAt: now() } - } - } - - const read = async ( - readOptions?: CreditsReadOptions - ): Promise> => { - if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } - - const context = scopeTracker.capture() - if (context === undefined) { - return { status: 'error', code: 'NOT_AUTHENTICATED' } - } - const { scope } = context - - if (matchesScopedRead(inFlight, context)) { - return releaseOnAbort(inFlight.promise, readOptions?.signal) - } - - // No caller signal reaches the shared request: it is bounded by its own - // timeout, and one caller walking away must not fail the readers still - // waiting on it. Each caller's signal releases only that caller, below. - const attempt: InFlightRead = { - context, - promise: (async () => { - const result = await requestBalance(scope) - // The publish guard: a balance that arrives after the host moved to - // another workspace or signed out belongs to neither, and a failure - // says nothing about the scope that has since taken over. - if (lifetime.disposed || !scopeTracker.isCurrent(context)) { - return { status: 'error', code: 'SUPERSEDED' } - } - - if (result.status !== 'ok') { - if (result.code === 'ACCESS_DENIED') snapshot = undefined - return result - } - - snapshot = result.value - return result - })() - } - - inFlight = attempt - // The slot is released when the request settles, not when this caller - // stops waiting, so an abandoned read still serves whoever joined it. - const release = () => { - if (inFlight === attempt) inFlight = undefined - } - attempt.promise.then(release, release) - - return releaseOnAbort(attempt.promise, readOptions?.signal) - } + value: { balance: data, scope, readAt: now() } + }) + }) return { - read, - getSnapshot: () => snapshot, - dispose: () => { - lifetime.disposed = true - snapshot = undefined - inFlight = undefined - scopeTracker.dispose() - } + read: reader.read, + getSnapshot: reader.getSnapshot, + dispose: reader.dispose } } diff --git a/packages/account/src/core/billing/paymentMethods.test.ts b/packages/account/src/core/billing/paymentMethods.test.ts index 96179a2db27..44b3bd1ec47 100644 --- a/packages/account/src/core/billing/paymentMethods.test.ts +++ b/packages/account/src/core/billing/paymentMethods.test.ts @@ -1,65 +1,33 @@ +/** + * What only the saved payment methods read does — its route, its projection, + * and the invalidation the host drives. The scope fence, the shared request, + * and the publish rules it inherits are proved once in `scopedReader.test.ts`. + */ import { describe, expect, it, vi } from 'vitest' -import type { SessionClient, SessionSnapshot } from '../session.js' -import type { AccountCredential } from '../sessionContracts.js' +import type { SessionSnapshot } from '../session.js' import { sessionBillingScopeSource } from './billingScope.js' import type { BillingHttpResponse, - BillingRequest, BillingResult, BillingTransport } from './billingContracts.js' import { createPaymentMethodsReader } from './paymentMethods.js' - -function credential( - overrides: Partial = {} -): AccountCredential { - return { - token: 'workspace-jwt', - expiresAt: Date.now() + 60 * 60 * 1000, - uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - permissions: ['workspace:read'], - ...overrides - } -} - -function authenticated(session: AccountCredential): SessionSnapshot { - return { - phase: 'authenticated', - user: { uid: session.uid, getIdToken: async () => 'id-token' }, - session - } -} - -const SIGNED_OUT: SessionSnapshot = { - phase: 'signed-out', - user: null, - session: undefined -} - -const TEAM = { id: 'ws-2', name: 'Team', type: 'team' } as const - -type SessionFake = Pick - -function fakeSession(initial: SessionSnapshot = authenticated(credential())) { - let snapshot = initial - const listeners = new Set<(next: SessionSnapshot) => void>() +import { + authenticated, + credential, + fakeTransport, + httpOk, + httpStatus +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' + +function fakeSession(snapshot: SessionSnapshot = authenticated(credential())) { const fake: SessionFake = { getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - } - } - return { - scopeSource: sessionBillingScopeSource(fake), - moveTo(next: SessionSnapshot) { - snapshot = next - for (const listener of [...listeners]) listener(snapshot) - } + subscribe: () => () => {} } + return { scopeSource: sessionBillingScopeSource(fake) } } const CARD = { @@ -72,38 +40,24 @@ const CARD = { const METHODS = [CARD] -function httpOk(body: unknown): BillingResult { - return { - status: 'ok', - value: { httpStatus: 200, body, header: () => null } - } -} - -function httpStatus( - status: number, - extra: { readonly authenticationRetrySkipped?: true } = {} -): BillingResult { - return { - status: 'ok', - value: { httpStatus: status, body: {}, header: () => null, ...extra } - } -} +const REPLACEMENT_CARD = { ...CARD, id: 'pm_2', last4: '1881' } -function fakeTransport(answers: BillingResult[]) { - const calls: BillingRequest[] = [] - let index = 0 - const transport: BillingTransport = vi.fn(async (request) => { - calls.push(request) - const answer = answers[Math.min(index, answers.length - 1)] - index++ - return answer +/** Holds the first answer open so an invalidation can land mid-flight. */ +function transportWithSlowFirstAnswer( + first: BillingResult +) { + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve }) - return { transport, calls } -} - -interface SupersedeContext { - readonly host: ReturnType - readonly reader: ReturnType + let calls = 0 + const transport: BillingTransport = vi.fn(async () => { + calls++ + if (calls > 1) return httpOk([REPLACEMENT_CARD]) + await gate + return first + }) + return { transport, release: () => release() } } describe('createPaymentMethodsReader', () => { @@ -156,22 +110,11 @@ describe('createPaymentMethodsReader', () => { expect(calls[0].timeoutMs).toBe(5_000) }) - it('serves concurrent readers of one scope from a single request', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(METHODS)]) - const reader = createPaymentMethodsReader({ transport, scopeSource }) - - const [first, second] = await Promise.all([reader.read(), reader.read()]) - - expect(transport).toHaveBeenCalledTimes(1) - expect(first).toEqual(second) - }) - it('drops the published list on invalidate and republishes on the next read', async () => { const { scopeSource } = fakeSession() const { transport } = fakeTransport([ httpOk(METHODS), - httpOk([{ ...CARD, id: 'pm_2', last4: '1881' }]) + httpOk([REPLACEMENT_CARD]) ]) const reader = createPaymentMethodsReader({ transport, scopeSource }) @@ -193,17 +136,7 @@ describe('createPaymentMethodsReader', () => { it('fences a request that predates an invalidation from publishing', async () => { const { scopeSource } = fakeSession() - let releaseStale = () => {} - const staleGate = new Promise((resolve) => { - releaseStale = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls > 1) return httpOk([{ ...CARD, id: 'pm_2', last4: '1881' }]) - await staleGate - return httpOk(METHODS) - }) + const { transport, release } = transportWithSlowFirstAnswer(httpOk(METHODS)) const reader = createPaymentMethodsReader({ transport, scopeSource }) const stale = reader.read() @@ -218,7 +151,7 @@ describe('createPaymentMethodsReader', () => { if (result.status !== 'ok') return expect(result.value.methods[0].id).toBe('pm_2') - releaseStale() + release() await stale expect(reader.getSnapshot()?.methods[0].id).toBe('pm_2') @@ -226,17 +159,7 @@ describe('createPaymentMethodsReader', () => { it('keeps the fresh list when an invalidated request is denied late', async () => { const { scopeSource } = fakeSession() - let releaseStale = () => {} - const staleGate = new Promise((resolve) => { - releaseStale = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls > 1) return httpOk([{ ...CARD, id: 'pm_2', last4: '1881' }]) - await staleGate - return httpStatus(403) - }) + const { transport, release } = transportWithSlowFirstAnswer(httpStatus(403)) const reader = createPaymentMethodsReader({ transport, scopeSource }) const stale = reader.read() @@ -245,201 +168,9 @@ describe('createPaymentMethodsReader', () => { expect(reader.getSnapshot()?.methods[0].id).toBe('pm_2') - releaseStale() + release() await stale expect(reader.getSnapshot()?.methods[0].id).toBe('pm_2') }) - - describe('scope safety', () => { - it('reports SUPERSEDED and caches nothing when the workspace changed in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(METHODS) - }) - const reader = createPaymentMethodsReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo(authenticated(credential({ workspace: TEAM }))) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('drops a published list when the host changes workspace', async () => { - const host = fakeSession() - const { transport } = fakeTransport([httpOk(METHODS)]) - const reader = createPaymentMethodsReader({ - transport, - scopeSource: host.scopeSource - }) - - await reader.read() - expect(reader.getSnapshot()).toBeDefined() - - host.moveTo(authenticated(credential({ workspace: TEAM }))) - - // Naming one workspace's card as chargeable by another is the failure - // this guards. - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('reports NOT_AUTHENTICATED without asking when nobody is signed in', async () => { - const { scopeSource } = fakeSession(SIGNED_OUT) - const { transport } = fakeTransport([httpOk(METHODS)]) - - const result = await createPaymentMethodsReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code: 'NOT_AUTHENTICATED' }) - expect(transport).not.toHaveBeenCalled() - }) - }) - - describe('failures', () => { - it.for([ - [401, false, 'ACCESS_DENIED'], - [401, true, 'REQUEST_FAILED'], - [403, false, 'ACCESS_DENIED'], - [404, false, 'NOT_FOUND'], - [500, false, 'REQUEST_FAILED'] - ] as const)( - 'maps %i (retry skipped: %s) to %s', - async ([status, retrySkipped, code]) => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpStatus( - status, - retrySkipped ? { authenticationRetrySkipped: true } : {} - ) - ]) - - const result = await createPaymentMethodsReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code, httpStatus: status }) - } - ) - - it('reports a 2xx body that does not match the contract as malformed', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk([{ ...CARD, id: 'card_1' }])]) - const reader = createPaymentMethodsReader({ transport, scopeSource }) - - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'MALFORMED_RESPONSE', - httpStatus: 200 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('keeps the last good list when a later read fails', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk(METHODS), - { status: 'error', code: 'REQUEST_FAILED' } - ]) - const reader = createPaymentMethodsReader({ transport, scopeSource }) - - await reader.read() - const second = await reader.read() - - expect(second).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - expect(reader.getSnapshot()?.methods[0].id).toBe('pm_1') - }) - - it.for([ - [ - 'the workspace changes', - ({ host }: SupersedeContext) => - host.moveTo(authenticated(credential({ workspace: TEAM }))) - ], - [ - 'the reader is disposed', - ({ reader }: SupersedeContext) => reader.dispose() - ] - ] as const)( - 'reports SUPERSEDED when a failure lands after %s', - async ([, supersede]) => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpStatus(500) - }) - const reader = createPaymentMethodsReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - supersede({ host, reader }) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - } - ) - - it('drops the published list when a later read is denied', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(METHODS), httpStatus(403)]) - const reader = createPaymentMethodsReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'ACCESS_DENIED', - httpStatus: 403 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - }) - - it('clears the list and rejects an in-flight result after dispose', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls === 2) await gate - return httpOk(METHODS) - }) - const reader = createPaymentMethodsReader({ transport, scopeSource }) - - await reader.read() - const pending = reader.read() - reader.dispose() - - expect(reader.getSnapshot()).toBeUndefined() - release() - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(await reader.read()).toEqual({ - status: 'error', - code: 'SUPERSEDED' - }) - }) }) diff --git a/packages/account/src/core/billing/paymentMethods.ts b/packages/account/src/core/billing/paymentMethods.ts index a87a901cb9e..4753a3c14c2 100644 --- a/packages/account/src/core/billing/paymentMethods.ts +++ b/packages/account/src/core/billing/paymentMethods.ts @@ -10,22 +10,9 @@ import { zListSavedPaymentMethodsResponse } from '@comfyorg/ingest-types/zod' import type { zSavedPaymentMethod } from '@comfyorg/ingest-types/zod' import type { z } from 'zod' -import type { - BillingRequest, - BillingResult, - BillingTransport -} from './billingContracts.js' -import type { - BillingScope, - BillingScopeContext, - BillingScopeSource -} from './billingScope.js' -import { createBillingScopeTracker } from './billingScope.js' -import { - matchesScopedRead, - readValidatedBillingResponse, - releaseOnAbort -} from './sharedRead.js' +import type { BillingResult, BillingTransport } from './billingContracts.js' +import type { BillingScope, BillingScopeSource } from './billingScope.js' +import { createScopedReader } from './scopedReader.js' export const PAYMENT_METHODS_ROUTE = '/billing/payment-methods' @@ -71,127 +58,37 @@ export interface PaymentMethodsReaderOptions { readonly now?: () => number } -interface InFlightRead { - readonly context: BillingScopeContext - readonly promise: Promise> - /** - * Set when the host invalidates while this request is in flight. The list it - * returns was resolved before the change the host is reporting, so it may be - * served to the callers already waiting on it but must not be published. - */ - readonly pending: { invalidated: boolean } -} - export function createPaymentMethodsReader( options: PaymentMethodsReaderOptions ): PaymentMethodsReader { const { transport, scopeSource, now = Date.now } = options - let snapshot: PaymentMethodsSnapshot | undefined - let inFlight: InFlightRead | undefined - const lifetime = { disposed: false } - const scopeTracker = createBillingScopeTracker(scopeSource, () => { - snapshot = undefined - inFlight = undefined - }) - - async function requestPaymentMethods( - scope: PaymentMethodsScope, - timeoutMs: number | undefined - ): Promise> { - const request: BillingRequest = { - method: 'GET', - route: PAYMENT_METHODS_ROUTE, - ...(timeoutMs === undefined ? {} : { timeoutMs }) - } - const response = await readValidatedBillingResponse( - transport, - request, - (body) => zListSavedPaymentMethodsResponse.safeParse(body) - ) - if (response.status === 'error') return response - - return { + const reader = createScopedReader< + readonly SavedPaymentMethod[], + PaymentMethodsSnapshot, + PaymentMethodsReadOptions + >({ + transport, + scopeSource, + route: PAYMENT_METHODS_ROUTE, + parse: (body) => zListSavedPaymentMethodsResponse.safeParse(body), + timeoutMs: (readOptions) => readOptions?.timeoutMs, + project: ({ data }, scope) => ({ status: 'ok', - value: { scope, methods: response.value.data, readAt: now() } - } - } - - async function read( - readOptions?: PaymentMethodsReadOptions - ): Promise> { - if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } - - const context = scopeTracker.capture() - if (context === undefined) { - return { status: 'error', code: 'NOT_AUTHENTICATED' } - } - const { scope } = context - - if (matchesScopedRead(inFlight, context)) { - return releaseOnAbort(inFlight.promise, readOptions?.signal) - } - - // The invalidation flag lives outside the attempt so the read body can - // consult it without referencing the object that holds its own promise. - const pending = { invalidated: false } - // No caller signal reaches the shared request: it is bounded by its own - // timeout, and one caller walking away must not fail the readers still - // waiting on it. Each caller's signal releases only that caller, below. - const promise = (async (): Promise< - BillingResult - > => { - const result = await requestPaymentMethods(scope, readOptions?.timeoutMs) - // A list that arrives after the host moved to another workspace names - // cards the current one cannot charge, and a failure says nothing about - // the scope that has since taken over. - if (lifetime.disposed || !scopeTracker.isCurrent(context)) { - return { status: 'error', code: 'SUPERSEDED' } - } - - if (result.status !== 'ok') { - // The same fence the publish path carries: a denial that predates an - // invalidation is no evidence about the list a later read published, - // and clearing on it would drop a fresh list for a stale refusal. - if (result.code === 'ACCESS_DENIED' && !pending.invalidated) { - snapshot = undefined - } - return result - } - - if (!pending.invalidated) snapshot = result.value - return result - })() - - const attempt: InFlightRead = { context, promise, pending } - inFlight = attempt - const release = () => { - if (inFlight === attempt) inFlight = undefined - } - promise.then(release, release) - - return releaseOnAbort(promise, readOptions?.signal) - } + value: { scope, methods: data, readAt: now() } + }), + // A list resolved before the change the host is reporting may be served to + // the callers already waiting on it, but must not be published. + publish: (value, fenced) => (fenced ? undefined : value) + }) return { - read, - getSnapshot: () => snapshot, + read: reader.read, + getSnapshot: reader.getSnapshot, invalidate: () => { - snapshot = undefined - // A request issued before this call resolved the list the host is - // reporting as wrong, so it is fenced off from publishing and its slot - // released: the read that follows an invalidation must issue its own - // request rather than join the one that predates it. - if (inFlight !== undefined) { - inFlight.pending.invalidated = true - inFlight = undefined - } + reader.setSnapshot(undefined) + reader.fenceInFlight({ detach: true }) }, - dispose: () => { - lifetime.disposed = true - snapshot = undefined - inFlight = undefined - scopeTracker.dispose() - } + dispose: reader.dispose } } diff --git a/packages/account/src/core/billing/plans.test.ts b/packages/account/src/core/billing/plans.test.ts index 9b449960014..7526a98ab1c 100644 --- a/packages/account/src/core/billing/plans.test.ts +++ b/packages/account/src/core/billing/plans.test.ts @@ -1,65 +1,26 @@ -import { describe, expect, it, vi } from 'vitest' +/** + * What only the plans read does. The scope fence, the shared request, and the + * publish rules it inherits are proved once in `scopedReader.test.ts`. + */ +import { describe, expect, it } from 'vitest' -import type { SessionClient, SessionSnapshot } from '../session.js' -import type { AccountCredential } from '../sessionContracts.js' +import type { SessionSnapshot } from '../session.js' import { sessionBillingScopeSource } from './billingScope.js' -import type { - BillingHttpResponse, - BillingRequest, - BillingResult, - BillingTransport -} from './billingContracts.js' import { createPlansReader } from './plans.js' - -function credential( - overrides: Partial = {} -): AccountCredential { - return { - token: 'workspace-jwt', - expiresAt: Date.now() + 60 * 60 * 1000, - uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - permissions: ['workspace:read'], - ...overrides - } -} - -function authenticated(session: AccountCredential): SessionSnapshot { - return { - phase: 'authenticated', - user: { uid: session.uid, getIdToken: async () => 'id-token' }, - session - } -} - -const SIGNED_OUT: SessionSnapshot = { - phase: 'signed-out', - user: null, - session: undefined -} - -const TEAM = { id: 'ws-2', name: 'Team', type: 'team' } as const - -type SessionFake = Pick - -function fakeSession(initial: SessionSnapshot = authenticated(credential())) { - let snapshot = initial - const listeners = new Set<(next: SessionSnapshot) => void>() +import { + authenticated, + credential, + fakeTransport, + httpOk +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' + +function fakeSession(snapshot: SessionSnapshot = authenticated(credential())) { const fake: SessionFake = { getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - } - } - return { - scopeSource: sessionBillingScopeSource(fake), - moveTo(next: SessionSnapshot) { - snapshot = next - for (const listener of [...listeners]) listener(snapshot) - } + subscribe: () => () => {} } + return { scopeSource: sessionBillingScopeSource(fake) } } const PLAN = { @@ -79,40 +40,6 @@ const PLAN = { const CATALOG = { current_plan_slug: 'free', plans: [PLAN] } -function httpOk(body: unknown): BillingResult { - return { - status: 'ok', - value: { httpStatus: 200, body, header: () => null } - } -} - -function httpStatus( - status: number, - extra: { readonly authenticationRetrySkipped?: true } = {} -): BillingResult { - return { - status: 'ok', - value: { httpStatus: status, body: {}, header: () => null, ...extra } - } -} - -function fakeTransport(answers: BillingResult[]) { - const calls: BillingRequest[] = [] - let index = 0 - const transport: BillingTransport = vi.fn(async (request) => { - calls.push(request) - const answer = answers[Math.min(index, answers.length - 1)] - index++ - return answer - }) - return { transport, calls } -} - -interface SupersedeContext { - readonly host: ReturnType - readonly reader: ReturnType -} - describe('createPlansReader', () => { it('reads the catalog from the billing plans route', async () => { const { scopeSource } = fakeSession() @@ -150,219 +77,4 @@ describe('createPlansReader', () => { expect(calls[0].timeoutMs).toBe(5_000) }) - - it('serves concurrent readers of one scope from a single request', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(CATALOG)]) - const reader = createPlansReader({ transport, scopeSource }) - - const [first, second] = await Promise.all([reader.read(), reader.read()]) - - expect(transport).toHaveBeenCalledTimes(1) - expect(first).toEqual(second) - }) - - it('requests again on a later read rather than serving the cache', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(CATALOG)]) - const reader = createPlansReader({ transport, scopeSource }) - - await reader.read() - await reader.read() - - expect(transport).toHaveBeenCalledTimes(2) - }) - - describe('scope safety', () => { - it('reports SUPERSEDED and caches nothing when the workspace changed in flight', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(CATALOG) - }) - const reader = createPlansReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo(authenticated(credential({ workspace: TEAM }))) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - // Availability is resolved for the actor that asked, so a catalog for - // the workspace just left cannot be offered under the new one. - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('drops a published catalog when the host changes workspace', async () => { - const host = fakeSession() - const { transport } = fakeTransport([httpOk(CATALOG)]) - const reader = createPlansReader({ - transport, - scopeSource: host.scopeSource - }) - - await reader.read() - expect(reader.getSnapshot()).toBeDefined() - - host.moveTo(authenticated(credential({ workspace: TEAM }))) - - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('reports NOT_AUTHENTICATED without asking when nobody is signed in', async () => { - const { scopeSource } = fakeSession(SIGNED_OUT) - const { transport } = fakeTransport([httpOk(CATALOG)]) - - const result = await createPlansReader({ transport, scopeSource }).read() - - expect(result).toEqual({ status: 'error', code: 'NOT_AUTHENTICATED' }) - expect(transport).not.toHaveBeenCalled() - }) - }) - - describe('failures', () => { - it.for([ - [401, false, 'ACCESS_DENIED'], - // A 401 the transport could not replay says the token went stale, not - // that the catalog is off limits. - [401, true, 'REQUEST_FAILED'], - [403, false, 'ACCESS_DENIED'], - [404, false, 'NOT_FOUND'], - [500, false, 'REQUEST_FAILED'] - ] as const)( - 'maps %i (retry skipped: %s) to %s', - async ([status, retrySkipped, code]) => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpStatus( - status, - retrySkipped ? { authenticationRetrySkipped: true } : {} - ) - ]) - - const result = await createPlansReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code, httpStatus: status }) - } - ) - - it('reports a 2xx body that does not match the contract as malformed', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk({ plans: [{ ...PLAN, tier: 'GOLD' }] }) - ]) - const reader = createPlansReader({ transport, scopeSource }) - - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'MALFORMED_RESPONSE', - httpStatus: 200 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('keeps the last good catalog when a later read fails', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk(CATALOG), - { status: 'error', code: 'REQUEST_FAILED' } - ]) - const reader = createPlansReader({ transport, scopeSource }) - - await reader.read() - const second = await reader.read() - - expect(second).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - expect(reader.getSnapshot()?.data.plans).toHaveLength(1) - }) - - it.for([ - [ - 'the workspace changes', - ({ host }: SupersedeContext) => - host.moveTo(authenticated(credential({ workspace: TEAM }))) - ], - [ - 'the reader is disposed', - ({ reader }: SupersedeContext) => reader.dispose() - ] - ] as const)( - 'reports SUPERSEDED when a failure lands after %s', - async ([, supersede]) => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpStatus(500) - }) - const reader = createPlansReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - supersede({ host, reader }) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - } - ) - - it('drops the published catalog when a later read is denied', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(CATALOG), httpStatus(403)]) - const reader = createPlansReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'ACCESS_DENIED', - httpStatus: 403 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - }) - - it('clears the catalog and rejects an in-flight result after dispose', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls === 2) await gate - return httpOk(CATALOG) - }) - const reader = createPlansReader({ transport, scopeSource }) - - await reader.read() - const pending = reader.read() - reader.dispose() - - expect(reader.getSnapshot()).toBeUndefined() - release() - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(await reader.read()).toEqual({ - status: 'error', - code: 'SUPERSEDED' - }) - }) }) diff --git a/packages/account/src/core/billing/plans.ts b/packages/account/src/core/billing/plans.ts index 40092d5f6a1..6ce87ef5f0b 100644 --- a/packages/account/src/core/billing/plans.ts +++ b/packages/account/src/core/billing/plans.ts @@ -8,22 +8,9 @@ import { zGetBillingPlansResponse } from '@comfyorg/ingest-types/zod' import type { z } from 'zod' -import type { - BillingRequest, - BillingResult, - BillingTransport -} from './billingContracts.js' -import type { - BillingScope, - BillingScopeContext, - BillingScopeSource -} from './billingScope.js' -import { createBillingScopeTracker } from './billingScope.js' -import { - matchesScopedRead, - readValidatedBillingResponse, - releaseOnAbort -} from './sharedRead.js' +import type { BillingResult, BillingTransport } from './billingContracts.js' +import type { BillingScope, BillingScopeSource } from './billingScope.js' +import { createScopedReader } from './scopedReader.js' export const PLANS_ROUTE = '/billing/plans' @@ -64,100 +51,28 @@ export interface PlansReaderOptions { readonly now?: () => number } -interface InFlightRead { - readonly context: BillingScopeContext - readonly promise: Promise> -} - export function createPlansReader(options: PlansReaderOptions): PlansReader { const { transport, scopeSource, now = Date.now } = options - let snapshot: PlansSnapshot | undefined - let inFlight: InFlightRead | undefined - const lifetime = { disposed: false } - const scopeTracker = createBillingScopeTracker(scopeSource, () => { - snapshot = undefined - inFlight = undefined - }) - - async function requestPlans( - scope: PlansScope, - timeoutMs: number | undefined - ): Promise> { - const request: BillingRequest = { - method: 'GET', - route: PLANS_ROUTE, - ...(timeoutMs === undefined ? {} : { timeoutMs }) - } - const response = await readValidatedBillingResponse( - transport, - request, - (body) => zGetBillingPlansResponse.safeParse(body) - ) - if (response.status === 'error') return response - - return { + const reader = createScopedReader< + BillingPlansData, + PlansSnapshot, + PlansReadOptions + >({ + transport, + scopeSource, + route: PLANS_ROUTE, + parse: (body) => zGetBillingPlansResponse.safeParse(body), + timeoutMs: (readOptions) => readOptions?.timeoutMs, + project: ({ data }, scope) => ({ status: 'ok', - value: { scope, data: response.value.data, readAt: now() } - } - } - - async function read( - readOptions?: PlansReadOptions - ): Promise> { - if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } - - const context = scopeTracker.capture() - if (context === undefined) { - return { status: 'error', code: 'NOT_AUTHENTICATED' } - } - const { scope } = context - - if (matchesScopedRead(inFlight, context)) { - return releaseOnAbort(inFlight.promise, readOptions?.signal) - } - - // No caller signal reaches the shared request: it is bounded by its own - // timeout, and one caller walking away must not fail the readers still - // waiting on it. Each caller's signal releases only that caller, below. - const attempt: InFlightRead = { - context, - promise: (async () => { - const result = await requestPlans(scope, readOptions?.timeoutMs) - // A result that arrives after the host moved to another workspace was - // resolved for eligibility the current actor no longer has, and a - // failure says nothing about the scope that has since taken over. - if (lifetime.disposed || !scopeTracker.isCurrent(context)) { - return { status: 'error', code: 'SUPERSEDED' } - } - - if (result.status !== 'ok') { - if (result.code === 'ACCESS_DENIED') snapshot = undefined - return result - } - - snapshot = result.value - return result - })() - } - - inFlight = attempt - const release = () => { - if (inFlight === attempt) inFlight = undefined - } - attempt.promise.then(release, release) - - return releaseOnAbort(attempt.promise, readOptions?.signal) - } + value: { scope, data, readAt: now() } + }) + }) return { - read, - getSnapshot: () => snapshot, - dispose: () => { - lifetime.disposed = true - snapshot = undefined - inFlight = undefined - scopeTracker.dispose() - } + read: reader.read, + getSnapshot: reader.getSnapshot, + dispose: reader.dispose } } diff --git a/packages/account/src/core/billing/scopedReader.test.ts b/packages/account/src/core/billing/scopedReader.test.ts new file mode 100644 index 00000000000..5bb105efa22 --- /dev/null +++ b/packages/account/src/core/billing/scopedReader.test.ts @@ -0,0 +1,582 @@ +/** + * The contract every billing reader inherits from `createScopedReader`, proved + * once against each reader that is built on it rather than five times over. + * A reader's own test file keeps what only that reader does: its route, its + * decoder, its projection, and the cache or invalidation it owns. + */ +import { describe, expect, it, vi } from 'vitest' + +import type { SessionSnapshot } from '../session.js' +import type { + BillingHttpResponse, + BillingResult, + BillingTransport +} from './billingContracts.js' +import type { BillingScopeSource } from './billingScope.js' +import { sessionBillingScopeSource } from './billingScope.js' +import { createCapabilitiesReader } from './capabilities.js' +import { createCreditsReader } from './credits.js' +import { createPaymentMethodsReader } from './paymentMethods.js' +import { createPlansReader } from './plans.js' +import { createBillingStatusReader } from './status.js' +import { + authenticated, + credential, + fakeTransport, + httpOk, + httpStatus +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' + +const SIGNED_OUT: SessionSnapshot = { + phase: 'signed-out', + user: null, + session: undefined +} + +const TEAM = { id: 'ws-2', name: 'Team', type: 'team' } as const + +function fakeSession(initial: SessionSnapshot = authenticated(credential())) { + let snapshot = initial + const listeners = new Set<(next: SessionSnapshot) => void>() + const fake: SessionFake = { + getSnapshot: () => snapshot, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + } + return { + scopeSource: sessionBillingScopeSource(fake), + moveTo(next: SessionSnapshot) { + snapshot = next + for (const listener of [...listeners]) listener(snapshot) + }, + moveToTeam() { + this.moveTo(authenticated(credential({ workspace: TEAM }))) + } + } +} + +/** A transport whose every answer waits on a gate this test opens. */ +function gatedTransport(answer: BillingResult) { + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + const transport: BillingTransport = vi.fn(async () => { + await gate + return answer + }) + return { transport, release: () => release() } +} + +const BALANCE = { + amount_micros: 12_500_000, + currency: 'USD', + prepaid_balance_micros: 10_000_000, + pending_charges_micros: 500_000, + effective_balance_micros: 12_000_000 +} + +const STATUS = { + action_url: 'https://billing.example/continue', + billing_rail: 'stripe', + billing_status: 'pending_payment', + has_funds: true, + is_active: true, + max_seats: 10, + occupied_seats: 4, + pending_billing_op_id: 'op-1', + pending_billing_op_type: 'subscription', + scheduled_change: null, + team_credit_stop: null +} + +const PLAN = { + availability: { available: true }, + credits_cents: 2000, + duration: 'MONTHLY', + max_seats: 1, + price_cents: 2000, + seat_summary: { + seat_count: 1, + total_cost_cents: 2000, + total_credits_cents: 2000 + }, + slug: 'creator_monthly', + tier: 'CREATOR' +} + +const CATALOG = { current_plan_slug: 'free', plans: [PLAN] } + +const CARD = { + brand: 'visa', + id: 'pm_1', + is_default: true, + last4: '4242', + type: 'card' +} + +function capabilitiesBody(overrides: Record = {}) { + return { + capabilities: { + can_cancel: false, + can_change_seats: false, + can_downgrade_to_personal: false, + can_invite_members: false, + can_reactivate: false, + can_subscribe_self_serve: false, + can_top_up: true + }, + expires_at: new Date(Date.now() + 10 * 60 * 1000).toISOString(), + resolved_for: { user_id: 'uid-1', workspace_id: 'ws-1' }, + revision: 42, + rollout_defaults_applied: { + can_downgrade_to_personal: false, + can_subscribe_self_serve: false, + can_top_up: true + }, + ...overrides + } +} + +interface ReaderUnderTest { + readonly read: () => Promise> + /** A read that reaches the transport even for a reader that paces itself. */ + readonly refetch: () => Promise> + readonly getSnapshot: () => unknown + readonly dispose: () => void +} + +interface ScopedReaderOptions { + readonly transport: BillingTransport + readonly scopeSource: BillingScopeSource +} + +interface ReaderCase { + readonly name: string + /** A 2xx body this reader's decoder accepts. */ + readonly body: unknown + /** A 2xx body this reader's decoder must reject. */ + readonly malformedBody: unknown + /** True for a reader that may serve a cached answer instead of asking. */ + readonly paced: boolean + readonly create: (options: ScopedReaderOptions) => ReaderUnderTest +} + +function alwaysRequests(reader: { + read: () => Promise> + getSnapshot: () => unknown + dispose: () => void +}): ReaderUnderTest { + return { + read: reader.read, + refetch: reader.read, + getSnapshot: reader.getSnapshot, + dispose: reader.dispose + } +} + +const CASES: readonly ReaderCase[] = [ + { + name: 'credits', + body: BALANCE, + malformedBody: { amount_micros: 'a lot', currency: 'USD' }, + paced: false, + create: (options) => alwaysRequests(createCreditsReader(options)) + }, + { + name: 'billing status', + body: STATUS, + malformedBody: { ...STATUS, pending_billing_op_type: 'refund' }, + paced: false, + create: (options) => alwaysRequests(createBillingStatusReader(options)) + }, + { + name: 'plans', + body: CATALOG, + malformedBody: { plans: [{ ...PLAN, tier: 'GOLD' }] }, + paced: false, + create: (options) => alwaysRequests(createPlansReader(options)) + }, + { + name: 'payment methods', + body: [CARD], + malformedBody: [{ ...CARD, id: 'card_1' }], + paced: false, + create: (options) => alwaysRequests(createPaymentMethodsReader(options)) + }, + { + name: 'capabilities', + body: capabilitiesBody(), + malformedBody: capabilitiesBody({ revision: 'forty-two' }), + paced: true, + create: (options) => { + const reader = createCapabilitiesReader(options) + return { + read: () => reader.read(), + refetch: () => reader.read({ forceRefresh: true }), + getSnapshot: reader.getSnapshot, + dispose: reader.dispose + } + } + } +] + +/** Readers that publish no cache to serve, so every read reaches the transport. */ +const UNPACED = CASES.filter((readerCase) => !readerCase.paced) + +describe('the scope fence every billing reader inherits', () => { + it.for(CASES)( + 'reports NOT_AUTHENTICATED without asking, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession(SIGNED_OUT) + const { transport } = fakeTransport([httpOk(readerCase.body)]) + + const result = await readerCase.create({ transport, scopeSource }).read() + + expect(result).toEqual({ status: 'error', code: 'NOT_AUTHENTICATED' }) + expect(transport).not.toHaveBeenCalled() + } + ) + + it.for(CASES)( + 'reports SUPERSEDED and publishes nothing when the workspace changes in flight, for $name', + async (readerCase) => { + const host = fakeSession() + const { transport, release } = gatedTransport(httpOk(readerCase.body)) + const reader = readerCase.create({ + transport, + scopeSource: host.scopeSource + }) + + const pending = reader.read() + host.moveToTeam() + release() + + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(reader.getSnapshot()).toBeUndefined() + } + ) + + it.for(CASES)( + 'reports SUPERSEDED and publishes nothing when the host signs out in flight, for $name', + async (readerCase) => { + const host = fakeSession() + const { transport, release } = gatedTransport(httpOk(readerCase.body)) + const reader = readerCase.create({ + transport, + scopeSource: host.scopeSource + }) + + const pending = reader.read() + host.moveTo(SIGNED_OUT) + release() + + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(reader.getSnapshot()).toBeUndefined() + } + ) + + it.for(CASES)( + 'reports SUPERSEDED when a failure lands after the workspace changes, for $name', + async (readerCase) => { + const host = fakeSession() + const { transport, release } = gatedTransport(httpStatus(500)) + const reader = readerCase.create({ + transport, + scopeSource: host.scopeSource + }) + + const pending = reader.read() + host.moveToTeam() + release() + + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + } + ) + + // Disposal short-circuits the same guard for every reader, so one stands in + // for all five rather than crossing the trigger with the reader dimension. + it('reports SUPERSEDED when a failure lands after dispose', async () => { + const { scopeSource } = fakeSession() + const { transport, release } = gatedTransport(httpStatus(500)) + const reader = createCreditsReader({ transport, scopeSource }) + + const pending = reader.read() + reader.dispose() + release() + + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + }) + + it.for(CASES)( + 'drops the published snapshot and refuses the next read when the host signs out, for $name', + async (readerCase) => { + const host = fakeSession() + const { transport } = fakeTransport([httpOk(readerCase.body)]) + const reader = readerCase.create({ + transport, + scopeSource: host.scopeSource + }) + + await reader.read() + host.moveTo(SIGNED_OUT) + + expect(reader.getSnapshot()).toBeUndefined() + expect(await reader.read()).toEqual({ + status: 'error', + code: 'NOT_AUTHENTICATED' + }) + } + ) + + it.for(CASES)( + 'drops the published snapshot when the host changes workspace, for $name', + async (readerCase) => { + const host = fakeSession() + const { transport } = fakeTransport([httpOk(readerCase.body)]) + const reader = readerCase.create({ + transport, + scopeSource: host.scopeSource + }) + + await reader.read() + expect(reader.getSnapshot()).toBeDefined() + + host.moveToTeam() + + // Showing one workspace's billing state under another's name is the + // failure this guards; a stale answer is worse than none. + expect(reader.getSnapshot()).toBeUndefined() + } + ) + + it.for(CASES)( + 'clears the published snapshot and rejects an in-flight result after dispose, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession() + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + let calls = 0 + const transport: BillingTransport = vi.fn(async () => { + calls++ + if (calls === 2) await gate + return httpOk(readerCase.body) + }) + const reader = readerCase.create({ transport, scopeSource }) + + await reader.read() + const pending = reader.refetch() + reader.dispose() + + expect(reader.getSnapshot()).toBeUndefined() + release() + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(reader.getSnapshot()).toBeUndefined() + } + ) +}) + +describe('what a settled read does to the published snapshot', () => { + it.for(CASES)( + 'reports a 2xx body that does not match the contract as malformed, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([httpOk(readerCase.malformedBody)]) + const reader = readerCase.create({ transport, scopeSource }) + + const result = await reader.read() + + expect(result).toEqual({ + status: 'error', + code: 'MALFORMED_RESPONSE', + httpStatus: 200 + }) + expect(reader.getSnapshot()).toBeUndefined() + } + ) + + it.for(CASES)( + 'drops the published snapshot when a later read is denied, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([ + httpOk(readerCase.body), + httpStatus(403) + ]) + const reader = readerCase.create({ transport, scopeSource }) + + await reader.read() + const result = await reader.refetch() + + expect(result).toEqual({ + status: 'error', + code: 'ACCESS_DENIED', + httpStatus: 403 + }) + expect(reader.getSnapshot()).toBeUndefined() + } + ) + + it.for(CASES)( + 'keeps the published snapshot when a later read fails transiently, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([ + httpOk(readerCase.body), + { status: 'error', code: 'REQUEST_FAILED' } + ]) + const reader = readerCase.create({ transport, scopeSource }) + + await reader.read() + const result = await reader.refetch() + + // The cache exists to survive a failure, not to skip a read: a transient + // outage leaves the answer stale rather than blanking it. + expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) + expect(reader.getSnapshot()).toBeDefined() + } + ) + + // Capabilities is excluded because it paces itself: a second read inside the + // server-declared lifetime is served from the cache by design, which its own + // test file covers. + it.for(UNPACED)( + 'requests again on a later read rather than serving the cache, for $name', + async (readerCase) => { + const { scopeSource } = fakeSession() + const { transport, calls } = fakeTransport([httpOk(readerCase.body)]) + const reader = readerCase.create({ transport, scopeSource }) + + await reader.read() + await reader.read() + + expect(calls).toHaveLength(2) + } + ) + + it.for([ + [401, 'ACCESS_DENIED'], + [403, 'ACCESS_DENIED'], + [404, 'NOT_FOUND'], + [409, 'CONFLICT'], + [500, 'REQUEST_FAILED'], + [503, 'REQUEST_FAILED'] + ] as const)('maps %i to %s', async ([status, code]) => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([httpStatus(status)]) + + const result = await createCreditsReader({ transport, scopeSource }).read() + + expect(result).toEqual({ status: 'error', code, httpStatus: status }) + }) +}) + +/** + * One reader stands in for all five here: the sharing and release path is the + * skeleton's alone, and these assertions need a concrete snapshot to read. + */ +describe('sharing one request per scope', () => { + it('serves concurrent readers of one scope from a single request', async () => { + const { scopeSource } = fakeSession() + const { transport, calls } = fakeTransport([httpOk(BALANCE)]) + const reader = createCreditsReader({ transport, scopeSource }) + + const [first, second] = await Promise.all([reader.read(), reader.read()]) + + expect(calls).toHaveLength(1) + expect(first).toEqual(second) + }) + + it('does not join a read belonging to another scope', async () => { + const host = fakeSession() + const { transport, calls } = fakeTransport([httpOk(BALANCE)]) + const reader = createCreditsReader({ + transport, + scopeSource: host.scopeSource + }) + + const personal = reader.read() + host.moveToTeam() + const team = reader.read() + await Promise.all([personal, team]) + + expect(calls).toHaveLength(2) + expect(await personal).toEqual({ status: 'error', code: 'SUPERSEDED' }) + }) + + it('releases a joining caller that aborts, without disturbing the shared read', async () => { + const { scopeSource } = fakeSession() + const { transport, release } = gatedTransport(httpOk(BALANCE)) + const reader = createCreditsReader({ transport, scopeSource }) + const joiner = new AbortController() + + const shared = reader.read() + const joined = reader.read({ signal: joiner.signal }) + joiner.abort() + + expect(await joined).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) + release() + expect((await shared).status).toBe('ok') + expect(reader.getSnapshot()?.balance.amount_micros).toBe(12_500_000) + }) + + it('keeps joined callers alive when the initiating caller aborts', async () => { + const { scopeSource } = fakeSession() + const { transport, release } = gatedTransport(httpOk(BALANCE)) + const reader = createCreditsReader({ transport, scopeSource }) + const initiator = new AbortController() + + const first = reader.read({ signal: initiator.signal }) + const joined = reader.read() + initiator.abort() + + expect(await first).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) + release() + expect((await joined).status).toBe('ok') + }) + + it('releases a caller whose signal was already aborted', async () => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([httpOk(BALANCE)]) + const reader = createCreditsReader({ transport, scopeSource }) + + const result = await reader.read({ signal: AbortSignal.abort() }) + + expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) + }) + + it('prevents an older read from publishing after a scope round trip', async () => { + const host = fakeSession() + const releases: Array<(balance: typeof BALANCE) => void> = [] + const transport: BillingTransport = vi.fn( + () => + new Promise>((resolve) => { + releases.push((balance) => resolve(httpOk(balance))) + }) + ) + const reader = createCreditsReader({ + transport, + scopeSource: host.scopeSource + }) + + const firstA = reader.read() + host.moveToTeam() + const readB = reader.read() + host.moveTo(authenticated(credential())) + const latestA = reader.read() + + releases[2]({ ...BALANCE, amount_micros: 99 }) + await latestA + releases[0]({ ...BALANCE, amount_micros: 10 }) + releases[1]({ ...BALANCE, amount_micros: 20 }) + + expect(await firstA).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(await readB).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(reader.getSnapshot()?.balance.amount_micros).toBe(99) + }) +}) diff --git a/packages/account/src/core/billing/scopedReader.ts b/packages/account/src/core/billing/scopedReader.ts new file mode 100644 index 00000000000..e719dfca93d --- /dev/null +++ b/packages/account/src/core/billing/scopedReader.ts @@ -0,0 +1,247 @@ +/** + * The one shape every billing read has: capture the scope, issue a validated + * request, and refuse to attribute the answer to a scope that has since taken + * over. Only the route, the decoder, and the projection into a snapshot differ + * between reads, so only those live in the readers. + * + * What the skeleton owns is what a reader therefore cannot get wrong on its + * own: one shared request per scope, a caller's signal releasing only that + * caller, the publish fence that reports a late answer as `SUPERSEDED`, and + * the denial that drops a published snapshot unless it predates a change the + * host reported. + */ +import type { + BillingRequest, + BillingResult, + BillingTransport +} from './billingContracts.js' +import type { + BillingScope, + BillingScopeContext, + BillingScopeSource +} from './billingScope.js' +import { createBillingScopeTracker } from './billingScope.js' +import type { + ParsedBillingBody, + ValidatedBillingResponse +} from './sharedRead.js' +import { + matchesScopedRead, + readValidatedBillingResponse, + releaseOnAbort +} from './sharedRead.js' + +/** Every reader's read options carry at least the caller's release signal. */ +export interface ScopedReadOptions { + readonly signal?: AbortSignal +} + +export interface ScopedReaderDefinition< + TData, + TSnapshot, + TOptions extends ScopedReadOptions +> { + readonly transport: BillingTransport + /** Where the core learns which user, workspace, and role it runs as. */ + readonly scopeSource: BillingScopeSource + readonly route: string + readonly parse: (body: unknown) => ParsedBillingBody + /** + * The reader's own reading of a validated response. Returning a failure is + * how a reader refuses an answer its decoder alone cannot reject. + */ + readonly project: ( + response: ValidatedBillingResponse, + scope: BillingScope + ) => BillingResult + /** The request budget, for a read that bounds itself or lets its caller. */ + readonly timeoutMs?: (options: TOptions | undefined) => number | undefined + /** + * The published snapshot this call may be served from instead of asking. + * Absent for a reader that always requests. + */ + readonly cached?: ( + snapshot: TSnapshot | undefined, + scope: BillingScope, + options: TOptions | undefined + ) => TSnapshot | undefined + /** + * What to publish once the read settles in scope, given whether the host + * fenced the request while it was in flight. `undefined` publishes nothing, + * and the callers waiting on the request are still served what it read. + */ + readonly publish?: ( + value: TSnapshot, + fenced: boolean + ) => TSnapshot | undefined +} + +export interface ScopedReader { + readonly read: (options?: TOptions) => Promise> + readonly getSnapshot: () => TSnapshot | undefined + /** Replaces what `getSnapshot` publishes; `undefined` drops it. */ + readonly setSnapshot: (snapshot: TSnapshot | undefined) => void + /** + * Marks a request already in flight as predating a change the host is + * reporting, leaving `publish` to decide what its answer is still worth. + * `detach` also frees the shared slot, so the read that follows issues its + * own request rather than joining the one that predates the change. + */ + readonly fenceInFlight: (options?: { readonly detach?: boolean }) => void + readonly dispose: () => void +} + +interface InFlightRead { + readonly context: BillingScopeContext + readonly promise: Promise> + /** + * Lives outside the attempt so the read body can consult it without + * referencing the object that holds its own promise. + */ + readonly pending: { fenced: boolean } +} + +function publishAsRead(value: TSnapshot): TSnapshot { + return value +} + +export function createScopedReader< + TData, + TSnapshot, + TOptions extends ScopedReadOptions +>( + definition: ScopedReaderDefinition +): ScopedReader { + const { + transport, + scopeSource, + route, + parse, + project, + timeoutMs, + cached, + publish = publishAsRead + } = definition + + let snapshot: TSnapshot | undefined + let inFlight: InFlightRead | undefined + const lifetime = { disposed: false } + const scopeTracker = createBillingScopeTracker(scopeSource, () => { + snapshot = undefined + inFlight = undefined + }) + + async function request( + scope: BillingScope, + options: TOptions | undefined + ): Promise> { + const budget = timeoutMs?.(options) + const billingRequest: BillingRequest = { + method: 'GET', + route, + ...(budget === undefined ? {} : { timeoutMs: budget }) + } + const response = await readValidatedBillingResponse( + transport, + billingRequest, + parse + ) + if (response.status === 'error') return response + + return project(response.value, scope) + } + + function publishSettled( + value: TSnapshot, + fenced: boolean + ): BillingResult { + const published = publish(value, fenced) + if (published !== undefined) snapshot = published + return { status: 'ok', value: published ?? value } + } + + async function settle( + context: BillingScopeContext, + pending: { fenced: boolean }, + options: TOptions | undefined + ): Promise> { + const result = await request(context.scope, options) + // The publish guard. Between issuing the request and settling it the host + // may have changed workspace or signed out, so an answer cached now would + // be attributed to whoever is signed in next, and a failure says nothing + // about the scope that has since taken over. + if (lifetime.disposed || !scopeTracker.isCurrent(context)) { + return { status: 'error', code: 'SUPERSEDED' } + } + + if (result.status !== 'ok') { + // A denial that predates a fence is no evidence about what a later read + // published, and clearing on it would drop a fresh answer for a stale + // refusal. + if (result.code === 'ACCESS_DENIED' && !pending.fenced) { + snapshot = undefined + } + return result + } + + return publishSettled(result.value, pending.fenced) + } + + async function read(options?: TOptions): Promise> { + if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } + + const context = scopeTracker.capture() + if (context === undefined) { + return { status: 'error', code: 'NOT_AUTHENTICATED' } + } + + const served = cached?.(snapshot, context.scope, options) + if (served !== undefined) return { status: 'ok', value: served } + + // One read per scope. A caller arriving mid-flight for the same scope + // joins rather than issuing a second identical request; a caller for a + // different scope starts its own, and the older one can no longer publish. + if (matchesScopedRead(inFlight, context)) { + return releaseOnAbort(inFlight.promise, options?.signal) + } + + // No caller signal reaches the shared request: it is bounded by its own + // timeout, and one caller walking away must not fail the readers still + // waiting on it. Each caller's signal releases only that caller, below. + const pending = { fenced: false } + const attempt: InFlightRead = { + context, + promise: settle(context, pending, options), + pending + } + + inFlight = attempt + // The slot is released when the request settles, not when this caller + // stops waiting, so an abandoned read still serves whoever joined it. + const release = () => { + if (inFlight === attempt) inFlight = undefined + } + attempt.promise.then(release, release) + + return releaseOnAbort(attempt.promise, options?.signal) + } + + return { + read, + getSnapshot: () => snapshot, + setSnapshot: (next) => { + snapshot = next + }, + fenceInFlight: (fenceOptions) => { + if (inFlight === undefined) return + inFlight.pending.fenced = true + if (fenceOptions?.detach === true) inFlight = undefined + }, + dispose: () => { + lifetime.disposed = true + snapshot = undefined + inFlight = undefined + scopeTracker.dispose() + } + } +} diff --git a/packages/account/src/core/billing/sharedRead.ts b/packages/account/src/core/billing/sharedRead.ts index 6e3e0259dd0..bd77b146278 100644 --- a/packages/account/src/core/billing/sharedRead.ts +++ b/packages/account/src/core/billing/sharedRead.ts @@ -33,11 +33,11 @@ const ABANDONED = { code: 'REQUEST_FAILED' } as const satisfies BillingResult -type ParsedBody = +export type ParsedBillingBody = | { readonly success: true; readonly data: T } | { readonly success: false } -interface ValidatedBillingResponse { +export interface ValidatedBillingResponse { readonly data: T readonly body: unknown readonly httpStatus: number @@ -56,7 +56,7 @@ export function matchesScopedRead< export async function readValidatedBillingResponse( transport: BillingTransport, request: BillingRequest, - parse: (body: unknown) => ParsedBody + parse: (body: unknown) => ParsedBillingBody ): Promise>> { const response = await transport(request) if (response.status === 'error') return response diff --git a/packages/account/src/core/billing/status.test.ts b/packages/account/src/core/billing/status.test.ts index f86b40b4f56..aee054312f2 100644 --- a/packages/account/src/core/billing/status.test.ts +++ b/packages/account/src/core/billing/status.test.ts @@ -1,63 +1,27 @@ +/** + * What only the billing status read does. The scope fence, the shared request, + * and the publish rules it inherits are proved once in `scopedReader.test.ts`. + */ import { describe, expect, it, vi } from 'vitest' -import type { SessionClient, SessionSnapshot } from '../session.js' -import type { AccountCredential } from '../sessionContracts.js' +import type { SessionSnapshot } from '../session.js' import { sessionBillingScopeSource } from './billingScope.js' -import type { - BillingHttpResponse, - BillingRequest, - BillingResult, - BillingTransport -} from './billingContracts.js' +import type { BillingTransport } from './billingContracts.js' import { createBillingStatusReader } from './status.js' - -function credential( - overrides: Partial = {} -): AccountCredential { - return { - token: 'workspace-jwt', - expiresAt: Date.now() + 60 * 60 * 1000, - uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, - role: 'owner', - permissions: ['workspace:read'], - ...overrides - } -} - -function authenticated(session: AccountCredential): SessionSnapshot { - return { - phase: 'authenticated', - user: { uid: session.uid, getIdToken: async () => 'id-token' }, - session - } -} - -const SIGNED_OUT: SessionSnapshot = { - phase: 'signed-out', - user: null, - session: undefined -} - -type SessionFake = Pick - -function fakeSession(initial: SessionSnapshot = authenticated(credential())) { - let snapshot = initial - const listeners = new Set<(next: SessionSnapshot) => void>() +import { + authenticated, + credential, + fakeTransport, + httpOk +} from './__fixtures__/billingTestFixtures.js' +import type { SessionFake } from './__fixtures__/billingTestFixtures.js' + +function fakeSession(snapshot: SessionSnapshot = authenticated(credential())) { const fake: SessionFake = { getSnapshot: () => snapshot, - subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - } - } - return { - scopeSource: sessionBillingScopeSource(fake), - moveTo(next: SessionSnapshot) { - snapshot = next - for (const listener of [...listeners]) listener(snapshot) - } + subscribe: () => () => {} } + return { scopeSource: sessionBillingScopeSource(fake) } } const STATUS = { @@ -74,37 +38,6 @@ const STATUS = { team_credit_stop: null } -function httpOk(body: unknown): BillingResult { - return { - status: 'ok', - value: { httpStatus: 200, body, header: () => null } - } -} - -function httpStatus(status: number): BillingResult { - return { - status: 'ok', - value: { httpStatus: status, body: {}, header: () => null } - } -} - -function fakeTransport(answers: BillingResult[]) { - const calls: BillingRequest[] = [] - let index = 0 - const transport: BillingTransport = vi.fn(async (request) => { - calls.push(request) - const answer = answers[Math.min(index, answers.length - 1)] - index++ - return answer - }) - return { transport, calls } -} - -interface SupersedeContext { - readonly host: ReturnType - readonly reader: ReturnType -} - describe('createBillingStatusReader', () => { it('reads and validates the authoritative billing status', async () => { const { scopeSource } = fakeSession() @@ -127,103 +60,6 @@ describe('createBillingStatusReader', () => { }) }) - it('deduplicates concurrent reads but refetches on a later read', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(STATUS)]) - const reader = createBillingStatusReader({ transport, scopeSource }) - - const [first, second] = await Promise.all([reader.read(), reader.read()]) - await reader.read() - - expect(first).toEqual(second) - expect(transport).toHaveBeenCalledTimes(2) - }) - - it('releases an aborted caller without cancelling the shared read', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(STATUS) - }) - const reader = createBillingStatusReader({ transport, scopeSource }) - - const controller = new AbortController() - const abandoned = reader.read({ signal: controller.signal }) - const remaining = reader.read() - controller.abort() - - expect(await abandoned).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - release() - expect((await remaining).status).toBe('ok') - expect(reader.getSnapshot()?.status.pending_billing_op_id).toBe('op-1') - }) - - it('rejects a response that settles after a workspace change', async () => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpOk(STATUS) - }) - const reader = createBillingStatusReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - host.moveTo( - authenticated( - credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) - ) - ) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it('clears a published status when the session scope changes', async () => { - const host = fakeSession() - const { transport } = fakeTransport([httpOk(STATUS)]) - const reader = createBillingStatusReader({ - transport, - scopeSource: host.scopeSource - }) - - await reader.read() - host.moveTo(SIGNED_OUT) - - expect(reader.getSnapshot()).toBeUndefined() - expect(await reader.read()).toEqual({ - status: 'error', - code: 'NOT_AUTHENTICATED' - }) - }) - - it.for([ - [401, 'ACCESS_DENIED'], - [404, 'NOT_FOUND'], - [409, 'CONFLICT'], - [503, 'REQUEST_FAILED'] - ] as const)('maps %i to %s', async ([status, code]) => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpStatus(status)]) - - const result = await createBillingStatusReader({ - transport, - scopeSource - }).read() - - expect(result).toEqual({ status: 'error', code, httpStatus: status }) - }) - it('reports a malformed successful response without replacing the last snapshot', async () => { const { scopeSource } = fakeSession() const { transport } = fakeTransport([ @@ -245,78 +81,6 @@ describe('createBillingStatusReader', () => { ) }) - it('passes transport failures through without replacing the last snapshot', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([ - httpOk(STATUS), - { status: 'error', code: 'REQUEST_FAILED' } - ]) - const reader = createBillingStatusReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read() - - expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) - expect(reader.getSnapshot()?.status.pending_billing_op_id).toBe('op-1') - }) - - it('drops the last status snapshot when a later read is denied', async () => { - const { scopeSource } = fakeSession() - const { transport } = fakeTransport([httpOk(STATUS), httpStatus(403)]) - const reader = createBillingStatusReader({ transport, scopeSource }) - - await reader.read() - const result = await reader.read() - - expect(result).toEqual({ - status: 'error', - code: 'ACCESS_DENIED', - httpStatus: 403 - }) - expect(reader.getSnapshot()).toBeUndefined() - }) - - it.for([ - [ - 'the workspace changes', - ({ host }: SupersedeContext) => - host.moveTo( - authenticated( - credential({ - workspace: { id: 'ws-2', name: 'Team', type: 'team' } - }) - ) - ) - ], - [ - 'the reader is disposed', - ({ reader }: SupersedeContext) => reader.dispose() - ] - ] as const)( - 'reports SUPERSEDED when a failure lands after %s', - async ([, supersede]) => { - const host = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - const transport: BillingTransport = vi.fn(async () => { - await gate - return httpStatus(500) - }) - const reader = createBillingStatusReader({ - transport, - scopeSource: host.scopeSource - }) - - const pending = reader.read() - supersede({ host, reader }) - release() - - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - } - ) - it('normalizes a throwing host transport to a coded failure', async () => { const { scopeSource } = fakeSession() const transport: BillingTransport = vi.fn(() => { @@ -330,28 +94,4 @@ describe('createBillingStatusReader', () => { expect(result).toEqual({ status: 'error', code: 'REQUEST_FAILED' }) }) - - it('clears account data and rejects an in-flight result after dispose', async () => { - const { scopeSource } = fakeSession() - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) - let calls = 0 - const transport: BillingTransport = vi.fn(async () => { - calls++ - if (calls === 2) await gate - return httpOk(STATUS) - }) - const reader = createBillingStatusReader({ transport, scopeSource }) - - await reader.read() - const pending = reader.read() - reader.dispose() - - expect(reader.getSnapshot()).toBeUndefined() - release() - expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) - expect(reader.getSnapshot()).toBeUndefined() - }) }) diff --git a/packages/account/src/core/billing/status.ts b/packages/account/src/core/billing/status.ts index ba11910aa51..48c0ece9d8a 100644 --- a/packages/account/src/core/billing/status.ts +++ b/packages/account/src/core/billing/status.ts @@ -2,17 +2,8 @@ import { zBillingStatusResponse } from '@comfyorg/ingest-types/zod' import type { z } from 'zod' import type { BillingResult, BillingTransport } from './billingContracts.js' -import type { - BillingScope, - BillingScopeContext, - BillingScopeSource -} from './billingScope.js' -import { createBillingScopeTracker } from './billingScope.js' -import { - matchesScopedRead, - readValidatedBillingResponse, - releaseOnAbort -} from './sharedRead.js' +import type { BillingScope, BillingScopeSource } from './billingScope.js' +import { createScopedReader } from './scopedReader.js' export const BILLING_STATUS_ROUTE = '/billing/status' @@ -45,93 +36,29 @@ export interface BillingStatusReaderOptions { readonly now?: () => number } -interface InFlightRead { - readonly context: BillingScopeContext - readonly promise: Promise> -} - export function createBillingStatusReader( options: BillingStatusReaderOptions ): BillingStatusReader { const { transport, scopeSource, now = Date.now } = options - let snapshot: BillingStatusSnapshot | undefined - let inFlight: InFlightRead | undefined - const lifetime = { disposed: false } - const scopeTracker = createBillingScopeTracker(scopeSource, () => { - snapshot = undefined - inFlight = undefined - }) - - async function requestStatus( - scope: BillingStatusScope - ): Promise> { - const response = await readValidatedBillingResponse( - transport, - { method: 'GET', route: BILLING_STATUS_ROUTE }, - (body) => zBillingStatusResponse.safeParse(body) - ) - if (response.status === 'error') return response - - return { + const reader = createScopedReader< + BillingStatusData, + BillingStatusSnapshot, + BillingStatusReadOptions + >({ + transport, + scopeSource, + route: BILLING_STATUS_ROUTE, + parse: (body) => zBillingStatusResponse.safeParse(body), + project: ({ data }, scope) => ({ status: 'ok', - value: { status: response.value.data, scope, readAt: now() } - } - } - - async function read( - readOptions?: BillingStatusReadOptions - ): Promise> { - if (lifetime.disposed) return { status: 'error', code: 'SUPERSEDED' } - - const context = scopeTracker.capture() - if (context === undefined) { - return { status: 'error', code: 'NOT_AUTHENTICATED' } - } - const { scope } = context - - if (matchesScopedRead(inFlight, context)) { - return releaseOnAbort(inFlight.promise, readOptions?.signal) - } - - const attempt: InFlightRead = { - context, - promise: (async () => { - const result = await requestStatus(scope) - // A status that arrives after the host moved to another workspace - // describes neither, and a failure says nothing about the scope that - // has since taken over. - if (lifetime.disposed || !scopeTracker.isCurrent(context)) { - return { status: 'error', code: 'SUPERSEDED' } - } - - if (result.status !== 'ok') { - if (result.code === 'ACCESS_DENIED') snapshot = undefined - return result - } - - snapshot = result.value - return result - })() - } - - inFlight = attempt - const release = () => { - if (inFlight === attempt) inFlight = undefined - } - attempt.promise.then(release, release) - - return releaseOnAbort(attempt.promise, readOptions?.signal) - } + value: { status: data, scope, readAt: now() } + }) + }) return { - read, - getSnapshot: () => snapshot, - dispose: () => { - lifetime.disposed = true - snapshot = undefined - inFlight = undefined - scopeTracker.dispose() - } + read: reader.read, + getSnapshot: reader.getSnapshot, + dispose: reader.dispose } }