Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refactor(api): confirm Exchange billing from the billing worker (#4043)
Abimael Martell16d5e3915ce2
diff --git a/apps/api/src/lib/exchange.test.ts b/apps/api/src/lib/exchange.test.tsindex 416e2b627..6a4f0a69d 100644--- a/apps/api/src/lib/exchange.test.ts+++ b/apps/api/src/lib/exchange.test.ts@@ -550,11 +550,13 @@ describe("Exchange routing", () => {status: 200,} as Awaited<ReturnType<typeof fetch>>);- await reportExchangeBilling({- accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",- status: "confirmed",- billingReference: "bill-1",- });+ await expect(+ reportExchangeBilling({+ accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",+ status: "confirmed",+ billingReference: "bill-1",+ }),+ ).resolves.toBe(true);expect(fetch).toHaveBeenCalledWith("https://exchange.example/v1/access-events/6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60/billing",@@ -564,10 +566,12 @@ describe("Exchange routing", () => {}),);- await reportExchangeBilling({- accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",- status: "void",- });+ await expect(+ reportExchangeBilling({+ accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",+ status: "void",+ }),+ ).resolves.toBe(true);expect(fetch).toHaveBeenLastCalledWith("https://exchange.example/v1/access-events/6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60/billing",@@ -578,12 +582,84 @@ describe("Exchange routing", () => {);vi.mocked(fetch).mockRejectedValue(new Error("connect timeout"));- await expect(- reportExchangeBilling({+ vi.useFakeTimers();+ try {+ const report = reportExchangeBilling({accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",status: "confirmed",billingReference: "bill-1",+ });+ await vi.runAllTimersAsync();+ await expect(report).resolves.toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it("retries transient billing report failures and stops on definitive rejections", async () => {+ vi.mocked(fetch)+ .mockResolvedValueOnce({+ ok: false,+ status: 503,+ } as Awaited<ReturnType<typeof fetch>>)+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ } as Awaited<ReturnType<typeof fetch>>);++ vi.useFakeTimers();+ try {+ const report = reportExchangeBilling({+ accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",+ status: "confirmed",+ });+ await vi.runAllTimersAsync();+ await expect(report).resolves.toBe(true);+ } finally {+ vi.useRealTimers();+ }+ expect(fetch).toHaveBeenCalledTimes(2);++ // 429 is transient rate limiting, not a final answer: it retries.+ vi.mocked(fetch).mockClear();+ vi.mocked(fetch)+ .mockResolvedValueOnce({+ ok: false,+ status: 429,+ headers: new Headers({ "retry-after": "1" }),+ } as Awaited<ReturnType<typeof fetch>>)+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ } as Awaited<ReturnType<typeof fetch>>);++ vi.useFakeTimers();+ try {+ const report = reportExchangeBilling({+ accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",+ status: "confirmed",+ });+ await vi.runAllTimersAsync();+ await expect(report).resolves.toBe(true);+ } finally {+ vi.useRealTimers();+ }+ expect(fetch).toHaveBeenCalledTimes(2);++ // Any other 4xx is the Exchange's final answer (conflict, unknown+ // event): no retry, report failure to the caller.+ vi.mocked(fetch).mockClear();+ vi.mocked(fetch).mockResolvedValue({+ ok: false,+ status: 409,+ } as Awaited<ReturnType<typeof fetch>>);++ await expect(+ reportExchangeBilling({+ accessEventId: "6f1f5aab-3f78-4d0a-8a3d-2b1d3c4e5f60",+ status: "void",}),- ).resolves.toBeUndefined();+ ).resolves.toBe(false);+ expect(fetch).toHaveBeenCalledTimes(1);});});diff --git a/apps/api/src/lib/exchange.ts b/apps/api/src/lib/exchange.tsindex 9de05a473..c599e1e6f 100644--- a/apps/api/src/lib/exchange.ts+++ b/apps/api/src/lib/exchange.ts@@ -547,53 +547,119 @@ export function getExchangeSuccessCredits(input: {}const EXCHANGE_BILLING_TIMEOUT_MS = 5_000;+const EXCHANGE_BILLING_ATTEMPTS = 3;+const EXCHANGE_BILLING_RETRY_DELAY_MS = 2_000;+const EXCHANGE_BILLING_RETRY_MAX_DELAY_MS = 15_000;++// Retry-After from a 429, in milliseconds, when present and sane.+// Accepts both delta-seconds and HTTP-date forms.+function getRetryAfterMs(response: {+ headers?: { get?: (name: string) => string | null };+}): number | undefined {+ const header = response.headers?.get?.("retry-after");+ if (!header) {+ return undefined;+ }++ const seconds = Number(header);+ if (Number.isFinite(seconds)) {+ return seconds > 0 ? seconds * 1_000 : undefined;+ }++ const resetAt = Date.parse(header);+ if (Number.isNaN(resetAt)) {+ return undefined;+ }+ const delayMs = resetAt - Date.now();+ return delayMs > 0 ? delayMs : undefined;+}/*** Report the billing outcome of a delivered Exchange access so the service* can reconcile its ledger: "confirmed" once the customer was billed, "void"* when the delivered access was ultimately discarded and never billed.- * Failures only log - the service flags unresolved events for follow-up.+ * Retries transient failures with a short backoff; never throws. Returns+ * whether the report was accepted - a sustained failure leaves the event+ * pending on the Exchange, which flags unresolved events for follow-up.*/export async function reportExchangeBilling(input: {accessEventId: string;status: "confirmed" | "void";billingReference?: string;-}): Promise<void> {+}): Promise<boolean> {const baseUrl = getExchangeBaseUrl();if (!baseUrl) {- return;+ return false;}- try {- const response = await fetch(- `${baseUrl}/v1/access-events/${encodeURIComponent(input.accessEventId)}/billing`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({+ for (let attempt = 1; attempt <= EXCHANGE_BILLING_ATTEMPTS; attempt++) {+ let retryAfterMs: number | undefined;++ try {+ const response = await fetch(+ `${baseUrl}/v1/access-events/${encodeURIComponent(input.accessEventId)}/billing`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ status: input.status,+ ...(input.billingReference === undefined+ ? {}+ : { billingReference: input.billingReference }),+ }),+ signal: AbortSignal.timeout(EXCHANGE_BILLING_TIMEOUT_MS),+ },+ );++ if (response.ok) {+ return true;+ }++ // 4xx responses other than 429 are definitive (conflict, unknown+ // event) - the Exchange has spoken and a retry cannot change the+ // answer. 429 is transient rate limiting and retries.+ if (response.status < 500 && response.status !== 429) {+ rootLogger.warn("Exchange billing report rejected", {+ accessEventId: input.accessEventId,status: input.status,- ...(input.billingReference === undefined- ? {}- : { billingReference: input.billingReference }),- }),- signal: AbortSignal.timeout(EXCHANGE_BILLING_TIMEOUT_MS),- },- );+ statusCode: response.status,+ });+ return false;+ }++ if (response.status === 429) {+ retryAfterMs = getRetryAfterMs(response);+ }- if (!response.ok) {rootLogger.warn("Exchange billing report failed", {accessEventId: input.accessEventId,status: input.status,statusCode: response.status,+ attempt,+ });+ } catch (error) {+ rootLogger.warn("Exchange billing report errored", {+ accessEventId: input.accessEventId,+ status: input.status,+ attempt,+ error,});}- } catch (error) {- rootLogger.warn("Exchange billing report errored", {- accessEventId: input.accessEventId,- status: input.status,- error,- });++ if (attempt < EXCHANGE_BILLING_ATTEMPTS) {+ // Full jitter on the backoff so a batch of reports failing together+ // does not retry against a degraded Exchange in synchronized bursts.+ // Retry-After, when given, is the lower bound.+ const backoff = EXCHANGE_BILLING_RETRY_DELAY_MS * attempt;+ const delay = Math.min(+ Math.max(retryAfterMs ?? 0, Math.random() * backoff),+ EXCHANGE_BILLING_RETRY_MAX_DELAY_MS,+ );+ await new Promise(resolve => setTimeout(resolve, delay));+ }}++ return false;}/**diff --git a/apps/api/src/services/billing/batch_billing.ts b/apps/api/src/services/billing/batch_billing.tsindex d6a4f75df..f09c80175 100644--- a/apps/api/src/services/billing/batch_billing.ts+++ b/apps/api/src/services/billing/batch_billing.ts@@ -13,6 +13,71 @@ import {type BillingEndpoint,type BillingMetadata,} from "./types";+import { reportExchangeBilling } from "../../lib/exchange";++// Upper bound on concurrent Exchange confirmation requests across the+// whole worker, so slow or retrying deliveries from overlapping batch+// runs never stack into a burst against the Exchange.+const EXCHANGE_CONFIRM_CONCURRENCY = 16;+let exchangeConfirmSlots = EXCHANGE_CONFIRM_CONCURRENCY;+const exchangeConfirmWaiters: Array<() => void> = [];++async function withExchangeConfirmSlot<T>(fn: () => Promise<T>): Promise<T> {+ if (exchangeConfirmSlots > 0) {+ exchangeConfirmSlots--;+ } else {+ await new Promise<void>(resolve => exchangeConfirmWaiters.push(resolve));+ }+ try {+ return await fn();+ } finally {+ const next = exchangeConfirmWaiters.shift();+ if (next !== undefined) {+ next();+ } else {+ exchangeConfirmSlots++;+ }+ }+}++// Confirm the Exchange accesses behind a set of committed billing+// operations. Runs after the batch lock is released so an Exchange outage+// can never stall the billing loop past its lease. reportExchangeBilling+// retries internally and never throws; a sustained failure leaves the+// event pending on the Exchange, which flags unresolved events for+// reconciliation.+async function confirmExchangeOutcomes(+ operations: BillingOperation[],+): Promise<void> {+ // A small worker pool pulls operations one at a time, so a slow+ // Exchange queues at most EXCHANGE_CONFIRM_CONCURRENCY waiters per+ // invocation on the shared budget instead of one per operation.+ let nextIndex = 0;+ const workerCount = Math.min(+ EXCHANGE_CONFIRM_CONCURRENCY,+ operations.length,+ );+ await Promise.all(+ Array.from({ length: workerCount }, async () => {+ while (true) {+ const index = nextIndex++;+ if (index >= operations.length) {+ return;+ }+ const op = operations[index];+ await withExchangeConfirmSlot(() =>+ reportExchangeBilling({+ accessEventId: op.exchange_access_event_id!,+ status: "confirmed",+ ...(op.billing_reference === undefined+ ? {}+ : { billingReference: op.billing_reference }),+ }),+ );+ }+ }),+ );+}// Configuration constantsconst BATCH_KEY = "billing_batch";@@ -31,6 +96,11 @@ interface BillingOperation {timestamp: string;api_key_id: number | null;autumnTrackInRequest: boolean;+ // Exchange access backing this operation, if any: its ledger event is+ // confirmed once the debit commits. Failed or ambiguous commits leave+ // the event pending for reconciliation rather than voiding it.+ exchange_access_event_id?: string;+ billing_reference?: string;}// Grouped billing operations for batch processing@@ -109,6 +179,10 @@ export async function processBillingBatch() {return;}+ // Exchange operations whose debit committed this run; their ledger+ // confirmations are delivered after the lock is released.+ const committedExchangeOps: BillingOperation[] = [];+try {// Get all operations from Redis listconst operations: BillingOperation[] = [];@@ -188,6 +262,11 @@ export async function processBillingBatch() {if (!billingResult.success) {await refundRequestTrackedCredits(group);+ // Deliberately no Exchange outcome here: supaBillTeam maps thrown+ // errors to success: false, and a transport error can occur after+ // the debit committed, so voiding could erase a real debit. The+ // events stay pending on the Exchange, which flags unresolved+ // events for reconciliation.logger.warn(`β οΈ Billing returned success: false for team ${group.team_id}`,{@@ -204,8 +283,18 @@ export async function processBillingBatch() {);// Ledger commit only β usage is tracked to Autumn at request time, not here.++ // The debit is committed: confirm the Exchange accesses it covered+ // once the batch lock is released.+ committedExchangeOps.push(+ ...group.operations.filter(+ op => op.exchange_access_event_id !== undefined,+ ),+ );} catch (error) {await refundRequestTrackedCredits(group);+ // No Exchange outcome here either β same ambiguity as the+ // success: false branch above; the events stay pending.logger.error(`β Failed to bill team ${group.team_id}`, {error,group,@@ -231,6 +320,8 @@ export async function processBillingBatch() {} finally {await releaseLock();}++ await confirmExchangeOutcomes(committedExchangeOps);}// Start periodic batch processing@@ -262,6 +353,7 @@ export async function queueBillingOperation(billing: BillingMetadata,is_extract: boolean = false,autumnTrackInRequest: boolean = false,+ exchange?: { accessEventId: string; billingReference?: string },) {// Skip queuing for preview teamsif (team_id === "preview" || team_id.startsWith("preview_")) {@@ -285,6 +377,14 @@ export async function queueBillingOperation(timestamp: new Date().toISOString(),api_key_id,autumnTrackInRequest,+ ...(exchange === undefined+ ? {}+ : {+ exchange_access_event_id: exchange.accessEventId,+ ...(exchange.billingReference === undefined+ ? {}+ : { billing_reference: exchange.billingReference }),+ }),};// Add operation to Redis listdiff --git a/apps/api/src/services/indexing/index-worker.ts b/apps/api/src/services/indexing/index-worker.tsindex 9656c9421..cd671fd62 100644--- a/apps/api/src/services/indexing/index-worker.ts+++ b/apps/api/src/services/indexing/index-worker.ts@@ -88,6 +88,7 @@ const processBillingJobInternal = async (token: string, job: Job) => {is_extract,api_key_id,autumnTrackInRequest,+ exchangeAccessEventId,} = job.data;logger.info(`Adding team ${team_id} billing operation to batch queue`, {@@ -107,6 +108,13 @@ const processBillingJobInternal = async (token: string, job: Job) => {}),is_extract,autumnTrackInRequest,+ typeof exchangeAccessEventId === "string" &&+ exchangeAccessEventId.length > 0+ ? {+ accessEventId: exchangeAccessEventId,+ billingReference: String(job.id),+ }+ : undefined,);} else {logger.warn(`Unknown billing job type: ${job.name}`);diff --git a/apps/api/src/services/worker/scrape-worker.ts b/apps/api/src/services/worker/scrape-worker.tsindex 41d0b7b20..ac40ba261 100644--- a/apps/api/src/services/worker/scrape-worker.ts+++ b/apps/api/src/services/worker/scrape-worker.ts@@ -185,7 +185,10 @@ async function billScrapeJob(},);- // Add directly to the billing queue - the billing worker will handle the rest+ // Add directly to the billing queue - the billing worker will handle+ // the rest, including confirming the Exchange access event once the+ // debit actually commits. A failed commit leaves the event pending+ // for reconciliation - it is never voided on an ambiguous outcome.await getBillingQueue().add("bill_team",{@@ -197,6 +200,9 @@ async function billScrapeJob(originating_job_id: job.id,api_key_id: job.data.apiKeyId,autumnTrackInRequest: trackedInRequest,+ ...(exchange?.accessEventId === undefined+ ? {}+ : { exchangeAccessEventId: exchange.accessEventId }),},{jobId: billingJobId,@@ -204,18 +210,6 @@ async function billScrapeJob(},);- // Reconcile the Exchange ledger. Awaited so the confirmation lands- // before any later failure path could attempt to void this access -- // the service rejects confirmed->void, making the order decisive.- // reportExchangeBilling never throws and is bounded by its timeout.- if (exchange?.accessEventId !== undefined) {- await reportExchangeBilling({- accessEventId: exchange.accessEventId,- status: "confirmed",- billingReference: billingJobId,- });- }-return creditsToBeBilled;} catch (error) {logger.error(@@ -230,6 +224,18 @@ async function billScrapeJob(featureId,});}+ // The billing operation never reached the queue, so no debit will+ // commit and no confirmation will ever arrive: void the Exchange+ // access event instead of leaving it dangling. If the enqueue+ // actually succeeded and only the acknowledgement was lost, the+ // eventual confirmation repairs the void (void -> confirmed is+ // legal on the Exchange). Fire-and-forget.+ if (exchange?.accessEventId !== undefined) {+ void reportExchangeBilling({+ accessEventId: exchange.accessEventId,+ status: "void",+ });+ }captureExceptionWithZdrCheck(error, {extra: { zeroDataRetention: job.data.zeroDataRetention ?? false },});@@ -982,10 +988,11 @@ async function processJob(job: NuQJob<ScrapeJobSingleUrls>) {// The Exchange delivered this access but the scrape ultimately failed,// so the customer was never billed for it - void the access event so- // the Exchange ledger reconciles. Fire-and-forget. If billing did- // happen before a later step failed, its confirmation was awaited- // above and the service rejects confirmed->void, so a paid access can- // never be marked void.+ // the Exchange ledger reconciles. Fire-and-forget. If billing was in+ // fact queued before a later step failed, the billing worker's+ // confirmation authoritatively repairs this void (void -> confirmed is+ // legal on the Exchange; confirmed -> void is not), so a paid access+ // can never end up voided.if (pipeline?.success && pipeline.exchange?.accessEventId !== undefined) {void reportExchangeBilling({accessEventId: pipeline.exchange.accessEventId,