Skip to content
Merged
19 changes: 19 additions & 0 deletions packages/account-core/src/core/billing/contracts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated billing contracts

One file per endpoint contract the billing SDK core decodes. Each pins the
fields the core actually reads and the enum members it branches on, so a
regenerated `@comfyorg/ingest-types` that renames, drops, or widens one of them
fails here instead of surfacing as a runtime `MALFORMED_RESPONSE`.

Each file pins its contract twice, and the two halves fail in different jobs:

- `describe` blocks hold the runtime pins — what the generated schema accepts
and rejects. `pnpm --filter @comfyorg/account-core test` fails on those.
- Module-scope `expectTypeOf` calls hold the type pins — the shapes the SDK
reads off a parsed body. Vitest never evaluates them; the package
`typecheck` script is what fails, as a `TS2344`. They sit outside `it` so
the vitest report never counts a pass vitest did not check.

A failure means the backend contract moved: fix the SDK, not the test. Where
the SDK reads a field more leniently than the generated schema does, the test
name says so — that row pins the generated shape, not the SDK's.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { zBillingBalanceResponse } from '@comfyorg/ingest-types/zod'
import { describe, expect, expectTypeOf, it } from 'vitest'
import type { z } from 'zod'

type BalanceBody = z.input<typeof zBillingBalanceResponse>
type Balance = z.infer<typeof zBillingBalanceResponse>

function balanceBody(overrides: Partial<BalanceBody> = {}): BalanceBody {
return {
amount_micros: 12_500_000,
currency: 'usd',
...overrides
}
}

// Compile-time pins: a regen that moves these fails the package typecheck.
expectTypeOf<Balance['amount_micros']>().toEqualTypeOf<number>()
expectTypeOf<
Pick<
Balance,
| 'cloud_credit_balance_micros'
| 'effective_balance_micros'
| 'pending_charges_micros'
| 'prepaid_balance_micros'
>
>().toEqualTypeOf<{
cloud_credit_balance_micros?: number
effective_balance_micros?: number
pending_charges_micros?: number
prepaid_balance_micros?: number
}>()

describe('billing balance contract', () => {
it('accepts a balance carrying only the required fields', () => {
expect(zBillingBalanceResponse.safeParse(balanceBody())).toMatchObject({
success: true
})
})

it('keeps every balance breakdown optional beside the headline amount', () => {
const breakdown = balanceBody({
cloud_credit_balance_micros: 1,
effective_balance_micros: 2,
pending_charges_micros: 3,
prepaid_balance_micros: 4
})

expect(zBillingBalanceResponse.safeParse(breakdown)).toMatchObject({
success: true
})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { zBillingCapabilitiesResponse } from '@comfyorg/ingest-types/zod'
import type {
zBillingCapabilities,
zBillingCapabilityRolloutDefaults,
zBillingCapabilityScope
} from '@comfyorg/ingest-types/zod'
import { describe, expect, expectTypeOf, it } from 'vitest'
import type { z } from 'zod'

type CapabilitiesResponseBody = z.input<typeof zBillingCapabilitiesResponse>
type CapabilitiesResponse = z.infer<typeof zBillingCapabilitiesResponse>
type Capabilities = z.infer<typeof zBillingCapabilities>
type CapabilityScope = z.infer<typeof zBillingCapabilityScope>
type RolloutDefaults = z.infer<typeof zBillingCapabilityRolloutDefaults>

function capabilities(): Capabilities {
return {
can_cancel: true,
can_change_seats: true,
can_downgrade_to_personal: false,
can_invite_members: true,
can_reactivate: false,
can_subscribe_self_serve: true,
can_top_up: true
}
}

function capabilitiesBody(
Comment thread
CodeJuggernaut marked this conversation as resolved.
Resolved
overrides: Partial<CapabilitiesResponseBody> = {}
): CapabilitiesResponseBody {
return {
capabilities: capabilities(),
expires_at: '2024-06-15T12:01:00.000Z',
resolved_for: { user_id: 'uid-1', workspace_id: 'ws-1' },
revision: 42n,
rollout_defaults_applied: {
can_downgrade_to_personal: false,
can_subscribe_self_serve: false,
can_top_up: false
},
...overrides
}
}

// Compile-time pins: a regen that moves these fails the package typecheck.

// The five fields the reader composes its own schema from.
expectTypeOf<keyof CapabilitiesResponse>().toEqualTypeOf<
| 'capabilities'
| 'expires_at'
| 'resolved_for'
| 'revision'
| 'rollout_defaults_applied'
>()
expectTypeOf<Capabilities>().toEqualTypeOf<{
can_cancel: boolean
can_change_seats: boolean
can_downgrade_to_personal: boolean
can_invite_members: boolean
can_reactivate: boolean
can_subscribe_self_serve: boolean
can_top_up: boolean
}>()
expectTypeOf<CapabilityScope>().toEqualTypeOf<{
user_id: string
workspace_id: string
}>()
expectTypeOf<RolloutDefaults>().toEqualTypeOf<{
can_downgrade_to_personal: boolean
can_subscribe_self_serve: boolean
can_top_up: boolean
}>()
// The expiry the reader paces freshness from; the revision it reads as a number.
expectTypeOf<CapabilitiesResponse['expires_at']>().toEqualTypeOf<string>()
expectTypeOf<CapabilitiesResponse['revision']>().toEqualTypeOf<bigint>()

describe('billing capabilities contract', () => {
it('accepts the body the capabilities endpoint returns', () => {
expect(
zBillingCapabilitiesResponse.safeParse(capabilitiesBody())
).toMatchObject({ success: true })
})

it('requires a datetime expiry, which the reader re-decodes leniently as a plain string', () => {
expect(
zBillingCapabilitiesResponse.safeParse(
capabilitiesBody({ expires_at: 'not-a-date' })
).success
).toBe(false)
})

it('bounds the revision to the safe range the reader reads it back as a number over', () => {
const safe = { ...capabilitiesBody(), revision: Number.MAX_SAFE_INTEGER }
const unsafe = capabilitiesBody({
revision: BigInt(Number.MAX_SAFE_INTEGER) + 1n
})

expect(zBillingCapabilitiesResponse.safeParse(safe)).toMatchObject({
success: true
})
expect(zBillingCapabilitiesResponse.safeParse(unsafe).success).toBe(false)
})

it('omits denied reasons, which the reader therefore decodes off the raw body', () => {
const parsed = zBillingCapabilitiesResponse.safeParse({
...capabilitiesBody(),
denied_reasons: { can_subscribe_self_serve: 'not_workspace_owner' }
})

expect(parsed).toMatchObject({ success: true })
expect(parsed.success && 'denied_reasons' in parsed.data).toBe(false)
Comment thread
dante01yoon marked this conversation as resolved.
Resolved
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { zBillingOpStatusResponse } from '@comfyorg/ingest-types/zod'
import { describe, expect, expectTypeOf, it } from 'vitest'
import type { z } from 'zod'

type OpStatusBody = z.input<typeof zBillingOpStatusResponse>
type OpStatus = z.infer<typeof zBillingOpStatusResponse>

function opStatusBody(overrides: Partial<OpStatusBody> = {}): OpStatusBody {
return {
id: 'op-1',
started_at: '2024-06-15T12:00:00.000Z',
status: 'pending',
...overrides
}
}

/** Every value the reducer distinguishes; 'pending' is its stay-put branch. */
const REDUCED_STATUSES = [
'pending',
'succeeded',
'failed',
'reconciliation_needed'
] as const satisfies readonly OpStatus['status'][]

/** Every value the pending reducer reads or `settleChallenge` assigns. */
const AUTHENTICATION_STATES = [
'requires_action',
'processing',
'failed_retryable',
'succeeded',
'reconciliation_needed'
] as const satisfies readonly NonNullable<OpStatus['authentication_state']>[]

// Compile-time pins: a regen that moves these fails the package typecheck.

// The tables above are exhaustive, so a new member reaches an `it.for` row.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: Minor (record)

What: the body's TO-BE bullet still quotes carries exactly the four statuses the reducer handles, a test title 278fcc0 deleted when that pin became an unnamed module-scope expectTypeOf at packages/account-core/src/core/billing/contracts/billingOpStatus.contract.test.ts:36-38.

Why this is an issue: a regen that adds a fifth status now fails the package typecheck with a TS2344 at that file, not a named vitest test, so the bullet sends the reader to a test that does not exist.

Proposed Fix: replace the quoted name with the pin's location and let the "named block" phrasing cover only the parse rows.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both stale sentences are fixed in the description.

The TO-BE bullet now points at billingOpStatus.contract.test.ts:36 and says the pin sits at module scope, instead of quoting a test title that no longer exists. The Testing line reads 12 files, 90 tests, and adds that the type pins are not among them because they fail the package typecheck rather than the test run.

Both were mine to catch before you did — the body describes a tree two commits older than itself, and it becomes the squash message.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both records are already corrected in the body — it was edited at 07:34Z, a couple of minutes after this review landed, so you were reading the pre-edit copy.

  • Testing line now reads 12 files, 90 tests, all passing. Verified independently at b3f14e9: vitest run src/core/billing/contracts reports Test Files 12 passed (12), Tests 90 passed (90).
  • The TO-BE bullet no longer quotes the deleted title. It now names both gates and cites the pin's location: the enum rows (accepts the %s status) fail under vitest run, while the exhaustiveness pin at billingOpStatus.contract.test.ts:36 sits at module scope and fails as a TS2344 under the package typecheck, not in the test run.

No code change and the head is unchanged at b3f14e9. Leaving the thread for you to close.

expectTypeOf<OpStatus['status']>().toEqualTypeOf<
(typeof REDUCED_STATUSES)[number]
>()
expectTypeOf<OpStatus['authentication_state']>().toEqualTypeOf<
(typeof AUTHENTICATION_STATES)[number] | undefined
>()
// The decline reasons a failed operation reports, including the fallback.
expectTypeOf<OpStatus['decline_reason']>().toEqualTypeOf<
| 'card_declined'
| 'insufficient_funds'
| 'expired_card'
| 'incorrect_cvc'
| 'authentication_required'
| 'authentication_failed'
| 'processing_error'
| 'generic'
| undefined
>()
// The recovery actions a host offers after a decline.
expectTypeOf<OpStatus['recovery_action']>().toEqualTypeOf<
| 'retry'
| 'replace_payment_method'
| 'authenticate_payment'
| 'contact_support'
| undefined
>()
// The server phases the pending state mirrors.
expectTypeOf<OpStatus['phase']>().toEqualTypeOf<
| 'awaiting_payment_method'
| 'awaiting_invoice_payment'
| 'in_progress'
| undefined
>()
expectTypeOf<OpStatus['id']>().toEqualTypeOf<string>()
expectTypeOf<OpStatus['action_url']>().toEqualTypeOf<string | undefined>()
expectTypeOf<OpStatus['payment_intent_client_secret']>().toEqualTypeOf<
string | undefined
>()
expectTypeOf<OpStatus['retryable']>().toEqualTypeOf<boolean | undefined>()

describe('billing operation status contract', () => {
it('accepts a status carrying only the required fields', () => {
expect(zBillingOpStatusResponse.safeParse(opStatusBody())).toMatchObject({
success: true
})
})
Comment thread
dante01yoon marked this conversation as resolved.
Resolved

it('requires a datetime start time, so a malformed one fails the whole poll', () => {
expect(
zBillingOpStatusResponse.safeParse(
opStatusBody({ started_at: 'not-a-date' })
).success
).toBe(false)
})

it.for(REDUCED_STATUSES)('accepts the %s status', (status) => {
expect(
zBillingOpStatusResponse.safeParse(opStatusBody({ status }))
).toMatchObject({ success: true })
})

it.for(AUTHENTICATION_STATES)(
'accepts the %s authentication state',
(authentication_state) => {
expect(
zBillingOpStatusResponse.safeParse(
opStatusBody({ authentication_state })
)
).toMatchObject({ success: true })
}
)

it('leaves retryable absent by default, so a decline is not retryable unless the server says so', () => {
const parsed = zBillingOpStatusResponse.safeParse(
opStatusBody({ status: 'failed' })
)

expect(parsed.success && parsed.data.retryable).toBeUndefined()
})
})
Loading
Loading