Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 46 additions & 11 deletions packages/account-ui/src/billing/__fixtures__/billingHarness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']
}
Expand All @@ -53,23 +59,38 @@ 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'),
remint: outsideBillingContract('remint'),
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 = {
Expand Down Expand Up @@ -137,9 +158,14 @@ export const NO_RESPONSE: BillingResult<BillingHttpResponse> = {
code: 'REQUEST_FAILED'
}

type Answer = BillingResult<BillingHttpResponse>
type Answer =
| BillingResult<BillingHttpResponse>
| Promise<BillingResult<BillingHttpResponse>>

/** 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<string, Answer[]>()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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. */
Expand Down
74 changes: 73 additions & 1 deletion packages/account-ui/src/billing/useCredits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -17,6 +23,16 @@ beforeEach(() => {
vi.setSystemTime(NOW)
})

const SWITCHED_MICROS = 7_500_000

function deferred<T>() {
let resolve: (value: T) => void = () => {}
const promise = new Promise<T>((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({
Expand All @@ -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<BillingResult<BillingHttpResponse>>()
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({
Expand Down
20 changes: 19 additions & 1 deletion packages/account-ui/src/billing/useCredits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,18 @@ export interface Credits {
/** Micros, as the core reports them; formatting is the host's, with its locale. */
readonly balance: Readonly<Ref<BillingBalance | undefined>>
readonly loading: Readonly<Ref<boolean>>
/** 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<Ref<BillingFailure | undefined>>
/**
* 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<BillingResult<CreditsSnapshot>>
}

Expand All @@ -35,13 +45,21 @@ export function useCredits(options: CreditsOptions = {}): Credits {
const loading = ref(false)
const failure = ref<BillingFailure | undefined>()

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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
failure.value = result
}
Expand Down
Loading