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
14 changes: 4 additions & 10 deletions src/platform/workspace/api/workspaceApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import { useAuthStore } from '@/stores/authStore'
import type { UserId } from '@/types/authTypes'

import { createWebSessionAdapter } from './webSessionAdapter'
import { WorkspaceApiError } from './workspaceApiError'
import { workspaceApiUrl } from './workspaceApiUrl'

export type WorkspaceType = 'personal' | 'team'
Expand Down Expand Up @@ -105,6 +106,8 @@ export interface SubscribeOptions {
billingCycle?: SubscribeBillingCycle
confirmReactivation?: boolean
prorationAt?: string
/** Set when the caller reported this attempt's `billing.operation.started`; never sent to the server. */
attemptStartedAt?: number
}

export interface PreviewSubscribeOptions {
Expand Down Expand Up @@ -149,16 +152,7 @@ interface GetBillingEventsParams {
limit?: number
}

export class WorkspaceApiError extends Error {
constructor(
message: string,
public readonly status?: number,
public readonly code?: string
) {
super(message)
this.name = 'WorkspaceApiError'
}
}
export { WorkspaceApiError }

const workspaceApiClient = axios.create({
headers: {
Expand Down
14 changes: 14 additions & 0 deletions src/platform/workspace/api/workspaceApiError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* A leaf module, so a subclass can be declared wherever the class is needed
* without pulling the workspace client and its stores into the import graph.
*/
export class WorkspaceApiError extends Error {
constructor(
message: string,
public readonly status?: number,
public readonly code?: string
) {
super(message)
this.name = 'WorkspaceApiError'
}
}
168 changes: 164 additions & 4 deletions src/platform/workspace/billing/sdk/billingSdkStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ import {
settledOperation,
settledTopup
} from './billingSdkTestUtils'
import type { HostedBillingDestination } from '@comfyorg/account-core/billing'
import type {
BillingOperationKind,
BillingOperationTelemetryEvent,
HostedBillingDestination
} from '@comfyorg/account-core/billing'
import { BILLING_OPERATION_TELEMETRY_EVENT } from '@comfyorg/account-core/billing'
import type { BillingSdk, BillingSdkOptions } from './createBillingSdk'

const mockCreateBillingSdk = vi.hoisted(() =>
Expand Down Expand Up @@ -508,7 +513,7 @@ describe('useBillingSdkStore subscription commands', () => {

await expect(useBillingSdkStore().cancelSubscription()).resolves.toEqual({
status: 'ok',
value: undefined
value: { operationObserved: true }
})
expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce()
expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce()
Expand All @@ -520,7 +525,7 @@ describe('useBillingSdkStore subscription commands', () => {

await expect(useBillingSdkStore().resubscribe()).resolves.toEqual({
status: 'ok',
value: undefined
value: { operationObserved: true }
})
expect(
useBillingContext().reconcileSubscriptionSuccess
Expand Down Expand Up @@ -569,7 +574,8 @@ describe('useBillingSdkStore subscription commands', () => {
value: {
billing_op_id: 'op-1',
status: 'subscribed',
requiredPayment: false
requiredPayment: false,
operationObserved: true
}
})
expect(harness.sdk.commands.subscribe).toHaveBeenCalledWith({
Expand Down Expand Up @@ -888,6 +894,160 @@ describe('useBillingSdkStore subscription commands', () => {
})
})

describe('useBillingSdkStore telemetry ownership', () => {
type Store = ReturnType<typeof useBillingSdkStore>

const SETTLED = {
status: 'ok',
value: {
phase: 'succeeded',
operation: settledOperation('succeeded', 'subscription')
}
} as const

const EVENTS = {
started: { name: 'started', resumed: false },
'resumed started': { name: 'started', resumed: true },
terminal: { name: 'succeeded', resumed: false },
'resumed terminal': { name: 'succeeded', resumed: true }
} as const

function lifecycleEvent(
kind: BillingOperationKind,
{ name, resumed }: (typeof EVENTS)[keyof typeof EVENTS]
): BillingOperationTelemetryEvent {
return {
name: BILLING_OPERATION_TELEMETRY_EVENT[name],
billing_op_id: 'op-1',
operation_type: kind,
presentation: 'hosted',
resumed
}
}

const COMMANDS = {
'a cancel': {
kind: 'cancel',
stub: (fire: () => void) =>
vi
.mocked(harness.sdk.commands.cancelSubscription)
.mockImplementation(async () => {
fire()
return SETTLED
}),
run: (store: Store) => store.cancelSubscription()
},
'a subscribe the caller announced': {
kind: 'subscription',
stub: (fire: () => void) =>
vi
.mocked(harness.sdk.commands.subscribe)
.mockImplementation(async () => {
fire()
return SETTLED
}),
run: (store: Store) =>
store.subscribe({ plan_slug: 'pro-yearly' }, { callerStarted: true })
},
'a subscribe no caller announced': {
kind: 'subscription',
stub: (fire: () => void) =>
vi
.mocked(harness.sdk.commands.subscribe)
.mockImplementation(async () => {
fire()
return SETTLED
}),
run: (store: Store) => store.subscribe({ plan_slug: 'pro-yearly' })
},
'a resubscribe': {
kind: 'subscription',
stub: (fire: () => void) =>
vi
.mocked(harness.sdk.commands.resubscribe)
.mockImplementation(async () => {
fire()
return SETTLED
}),
run: (store: Store) => store.resubscribe()
}
} as const

it.for([
{ command: 'a cancel', event: 'started', reports: 0 },
{ command: 'a cancel', event: 'resumed started', reports: 1 },
{ command: 'a cancel', event: 'terminal', reports: 1 },
{ command: 'a cancel', event: 'resumed terminal', reports: 1 },
{
command: 'a subscribe the caller announced',
event: 'started',
reports: 0
},
{
command: 'a subscribe the caller announced',
event: 'resumed started',
reports: 1
},
{
command: 'a subscribe the caller announced',
event: 'terminal',
reports: 1
},
{
command: 'a subscribe the caller announced',
event: 'resumed terminal',
reports: 1
},
{
command: 'a subscribe no caller announced',
event: 'started',
reports: 1
},
{
command: 'a subscribe no caller announced',
event: 'resumed started',
reports: 1
},
{
command: 'a subscribe no caller announced',
event: 'terminal',
reports: 1
},
{
command: 'a subscribe no caller announced',
event: 'resumed terminal',
reports: 1
},
{ command: 'a resubscribe', event: 'started', reports: 1 },
{ command: 'a resubscribe', event: 'resumed started', reports: 1 },
{ command: 'a resubscribe', event: 'terminal', reports: 1 },
{ command: 'a resubscribe', event: 'resumed terminal', reports: 1 }
] as const)(
'reports $reports event(s) for a lifecycle $event inside $command',
async ({ command, event, reports }) => {
const { kind, stub, run } = COMMANDS[command]
const store = useBillingSdkStore()
stub(() => options.onTelemetry(lifecycleEvent(kind, EVENTS[event])))

await run(store)

expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledTimes(reports)
}
)

it('reports a started that arrives once the announced command has settled', async () => {
const store = useBillingSdkStore()
vi.mocked(harness.sdk.commands.cancelSubscription).mockResolvedValue(
SETTLED
)
await store.cancelSubscription()

options.onTelemetry(lifecycleEvent('cancel', EVENTS.started))

expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledOnce()
})
})

describe('useBillingSdkStore operation projections', () => {
const otherWorkspace = {
userId: 'uid-1',
Expand Down
74 changes: 51 additions & 23 deletions src/platform/workspace/billing/sdk/billingSdkStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* dialog performs for the operations it issues itself.
*/
import type {
BillingOperationKind,
BillingOperationState,
BillingEventsReadOptions,
BillingOperationTelemetryEvent,
Expand Down Expand Up @@ -41,8 +42,7 @@ import type {
BillingStatusResponse,
CreateTopupResponse,
PreviewSubscribeResponse,
SavedPaymentMethod,
SubscribeResponse
SavedPaymentMethod
} from '@/platform/workspace/api/workspaceApi'
import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl'
import { needsCustomerAttention } from '@/platform/workspace/billing/customerAttention'
Expand All @@ -59,7 +59,11 @@ import { projectBillingStatus } from './billingStatusView'
import { createBillingSdk } from './createBillingSdk'
import type { BillingOperationRecordView } from './operationRecordView'
import { projectOperationRecord } from './operationRecordView'
import type { SubscriptionRailOutcome } from './subscriptionOperationView'
import type {
SettledCommand,
SettledSubscribeResponse,
SubscriptionRailOutcome
} from './subscriptionOperationView'
import {
projectPaymentPortalResult,
projectPreviewSubscribeResult,
Expand Down Expand Up @@ -107,6 +111,7 @@ export const useBillingSdkStore = defineStore('billingSdk', () => {
const operations = shallowRef<readonly BillingOperationState[]>([])
const dismissed = shallowRef<ReadonlySet<string>>(new Set())
const resumedOperations = new Set<string>()
const callerStarted = new Set<BillingOperationKind>()
const drivenChallenges = new Set<string>()
const offeredActions = new Map<string, Set<string>>()
const progressToasts = new Map<
Expand Down Expand Up @@ -206,20 +211,36 @@ export const useBillingSdkStore = defineStore('billingSdk', () => {

// A top-up the dialog issued is reported by the dialog, exactly as before;
// the lifecycle's events stand in for the poller's only on an operation
// this tab reattached to. A cancel or resubscribe has no such second
// reporter on this rail — the poller owned both ends of it on the legacy
// one — so the lifecycle's events are the only ones it emits.
// this tab reattached to. A cancel or subscribe the caller announced with
// its own `started` keeps that one event: the lifecycle's `started` is
// dropped inside the caller's command window, and its terminal is always
// forwarded, since only the lifecycle holds the operation's id, category
// and timing. A command no caller announced — a resubscribe, a checkout
// that reports nothing — is reported at both ends by the lifecycle.
function reportTelemetry(event: BillingOperationTelemetryEvent) {
if (event.operation_type === 'topup' && !event.resumed) return
if (
event.resumed &&
event.name === BILLING_OPERATION_TELEMETRY_EVENT.started
) {
resumedOperations.add(event.billing_op_id)
const started = event.name === BILLING_OPERATION_TELEMETRY_EVENT.started
if (started && event.resumed) resumedOperations.add(event.billing_op_id)
if (started && !event.resumed && callerStarted.has(event.operation_type)) {
return
}
useTelemetry()?.trackBillingEvent(toBillingTelemetryEvent(event))
}

// Sound because the lifecycle runs one command per kind at a time and
// emits both of an issued operation's events before the command resolves.
async function withCallerStart<T>(
kind: BillingOperationKind,
run: () => Promise<T>
): Promise<T> {
callerStarted.add(kind)
try {
return await run()
} finally {
callerStarted.delete(kind)
}
}

function onTopupChanged(state: BillingOperationState) {
if (state.phase === 'pending') {
syncProgressToast(state, 'topup')
Expand Down Expand Up @@ -429,28 +450,35 @@ export const useBillingSdkStore = defineStore('billingSdk', () => {
])
}

function cancelSubscription(): Promise<SubscriptionRailOutcome> {
return runSubscriptionCommand(
async () =>
projectSubscriptionResult(await sdk.commands.cancelSubscription()),
refreshAfterCancel
function cancelSubscription(): Promise<
SubscriptionRailOutcome<SettledCommand>
> {
return withCallerStart('cancel', () =>
runSubscriptionCommand(
async () =>
projectSubscriptionResult(await sdk.commands.cancelSubscription()),
refreshAfterCancel
)
)
}

function resubscribe(): Promise<SubscriptionRailOutcome> {
function resubscribe(): Promise<SubscriptionRailOutcome<SettledCommand>> {
return runSubscriptionCommand(
async () => projectSubscriptionResult(await sdk.commands.resubscribe()),
refreshAfterSubscriptionChange
)
}

function subscribe(
input: SubscribeInput
): Promise<SubscriptionRailOutcome<SubscribeResponse>> {
return runSubscriptionCommand(
async () => projectSubscribeResult(await sdk.commands.subscribe(input)),
refreshAfterSubscriptionChange
)
input: SubscribeInput,
{ callerStarted: announced = false }: { callerStarted?: boolean } = {}
): Promise<SubscriptionRailOutcome<SettledSubscribeResponse>> {
const run = () =>
runSubscriptionCommand(
async () => projectSubscribeResult(await sdk.commands.subscribe(input)),
refreshAfterSubscriptionChange
)
return announced ? withCallerStart('subscription', run) : run()
}

// A quote changes nothing, so it refreshes nothing; it shares the route
Expand Down
Loading
Loading