Skip to content
Merged
13 changes: 7 additions & 6 deletions src/platform/telemetry/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,12 @@ type BillingTimedOut = {
failure_category: 'poll_timeout'
}

/** The stage one attempt at a billing operation settled on. */
export type BillingOperationTerminal =
| BillingSucceeded
| (BillingFailed & { decline_reason?: BillingDeclineReason })
| BillingTimedOut

type SubscriptionCheckoutBillingEvent = {
operation: 'subscription_checkout'
billing_op_id?: string
Expand Down Expand Up @@ -1386,12 +1392,7 @@ type BillingOperationBillingEvent = {
* true duration.
*/
duration_ms?: number
} & (
| BillingStarted
| BillingSucceeded
| (BillingFailed & { decline_reason?: BillingDeclineReason })
| BillingTimedOut
)
} & (BillingStarted | BillingOperationTerminal)

type ResubscribeBillingEvent = {
operation: 'resubscribe'
Expand Down
4 changes: 3 additions & 1 deletion src/platform/telemetry/utils/billingFailureCategory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import { AuthStoreError } from '@/stores/authStore'
import type { BillingFailure } from '../types'

/**
* A `WorkspaceApiError`/`AuthStoreError` with no `status` never reached the
* A `WorkspaceApiError` that names its category keeps it. Otherwise a
* `WorkspaceApiError`/`AuthStoreError` with no `status` never reached the
* backend (`network`); a `TypeError` naming fetch/network/load is what `fetch`
* throws for connectivity failures.
*/
export function categorizeBillingApiError(
err: unknown
): BillingFailure['failure_category'] {
if (err instanceof WorkspaceApiError) {
if (err.failureCategory) return err.failureCategory
return err.status === undefined ? 'network' : 'api_rejected'
}
if (err instanceof AuthStoreError) {
Expand Down
6 changes: 5 additions & 1 deletion src/platform/workspace/api/workspaceApiError.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { BillingFailure } from '@/platform/telemetry/types'

/**
* 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.
Expand All @@ -6,7 +8,9 @@ export class WorkspaceApiError extends Error {
constructor(
message: string,
public readonly status?: number,
public readonly code?: string
public readonly code?: string,
/** For a failure `status` cannot classify, such as a billing SDK refusal. */
public readonly failureCategory?: BillingFailure['failure_category']
) {
super(message)
this.name = 'WorkspaceApiError'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ describe('projectTopupResult', () => {
).toMatchObject({ billing_op_id: 'op-1', status: 'failed' })
})

it('reports nothing for a purchase this tab stopped observing', () => {
it('reports a purchase this tab stopped observing as still pending', () => {
expect(
projectTopupResult(
{ status: 'unsettled', operation: settledTopup('timed_out') },
1000
)
).toBeUndefined()
).toMatchObject({ billing_op_id: 'op-1', status: 'pending' })
})

it('throws the API error whose code the dialog already handles', () => {
Expand Down
88 changes: 77 additions & 11 deletions src/platform/workspace/billing/sdk/topupOperationView.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* Projections from the SDK's operation state and top-up result onto the two
* shapes the top-up dialog already reads: the poller's operation record and
* the `CreateTopupResponse` the legacy call returned. The dialog is untouched;
* these give it the same inputs from the other rail.
* the `CreateTopupResponse` the legacy call returned, plus the terminal the
* SDK observed where those shapes cannot hold it.
*/
import type {
BillingDeclineReason,
Expand All @@ -16,6 +16,10 @@ import {
} from '@comfyorg/account-core/billing'

import { t } from '@/i18n'
import type {
BillingFailure,
BillingOperationTerminal
} from '@/platform/telemetry/types'
import type {
BillingAuthenticationState,
BillingOperationPhase,
Expand Down Expand Up @@ -72,36 +76,98 @@ export function projectTopupOperation(
}
}

/**
* A purchase the SDK settled without crediting, as the response the dialog
* handles, carrying the terminal its status cannot: the decline reason, or
* that this tab stopped watching, or that support must reconcile it.
*/
export class UncreditedTopupResponse implements CreateTopupResponse {
readonly topup_id = ''

constructor(
readonly billing_op_id: string,
readonly status: 'failed' | 'pending',
readonly amount_cents: number,
readonly terminal: BillingOperationTerminal
) {}
}

/**
* Most SDK refusals carry no HTTP status, which a status-less API error
* would otherwise report as a network failure, so each names its category.
*/
function topupFailureError(failure: TopupFailure): WorkspaceApiError {
const serverCode = 'serverCode' in failure ? failure.serverCode : undefined
return new WorkspaceApiError(
t('credits.topUp.unknownError'),
'httpStatus' in failure ? failure.httpStatus : undefined,
serverCode === undefined ? failure.code : unwrapServerCode(serverCode)
serverCode === undefined ? failure.code : unwrapServerCode(serverCode),
topupFailureCategory(failure)
)
}

function topupFailureCategory(
failure: TopupFailure
): BillingFailure['failure_category'] {
switch (failure.code) {
case 'REQUEST_FAILED':
return failure.httpStatus === undefined ? 'network' : 'api_rejected'
case 'SUPERSEDED':
return 'stale_operation'
case 'INVALID_AMOUNT':
return 'validation'
default:
return 'api_rejected'
}
}

/**
* A settled result as the response the dialog handles today. `unsettled` has
* no counterpart: the dialog reads an undefined response as "nothing to
* report" and the operation stays visible through `projectTopupOperation`.
* `topup_id` is not surfaced by the SDK and nothing reads it.
* A settled result as the response the dialog handles today. `unsettled` is
* the pending response: the server may still settle it, and the operation
* stays visible through `projectTopupOperation`. `topup_id` is not surfaced
* by the SDK and nothing reads it.
*/
export function projectTopupResult(
result: TopupResult,
amountCents: number
): CreateTopupResponse | undefined {
): CreateTopupResponse {
switch (result.status) {
case 'ok':
case 'declined':
return {
billing_op_id: result.operation.id,
topup_id: '',
status: result.status === 'ok' ? 'completed' : 'failed',
status: 'completed',
amount_cents: amountCents
}
case 'declined':
return new UncreditedTopupResponse(
result.operation.id,
'failed',
amountCents,
{
stage: 'failed',
outcome: 'failure',
failure_category: 'provider_decline',
decline_reason: result.operation.declineReason
}
)
case 'unsettled':
return undefined
return new UncreditedTopupResponse(
result.operation.id,
'pending',
amountCents,
result.operation.phase === 'timed_out'
? {
stage: 'timeout',
outcome: 'failure',
failure_category: 'poll_timeout'
}
: {
stage: 'failed',
outcome: 'failure',
failure_category: 'reconciliation_needed'
}
)
case 'error':
throw topupFailureError(result)
}
Expand Down
Loading
Loading