diff --git a/docs/adr/AUTH-BILLING-0032-billing-stays-outside-the-account-package-in-v1.md b/docs/adr/AUTH-BILLING-0032-billing-stays-outside-the-account-package-in-v1.md index 54251766436..c132497ab5a 100644 --- a/docs/adr/AUTH-BILLING-0032-billing-stays-outside-the-account-package-in-v1.md +++ b/docs/adr/AUTH-BILLING-0032-billing-stays-outside-the-account-package-in-v1.md @@ -108,6 +108,20 @@ top-up endpoint called directly from the site. explicit comparison; aligning the balance reader is a separate change against a hardened path, not a docs edit. + A scope guard keeps a stale response from being published. It does + not, on its own, keep that response from clearing state a newer read + has already published: "do not publish stale data" and "do not let + stale data destroy fresh data" are separate rules and each needs its + own guard. A reader that answers `SUPERSEDED` by clearing its own + state therefore needs a generation check too, or a read condemned by + a scope change wipes the balance produced for the scope the host + moved to. `useCredits` stamps each refresh and publishes only the + newest one (#17824). The publish half of the same rule has been + closed independently in the core reader, at the host ownership + boundary (#17662), and in the composables that read through it + (#17799), so a composable added later takes both halves deliberately + rather than inheriting either. + 4. **No new local copies.** This ADR authorizes exactly the two existing modules. Further billing surfaces — subscriptions, embedded checkout, retention — do not get a site-local diff --git a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts index ba71346a78b..19fc86a32b9 100644 --- a/packages/account-ui/src/billing/__fixtures__/billingHarness.ts +++ b/packages/account-ui/src/billing/__fixtures__/billingHarness.ts @@ -35,12 +35,18 @@ import type { BillingClient } from '../billingClient' export const NOW = 1_000_000 -function credential(): AccountCredential { +function credential( + workspace: AccountCredential['workspace'] = { + id: 'ws-1', + name: 'Personal', + type: 'personal' + } +): AccountCredential { return { token: 'workspace-jwt', expiresAt: NOW + 60 * 60 * 1000, uid: 'uid-1', - workspace: { id: 'ws-1', name: 'Personal', type: 'personal' }, + workspace, role: 'owner', permissions: ['workspace:read'] } @@ -53,16 +59,24 @@ function outsideBillingContract(member: string) { } } -function fakeSession(): SessionClient { - const session = credential() - const snapshot: SessionSnapshot = { +function authenticated(session: AccountCredential): SessionSnapshot { + return { phase: 'authenticated', user: { uid: session.uid, getIdToken: async () => 'id-token' }, session } - return { +} + +/** A host whose scope can move, so the readers report a real scope change. */ +function fakeSession() { + let snapshot = authenticated(credential()) + const listeners = new Set<(next: SessionSnapshot) => void>() + const session: SessionClient = { getSnapshot: () => snapshot, - subscribe: () => () => {}, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, attachIdentity: outsideBillingContract('attachIdentity'), getToken: outsideBillingContract('getToken'), ensureFresh: outsideBillingContract('ensureFresh'), @@ -70,6 +84,13 @@ function fakeSession(): SessionClient { invalidate: outsideBillingContract('invalidate'), clearStoredCredential: outsideBillingContract('clearStoredCredential') } + return { + session, + moveTo(workspace: AccountCredential['workspace']) { + snapshot = authenticated(credential(workspace)) + for (const listener of [...listeners]) listener(snapshot) + } + } } const STATUS_DATA: BillingStatusData = { @@ -137,9 +158,14 @@ export const NO_RESPONSE: BillingResult = { code: 'REQUEST_FAILED' } -type Answer = BillingResult +type Answer = + | BillingResult + | Promise> -/** Answers per route are consumed in order; the last one repeats. */ +/** + * Answers per route are consumed in order; the last one repeats. A promise + * answer holds its request open until the test resolves it. + */ function fakeTransport() { const calls: BillingRequest[] = [] const queues = new Map() @@ -170,7 +196,8 @@ export interface HarnessOptions { } export function createBillingHarness(options: HarnessOptions = {}) { - const scopeSource = sessionBillingScopeSource(fakeSession()) + const host = fakeSession() + const scopeSource = sessionBillingScopeSource(host.session) const { transport, calls, answer, routes } = fakeTransport() const readerOptions = { transport, scopeSource } const capabilities = createCapabilitiesReader(readerOptions) @@ -235,7 +262,15 @@ export function createBillingHarness(options: HarnessOptions = {}) { httpOk(opStatus({ status: 'succeeded' })) ) - return { client, calls, answer, routes } + return { + client, + calls, + answer, + routes, + /** Moves the host to another workspace, as the switcher does. */ + moveToWorkspace: (id: string) => + host.moveTo({ id, name: 'Team', type: 'team' }) + } } /** Lets every read, the POST, and the first poll cadence settle. */ diff --git a/packages/account-ui/src/billing/useCredits.test.ts b/packages/account-ui/src/billing/useCredits.test.ts index e9a00f4689d..d33ba066b9c 100644 --- a/packages/account-ui/src/billing/useCredits.test.ts +++ b/packages/account-ui/src/billing/useCredits.test.ts @@ -2,12 +2,18 @@ import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, h, nextTick } from 'vue' +import type { + BillingHttpResponse, + BillingResult +} from '@comfyorg/account/billing' + import { BASELINE_MICROS, NO_RESPONSE, NOW, balance, - createBillingHarness + createBillingHarness, + httpOk } from './__fixtures__/billingHarness' import { provideBillingClient } from './billingClient' import { useCredits } from './useCredits' @@ -17,6 +23,16 @@ beforeEach(() => { vi.setSystemTime(NOW) }) +const SWITCHED_MICROS = 7_500_000 + +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} + describe('useCredits', () => { it('reads the balance on setup and keeps the last one through a failed refresh', async () => { const { client, answer } = createBillingHarness({ @@ -38,6 +54,62 @@ describe('useCredits', () => { expect(credits.failure.value).toEqual(NO_RESPONSE) }) + it('drops the balance without reporting a failure when the host changes workspace', async () => { + const { client, moveToWorkspace } = createBillingHarness({ + balances: [BASELINE_MICROS] + }) + + const credits = useCredits({ client }) + await vi.advanceTimersByTimeAsync(0) + expect(credits.balance.value).toEqual(balance(BASELINE_MICROS)) + + const superseded = credits.refresh() + moveToWorkspace('ws-2') + await expect(superseded).resolves.toEqual({ + status: 'error', + code: 'SUPERSEDED' + }) + + expect( + credits.balance.value, + 'these credits belong to the workspace the host left' + ).toBeUndefined() + expect( + credits.failure.value, + 'the user did not cause the switch and has nothing to retry' + ).toBeUndefined() + }) + + it('keeps the balance of the workspace moved to when the read it replaced settles last', async () => { + const { client, answer, moveToWorkspace } = createBillingHarness() + const held = deferred>() + answer( + 'GET', + '/billing/balance', + held.promise, + httpOk(balance(SWITCHED_MICROS)) + ) + + const credits = useCredits({ client, immediate: false }) + const superseded = credits.refresh() + await vi.advanceTimersByTimeAsync(0) + moveToWorkspace('ws-2') + await expect(credits.refresh()).resolves.toMatchObject({ status: 'ok' }) + expect(credits.balance.value).toEqual(balance(SWITCHED_MICROS)) + + held.resolve(httpOk(balance(BASELINE_MICROS))) + await expect(superseded).resolves.toEqual({ + status: 'error', + code: 'SUPERSEDED' + }) + + expect( + credits.balance.value, + 'the switch that superseded the slower read is the one already on screen' + ).toEqual(balance(SWITCHED_MICROS)) + expect(credits.failure.value).toBeUndefined() + }) + it('resolves the client from the nearest provider when none is passed', async () => { const { client } = createBillingHarness({ balances: [BASELINE_MICROS] }) const Child = defineComponent({ diff --git a/packages/account-ui/src/billing/useCredits.ts b/packages/account-ui/src/billing/useCredits.ts index 24dea212e92..873331738ea 100644 --- a/packages/account-ui/src/billing/useCredits.ts +++ b/packages/account-ui/src/billing/useCredits.ts @@ -21,8 +21,18 @@ export interface Credits { /** Micros, as the core reports them; formatting is the host's, with its locale. */ readonly balance: Readonly> readonly loading: Readonly> - /** The last read's failure; a failed refresh keeps the previous balance on screen. */ + /** + * The last read's failure; a failed refresh keeps the previous balance on + * screen. A scope change is not surfaced as one: it drops the balance, + * which states the credits of the workspace the host left, and leaves + * nothing for the user to retry. + */ readonly failure: Readonly> + /** + * Reads the balance again. Only the newest read publishes: an earlier one + * that settles after it still answers its own caller, so the scope change + * that condemned it cannot clear the balance that replaced it. + */ readonly refresh: () => Promise> } @@ -35,13 +45,21 @@ export function useCredits(options: CreditsOptions = {}): Credits { const loading = ref(false) const failure = ref() + let latest = 0 + async function refresh() { + const attempt = ++latest loading.value = true const result = await credits.read() + if (attempt !== latest) return result + loading.value = false if (result.status === 'ok') { balance.value = result.value.balance failure.value = undefined + } else if (result.code === 'SUPERSEDED') { + balance.value = undefined + failure.value = undefined } else { failure.value = result }