Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Bill each rank check batch with one Autumn hold and one settle (EVE-322) (#696)
Carter Smith246a2ae26969
diff --git a/docs/maintainers/specs/0002-hosted-dataforseo-metering-with-autumn.md b/docs/maintainers/specs/0002-hosted-dataforseo-metering-with-autumn.mdindex b2b1ea85..bb9fda21 100644--- a/docs/maintainers/specs/0002-hosted-dataforseo-metering-with-autumn.md+++ b/docs/maintainers/specs/0002-hosted-dataforseo-metering-with-autumn.md@@ -2,7 +2,7 @@## Status-Accepted. Revised when the pre-call balance check became an atomic credit hold.+Accepted. Revised when the pre-call balance check became an atomic credit hold, and again when live rank check batches began to share holds.## Context@@ -31,6 +31,8 @@ In hosted mode, every metered call:Estimate and deduction use one formula (`creditsForProviderUsd`), so they cannot drift apart. A hold that is never settled expires on its own and returns the credits.+A live rank check batch shares its holds instead of taking one per call. It takes at most one hold on each balance, and each call goes where a hold of its own would go: in order, on `usage_credits` while they cover it, else on `topup_credits`, else that call alone is refused. Each hold is settled once, with only its own calls. Every call is still converted to credits on its own, so a batch costs exactly what the same calls would cost one at a time.+In non-hosted mode, the client skips Autumn and executes the DataForSEO call directly.Raw fetch helpers remain low-level transport and parsing functions. They are not the application entry point for hosted features.@@ -41,7 +43,7 @@ This makes the metered path the easiest path. Feature code asks for DataForSEO dConcurrent calls each take their own hold and do not wait on each other, so normal parallel work is unchanged. The sum of in-flight holds can never exceed the balance, so an organization can spend at most its balance plus any amount by which an estimate undershoots the real cost. An undershoot is reported so the price table can be corrected.-A hold costs two Autumn round trips per call (hold, finalize), which is no more than the balance reads and usage tracking it replaces.+A hold costs two Autumn round trips (hold, finalize), which is no more than the balance reads and usage tracking it replaces. A live rank check batch shares its holds because it starts many calls for one organization at once: a hold and a finalize for each call sent dozens of concurrent Autumn requests for one customer, and a finalize that times out loses its charge.## Alternatives considereddiff --git a/src/server/billing/subscription.test.ts b/src/server/billing/subscription.test.tsindex d0466fac..dd333fdf 100644--- a/src/server/billing/subscription.test.ts+++ b/src/server/billing/subscription.test.ts@@ -206,10 +206,12 @@ describe("reserveUsageCredits", () => {: { allowed: true, balance: { remaining: 900 } },);- const hold = await reserveUsageCredits({+ const {+ holds: [hold],+ } = await reserveUsageCredits({customer,customerId: "org_123",- estimatedCredits: 100,+ callCredits: [100],creditFeature: "backlinks",});@@ -228,6 +230,73 @@ describe("reserveUsageCredits", () => {expect(topupCall.lock?.expiresAt).toBeGreaterThan(Date.now() + 29 * 60_000);});+ it("places each call where its own hold would land: monthly first, else top-up, else refused", async () => {+ // Monthly 3, top-up 20; calls of 7, 3 and 30 credits. Per call: the 7+ // misses monthly and lands on top-up, the 3 fits monthly, the 30 fits+ // neither. Top-up alone could cover 7 + 3 but must not take the 3.+ const remaining = { monthly: 3, topup: 20 };+ checkMock.mockImplementation(async ({ featureId, requiredBalance = 1 }) => {+ const balance =+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ ? remaining.monthly+ : remaining.topup;+ return {+ allowed: balance >= requiredBalance,+ balance: { remaining: balance },+ };+ });++ const reserved = await reserveUsageCredits({+ customer,+ customerId: "org_123",+ callCredits: [7, 3, 30],+ });++ expect(reserved).toMatchObject({+ holds: [+ {+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ estimatedCredits: 3,+ callIndexes: [1],+ },+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ estimatedCredits: 7,+ callIndexes: [0],+ },+ ],+ refusedCalls: [2],+ });+ expect(vi.mocked(captureServerEvent).mock.calls[0][0]).toMatchObject({+ event: "usage:credits_gate_refused",+ properties: { estimated_credits: 30 },+ });+ });++ it("releases an earlier hold when a later one fails", async () => {+ checkMock.mockImplementation(async ({ featureId, requiredBalance = 1 }) => {+ if (featureId !== AUTUMN_SEO_DATA_BALANCE_FEATURE_ID) {+ throw new Error("socket hang up");+ }+ return { allowed: requiredBalance <= 3, balance: { remaining: 3 } };+ });+ finalizeMock.mockResolvedValue({ success: true });++ await expect(+ reserveUsageCredits({+ customer,+ customerId: "org_123",+ callCredits: [3, 3],+ }),+ ).rejects.toThrow("socket hang up");++ const monthlyHold = checkMock.mock.calls[1][0];+ expect(monthlyHold.requiredBalance).toBe(3);+ expect(finalizeMock.mock.calls.map(([arg]) => arg)).toMatchObject([+ { lockId: monthlyHold.lock?.lockId, action: "release" },+ ]);+ });+it("refuses when neither pool covers the estimate and reports it", async () => {// An org that never topped up reads allowed:false + balance:null on// topup_credits: a refusal, not a broken read.@@ -241,7 +310,7 @@ describe("reserveUsageCredits", () => {reserveUsageCredits({customer,customerId: "org_123",- estimatedCredits: 100,+ callCredits: [100],creditFeature: "backlinks",}),).rejects.toMatchObject({ code: "INSUFFICIENT_CREDITS" });@@ -264,7 +333,7 @@ describe("reserveUsageCredits", () => {const result = reserveUsageCredits({customer,customerId: "org_123",- estimatedCredits: 100,+ callCredits: [100],});const assertion = expect(result).rejects.toMatchObject({code: "INTERNAL_ERROR",@@ -296,13 +365,17 @@ describe("reserveUsageCredits", () => {const result = reserveUsageCredits({customer,customerId: "org_123",- estimatedCredits: 100,+ callCredits: [100],});await vi.runAllTimersAsync();await expect(result).resolves.toMatchObject({- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- lockId: checkMock.mock.calls[0][0].lock?.lockId,+ holds: [+ {+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ lockId: checkMock.mock.calls[0][0].lock?.lockId,+ },+ ],});expect(checkMock).toHaveBeenCalledTimes(2);});@@ -313,6 +386,7 @@ describe("settleUsageCredits", () => {lockId: "dfs_org_123_lock",featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,estimatedCredits: 100,+ callIndexes: [0],} as const;const cost = { costUsd: 0.05, path: ["v3", "backlinks", "summary", "live"] };@@ -323,7 +397,7 @@ describe("settleUsageCredits", () => {it("releases the hold when nothing was billed", async () => {finalizeMock.mockResolvedValue({ success: true });- await settleUsageCredits({ customer, hold, cost: null });+ await settleUsageCredits({ customer, hold, costs: [] });expect(finalizeMock).toHaveBeenCalledTimes(1);expect(finalizeMock.mock.calls[0][0]).toMatchObject({@@ -349,7 +423,7 @@ describe("settleUsageCredits", () => {customer,hold,creditFeature: "backlinks",- cost,+ costs: [cost],});await vi.runAllTimersAsync();@@ -368,7 +442,7 @@ describe("settleUsageCredits", () => {customer,hold,creditFeature: "backlinks",- cost,+ costs: [cost],});await vi.runAllTimersAsync();diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.tsindex f4b00f1c..2457da13 100644--- a/src/server/billing/subscription.ts+++ b/src/server/billing/subscription.ts@@ -1,3 +1,4 @@+/* eslint-disable max-lines -- the org billing seam: customer lookup, credit gates, and credit holds with their settlement */import { env } from "cloudflare:workers";import type { EnsuredUserContext } from "@/middleware/ensure-user/types";import {@@ -216,6 +217,8 @@ type UsageCreditHold = {lockId: string;featureId: UsageCreditFeatureId;estimatedCredits: number;+ /** Indexes of the reserved provider calls this hold covers. */+ callIndexes: readonly number[];};/**@@ -238,10 +241,16 @@ async function holdCredits(customerId: string,featureId: UsageCreditFeatureId,estimatedCredits: number,+ callIndexes: readonly number[],properties: Record<string, unknown>,) {const lockId = `dfs_${customerId}_${crypto.randomUUID()}`;- const hold: UsageCreditHold = { lockId, featureId, estimatedCredits };+ const hold: UsageCreditHold = {+ lockId,+ featureId,+ estimatedCredits,+ callIndexes,+ };const attempt = () =>autumn.check({@@ -276,56 +285,121 @@ async function holdCredits(}/**- * Reserves the estimated credits for one provider call before it is made:- * monthly `usage_credits` first, else the whole estimate on `topup_credits`.- * Throws INSUFFICIENT_CREDITS (and emits the refusal event) when neither- * covers it. The caller must settle the returned hold with- * `settleUsageCredits` once the call's real cost is known.+ * Reserves credits for a batch of provider calls before they are made, from+ * one estimate per call, and places each call where a hold of its own would+ * land: in order, on monthly `usage_credits` while they cover it, else on+ * `topup_credits`, else the call is refused. At most one hold per pool, so+ * the common case (monthly covers the batch) is a single Autumn request.+ *+ * Throws INSUFFICIENT_CREDITS when no call fits; `refusedCalls` lists the+ * ones that did not when some did. Either way the refusal event is emitted.+ * The caller must settle every returned hold with `settleUsageCredits` once+ * its calls' real cost is known.*/export async function reserveUsageCredits(args: {customer: BillingCustomerContext;customerId: string;- estimatedCredits: number;+ callCredits: number[];creditFeature?: CreditFeature;-}): Promise<UsageCreditHold> {- const estimatedCredits = Math.max(1, args.estimatedCredits);+}): Promise<{ holds: UsageCreditHold[]; refusedCalls: number[] }> {+ const callCredits = args.callCredits.map((credits) => Math.max(1, credits));+ const allCalls = callCredits.map((_, index) => index);+ const creditsFor = (calls: number[]) =>+ calls.reduce((sum, index) => sum + callCredits[index], 0);const properties = {creditFeature: args.creditFeature,provider: "dataforseo",- estimatedCredits,+ estimatedCredits: creditsFor(allCalls),+ };+ // Holds `featureId` for the calls, in order, that fit `remaining`; null+ // when none does. A refusal here means the balance moved since the read.+ const holdFitting = async (+ featureId: UsageCreditFeatureId,+ calls: number[],+ remaining = Infinity,+ ) => {+ const fitting: number[] = [];+ let credits = 0;+ for (const index of calls) {+ if (credits + callCredits[index] > remaining) continue;+ fitting.push(index);+ credits += callCredits[index];+ }+ if (fitting.length === 0) return null;+ return holdCredits(+ args.customerId,+ featureId,+ credits,+ fitting,+ properties,+ );};- const monthly = await holdCredits(- args.customerId,- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- estimatedCredits,- properties,- );- if (monthly.allowed) return monthly.hold;+ const holds: UsageCreditHold[] = [];+ let monthlyRemaining = 0;+ let topupRemaining = 0;+ let refusedCalls: number[] = [];+ try {+ const monthly = await holdFitting(+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ allCalls,+ );+ if (monthly?.allowed) return { holds: [monthly.hold], refusedCalls };+ monthlyRemaining = monthly?.balance?.remaining ?? 0;- const topup = await holdCredits(- args.customerId,- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- estimatedCredits,- properties,- );- if (topup.allowed) return topup.hold;+ const partial = await holdFitting(+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ allCalls,+ monthlyRemaining,+ );+ if (partial?.allowed) holds.push(partial.hold);+ const topupCalls = allCalls.filter(+ (index) => !holds.some((hold) => hold.callIndexes.includes(index)),+ );- await captureServerEvent({- distinctId: args.customer.userId,- event: "usage:credits_gate_refused",- organizationId: args.customer.organizationId,- properties: {- project_id: args.customer.projectId,- reason: "estimate_exceeds_balance",- source: "dataforseo",- credit_feature: args.creditFeature,- estimated_credits: estimatedCredits,- monthly_remaining: monthly.balance?.remaining ?? 0,- topup_remaining: topup.balance?.remaining ?? 0,- },- });- throw new AppError("INSUFFICIENT_CREDITS");+ let topup = await holdFitting(+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ topupCalls,+ );+ if (topup && !topup.allowed) {+ topupRemaining = topup.balance?.remaining ?? 0;+ topup = await holdFitting(+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ topupCalls,+ topupRemaining,+ );+ }+ if (topup?.allowed) holds.push(topup.hold);+ refusedCalls = allCalls.filter(+ (index) => !holds.some((hold) => hold.callIndexes.includes(index)),+ );+ } catch (error) {+ // A later hold failed after earlier ones landed: release those rather+ // than strand their credits until the hold TTL.+ for (const hold of holds) {+ await settleUsageCredits({ customer: args.customer, hold, costs: [] });+ }+ throw error;+ }++ if (refusedCalls.length > 0) {+ await captureServerEvent({+ distinctId: args.customer.userId,+ event: "usage:credits_gate_refused",+ organizationId: args.customer.organizationId,+ properties: {+ project_id: args.customer.projectId,+ reason: "estimate_exceeds_balance",+ source: "dataforseo",+ credit_feature: args.creditFeature,+ estimated_credits: creditsFor(refusedCalls),+ monthly_remaining: monthlyRemaining,+ topup_remaining: topupRemaining,+ },+ });+ }+ if (holds.length === 0) throw new AppError("INSUFFICIENT_CREDITS");+ return { holds, refusedCalls };}// The SDK throws 4xx responses with the raw response body attached. Autumn@@ -344,7 +418,9 @@ function errorBodyIncludes(error: unknown, text: string) {/*** Settles a hold on the provider's real cost: confirms the deduction at the* actual credits (Autumn deducts the override, above or below the hold, and- * returns the rest) or releases the hold when nothing was billed. Never+ * returns the rest) or releases the hold when nothing was billed. A hold can+ * cover several provider calls; each is credited separately, so a batch is+ * charged exactly what the same calls would cost one by one. Never* throws: the customer already has the data, so a finalize that still fails* after one retry is logged with everything needed to reconcile it and the* hold expires at its TTL.@@ -354,13 +430,17 @@ export async function settleUsageCredits(args: {hold: UsageCreditHold;/** Resolved from the billed path by the caller; unknown for an unbilled call. */creditFeature?: CreditFeature;- /** Billed provider cost, or null when the call was not charged. */- cost: { costUsd: number; path: string[] } | null;+ /** Billed provider calls under this hold; empty when none was charged. */+ costs: Array<{ costUsd: number; path: string[] }>;}): Promise<void> {- const { customer, hold, creditFeature, cost } = args;- const actualCredits = cost ? creditsForProviderUsd(cost.costUsd) : 0;- const totalCostUsd = cost ? applyBillingMarkupUsd(cost.costUsd) : 0;- const paths = cost ? [cost.path.join("/")] : [];+ const { customer, hold, creditFeature, costs } = args;+ let actualCredits = 0;+ let totalCostUsd = 0;+ for (const cost of costs) {+ actualCredits += creditsForProviderUsd(cost.costUsd);+ totalCostUsd += applyBillingMarkupUsd(cost.costUsd);+ }+ const paths = [...new Set(costs.map((cost) => cost.path.join("/")))];// No SDK-level 5xx retry (AUTUMN_TRACK_RETRY_OPTIONS): this loop owns// the retry so a "Lock not found" can only be seen on our second attempt.diff --git a/src/server/lib/dataforseo/client.test.ts b/src/server/lib/dataforseo/client.test.tsindex eb317506..7149dca3 100644--- a/src/server/lib/dataforseo/client.test.ts+++ b/src/server/lib/dataforseo/client.test.ts@@ -2,6 +2,7 @@import { describe, expect, it, vi } from "vitest";import {AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,creditsForProviderUsd,} from "@/shared/billing";@@ -131,6 +132,7 @@ import { dataforseoPricing } from "@/server/lib/dataforseo/pricing";import { DataforseoChargedTaskError } from "@/server/lib/dataforseo/envelope";import { AppError } from "@/server/lib/errors";import { fetchBacklinksSummary } from "@/server/lib/dataforseo/backlinks";+import { fetchRankCheckSerp } from "@/server/lib/dataforseo/serp";const billingCustomer = {organizationId: "org_123",@@ -287,6 +289,110 @@ describe("meterDataforseoCall", () => {});});+describe("rankCheckBatch", () => {+ const input = {+ keyword: "running shoes",+ keywordId: "kw_1",+ locationCode: 2840,+ languageCode: "en",+ device: "desktop" as const,+ targetDomain: "example.com",+ depth: 10,+ };+ const callEstimate = creditsForProviderUsd(+ dataforseoPricing.serp.rankCheck(input),+ );+ // 2 * ceil(1.28) = 4 credits for two calls, not ceil(2.56) = 3 for their+ // summed cost: each call is credited as it would be unbatched.+ const billed = {+ data: {+ keywordId: "kw_1",+ keyword: "running shoes",+ position: 3,+ url: null,+ serpFeatures: [],+ },+ billing: {+ costUsd: 0.001,+ path: ["v3", "serp", "google", "organic", "live", "advanced"],+ },+ };++ it("bills the batch with one hold on the summed estimate and one confirm on the billed calls", async () => {+ setupHostedMode();+ mockMonthlyBalance(5000);+ vi.mocked(fetchRankCheckSerp)+ .mockResolvedValueOnce(billed)+ .mockRejectedValueOnce(+ new AppError("UPSTREAM_UNAVAILABLE", "DataForSEO timed out"),+ )+ .mockResolvedValueOnce(billed);++ const client = createDataforseoClient(billingCustomer);+ const settled = await client.serp.rankCheckBatch([input, input, input]);++ expect(settled.map((outcome) => outcome.status)).toEqual([+ "fulfilled",+ "rejected",+ "fulfilled",+ ]);+ expect(checkMock).toHaveBeenCalledTimes(1);+ expect(checkMock.mock.calls[0][0]).toMatchObject({+ requiredBalance: 3 * callEstimate,+ });+ expect(finalizeMock).toHaveBeenCalledTimes(1);+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({+ action: "confirm",+ overrideValue: 2 * creditsForProviderUsd(0.001),+ });+ });++ it("splits a batch across monthly and top-up when only both together cover it", async () => {+ setupHostedMode();+ // Monthly covers two calls, top-up one: neither covers all three.+ checkMock.mockImplementation(async (args) => {+ const balance =+ args.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ ? 2 * callEstimate+ : callEstimate;+ return {+ allowed: balance >= (args.requiredBalance ?? 1),+ balance: { remaining: balance },+ };+ });+ vi.mocked(fetchRankCheckSerp).mockResolvedValue(billed);++ const client = createDataforseoClient(billingCustomer);+ const settled = await client.serp.rankCheckBatch([input, input, input]);++ expect(settled.every((outcome) => outcome.status === "fulfilled")).toBe(+ true,+ );+ // After the refused whole-batch monthly hold.+ const [monthlyHold, topupHold] = checkMock.mock.calls+ .slice(1)+ .map(([arg]) => arg);+ expect(monthlyHold).toMatchObject({+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ requiredBalance: 2 * callEstimate,+ });+ expect(topupHold).toMatchObject({+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ requiredBalance: callEstimate,+ });+ expect(finalizeMock.mock.calls.map(([arg]) => arg)).toMatchObject([+ {+ lockId: monthlyHold.lock?.lockId,+ overrideValue: 2 * creditsForProviderUsd(0.001),+ },+ {+ lockId: topupHold.lock?.lockId,+ overrideValue: creditsForProviderUsd(0.001),+ },+ ]);+ });+});+describe("mapDataforseoPathToCreditFeature", () => {it.each([["v3/dataforseo_labs/google/related_keywords/live", "keyword_research"],diff --git a/src/server/lib/dataforseo/client.ts b/src/server/lib/dataforseo/client.tsindex 24d2b9b8..10c90508 100644--- a/src/server/lib/dataforseo/client.ts+++ b/src/server/lib/dataforseo/client.ts@@ -202,12 +202,17 @@ export function createDataforseoClient(customer: BillingCustomerContext) {},serp: {live: meter(customer, fetchLiveSerp, dataforseoPricing.serp.live),- rankCheck: meter(- customer,- fetchRankCheckSerp,- dataforseoPricing.serp.rankCheck,- "rank_tracking",- ),+ // A rank check batch shares one credit hold and one settle across its+ // live calls (see meterDataforseoCalls). Resolves per call, in order.+ rankCheckBatch: (inputs: Parameters<typeof fetchRankCheckSerp>[0][]) =>+ meterDataforseoCalls(+ customer,+ inputs.map((input) => () => fetchRankCheckSerp(input)),+ inputs.map((input) =>+ creditsForProviderUsd(dataforseoPricing.serp.rankCheck(input)),+ ),+ "rank_tracking",+ ),// Posts up to 100 queued rank check tasks; one metered charge covers the// whole batch (DataForSEO bills task_post at post time, collection is// free).@@ -279,68 +284,88 @@ export function createDataforseoClient(customer: BillingCustomerContext) {/*** The one seam every DataForSEO charge passes through (hosted mode only).- * Order: reserve the estimate on the org's credits -> provider call -> settle- * the hold on the real cost. The hold is atomic in Autumn, so concurrent+ * Order: reserve the estimate on the org's credits -> provider calls -> settle+ * the hold on their real cost. The hold is atomic in Autumn, so concurrent* calls cannot all pass on one stale balance reading.+ *+ * A batch of calls shares one hold and one settle per credit pool it draws+ * on, with each call placed and refused as its own hold would be (see+ * reserveUsageCredits): holding and settling per call sent up to 40 Autumn+ * requests per rank check batch, and enough of them hit the SDK's timeout to+ * drop charges.*/-async function meterDataforseoCall<T>(+async function meterDataforseoCalls<T>(customer: BillingCustomerContext,- execute: () => Promise<DataforseoApiResponse<T>>,- estimatedCredits: number,+ executes: Array<() => Promise<DataforseoApiResponse<T>>>,+ callCredits: number[],creditFeature?: CreditFeature,-): Promise<T> {+): Promise<PromiseSettledResult<T>[]> {+ if (executes.length === 0) return [];const isHostedMode = await isHostedServerAuthMode();if (!isHostedMode) {- const result = await execute();- return result.data;+ return Promise.allSettled(+ executes.map(async (execute) => (await execute()).data),+ );}const billingCustomer = await getOrCreateOrganizationCustomer(customer);- const hold = await reserveUsageCredits({+ const { holds, refusedCalls } = await reserveUsageCredits({customer,customerId: billingCustomer.id,- estimatedCredits,+ callCredits,creditFeature,});- const settle = (cost: DataforseoApiCallCost | null) =>- settleUsageCredits({- customer,- hold,- creditFeature:- creditFeature ??- (cost ? mapDataforseoPathToCreditFeature(cost.path) : undefined),- cost,- });-const work = (async () => {- let result: DataforseoApiResponse<T>;- try {- result = await execute();- } catch (error) {- if (!(error instanceof DataforseoChargedTaskError)) {- // Transport / auth / upstream failure: nothing was billed.- await settle(null);- throw error;- }- // A malformed request (DataForSEO "Invalid Field: ...") that DataForSEO- // did not bill returns no value to the customer, so don't charge — surface- // it as a non-reportable VALIDATION_ERROR. If DataForSEO still billed us- // (costUsd > 0), settle on that cost so the spend stays metered and- // visible instead of silently eaten.- if (error.isInvalidField && error.billing.costUsd <= 0) {- await settle(null);- throw new AppError("VALIDATION_ERROR", error.message);- }- await settle(error.billing);- throw error;+ const billed: Array<DataforseoApiCallCost | null> = executes.map(+ () => null,+ );+ const settled = await Promise.allSettled(+ executes.map(async (execute, index) => {+ if (refusedCalls.includes(index)) {+ throw new AppError("INSUFFICIENT_CREDITS");+ }+ try {+ const result = await execute();+ billed[index] = result.billing;+ return result.data;+ } catch (error) {+ // Transport / auth / upstream failure: nothing was billed.+ if (!(error instanceof DataforseoChargedTaskError)) throw error;+ // A malformed request (DataForSEO "Invalid Field: ...") that+ // DataForSEO did not bill returns no value to the customer, so don't+ // charge — surface it as a non-reportable VALIDATION_ERROR. If+ // DataForSEO still billed us (costUsd > 0), charge that cost so the+ // spend stays metered and visible instead of silently eaten.+ if (error.isInvalidField && error.billing.costUsd <= 0) {+ throw new AppError("VALIDATION_ERROR", error.message);+ }+ billed[index] = error.billing;+ throw error;+ }+ }),+ );++ for (const hold of holds) {+ const costs = hold.callIndexes+ .map((index) => billed[index])+ .filter((cost) => cost !== null);+ await settleUsageCredits({+ customer,+ hold,+ creditFeature:+ creditFeature ??+ (costs.length > 0+ ? mapDataforseoPathToCreditFeature(costs[0].path)+ : undefined),+ costs,+ });}- await settle(result.billing);- return result.data;+ return settled;})();- // Register the call + settle with the request: workerd cancels pending I/O+ // Register the calls + settle with the request: workerd cancels pending I/O// once the client goes away, and a hold that never settles would let a// disconnect-after-dispatch skip the deduction. The rejection is handled by// the await below; the background handle only keeps the chain alive.@@ -351,3 +376,19 @@ async function meterDataforseoCall<T>(}return await work;}++async function meterDataforseoCall<T>(+ customer: BillingCustomerContext,+ execute: () => Promise<DataforseoApiResponse<T>>,+ estimatedCredits: number,+ creditFeature?: CreditFeature,+): Promise<T> {+ const [result] = await meterDataforseoCalls(+ customer,+ [execute],+ [estimatedCredits],+ creditFeature,+ );+ if (result.status === "rejected") throw result.reason;+ return result.value;+}diff --git a/src/server/workflows/rankCheckPaths.ts b/src/server/workflows/rankCheckPaths.tsindex 06f66c9f..abaee373 100644--- a/src/server/workflows/rankCheckPaths.ts+++ b/src/server/workflows/rankCheckPaths.ts@@ -77,34 +77,36 @@ function expandToTaskInputs(/*** Check keyword/device pairs against the live endpoint and persist snapshots.- * Per-call failures are logged and skipped (the metered client already charged- * or refused each call individually). Returns the snapshot count written.+ * The batch is billed with one credit hold and one settle. Per-call failures+ * are logged and skipped; if the hold itself fails, no call runs and every+ * pair fails with that error. Returns the snapshot count written.*/async function checkBatchLive(ctx: CheckContext,tasks: RankCheckTaskInput[],): Promise<number> {- const settled = await Promise.allSettled(- tasks.map((task) =>- ctx.client.serp- .rankCheck({- keyword: task.keyword,- keywordId: task.keywordId,- locationCode: ctx.locationCode,- languageCode: ctx.languageCode,- locationName: ctx.locationName,- device: task.device,- targetDomain: ctx.domain,- depth: ctx.serpDepth,- })- .then((r) => ({ ...r, device: task.device })),- ),- );+ let settled: PromiseSettledResult<RankCheckResult>[];+ try {+ settled = await ctx.client.serp.rankCheckBatch(+ tasks.map((task) => ({+ keyword: task.keyword,+ keywordId: task.keywordId,+ locationCode: ctx.locationCode,+ languageCode: ctx.languageCode,+ locationName: ctx.locationName,+ device: task.device,+ targetDomain: ctx.domain,+ depth: ctx.serpDepth,+ })),+ );+ } catch (error) {+ settled = tasks.map(() => ({ status: "rejected", reason: error }));+ }const results: RankCheckResultWithDevice[] = [];let firstError: string | null = null;settled.forEach((outcome, index) => {if (outcome.status === "fulfilled") {- results.push(outcome.value);+ results.push({ ...outcome.value, device: tasks[index].device });return;}const reason: unknown = outcome.reason;@@ -135,7 +137,7 @@ async function checkBatchLive(* Check keywords via Live API, parallel devices per keyword, real-time progress.* Snapshots are written incrementally after each batch so partial results* survive batch failures. ~6s per keyword batch.- * Billing is handled per-call by the metered client.+ * Each batch is billed with one credit hold and one settle (checkBatchLive).*/export async function runLiveCheck(step: WorkflowStep,@@ -286,7 +288,7 @@ export interface QueuedCheckStats {* ~15 minutes, writing snapshots incrementally as tasks complete. Anything* still unfinished after the polling window — plus tasks DataForSEO rejected* or failed — gets one shot at the live endpoint so a run never hangs on a- * stuck queue. Billing happens at task_post (and per live-fallback call).+ * stuck queue. Billing happens at task_post (and per live-fallback batch).*/export async function runQueuedCheck(step: WorkflowStep,