From bbaf5f1557e92839c2c6aa8d278c4c8b081dda23 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Fri, 30 Oct 2026 18:11:46 -0400 Subject: [PATCH] feat(account-core): auto top-up reader, save and preview in the billing SDK Add createAutoTopUpReader over GET /billing/auto-reload, saveAutoTopUp (PUT /billing/auto-reload) and previewAutoTopUp (GET /billing/auto-reload/preview), decoded with the generated schemas and int64 fields read as safe integers. BillingRequest now accepts PUT. A PUT without an idempotency key is not replayed on 401, the same rule POST already follows. --- .../src/core/billing/autoTopUp.test.ts | 399 ++++++++++++++++++ .../src/core/billing/autoTopUp.ts | 194 +++++++++ .../src/core/billing/billingContracts.ts | 2 +- .../credentialedTransport.webSession.test.ts | 8 + .../account-core/src/core/billing/index.ts | 20 + .../src/core/billing/scopedReader.test.ts | 33 ++ .../src/core/billing/transport.test.ts | 68 ++- 7 files changed, 702 insertions(+), 22 deletions(-) create mode 100644 packages/account-core/src/core/billing/autoTopUp.test.ts create mode 100644 packages/account-core/src/core/billing/autoTopUp.ts diff --git a/packages/account-core/src/core/billing/autoTopUp.test.ts b/packages/account-core/src/core/billing/autoTopUp.test.ts new file mode 100644 index 00000000000..cfb6ec1515b --- /dev/null +++ b/packages/account-core/src/core/billing/autoTopUp.test.ts @@ -0,0 +1,399 @@ +import { describe, expect, it, vi } from 'vitest' + +import type { SessionSnapshot } from '#/core/session' +import { + createAutoTopUpReader, + previewAutoTopUp, + saveAutoTopUp +} from './autoTopUp' +import type { SaveAutoTopUpInput } from './autoTopUp' +import type { + BillingHttpResponse, + BillingResult, + BillingTransport +} from './billingContracts' +import { sessionBillingScopeSource } from './billingScope' +import { + authenticated, + credential, + fakeTransport, + httpOk, + httpStatus +} from './__fixtures__/billingTestFixtures' +import type { SessionFake } from './__fixtures__/billingTestFixtures' + +function fakeSession(initial: SessionSnapshot = authenticated(credential())) { + let snapshot = initial + const listeners = new Set<(next: SessionSnapshot) => void>() + const fake: SessionFake = { + getSnapshot: () => snapshot, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + } + return { + scopeSource: sessionBillingScopeSource(fake), + moveToTeam() { + snapshot = authenticated( + credential({ workspace: { id: 'ws-2', name: 'Team', type: 'team' } }) + ) + for (const listener of Array.from(listeners)) listener(snapshot) + } + } +} + +const SETTINGS = { + card_expiring_soon: false, + card_expiry: { expired: false, month: 4, year: 2030 }, + configured: true, + cycle_resets_at: '2026-11-01T00:00:00Z', + declined_payment_method: null, + disabled_reason: null, + enabled: true, + last_failure_at: null, + last_failure_reason: null, + max_monthly_budget_cents: 100_000, + max_reload_credits: 50_000, + min_reload_credits: 500, + monthly_budget_cents: 20_000, + monthly_budget_is_default: false, + paused_by_budget: false, + paused_by_budget_remainder: false, + paused_by_decline: false, + reload_amount_cents: 1_000, + reload_credits: 2_000, + spent_this_cycle_cents: 3_000, + status: 'on', + target_credits: 3_000, + threshold_credits: 1_000 +} + +const SAVE_INPUT: SaveAutoTopUpInput = { + enabled: true, + monthly_budget_cents: 20_000, + target_credits: 3_000, + threshold_credits: 1_000 +} + +function refusal( + status: number, + code: string +): BillingResult { + return { + status: 'ok', + value: { + httpStatus: status, + body: { code, message: `refused: ${code}` }, + header: () => null + } + } +} + +function gatedTransport(answers: BillingResult[]) { + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + let calls = 0 + const transport: BillingTransport = vi.fn(async () => { + const answer = answers[Math.min(calls, answers.length - 1)] + calls++ + if (calls === 1) await gate + return answer + }) + return { transport, release: () => release() } +} + +describe('createAutoTopUpReader', () => { + it('reads the settings from the auto-reload route with int64 fields as numbers', async () => { + const { scopeSource } = fakeSession() + const { transport, calls } = fakeTransport([httpOk(SETTINGS)]) + + const result = await createAutoTopUpReader({ + transport, + scopeSource, + now: () => 1_700 + }).read({ timeoutMs: 5_000 }) + + expect(calls).toEqual([ + { method: 'GET', route: '/billing/auto-reload', timeoutMs: 5_000 } + ]) + expect(result).toEqual({ + status: 'ok', + value: { + scope: { userId: 'uid-1', workspaceId: 'ws-1', role: 'owner' }, + settings: SETTINGS, + readAt: 1_700 + } + }) + }) + + it('serves concurrent reads of one scope from a single request', async () => { + const { scopeSource } = fakeSession() + const { transport, calls } = fakeTransport([httpOk(SETTINGS)]) + const reader = createAutoTopUpReader({ transport, scopeSource }) + + const [first, second] = await Promise.all([reader.read(), reader.read()]) + + expect(calls).toHaveLength(1) + expect(first).toEqual(second) + }) + + it('reports a read the workspace change overtook as superseded', async () => { + const host = fakeSession() + const { transport, release } = gatedTransport([httpOk(SETTINGS)]) + const reader = createAutoTopUpReader({ + transport, + scopeSource: host.scopeSource + }) + + const pending = reader.read() + host.moveToTeam() + release() + + expect(await pending).toEqual({ status: 'error', code: 'SUPERSEDED' }) + expect(reader.getSnapshot()).toBeUndefined() + }) + + it('reports a body with a fractional credit count as malformed', async () => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([ + httpOk({ ...SETTINGS, threshold_credits: 10.5 }) + ]) + + const result = await createAutoTopUpReader({ + transport, + scopeSource + }).read() + + expect(result).toEqual({ + status: 'error', + code: 'MALFORMED_RESPONSE', + httpStatus: 200 + }) + }) + + it.for([ + [401, 'ACCESS_DENIED'], + [403, 'ACCESS_DENIED'], + [404, 'NOT_FOUND'], + [409, 'CONFLICT'], + [422, 'REQUEST_FAILED'], + [500, 'REQUEST_FAILED'], + [503, 'REQUEST_FAILED'] + ] as const)('maps %i to %s', async ([status, code]) => { + const { scopeSource } = fakeSession() + const { transport } = fakeTransport([httpStatus(status)]) + + const result = await createAutoTopUpReader({ + transport, + scopeSource + }).read() + + expect(result).toEqual({ status: 'error', code, httpStatus: status }) + }) + + it('drops the published settings on invalidate and keeps an older read from republishing them', async () => { + const { scopeSource } = fakeSession() + const disabled = { ...SETTINGS, enabled: false, status: 'off' } + const { transport, release } = gatedTransport([ + httpOk(SETTINGS), + httpOk(disabled) + ]) + const reader = createAutoTopUpReader({ transport, scopeSource }) + + const stale = reader.read() + reader.invalidate() + const fresh = await reader.read() + release() + await stale + + expect(transport).toHaveBeenCalledTimes(2) + expect(fresh).toMatchObject({ value: { settings: { enabled: false } } }) + expect(reader.getSnapshot()?.settings.enabled).toBe(false) + + reader.invalidate() + + expect(reader.getSnapshot()).toBeUndefined() + }) +}) + +describe('saveAutoTopUp', () => { + it('sends the generated request body as a PUT and returns the stored settings', async () => { + const { transport, calls } = fakeTransport([httpOk(SETTINGS)]) + + const result = await saveAutoTopUp(transport, SAVE_INPUT, { + timeoutMs: 5_000 + }) + + expect(calls).toEqual([ + { + method: 'PUT', + route: '/billing/auto-reload', + body: SAVE_INPUT, + timeoutMs: 5_000 + } + ]) + expect(result).toEqual({ status: 'ok', value: SETTINGS }) + }) + + it('sends no idempotency key, so a stale token is reported rather than replayed', async () => { + const { transport, calls } = fakeTransport([ + { + status: 'ok', + value: { + httpStatus: 401, + body: {}, + header: () => null, + authenticationRetrySkipped: true + } + } + ]) + + const result = await saveAutoTopUp(transport, SAVE_INPUT) + + expect(calls[0].idempotencyKey).toBeUndefined() + expect(result).toEqual({ + status: 'error', + code: 'REQUEST_FAILED', + httpStatus: 401 + }) + }) + + it.for([ + [400, 'INVALID_AUTO_TOP_UP', 'REQUEST_FAILED'], + [409, 'SUBSCRIPTION_CHANGE_IN_PROGRESS', 'CONFLICT'], + [422, 'AUTO_TOP_UP_NOT_ELIGIBLE', 'REQUEST_FAILED'], + [500, 'AUTO_TOP_UP_DISABLED_ACCOUNTING_UNAVAILABLE', 'REQUEST_FAILED'] + ] as const)( + 'returns a %i %s refusal as %s with the server code', + async ([status, serverCode, code]) => { + const { transport } = fakeTransport([refusal(status, serverCode)]) + + const result = await saveAutoTopUp(transport, SAVE_INPUT) + + expect(result).toEqual({ + status: 'error', + code, + httpStatus: status, + serverCode, + serverMessage: `refused: ${serverCode}` + }) + } + ) + + it('refuses a fractional credit count without sending anything', async () => { + const { transport } = fakeTransport([httpOk(SETTINGS)]) + + const result = await saveAutoTopUp(transport, { + ...SAVE_INPUT, + threshold_credits: 10.5 + }) + + expect(result).toEqual({ status: 'error', code: 'INVALID_REQUEST' }) + expect(transport).not.toHaveBeenCalled() + }) + + it('reports a stored-settings body that misses the contract as malformed', async () => { + const { transport } = fakeTransport([httpOk({ enabled: true })]) + + const result = await saveAutoTopUp(transport, SAVE_INPUT) + + expect(result).toEqual({ + status: 'error', + code: 'MALFORMED_RESPONSE', + httpStatus: 200 + }) + }) +}) + +describe('previewAutoTopUp', () => { + const CHARGES_NOW = { + charge_cents: 1_000, + charge_credits: 2_000, + charges_now: true, + not_charging_reason: 'above_threshold' + } + + it.for([ + [ + 'with a budget', + { + threshold_credits: 1_000, + target_credits: 3_000, + monthly_budget_cents: 20_000 + }, + '/billing/auto-reload/preview?threshold_credits=1000&target_credits=3000&monthly_budget_cents=20000' + ], + [ + 'without a budget', + { threshold_credits: 1_000, target_credits: 3_000 }, + '/billing/auto-reload/preview?threshold_credits=1000&target_credits=3000' + ] + ] as const)('encodes the query %s', async ([, query, route]) => { + const { transport, calls } = fakeTransport([httpOk(CHARGES_NOW)]) + + await previewAutoTopUp(transport, query) + + expect(calls).toEqual([{ method: 'GET', route }]) + }) + + it.for([ + ['charges now', CHARGES_NOW], + [ + 'does not charge now', + { + charge_cents: null, + charge_credits: null, + charges_now: false, + not_charging_reason: 'above_threshold' + } + ] + ] as const)('returns the estimate when saving %s', async ([, estimate]) => { + const { transport } = fakeTransport([httpOk(estimate)]) + + const result = await previewAutoTopUp(transport, { + threshold_credits: 1_000, + target_credits: 3_000 + }) + + expect(result).toEqual({ status: 'ok', value: estimate }) + }) + + it.for([ + [422, 'AUTO_TOP_UP_NOT_ELIGIBLE', 'REQUEST_FAILED'], + [409, 'SUBSCRIPTION_CHANGE_IN_PROGRESS', 'CONFLICT'], + [503, 'AUTO_TOP_UP_PREVIEW_UNAVAILABLE', 'REQUEST_FAILED'] + ] as const)( + 'returns a %i %s refusal as %s instead of throwing', + async ([status, serverCode, code]) => { + const { transport } = fakeTransport([refusal(status, serverCode)]) + + const result = await previewAutoTopUp(transport, { + threshold_credits: 1_000, + target_credits: 3_000 + }) + + expect(result).toEqual({ + status: 'error', + code, + httpStatus: status, + serverCode, + serverMessage: `refused: ${serverCode}` + }) + } + ) + + it('refuses a fractional threshold without sending anything', async () => { + const { transport } = fakeTransport([httpOk(CHARGES_NOW)]) + + const result = await previewAutoTopUp(transport, { + threshold_credits: 10.5, + target_credits: 3_000 + }) + + expect(result).toEqual({ status: 'error', code: 'INVALID_REQUEST' }) + expect(transport).not.toHaveBeenCalled() + }) +}) diff --git a/packages/account-core/src/core/billing/autoTopUp.ts b/packages/account-core/src/core/billing/autoTopUp.ts new file mode 100644 index 00000000000..d9ddcaf6939 --- /dev/null +++ b/packages/account-core/src/core/billing/autoTopUp.ts @@ -0,0 +1,194 @@ +import type { + AutoReloadSettingsRequest, + GetBillingAutoReloadPreviewData +} from '@comfyorg/ingest-types' +import { + zGetBillingAutoReloadPreviewQuery, + zGetBillingAutoReloadPreviewResponse, + zGetBillingAutoReloadResponse, + zPutBillingAutoReloadBody, + zPutBillingAutoReloadResponse +} from '@comfyorg/ingest-types/zod' +import type { z } from 'zod' + +import type { BillingResult, BillingTransport } from './billingContracts' +import type { BillingScope, BillingScopeSource } from './billingScope' +import { createScopedReader } from './scopedReader' +import { readValidatedBillingResponse } from './sharedRead' +import { wireCents } from './wireCents' + +export const AUTO_TOP_UP_ROUTE = '/billing/auto-reload' +export const AUTO_TOP_UP_PREVIEW_ROUTE = '/billing/auto-reload/preview' + +const settingsWireCents = { + max_monthly_budget_cents: wireCents, + max_reload_credits: wireCents.nullable(), + min_reload_credits: wireCents, + monthly_budget_cents: wireCents.nullable(), + reload_amount_cents: wireCents.nullable(), + reload_credits: wireCents.nullable(), + spent_this_cycle_cents: wireCents, + target_credits: wireCents.nullable(), + threshold_credits: wireCents.nullable() +} + +const ReadSettingsSchema = + zGetBillingAutoReloadResponse.extend(settingsWireCents) +const SavedSettingsSchema = + zPutBillingAutoReloadResponse.extend(settingsWireCents) +const PreviewSchema = zGetBillingAutoReloadPreviewResponse.extend({ + charge_cents: wireCents.nullable(), + charge_credits: wireCents.nullable() +}) + +/** The server's auto top-up settings and this cycle's automatic spend, as published. */ +export type AutoReloadSettings = z.infer + +/** The server's estimate of what saving the proposed settings would charge. */ +export type AutoReloadPreview = z.infer + +export type SaveAutoTopUpInput = AutoReloadSettingsRequest + +export type PreviewAutoTopUpQuery = GetBillingAutoReloadPreviewData['query'] + +/** A failure of the typed operation, or an input the generated request contract refuses before anything is sent. */ +export type AutoTopUpCommandResult = + | BillingResult + | { readonly status: 'error'; readonly code: 'INVALID_REQUEST' } + +export interface AutoTopUpCommandOptions { + readonly signal?: AbortSignal + readonly timeoutMs?: number +} + +export type AutoTopUpScope = BillingScope + +export interface AutoTopUpSnapshot { + readonly scope: AutoTopUpScope + readonly settings: AutoReloadSettings + /** ms since epoch at which this read settled. */ + readonly readAt: number +} + +export interface AutoTopUpReadOptions { + readonly signal?: AbortSignal + /** Bounds the request, when this caller is the one that issues it. */ + readonly timeoutMs?: number +} + +export interface AutoTopUpReader { + /** Always requests. Concurrent callers for one scope share a single request. */ + read: ( + options?: AutoTopUpReadOptions + ) => Promise> + /** The last settings published for the current scope. */ + getSnapshot: () => AutoTopUpSnapshot | undefined + /** Drops the published settings, and keeps a read already in flight from publishing. */ + invalidate: () => void + dispose: () => void +} + +export interface AutoTopUpReaderOptions { + readonly transport: BillingTransport + readonly scopeSource: BillingScopeSource + readonly now?: () => number +} + +const INVALID_REQUEST = { status: 'error', code: 'INVALID_REQUEST' } as const + +function requestBudget(options: AutoTopUpCommandOptions) { + return { + ...(options.signal === undefined ? {} : { signal: options.signal }), + ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }) + } +} + +function previewRoute(query: PreviewAutoTopUpQuery): string { + const search = new URLSearchParams({ + threshold_credits: String(query.threshold_credits), + target_credits: String(query.target_credits) + }) + if (query.monthly_budget_cents !== undefined) { + search.set('monthly_budget_cents', String(query.monthly_budget_cents)) + } + return `${AUTO_TOP_UP_PREVIEW_ROUTE}?${search.toString()}` +} + +export function createAutoTopUpReader( + options: AutoTopUpReaderOptions +): AutoTopUpReader { + const { transport, scopeSource, now = Date.now } = options + + const reader = createScopedReader< + AutoReloadSettings, + AutoTopUpSnapshot, + AutoTopUpReadOptions + >({ + transport, + scopeSource, + route: AUTO_TOP_UP_ROUTE, + parse: (body) => ReadSettingsSchema.safeParse(body), + timeoutMs: (readOptions) => readOptions?.timeoutMs, + project: ({ data }, scope) => ({ + status: 'ok', + value: { scope, settings: data, readAt: now() } + }), + publish: (value, fenced) => (fenced ? undefined : value) + }) + + return { + read: reader.read, + getSnapshot: reader.getSnapshot, + invalidate: () => { + reader.setSnapshot(undefined) + reader.fenceInFlight({ detach: true }) + }, + dispose: reader.dispose + } +} + +/** + * Saves the settings and returns what the server stored. Sent without an + * idempotency key, so a stale token is reported rather than replayed. + */ +export async function saveAutoTopUp( + transport: BillingTransport, + input: SaveAutoTopUpInput, + options: AutoTopUpCommandOptions = {} +): Promise> { + if (!zPutBillingAutoReloadBody.safeParse(input).success) { + return INVALID_REQUEST + } + const response = await readValidatedBillingResponse( + transport, + { + method: 'PUT', + route: AUTO_TOP_UP_ROUTE, + body: input, + ...requestBudget(options) + }, + (raw) => SavedSettingsSchema.safeParse(raw) + ) + return response.status === 'error' + ? response + : { status: 'ok', value: response.value.data } +} + +/** Asks the server what saving these settings would charge now, without saving them. */ +export async function previewAutoTopUp( + transport: BillingTransport, + query: PreviewAutoTopUpQuery, + options: AutoTopUpCommandOptions = {} +): Promise> { + if (!zGetBillingAutoReloadPreviewQuery.safeParse(query).success) { + return INVALID_REQUEST + } + const response = await readValidatedBillingResponse( + transport, + { method: 'GET', route: previewRoute(query), ...requestBudget(options) }, + (raw) => PreviewSchema.safeParse(raw) + ) + return response.status === 'error' + ? response + : { status: 'ok', value: response.value.data } +} diff --git a/packages/account-core/src/core/billing/billingContracts.ts b/packages/account-core/src/core/billing/billingContracts.ts index b9d32e519b6..c7d99ecbc50 100644 --- a/packages/account-core/src/core/billing/billingContracts.ts +++ b/packages/account-core/src/core/billing/billingContracts.ts @@ -141,7 +141,7 @@ interface BillingRequestBase { export type BillingRequest = BillingRequestBase & ( | { readonly method: 'GET'; readonly body?: never } - | { readonly method: 'POST'; readonly body?: unknown } + | { readonly method: 'POST' | 'PUT'; readonly body?: unknown } ) export interface BillingHttpResponse { diff --git a/packages/account-core/src/core/billing/credentialedTransport.webSession.test.ts b/packages/account-core/src/core/billing/credentialedTransport.webSession.test.ts index f80eeff3469..da418fb562a 100644 --- a/packages/account-core/src/core/billing/credentialedTransport.webSession.test.ts +++ b/packages/account-core/src/core/billing/credentialedTransport.webSession.test.ts @@ -93,6 +93,14 @@ describe('createCredentialedBillingTransport with a web session', () => { 'x-comfy-workspace-id': 'ws-1', 'x-csrf-token': 'stale-csrf' } + }, + { + method: 'PUT' as const, + expected: { + 'x-comfy-client': COMFY_CLIENT, + 'x-comfy-workspace-id': 'ws-1', + 'x-csrf-token': 'stale-csrf' + } } ])( 'sends the cookie headers authorize decides for a $method', diff --git a/packages/account-core/src/core/billing/index.ts b/packages/account-core/src/core/billing/index.ts index 0f1ca6e3535..0f9f4420f97 100644 --- a/packages/account-core/src/core/billing/index.ts +++ b/packages/account-core/src/core/billing/index.ts @@ -100,6 +100,26 @@ export { PAYMENT_METHODS_ROUTE, createPaymentMethodsReader } from './paymentMethods' +export type { + AutoReloadPreview, + AutoReloadSettings, + AutoTopUpCommandOptions, + AutoTopUpCommandResult, + AutoTopUpReadOptions, + AutoTopUpReader, + AutoTopUpReaderOptions, + AutoTopUpScope, + AutoTopUpSnapshot, + PreviewAutoTopUpQuery, + SaveAutoTopUpInput +} from './autoTopUp' +export { + AUTO_TOP_UP_PREVIEW_ROUTE, + AUTO_TOP_UP_ROUTE, + createAutoTopUpReader, + previewAutoTopUp, + saveAutoTopUp +} from './autoTopUp' export type { BillingStatusData, BillingStatusReader, diff --git a/packages/account-core/src/core/billing/scopedReader.test.ts b/packages/account-core/src/core/billing/scopedReader.test.ts index 11e557d9cee..3a5aac6c776 100644 --- a/packages/account-core/src/core/billing/scopedReader.test.ts +++ b/packages/account-core/src/core/billing/scopedReader.test.ts @@ -14,6 +14,7 @@ import type { } from './billingContracts' import type { BillingScopeSource } from './billingScope' import { sessionBillingScopeSource } from './billingScope' +import { createAutoTopUpReader } from './autoTopUp' import { createCapabilitiesReader } from './capabilities' import { createCreditsReader } from './credits' import { createBillingEventsReader } from './events' @@ -111,6 +112,31 @@ const PLAN = { tier: 'CREATOR' } +const AUTO_TOP_UP_OFF = { + card_expiry: null, + configured: false, + cycle_resets_at: null, + declined_payment_method: null, + disabled_reason: null, + enabled: false, + last_failure_at: null, + last_failure_reason: null, + max_monthly_budget_cents: 100_000, + max_reload_credits: null, + min_reload_credits: 500, + monthly_budget_cents: null, + monthly_budget_is_default: true, + paused_by_budget: false, + paused_by_budget_remainder: false, + paused_by_decline: false, + reload_amount_cents: null, + reload_credits: null, + spent_this_cycle_cents: 0, + status: 'off', + target_credits: null, + threshold_credits: null +} + const CATALOG = { current_plan_slug: 'free', plans: [PLAN] } const EVENTS_PAGE = { @@ -245,6 +271,13 @@ const CASES: readonly ReaderCase[] = [ paced: false, create: (options) => alwaysRequests(createBillingEventsReader(options)) }, + { + name: 'auto top-up', + body: AUTO_TOP_UP_OFF, + malformedBody: { ...AUTO_TOP_UP_OFF, status: 'paused' }, + paced: false, + create: (options) => alwaysRequests(createAutoTopUpReader(options)) + }, { name: 'capabilities', body: capabilitiesBody(), diff --git a/packages/account-core/src/core/billing/transport.test.ts b/packages/account-core/src/core/billing/transport.test.ts index 1ea69f1fa15..31fdbe36a42 100644 --- a/packages/account-core/src/core/billing/transport.test.ts +++ b/packages/account-core/src/core/billing/transport.test.ts @@ -376,20 +376,42 @@ describe('createSessionBillingTransport', () => { } ) - it('never replays a write the backend cannot deduplicate', async () => { - const { transport, fetchImpl, remint } = makeTransport({ + it.for(['POST', 'PUT'] as const)( + 'never replays a %s the backend cannot deduplicate', + async (method) => { + const { transport, fetchImpl, remint } = makeTransport({ + remint: { status: 'ok', session: credential({ token: 'fresh-jwt' }) }, + responses: [jsonResponse(401, {})] + }) + + const result = await transport({ method, route: '/billing/topup' }) + + expect(remint).not.toHaveBeenCalled() + expect(fetchImpl).toHaveBeenCalledTimes(1) + expect(result).toMatchObject({ + status: 'ok', + value: { httpStatus: 401, authenticationRetrySkipped: true } + }) + } + ) + + it('replays a PUT that carries an idempotency key', async () => { + const { transport, fetchImpl } = makeTransport({ remint: { status: 'ok', session: credential({ token: 'fresh-jwt' }) }, - responses: [jsonResponse(401, {})] + responses: [jsonResponse(401, {}), jsonResponse(200, { enabled: true })] }) - const result = await transport({ method: 'POST', route: '/billing/topup' }) - - expect(remint).not.toHaveBeenCalled() - expect(fetchImpl).toHaveBeenCalledTimes(1) - expect(result).toMatchObject({ - status: 'ok', - value: { httpStatus: 401, authenticationRetrySkipped: true } + const result = await transport({ + method: 'PUT', + route: '/billing/auto-reload', + body: { enabled: true }, + idempotencyKey: 'key-1' }) + + expect(fetchImpl).toHaveBeenCalledTimes(2) + expect(fetchImpl.mock.calls[1]?.[1]?.method).toBe('PUT') + expect(fetchImpl.mock.calls[1]?.[1]?.body).toBe('{"enabled":true}') + expect(result).toMatchObject({ status: 'ok', value: { httpStatus: 200 } }) }) it('replays a write that carries an idempotency key', async () => { @@ -652,19 +674,23 @@ describe('createCredentialedBillingTransport', () => { } ) - it('forwards a write body and the key the backend deduplicates it by', async () => { - const { transport, fetchImpl } = makeTransport() + it.for(['POST', 'PUT'] as const)( + 'forwards a %s body and the key the backend deduplicates it by', + async (method) => { + const { transport, fetchImpl } = makeTransport() - await transport({ - method: 'POST', - route: '/billing/topup', - body: { amount_cents: 500 }, - idempotencyKey: 'key-1' - }) + await transport({ + method, + route: '/billing/topup', + body: { amount_cents: 500 }, + idempotencyKey: 'key-1' + }) - expect(fetchImpl.mock.calls[0]?.[1]?.body).toBe('{"amount_cents":500}') - expect(sentHeaders(fetchImpl).get('Idempotency-Key')).toBe('key-1') - }) + expect(fetchImpl.mock.calls[0]?.[1]?.method).toBe(method) + expect(fetchImpl.mock.calls[0]?.[1]?.body).toBe('{"amount_cents":500}') + expect(sentHeaders(fetchImpl).get('Idempotency-Key')).toBe('key-1') + } + ) it('reports NOT_AUTHENTICATED without sending a request when no scope is established', async () => { const { transport, fetchImpl } = makeTransport({ initialScope: undefined })