Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Stop concurrent requests from spending DataForSEO credits past the balance (#685)
Carter Smith6665fb3198cf
diff --git a/specs/0002-hosted-dataforseo-metering-with-autumn.md b/specs/0002-hosted-dataforseo-metering-with-autumn.mdindex a4c0ada5..b2b1ea85 100644--- a/specs/0002-hosted-dataforseo-metering-with-autumn.md+++ b/specs/0002-hosted-dataforseo-metering-with-autumn.md@@ -2,7 +2,7 @@## Status-Accepted+Accepted. Revised when the pre-call balance check became an atomic credit hold.## Context@@ -10,7 +10,7 @@ In hosted mode, OpenSEO uses platform-managed DataForSEO credentials and bills eThe low-level DataForSEO helpers can make live requests directly. If feature code imports them freely, it is easy to skip billing checks, forget usage tracking, or meter against estimated cost instead of the cost DataForSEO actually returned.-Autumn's billing model fits this flow: check access before the call, then track usage after the call succeeds.+The first version checked that the balance was above zero before the call and tracked the real cost after it. That check is not atomic: many concurrent requests all read the same positive balance and all pass, so an organization could spend far past its credits before any deduction landed.## Decision@@ -19,31 +19,42 @@ Hosted DataForSEO access must go through `createDataforseoClient`.We model hosted SEO data billing in Autumn as a credit system:- `base-plan` grants recurring `usage_credits`-- `credit-top-up` sells more `usage_credits`-- `seo_data_usage` is the metered feature DataForSEO calls consume+- `credit-top-up` sells `topup_credits`, spent after `usage_credits`- `1000` credits equals `$1`-In hosted mode, the client:+In hosted mode, every metered call:-- accepts `BillingCustomerContext`, not an Autumn customer ID-- resolves the Autumn customer from `organizationId`-- checks `seo_data_usage` before calling DataForSEO, using a small minimum balance guardrail-- executes a raw `fetch*Raw` helper that returns parsed data plus provider billing metadata-- tracks the actual reported DataForSEO cost in Autumn after the call succeeds+1. Estimates an upper bound for its cost from the request input. Each client entry requires an estimator from `pricing.ts`, so an entry without a price does not compile.+2. Holds that estimate on `usage_credits`, or on `topup_credits` when the monthly balance cannot cover it, with Autumn's balance lock. Autumn grants or refuses the hold atomically. When neither balance covers it, the call fails with `INSUFFICIENT_CREDITS` and DataForSEO is never called.+3. Calls DataForSEO.+4. Confirms the hold at the cost DataForSEO reported, or releases it when the call was not billed. The call and the settlement are registered with the request, so a client that disconnects mid-call cannot skip the deduction.++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.In non-hosted mode, the client skips Autumn and executes the DataForSEO call directly.-Raw `fetch*Raw` helpers remain low-level transport and parsing functions. They are not the application entry point for hosted features.+Raw fetch helpers remain low-level transport and parsing functions. They are not the application entry point for hosted features.## RationaleThis makes the metered path the easiest path. Feature code asks for DataForSEO data once and gets billing enforcement by default.-It also keeps billing aligned with provider-reported cost. We do not know the exact charge until DataForSEO responds, so the client does a preflight balance check and records the exact usage event afterwards.+Concurrent 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.++## Alternatives considered++- **Keep the balance check and add a per-organization rate limit.** Still check-then-act, so a burst inside the limit still overdraws. Cloudflare's rate limiter is also per location and best effort. It throttles a busy paying organization before it stops an abusive one.+- **Serialize each organization's calls in a Durable Object.** Bounds overdraft to one call, but it adds a new stateful service to the billing path and slows legitimate parallel work such as keyword research and rank checks.+- **Reservation ledger in the app database.** Works without Autumn's lock feature, but it adds a table, a sweeper for abandoned rows and several writes per call, and it duplicates balances that already live in Autumn.+- **Hold a fixed amount per call instead of an estimate.** Removes the price table, but a flat hold is either too small to bound expensive calls such as batched rank checks, or too large for an organization with few credits left to make cheap calls.## Consequences-- New DataForSEO capabilities should be added to `src/server/lib/dataforseoClient.ts`, not called from feature code via raw helpers.+- New DataForSEO capabilities should be added to `createDataforseoClient` with a price estimate, not called from feature code via raw helpers.- Hosted feature services must pass billing customer context into the client.- Subscription eligibility remains a separate concern handled by auth middleware; the client is responsible for usage metering.- Direct raw DataForSEO imports in hosted application code should be treated as billing bypasses.+- A call is refused when the balance is below its estimate, not its real cost, so the last few credits of a balance can go unused until the next grant or top-up.+- Other spend with a cost known up front (for example JavaScript rendering in site audits) can use the same hold and settle functions. Agent LLM spend is still tracked after the fact because its token cost is not known before the call.diff --git a/src/server/billing/autumn.ts b/src/server/billing/autumn.tsindex c3849a48..cc646c97 100644--- a/src/server/billing/autumn.ts+++ b/src/server/billing/autumn.ts@@ -54,11 +54,23 @@ export const autumn = {get: (...args: Parameters<Autumn["customers"]["get"]>) =>loadAutumn().then((client) => client.customers.get(...args)),},+ balances: {+ // Confirms or releases a hold taken by `check({ lock })`. Not in the+ // SDK's fail-open set, so a lost deduction surfaces as an error.+ finalize: (...args: Parameters<Autumn["balances"]["finalize"]>) =>+ loadAutumn().then((client) => client.balances.finalize(...args)),+ },};// track() has no idempotency key, so replaying a deduction Autumn already// processed (5xx after a successful write, dropped connection) would// double-charge. Retry only 429s, which are rejected before processing.+// Lock checks and balances.finalize() use the same options: a replayed lock+// check surfaces 409 lock_already_exists, and a replayed finalize surfaces+// "Lock not found", on the caller's first attempt, where neither can be told+// apart from a real failure. None sets a per-call timeoutMs, so all get the+// client-wide 10s; finalize does not fail open, so a shorter deadline would+// drop deductions that Autumn completes in 5-10s.export const AUTUMN_TRACK_RETRY_OPTIONS: Parameters<Autumn["track"]>[1] = {retryCodes: ["429"],retries: {diff --git a/src/server/billing/subscription.test.ts b/src/server/billing/subscription.test.tsindex c25c0598..3a951e64 100644--- a/src/server/billing/subscription.test.ts+++ b/src/server/billing/subscription.test.ts@@ -5,12 +5,34 @@ import {AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,} from "@/shared/billing";-const { checkMock, getOrCreateMock, kvGetMock, kvPutMock } = vi.hoisted(() => ({- checkMock: vi.fn(),- getOrCreateMock: vi.fn(),- kvGetMock: vi.fn(),- kvPutMock: vi.fn(),-}));+interface CheckCallArg {+ featureId: string;+ requiredBalance?: number;+ sendEvent?: boolean;+ lock?: { lockId: string; enabled: true; expiresAt?: number };+}++interface FinalizeCallArg {+ lockId: string;+ action: "confirm" | "release";+ overrideValue?: number;+}++const { checkMock, finalizeMock, getOrCreateMock, kvGetMock, kvPutMock } =+ vi.hoisted(() => ({+ checkMock:+ vi.fn<(arg: CheckCallArg, options?: unknown) => Promise<unknown>>(),+ finalizeMock:+ vi.fn<+ (+ arg: FinalizeCallArg,+ options?: unknown,+ ) => Promise<{ success: boolean }>+ >(),+ getOrCreateMock: vi.fn(),+ kvGetMock: vi.fn(),+ kvPutMock: vi.fn(),+ }));vi.mock("cloudflare:workers", () => ({env: { KV: { get: kvGetMock, put: kvPutMock } },@@ -19,10 +41,12 @@ vi.mock("cloudflare:workers", () => ({vi.mock("@/server/billing/autumn", () => ({autumn: {check: checkMock,+ balances: { finalize: finalizeMock },customers: {getOrCreate: getOrCreateMock,},},+ AUTUMN_TRACK_RETRY_OPTIONS: {},}));vi.mock("@/server/lib/runtime-env", () => ({@@ -35,12 +59,22 @@ vi.mock("@/server/lib/posthog", () => ({captureServerEvent: vi.fn(),}));+import { captureServerEvent } from "@/server/lib/posthog";+import { AUTUMN_TRACK_RETRY_OPTIONS } from "@/server/billing/autumn";import {- assertUsageCreditsAvailable,customerHasPaidPlan,getOrCreateOrganizationCustomer,+ checkUsageCreditsDepleted,+ reserveUsageCredits,+ settleUsageCredits,} from "./subscription";+const customer = {+ organizationId: "org_123",+ userId: "user_123",+ userEmail: "[email protected]",+};+describe("subscription billing", () => {beforeEach(() => {vi.clearAllMocks();@@ -101,10 +135,13 @@ describe("subscription billing", () => {},);- const result = assertUsageCreditsAvailable("org_123");+ const result = checkUsageCreditsDepleted(customer);await vi.runAllTimersAsync();- await expect(result).resolves.toEqual({ monthlyRemaining: 250 });+ await expect(result).resolves.toEqual({+ depleted: false,+ monthlyRemaining: 250,+ });expect(monthlyChecks).toBe(2);});@@ -112,7 +149,7 @@ describe("subscription billing", () => {vi.useFakeTimers();checkMock.mockResolvedValue({ balance: null });- const result = assertUsageCreditsAvailable("org_123");+ const result = checkUsageCreditsDepleted(customer);const assertion = expect(result).rejects.toMatchObject({code: "INTERNAL_ERROR",});@@ -195,3 +232,191 @@ describe("subscription billing", () => {);});});++describe("reserveUsageCredits", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("holds the whole estimate on topup when monthly is short", async () => {+ checkMock.mockImplementation(async ({ featureId }) =>+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ ? { allowed: false, balance: { remaining: 40 } }+ : { allowed: true, balance: { remaining: 900 } },+ );++ const hold = await reserveUsageCredits({+ customer,+ customerId: "org_123",+ estimatedCredits: 100,+ creditFeature: "backlinks",+ });++ expect(hold).toMatchObject({+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ estimatedCredits: 100,+ });+ const topupCall = checkMock.mock.calls.find(+ ([arg]) => arg.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ )![0];+ expect(topupCall).toMatchObject({+ requiredBalance: 100,+ sendEvent: true,+ lock: { lockId: hold.lockId, enabled: true },+ });+ expect(topupCall.lock?.expiresAt).toBeGreaterThan(Date.now() + 29 * 60_000);+ });++ 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.+ checkMock.mockImplementation(async ({ featureId }) =>+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ ? { allowed: false, balance: { remaining: 40 } }+ : { allowed: false, balance: null },+ );++ await expect(+ reserveUsageCredits({+ customer,+ customerId: "org_123",+ estimatedCredits: 100,+ creditFeature: "backlinks",+ }),+ ).rejects.toMatchObject({ code: "INSUFFICIENT_CREDITS" });++ expect(vi.mocked(captureServerEvent).mock.calls[0][0]).toMatchObject({+ event: "usage:credits_gate_refused",+ properties: {+ estimated_credits: 100,+ monthly_remaining: 40,+ topup_remaining: 0,+ credit_feature: "backlinks",+ },+ });+ });++ it("retries a fail-open read once with the same lock, then fails closed", async () => {+ vi.useFakeTimers();+ checkMock.mockResolvedValue({ allowed: true, balance: null });++ const result = reserveUsageCredits({+ customer,+ customerId: "org_123",+ estimatedCredits: 100,+ });+ const assertion = expect(result).rejects.toMatchObject({+ code: "INTERNAL_ERROR",+ });+ await vi.runAllTimersAsync();++ await assertion;+ expect(checkMock).toHaveBeenCalledTimes(2);+ const [first, second] = checkMock.mock.calls.map(+ ([arg]) => arg.lock?.lockId,+ );+ expect(first).toBe(second);+ // 429-only retry: an SDK-level 5xx replay of the same lock would throw+ // lock_already_exists from the first attempt, outside the catch above.+ for (const [, options] of checkMock.mock.calls) {+ expect(options).toBe(AUTUMN_TRACK_RETRY_OPTIONS);+ }+ });++ it("treats lock_already_exists on the retry as the first hold having landed", async () => {+ vi.useFakeTimers();+ const lockExists = Object.assign(new Error("Status 409"), {+ body: '{"message":"Lock already exists","code":"lock_already_exists"}',+ });+ checkMock+ .mockResolvedValueOnce({ allowed: true, balance: null })+ .mockRejectedValueOnce(lockExists);++ const result = reserveUsageCredits({+ customer,+ customerId: "org_123",+ estimatedCredits: 100,+ });+ await vi.runAllTimersAsync();++ await expect(result).resolves.toMatchObject({+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ lockId: checkMock.mock.calls[0][0].lock?.lockId,+ });+ expect(checkMock).toHaveBeenCalledTimes(2);+ });+});++describe("settleUsageCredits", () => {+ const hold = {+ lockId: "dfs_org_123_lock",+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ estimatedCredits: 100,+ } as const;+ const cost = { costUsd: 0.05, path: ["v3", "backlinks", "summary", "live"] };++ afterEach(() => {+ vi.useRealTimers();+ });++ it("releases the hold when nothing was billed", async () => {+ finalizeMock.mockResolvedValue({ success: true });++ await settleUsageCredits({ customer, hold, cost: null });++ expect(finalizeMock).toHaveBeenCalledTimes(1);+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({+ lockId: hold.lockId,+ action: "release",+ });+ expect(finalizeMock.mock.calls[0][0]).not.toHaveProperty("overrideValue");+ // The 429-only retry rides on the per-call options.+ expect(finalizeMock.mock.calls[0][1]).toBe(AUTUMN_TRACK_RETRY_OPTIONS);+ expect(captureServerEvent).not.toHaveBeenCalled();+ });++ it("treats 'Lock not found' on the retry as the first attempt having landed", async () => {+ vi.useFakeTimers();+ const lockGone = Object.assign(new Error("Status 400"), {+ body: '{"message":"Lock not found for ID: dfs_org_123_lock","code":"invalid_request"}',+ });+ finalizeMock+ .mockRejectedValueOnce(new Error("socket hang up"))+ .mockRejectedValueOnce(lockGone);++ const result = settleUsageCredits({+ customer,+ hold,+ creditFeature: "backlinks",+ cost,+ });+ await vi.runAllTimersAsync();++ await expect(result).resolves.toBeUndefined();+ expect(captureServerEvent).toHaveBeenCalledWith(+ expect.objectContaining({ event: "usage:credits_consume" }),+ );+ });++ it("logs and resolves when finalize keeps failing", async () => {+ vi.useFakeTimers();+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ finalizeMock.mockRejectedValue(new Error("Status 503"));++ const result = settleUsageCredits({+ customer,+ hold,+ creditFeature: "backlinks",+ cost,+ });+ await vi.runAllTimersAsync();++ await expect(result).resolves.toBeUndefined();+ expect(finalizeMock).toHaveBeenCalledTimes(2);+ expect(console.error).toHaveBeenCalledWith(+ "[autumn] finalize failed",+ expect.objectContaining({ lockId: hold.lockId, held: 100, actual: 64 }),+ );+ expect(captureServerEvent).not.toHaveBeenCalled();+ });+});diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.tsindex 4f89e09b..f4b00f1c 100644--- a/src/server/billing/subscription.ts+++ b/src/server/billing/subscription.ts@@ -4,10 +4,9 @@ import {AUTUMN_MANAGED_ACCESS_FEATURE_ID,AUTUMN_PAID_PLAN_FEATURE_ID,AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- AUTUMN_SEO_DATA_CREDITS_PER_USD,AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- SEO_DATA_COST_MARKUP,- roundUsdForBilling,+ applyBillingMarkupUsd,+ creditsForProviderUsd,} from "@/shared/billing";import type { CreditFeature } from "@/shared/billing-credit-features";import { autumn, AUTUMN_TRACK_RETRY_OPTIONS } from "@/server/billing/autumn";@@ -63,6 +62,8 @@ export async function getOrCreateOrganizationCustomer(return { id: customer.id };}+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+export async function customerHasPaidPlan(customerId: string,opts: { retryDenied?: boolean } = {},@@ -78,7 +79,7 @@ export async function customerHasPaidPlan(// false negative does lasting damage — the scheduler would advance a paying// org's schedule and flag "plan_required" — callers opt into one re-check.// Interactive deny paths skip it to stay fast for genuinely free users.- await new Promise((resolve) => setTimeout(resolve, 300));+ await sleep(300);const retry = await autumn.check({customerId,featureId: AUTUMN_PAID_PLAN_FEATURE_ID,@@ -115,7 +116,7 @@ async function getUsageCreditsRemaining(customerId: string): Promise<{// SDK's retry policy only covers failed HTTP requests.let monthlyBalance = monthlyCheck.balance;if (!monthlyBalance) {- await new Promise((resolve) => setTimeout(resolve, 300));+ await sleep(300);const retry = await autumn.check({customerId,featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,@@ -203,29 +204,254 @@ export async function checkUsageCreditsDepleted(return { depleted: true, monthlyRemaining: check.monthlyRemaining };}+// A hold outlives the provider call it covers; an orphaned hold (isolate+// death between check and finalize) releases at this TTL with no deduction.+const HOLD_TTL_MS = 30 * 60_000;++type UsageCreditFeatureId =+ | typeof AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ | typeof AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID;++type UsageCreditHold = {+ lockId: string;+ featureId: UsageCreditFeatureId;+ estimatedCredits: number;+};+/**- * Throws INSUFFICIENT_CREDITS when the org has no usage/topup credits left.- * Returns the monthly remaining so a caller can split spend monthly-first.+ * Atomically holds `credits` on one balance feature. Autumn refuses the hold+ * (allowed: false) when the balance is short, so concurrent calls cannot all+ * pass on the same reading the way a plain balance check lets them.+ *+ * The SDK fails open on a failed request (timeout, 5xx) with `allowed: true,+ * balance: null`, including one Autumn actually processed; that is a broken+ * read, not a wallet, so retry it once and then fail closed. The retry reuses+ * the lockId: a 409 `lock_already_exists` means the first hold landed (a+ * refusal creates no lock), so the call proceeds on it instead of stranding a+ * second hold for HOLD_TTL_MS. The SDK's own 5xx retry is off+ * (AUTUMN_TRACK_RETRY_OPTIONS): it would replay a lock Autumn already took+ * and throw that 409 from the first attempt, where nothing catches it. An+ * absent feature reads `allowed: false, balance: null` and is a genuine+ * refusal.*/-export async function assertUsageCreditsAvailable(+async function holdCredits(customerId: string,-): Promise<{ monthlyRemaining: number }> {- const { monthlyRemaining, topupRemaining } =- await getUsageCreditsRemaining(customerId);+ featureId: UsageCreditFeatureId,+ estimatedCredits: number,+ properties: Record<string, unknown>,+) {+ const lockId = `dfs_${customerId}_${crypto.randomUUID()}`;+ const hold: UsageCreditHold = { lockId, featureId, estimatedCredits };+ const attempt = () =>+ autumn.check(+ {+ customerId,+ featureId,+ requiredBalance: estimatedCredits,+ sendEvent: true,+ properties,+ lock: { lockId, enabled: true, expiresAt: Date.now() + HOLD_TTL_MS },+ },+ AUTUMN_TRACK_RETRY_OPTIONS,+ );++ let result = await attempt();+ if (result.allowed && !result.balance) {+ await sleep(300);+ try {+ result = await attempt();+ } catch (error) {+ if (!errorBodyIncludes(error, "lock_already_exists")) throw error;+ return { hold, allowed: true, balance: null };+ }+ }+ if (result.allowed && !result.balance) {+ // INTERNAL_ERROR, not UPSTREAM_UNAVAILABLE: this must stay reportable.+ throw new AppError(+ "INTERNAL_ERROR",+ `Autumn check returned no ${featureId} balance for customer ${customerId}`,+ );+ }+ return { hold, allowed: result.allowed, balance: result.balance };+}++/**+ * 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.+ */+export async function reserveUsageCredits(args: {+ customer: BillingCustomerContext;+ customerId: string;+ estimatedCredits: number;+ creditFeature?: CreditFeature;+}): Promise<UsageCreditHold> {+ const estimatedCredits = Math.max(1, args.estimatedCredits);+ const properties = {+ creditFeature: args.creditFeature,+ provider: "dataforseo",+ estimatedCredits,+ };++ const monthly = await holdCredits(+ args.customerId,+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ estimatedCredits,+ properties,+ );+ if (monthly.allowed) return monthly.hold;++ const topup = await holdCredits(+ args.customerId,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ estimatedCredits,+ properties,+ );+ if (topup.allowed) return topup.hold;++ 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");+}++// The SDK throws 4xx responses with the raw response body attached. Autumn+// answers a reused lockId with 409 `lock_already_exists`, and a finalize for+// a lock it no longer holds with a 400 whose message starts "Lock not found"+// (the code is the generic invalid_request).+function errorBodyIncludes(error: unknown, text: string) {+ return (+ error instanceof Error &&+ "body" in error &&+ typeof error.body === "string" &&+ error.body.includes(text)+ );+}++/**+ * 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+ * 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.+ */+export async function settleUsageCredits(args: {+ customer: BillingCustomerContext;+ 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;+}): 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("/")] : [];++ // 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.+ const finalize = () =>+ autumn.balances.finalize(+ {+ lockId: hold.lockId,+ ...(actualCredits > 0+ ? { action: "confirm", overrideValue: actualCredits }+ : { action: "release" }),+ properties: {+ creditFeature,+ provider: "dataforseo",+ paths,+ totalCostUsd,+ estimatedCredits: hold.estimatedCredits,+ },+ },+ AUTUMN_TRACK_RETRY_OPTIONS,+ );++ let landed = false;+ let lastError: unknown;+ for (const attempt of [1, 2]) {+ if (attempt === 2) await sleep(250);+ try {+ landed = (await finalize()).success;+ } catch (error) {+ lastError = error;+ if (errorBodyIncludes(error, "Lock not found")) {+ // On the retry this means the first attempt landed; on the first+ // attempt the hold has already expired and the deduction is lost.+ landed = attempt === 2;+ break;+ }+ }+ if (landed) break;+ }+ if (!landed) {+ console.error("[autumn] finalize failed", {+ organizationId: customer.organizationId,+ lockId: hold.lockId,+ held: hold.estimatedCredits,+ actual: actualCredits,+ error: lastError,+ });+ return;+ }+ if (actualCredits <= 0) return;++ const onMonthly = hold.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID;+ await captureCreditsConsumed(customer, {+ credit_feature: creditFeature,+ monthly_credits: onMonthly ? actualCredits : 0,+ topup_credits: onMonthly ? 0 : actualCredits,+ total_credits: actualCredits,+ cost_usd: totalCostUsd,+ estimated_credits: hold.estimatedCredits,+ paths,+ });- if (monthlyRemaining + topupRemaining <= 0) {- throw new AppError("INSUFFICIENT_CREDITS");+ // The estimate is meant to be an upper bound; an undershoot means a price+ // constant in pricing.ts is stale and the spend bound has a hole.+ if (actualCredits > hold.estimatedCredits) {+ console.error("[billing] estimate undershoot", {+ paths,+ estimated: hold.estimatedCredits,+ actual: actualCredits,+ });}+}- return { monthlyRemaining };+function captureCreditsConsumed(+ customer: BillingCustomerContext,+ properties: Record<string, unknown>,+) {+ return captureServerEvent({+ distinctId: customer.userId,+ event: "usage:credits_consume",+ organizationId: customer.organizationId,+ properties: { project_id: customer.projectId, ...properties },+ });}/**- * Deducts a USD provider cost from the org's shared usage-credit pool: applies- * the platform markup, converts to credits, spends monthly `usage_credits`- * first then `topup_credits`, and emits the usage:credits_consume event. Both- * DataForSEO and agent-LLM spend route through here, so they draw from the- * one pool. Pass `monthlyRemaining` from the balance check that gated the call.+ * Deducts a USD provider cost from the org's shared usage-credit pool after+ * the fact: applies the platform markup, converts to credits, spends monthly+ * `usage_credits` first then `topup_credits`, and emits the+ * usage:credits_consume event. Only SAM's LLM spend uses this (token cost is+ * unknowable up front); DataForSEO calls reserve-then-settle instead. Pass+ * `monthlyRemaining` from the balance check that gated the call.*/export async function trackUsageCreditSpend(args: {customer: BillingCustomerContext;@@ -235,10 +461,8 @@ export async function trackUsageCreditSpend(args: {monthlyRemaining: number;properties?: Record<string, unknown>;}): Promise<{ monthlyCredits: number; topupCredits: number }> {- const totalCostUsd = roundUsdForBilling(args.costUsd * SEO_DATA_COST_MARKUP);- const totalCostCredits = Math.ceil(- totalCostUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD,- );+ const totalCostUsd = applyBillingMarkupUsd(args.costUsd);+ const totalCostCredits = creditsForProviderUsd(args.costUsd);if (totalCostCredits <= 0) return { monthlyCredits: 0, topupCredits: 0 };// Clamp at 0: Autumn balances can read negative after an overdraft, and a@@ -287,18 +511,12 @@ export async function trackUsageCreditSpend(args: {);}- await captureServerEvent({- distinctId: args.customer.userId,- event: "usage:credits_consume",- organizationId: args.customer.organizationId,- properties: {- project_id: args.customer.projectId,- credit_feature: args.creditFeature,- monthly_credits: monthlyDeduct,- topup_credits: topupDeduct,- total_credits: totalCostCredits,- cost_usd: totalCostUsd,- },+ await captureCreditsConsumed(args.customer, {+ credit_feature: args.creditFeature,+ monthly_credits: monthlyDeduct,+ topup_credits: topupDeduct,+ total_credits: totalCostCredits,+ cost_usd: totalCostUsd,});return { monthlyCredits: monthlyDeduct, topupCredits: topupDeduct };}diff --git a/src/server/lib/dataforseo/ai.ts b/src/server/lib/dataforseo/ai.tsindex 88698966..4a079df0 100644--- a/src/server/lib/dataforseo/ai.ts+++ b/src/server/lib/dataforseo/ai.ts@@ -37,6 +37,13 @@ function clampLimit(value: number, min: number, max: number): number {return Math.min(max, Math.max(min, Math.floor(value)));}+// Request defaults shared with pricing.ts, whose estimates must reserve for+// what this module actually sends.+export function resolveLlmMentionsLimit(limit?: number): number {+ return clampLimit(limit ?? 100, 1, 1000);+}+export const LLM_RESPONSE_WEB_SEARCH_DEFAULT = true;+function targetList(target: LlmTarget): LlmTarget[] {return [target];}@@ -69,7 +76,7 @@ export async function fetchLlmMentionsSearch(platform: input.platform,location_code: input.locationCode,language_code: input.languageCode,- limit: clampLimit(input.limit ?? 100, 1, 1000),+ limit: resolveLlmMentionsLimit(input.limit),},],{ classify: classifyAiSearchError },@@ -246,7 +253,11 @@ export async function fetchLlmCrossAggregatedMetrics(// LLM Responses (per-model)// ----------------------------------------------------------------------------type LlmResponseModelSlug = "chat_gpt" | "claude" | "gemini" | "perplexity";+export type LlmResponseModelSlug =+ | "chat_gpt"+ | "claude"+ | "gemini"+ | "perplexity";/*** Accepted `model_name` values per slug, mirroring DataForSEO's@@ -302,7 +313,7 @@ export async function fetchLlmResponse(const fields: LlmResponseRequestFields = {user_prompt: input.userPrompt,model_name: input.modelName,- web_search: input.webSearch ?? true,+ web_search: input.webSearch ?? LLM_RESPONSE_WEB_SEARCH_DEFAULT,max_output_tokens: clampLimit(input.maxOutputTokens ?? 1024, 256, 4096),...(supportsCountry && input.webSearchCountryCode? { web_search_country_iso_code: input.webSearchCountryCode }diff --git a/src/server/lib/dataforseo/backlinks.ts b/src/server/lib/dataforseo/backlinks.tsindex f20b16ee..d8adeebc 100644--- a/src/server/lib/dataforseo/backlinks.ts+++ b/src/server/lib/dataforseo/backlinks.ts@@ -203,6 +203,10 @@ export async function fetchBacklinksSummary(input: BacklinksRequest) {};}+// Shared with pricing.ts, whose estimate must reserve for the rows this+// module actually requests.+export const BACKLINKS_DEFAULT_LIMIT = 100;+export async function fetchBacklinksRows(input: BacklinksListRequest) {const filters = combineFilters(input.filters,@@ -219,7 +223,7 @@ export async function fetchBacklinksRows(input: BacklinksListRequest) {[{...buildCommonPayload(input),- limit: input.limit ?? 100,+ limit: input.limit ?? BACKLINKS_DEFAULT_LIMIT,offset: input.offset,order_by: input.orderBy ?? ["rank,desc"],mode: input.mode,@@ -253,7 +257,7 @@ export async function fetchReferringDomains(input: BacklinksListRequest) {[{...buildCommonPayload(input),- limit: input.limit ?? 100,+ limit: input.limit ?? BACKLINKS_DEFAULT_LIMIT,offset: input.offset,order_by: input.orderBy ?? ["backlinks,desc"],...(filters ? { filters } : {}),@@ -286,7 +290,7 @@ export async function fetchDomainPagesSummary(input: BacklinksListRequest) {[{...buildCommonPayload(input),- limit: input.limit ?? 100,+ limit: input.limit ?? BACKLINKS_DEFAULT_LIMIT,offset: input.offset,order_by: input.orderBy ?? ["backlinks,desc"],...(filters ? { filters } : {}),diff --git a/src/server/lib/dataforseo/client.test.ts b/src/server/lib/dataforseo/client.test.tsindex c8b22bf7..cfcf50e8 100644--- a/src/server/lib/dataforseo/client.test.ts+++ b/src/server/lib/dataforseo/client.test.ts@@ -2,41 +2,58 @@import { beforeEach, describe, expect, it, vi } from "vitest";import {AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- AUTUMN_SEO_DATA_CREDITS_PER_USD,- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- SEO_DATA_COST_MARKUP,+ creditsForProviderUsd,} from "@/shared/billing";-interface TrackCallArg {+interface CheckCallArg {customerId: string;featureId: string;- value: number;- properties?: { balanceFeatureId: string };+ requiredBalance?: number;+ lock?: { lockId: string };}-const { checkMock, trackMock, getOrCreateMock, isHostedServerAuthModeMock } =- vi.hoisted(() => ({- checkMock: vi.fn(),- trackMock: vi.fn<(arg: TrackCallArg) => void>(),- getOrCreateMock: vi.fn(),- isHostedServerAuthModeMock: vi.fn(),- }));+interface CheckResult {+ allowed: boolean;+ balance: { remaining: number } | null;+}++interface FinalizeCallArg {+ lockId: string;+ action: "confirm" | "release";+ overrideValue?: number;+}++const {+ checkMock,+ finalizeMock,+ getOrCreateMock,+ isHostedServerAuthModeMock,+ mockEnv,+} = vi.hoisted(() => ({+ checkMock: vi.fn<(arg: CheckCallArg) => Promise<CheckResult>>(),+ finalizeMock:+ vi.fn<(arg: FinalizeCallArg) => Promise<{ success: boolean }>>(),+ getOrCreateMock: vi.fn(),+ isHostedServerAuthModeMock: vi.fn(),+ mockEnv: {},+}));vi.mock("cloudflare:workers", () => ({+ env: mockEnv,waitUntil: vi.fn(),}));vi.mock("@/server/billing/autumn", () => ({autumn: {check: checkMock,- track: trackMock,+ balances: { finalize: finalizeMock },},AUTUMN_TRACK_RETRY_OPTIONS: {},}));-// Keep the real subscription module (its assertUsageCreditsAvailable calls the-// mocked autumn.check) and only stub the customer lookup, so the balance-assert-// logic stays exercised through these tests after it moved out of client.ts.+// Keep the real subscription module (reserve/settle run against the mocked+// autumn facade) and only stub the customer lookup, so the hold logic stays+// exercised end to end through the client.vi.mock("@/server/billing/subscription", async (importOriginal) => {const actual = await importOriginal<Record<string, unknown>>();return {@@ -70,6 +87,8 @@ vi.mock("@/server/lib/dataforseo/serp", () => ({fetchRankCheckSerp: vi.fn(),postRankCheckTasks: vi.fn(),fetchLocalSerp: vi.fn(),+ clampSerpDepth: (depth: number) => depth,+ SERP_ANALYSIS_DEPTH: 20,}));vi.mock("@/server/lib/dataforseo/business", () => ({fetchBusinessListingsSearch: vi.fn(),@@ -88,6 +107,7 @@ vi.mock("@/server/lib/dataforseo/backlinks", () => ({fetchReferringDomains: vi.fn(),fetchDomainPagesSummary: vi.fn(),fetchBacklinksHistory: vi.fn(),+ BACKLINKS_DEFAULT_LIMIT: 100,}));vi.mock("@/server/lib/dataforseo/lighthouse", () => ({fetchLighthouseResult: vi.fn(),@@ -98,13 +118,18 @@ vi.mock("@/server/lib/dataforseo/ai", () => ({fetchLlmTopPages: vi.fn(),fetchLlmCrossAggregatedMetrics: vi.fn(),fetchLlmResponse: vi.fn(),+ resolveLlmMentionsLimit: (limit?: number) => limit ?? 100,+ LLM_RESPONSE_WEB_SEARCH_DEFAULT: true,}));+import { waitUntil } from "cloudflare:workers";import {createDataforseoClient,mapDataforseoPathToCreditFeature,} from "@/server/lib/dataforseo/client";+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";const billingCustomer = {@@ -116,158 +141,106 @@ const billingCustomer = {const backlinksInput = {target: "example.com",};+const backlinksPath = ["v3", "backlinks", "summary", "live"];++// Below the summary estimate, as a real charge is (the estimate is an upper bound).+const RAW_COST = 0.02;+const EXPECTED_CREDITS = creditsForProviderUsd(RAW_COST);+const ESTIMATED_CREDITS = creditsForProviderUsd(+ dataforseoPricing.backlinks.summary(backlinksInput),+);function setupHostedMode() {isHostedServerAuthModeMock.mockResolvedValue(true);getOrCreateMock.mockResolvedValue({ id: "org_123" });+ finalizeMock.mockResolvedValue({ success: true });}-function mockBalances(monthly: number, topup: number) {- checkMock.mockImplementation(async (args: { featureId: string }) => {- if (args.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID) {- return { allowed: true, balance: { remaining: monthly } };- }- if (args.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID) {- return { allowed: true, balance: { remaining: topup } };- }- return { allowed: false, balance: null };+// Monthly balance only; topup reads empty.+function mockMonthlyBalance(monthly: number) {+ checkMock.mockImplementation(async (args) => {+ const remaining =+ args.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID ? monthly : 0;+ return {+ allowed: remaining >= (args.requiredBalance ?? 1),+ balance: { remaining },+ };});}function mockDataforseoResult(costUsd: number) {vi.mocked(fetchBacklinksSummary).mockResolvedValue({data: { rank: 42 },- billing: { costUsd, path: ["backlinks", "summary"] },+ billing: { costUsd, path: backlinksPath },});}-describe("meterDataforseoCall with split balances", () => {+describe("meterDataforseoCall", () => {beforeEach(() => {vi.clearAllMocks();});it("skips billing in non-hosted mode", async () => {isHostedServerAuthModeMock.mockResolvedValue(false);- mockDataforseoResult(0.05);+ mockDataforseoResult(RAW_COST);const client = createDataforseoClient(billingCustomer);const result = await client.backlinks.summary(backlinksInput);expect(result).toEqual({ rank: 42 });expect(checkMock).not.toHaveBeenCalled();- expect(trackMock).not.toHaveBeenCalled();+ expect(finalizeMock).not.toHaveBeenCalled();});- it("checks both monthly and topup balances in parallel", async () => {+ it("never calls the provider when the hold is refused", async () => {setupHostedMode();- mockBalances(5000, 3000);- mockDataforseoResult(0.05);-- const client = createDataforseoClient(billingCustomer);- await client.backlinks.summary(backlinksInput);-- expect(checkMock).toHaveBeenCalledTimes(2);- expect(checkMock).toHaveBeenCalledWith({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- });- expect(checkMock).toHaveBeenCalledWith({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- });- });-- const RAW_COST = 0.05;- const EXPECTED_CREDITS = Math.ceil(- RAW_COST * SEO_DATA_COST_MARKUP * AUTUMN_SEO_DATA_CREDITS_PER_USD,- );-- it("deducts entirely from monthly when monthly has enough", async () => {- setupHostedMode();- mockBalances(5000, 3000);+ mockMonthlyBalance(0);mockDataforseoResult(RAW_COST);const client = createDataforseoClient(billingCustomer);- await client.backlinks.summary(backlinksInput);-- expect(trackMock).toHaveBeenCalledTimes(1);- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- value: EXPECTED_CREDITS,- }),- expect.anything(),- );- });-- it("deducts entirely from topup when monthly is empty", async () => {- setupHostedMode();- mockBalances(0, 5000);- mockDataforseoResult(RAW_COST);+ await expect(+ client.backlinks.summary(backlinksInput),+ ).rejects.toMatchObject({ code: "INSUFFICIENT_CREDITS" });- const client = createDataforseoClient(billingCustomer);- await client.backlinks.summary(backlinksInput);-- expect(trackMock).toHaveBeenCalledTimes(1);- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- value: EXPECTED_CREDITS,- }),- expect.anything(),- );+ expect(checkMock).toHaveBeenCalledTimes(2);+ expect(fetchBacklinksSummary).not.toHaveBeenCalled();+ expect(finalizeMock).not.toHaveBeenCalled();});- it("splits deduction across monthly and topup when monthly is partially sufficient", async () => {+ it("holds the estimate, then confirms the hold at the billed cost", async () => {setupHostedMode();- const monthlyAvailable = 30;- mockBalances(monthlyAvailable, 5000);+ mockMonthlyBalance(5000);mockDataforseoResult(RAW_COST);const client = createDataforseoClient(billingCustomer);- await client.backlinks.summary(backlinksInput);-- expect(trackMock).toHaveBeenCalledTimes(2);- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- value: monthlyAvailable,- }),- expect.anything(),- );- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- value: EXPECTED_CREDITS - monthlyAvailable,- }),- expect.anything(),- );- });-- it("throws INSUFFICIENT_CREDITS when both balances are exactly zero", async () => {- setupHostedMode();- mockBalances(0, 0);- mockDataforseoResult(0.05);-- const client = createDataforseoClient(billingCustomer);- await expect(- client.backlinks.summary(backlinksInput),- ).rejects.toMatchObject({ code: "INSUFFICIENT_CREDITS" });+ const result = await client.backlinks.summary(backlinksInput);- expect(trackMock).not.toHaveBeenCalled();+ expect(result).toEqual({ rank: 42 });+ expect(checkMock).toHaveBeenCalledTimes(1);+ const [holdCall] = checkMock.mock.calls[0];+ expect(holdCall).toMatchObject({+ customerId: "org_123",+ featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ requiredBalance: ESTIMATED_CREDITS,+ });+ // The execute + settle chain is registered with the request so a client+ // disconnect after dispatch cannot skip the deduction.+ expect(vi.mocked(waitUntil)).toHaveBeenCalledTimes(1);+ expect(finalizeMock).toHaveBeenCalledTimes(1);+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({+ lockId: holdCall.lock?.lockId,+ action: "confirm",+ overrideValue: EXPECTED_CREDITS,+ });});- it("meters charged DataForSEO task errors before rethrowing", async () => {+ it("confirms a charged DataForSEO task failure at its cost before rethrowing", async () => {setupHostedMode();- mockBalances(5000, 3000);+ mockMonthlyBalance(5000);vi.mocked(fetchBacklinksSummary).mockRejectedValue(new DataforseoChargedTaskError("DataForSEO task failed", {costUsd: RAW_COST,- path: ["v3", "backlinks", "summary", "live"],+ path: backlinksPath,}),);@@ -276,24 +249,19 @@ describe("meterDataforseoCall with split balances", () => {"DataForSEO task failed",);- expect(trackMock).toHaveBeenCalledTimes(1);- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- value: EXPECTED_CREDITS,- }),- expect.anything(),- );+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({+ action: "confirm",+ overrideValue: EXPECTED_CREDITS,+ });});- it("skips the charge for an unbilled invalid-field failure and rethrows VALIDATION_ERROR", async () => {+ it("releases the hold for an unbilled invalid-field failure and throws VALIDATION_ERROR", async () => {setupHostedMode();- mockBalances(5000, 3000);+ mockMonthlyBalance(5000);vi.mocked(fetchBacklinksSummary).mockRejectedValue(new DataforseoChargedTaskError("Invalid Field: 'target'.",- { costUsd: 0, path: ["v3", "backlinks", "summary", "live"] },+ { costUsd: 0, path: backlinksPath },true,),);@@ -303,57 +271,23 @@ describe("meterDataforseoCall with split balances", () => {client.backlinks.summary(backlinksInput),).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(trackMock).not.toHaveBeenCalled();+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({ action: "release" });});- it("still meters an invalid-field failure that DataForSEO actually billed", async () => {+ it("releases the hold when the provider call fails before billing", async () => {setupHostedMode();- mockBalances(5000, 3000);+ mockMonthlyBalance(5000);vi.mocked(fetchBacklinksSummary).mockRejectedValue(- new DataforseoChargedTaskError(- "Invalid Field: 'target'.",- { costUsd: RAW_COST, path: ["v3", "backlinks", "summary", "live"] },- true,- ),+ new AppError("UPSTREAM_UNAVAILABLE", "DataForSEO timed out"),);const client = createDataforseoClient(billingCustomer);- await expect(client.backlinks.summary(backlinksInput)).rejects.toThrow(- "Invalid Field: 'target'.",- );-- expect(trackMock).toHaveBeenCalledTimes(1);- expect(trackMock).toHaveBeenCalledWith(- expect.objectContaining({- customerId: "org_123",- featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- value: EXPECTED_CREDITS,- }),- expect.anything(),- );- });-- it("includes balanceFeatureId in track properties", async () => {- setupHostedMode();- mockBalances(30, 5000);- mockDataforseoResult(0.05);-- const client = createDataforseoClient(billingCustomer);- await client.backlinks.summary(backlinksInput);-- const monthlyCall = trackMock.mock.calls.find(- ([arg]) => arg.featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- );- const topupCall = trackMock.mock.calls.find(- ([arg]) => arg.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- );+ await expect(+ client.backlinks.summary(backlinksInput),+ ).rejects.toMatchObject({ code: "UPSTREAM_UNAVAILABLE" });- expect(monthlyCall![0].properties?.balanceFeatureId).toBe(- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- );- expect(topupCall![0].properties?.balanceFeatureId).toBe(- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- );+ expect(vi.mocked(waitUntil)).toHaveBeenCalledTimes(1);+ expect(finalizeMock.mock.calls[0][0]).toMatchObject({ action: "release" });});});diff --git a/src/server/lib/dataforseo/client.ts b/src/server/lib/dataforseo/client.tsindex e0dafa4c..24d2b9b8 100644--- a/src/server/lib/dataforseo/client.ts+++ b/src/server/lib/dataforseo/client.ts@@ -1,11 +1,13 @@+import { waitUntil } from "cloudflare:workers";import {type CreditFeature,mapDataforseoPathToCreditFeature,} from "@/shared/billing-credit-features";+import { creditsForProviderUsd } from "@/shared/billing";import {- assertUsageCreditsAvailable,getOrCreateOrganizationCustomer,- trackUsageCreditSpend,+ reserveUsageCredits,+ settleUsageCredits,} from "@/server/billing/subscription";import type { BillingCustomerContext } from "@/server/billing/subscription";import {@@ -13,6 +15,7 @@ import {type DataforseoApiCallCost,type DataforseoApiResponse,} from "@/server/lib/dataforseo/envelope";+import { dataforseoPricing } from "@/server/lib/dataforseo/pricing";import {fetchBusinessListingsSearch,fetchMyBusinessInfo,@@ -62,8 +65,12 @@ export { mapDataforseoPathToCreditFeature };/*** Wraps a section fetcher with billing metering. Each entry on the client is- * `meter(customer, fetchX, defaultFeature?)`, which returns a function with- * the fetcher's own input type and resolves to its unwrapped `.data`.+ * `meter(customer, fetchX, dataforseoPricing.section.x, defaultFeature?)`,+ * which returns a function with the fetcher's own input type and resolves to+ * its unwrapped `.data`.+ *+ * `estimateRawUsd` is required: it is the upper bound reserved before the+ * call, so an entry cannot be added without a price (see pricing.ts).** `defaultFeature` is the fallback credit feature; a caller can override it per* call by passing `creditFeature` in the input (e.g. an MCP tool attributing@@ -73,12 +80,14 @@ export { mapDataforseoPathToCreditFeature };function meter<I, T>(customer: BillingCustomerContext,fetcher: (input: I) => Promise<DataforseoApiResponse<T>>,+ estimateRawUsd: (input: I) => number,defaultFeature?: CreditFeature,): (input: I & { creditFeature?: CreditFeature }) => Promise<T> {return (input) =>meterDataforseoCall(customer,() => fetcher(input),+ creditsForProviderUsd(estimateRawUsd(input)),input.creditFeature ?? defaultFeature,);}@@ -89,67 +98,195 @@ export function createDataforseoClient(customer: BillingCustomerContext) {businessListings: meter(customer,fetchBusinessListingsSearch,+ dataforseoPricing.business.businessListings,+ "local_seo",+ ),+ questionsAnswers: meter(+ customer,+ fetchQuestionsAnswers,+ dataforseoPricing.business.questionsAnswers,+ "local_seo",+ ),+ myBusinessInfo: meter(+ customer,+ fetchMyBusinessInfo,+ dataforseoPricing.business.myBusinessInfo,"local_seo",),- questionsAnswers: meter(customer, fetchQuestionsAnswers, "local_seo"),- myBusinessInfo: meter(customer, fetchMyBusinessInfo, "local_seo"),// task_post is where DataForSEO charges; collection runs unmetered// through fetchBusinessDataTaskResult (see index.ts).- reviewsTaskPost: meter(customer, postGoogleReviewsTask, "local_seo"),- updatesTaskPost: meter(customer, postMyBusinessUpdatesTask, "local_seo"),+ reviewsTaskPost: meter(+ customer,+ postGoogleReviewsTask,+ dataforseoPricing.business.reviewsTaskPost,+ "local_seo",+ ),+ updatesTaskPost: meter(+ customer,+ postMyBusinessUpdatesTask,+ dataforseoPricing.business.updatesTaskPost,+ "local_seo",+ ),},backlinks: {- summary: meter(customer, fetchBacklinksSummary),- rows: meter(customer, fetchBacklinksRows),- referringDomains: meter(customer, fetchReferringDomains),- domainPages: meter(customer, fetchDomainPagesSummary),- history: meter(customer, fetchBacklinksHistory),+ summary: meter(+ customer,+ fetchBacklinksSummary,+ dataforseoPricing.backlinks.summary,+ ),+ rows: meter(+ customer,+ fetchBacklinksRows,+ dataforseoPricing.backlinks.rows,+ ),+ referringDomains: meter(+ customer,+ fetchReferringDomains,+ dataforseoPricing.backlinks.referringDomains,+ ),+ domainPages: meter(+ customer,+ fetchDomainPagesSummary,+ dataforseoPricing.backlinks.domainPages,+ ),+ history: meter(+ customer,+ fetchBacklinksHistory,+ dataforseoPricing.backlinks.history,+ ),},keywords: {- related: meter(customer, fetchRelatedKeywords),- suggestions: meter(customer, fetchKeywordSuggestions),- ideas: meter(customer, fetchKeywordIdeas),+ related: meter(+ customer,+ fetchRelatedKeywords,+ dataforseoPricing.keywords.related,+ ),+ suggestions: meter(+ customer,+ fetchKeywordSuggestions,+ dataforseoPricing.keywords.suggestions,+ ),+ ideas: meter(+ customer,+ fetchKeywordIdeas,+ dataforseoPricing.keywords.ideas,+ ),// Google Ads endpoints for countries Labs doesn't support.- adsIdeas: meter(customer, fetchAdsKeywordIdeas),- adsSearchVolume: meter(customer, fetchAdsSearchVolume),+ adsIdeas: meter(+ customer,+ fetchAdsKeywordIdeas,+ dataforseoPricing.keywords.adsIdeas,+ ),+ adsSearchVolume: meter(+ customer,+ fetchAdsSearchVolume,+ dataforseoPricing.keywords.adsSearchVolume,+ ),},domain: {- rankOverview: meter(customer, fetchDomainRankOverview),- rankedKeywords: meter(customer, fetchRankedKeywords),- relevantPages: meter(customer, fetchRelevantPages),+ rankOverview: meter(+ customer,+ fetchDomainRankOverview,+ dataforseoPricing.domain.rankOverview,+ ),+ rankedKeywords: meter(+ customer,+ fetchRankedKeywords,+ dataforseoPricing.domain.rankedKeywords,+ ),+ relevantPages: meter(+ customer,+ fetchRelevantPages,+ dataforseoPricing.domain.relevantPages,+ ),},serp: {- live: meter(customer, fetchLiveSerp),- rankCheck: meter(customer, fetchRankCheckSerp, "rank_tracking"),+ live: meter(customer, fetchLiveSerp, dataforseoPricing.serp.live),+ rankCheck: meter(+ customer,+ fetchRankCheckSerp,+ dataforseoPricing.serp.rankCheck,+ "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).- rankCheckTaskPost: meter(customer, postRankCheckTasks, "rank_tracking"),- local: meter(customer, fetchLocalSerp, "local_seo"),+ rankCheckTaskPost: meter(+ customer,+ postRankCheckTasks,+ dataforseoPricing.serp.rankCheckTaskPost,+ "rank_tracking",+ ),+ local: meter(+ customer,+ fetchLocalSerp,+ dataforseoPricing.serp.local,+ "local_seo",+ ),},labs: {// Callers (e.g. the keyword-metrics MCP tool) can attribute the spend to// their own feature by passing `creditFeature` in the input; defaults to// rank_tracking when omitted.- keywordOverview: meter(customer, fetchKeywordOverview, "rank_tracking"),- serpCompetitors: meter(customer, fetchSerpCompetitors),+ keywordOverview: meter(+ customer,+ fetchKeywordOverview,+ dataforseoPricing.labs.keywordOverview,+ "rank_tracking",+ ),+ serpCompetitors: meter(+ customer,+ fetchSerpCompetitors,+ dataforseoPricing.labs.serpCompetitors,+ ),},lighthouse: {- live: meter(customer, fetchLighthouseResult),+ live: meter(+ customer,+ fetchLighthouseResult,+ dataforseoPricing.lighthouse.live,+ ),},aiSearch: {- mentionsSearch: meter(customer, fetchLlmMentionsSearch),- aggregatedMetrics: meter(customer, fetchLlmAggregatedMetrics),- topPages: meter(customer, fetchLlmTopPages),- crossAggregatedMetrics: meter(customer, fetchLlmCrossAggregatedMetrics),- llmResponse: meter(customer, fetchLlmResponse),+ mentionsSearch: meter(+ customer,+ fetchLlmMentionsSearch,+ dataforseoPricing.aiSearch.mentionsSearch,+ ),+ aggregatedMetrics: meter(+ customer,+ fetchLlmAggregatedMetrics,+ dataforseoPricing.aiSearch.aggregatedMetrics,+ ),+ topPages: meter(+ customer,+ fetchLlmTopPages,+ dataforseoPricing.aiSearch.topPages,+ ),+ crossAggregatedMetrics: meter(+ customer,+ fetchLlmCrossAggregatedMetrics,+ dataforseoPricing.aiSearch.crossAggregatedMetrics,+ ),+ llmResponse: meter(+ customer,+ fetchLlmResponse,+ dataforseoPricing.aiSearch.llmResponse,+ ),},} as const;}+/**+ * 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+ * calls cannot all pass on one stale balance reading.+ */async function meterDataforseoCall<T>(customer: BillingCustomerContext,execute: () => Promise<DataforseoApiResponse<T>>,+ estimatedCredits: number,creditFeature?: CreditFeature,): Promise<T> {const isHostedMode = await isHostedServerAuthMode();@@ -160,64 +297,57 @@ async function meterDataforseoCall<T>(}const billingCustomer = await getOrCreateOrganizationCustomer(customer);+ const hold = await reserveUsageCredits({+ customer,+ customerId: billingCustomer.id,+ estimatedCredits,+ creditFeature,+ });- const { monthlyRemaining } = await assertUsageCreditsAvailable(- billingCustomer.id,- );+ const settle = (cost: DataforseoApiCallCost | null) =>+ settleUsageCredits({+ customer,+ hold,+ creditFeature:+ creditFeature ??+ (cost ? mapDataforseoPathToCreditFeature(cost.path) : undefined),+ cost,+ });- let result: DataforseoApiResponse<T>;- try {- result = await execute();- } catch (error) {- if (error instanceof DataforseoChargedTaskError) {+ 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), fall through to the normal charge + capture path so the- // spend stays metered and visible instead of silently eaten.+ // (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 trackDataforseoCost({- customer,- customerId: billingCustomer.id,- billing: error.billing,- monthlyRemaining,- creditFeature,- });+ await settle(error.billing);+ throw error;}- throw error;- }-- await trackDataforseoCost({- customer,- customerId: billingCustomer.id,- billing: result.billing,- monthlyRemaining,- creditFeature,- });-- return result.data;-}+ await settle(result.billing);+ return result.data;+ })();-async function trackDataforseoCost(args: {- customer: BillingCustomerContext;- customerId: string;- billing: DataforseoApiCallCost;- monthlyRemaining: number;- creditFeature?: CreditFeature;-}) {- await trackUsageCreditSpend({- customer: args.customer,- customerId: args.customerId,- creditFeature:- args.creditFeature ?? mapDataforseoPathToCreditFeature(args.billing.path),- costUsd: args.billing.costUsd,- monthlyRemaining: args.monthlyRemaining,- properties: {- provider: "dataforseo",- paths: [args.billing.path.join("/")],- fromCache: false,- },- });+ // Register the call + 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.+ try {+ waitUntil(work.catch(() => undefined));+ } catch {+ // No request context (Workflow step, tests): the await below runs it.+ }+ return await work;}diff --git a/src/server/lib/dataforseo/pricing.test.ts b/src/server/lib/dataforseo/pricing.test.tsnew file mode 100644index 00000000..8ea7db34--- /dev/null+++ b/src/server/lib/dataforseo/pricing.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from "vitest";+import { dataforseoPricing } from "@/server/lib/dataforseo/pricing";+import { creditsForProviderUsd } from "@/shared/billing";+import { estimateRankCheckCredits } from "@/shared/rank-tracking";++const location = { locationCode: 2840, languageCode: "en" };++describe("dataforseoPricing", () => {+ it.each([+ {+ name: "Labs research, 500 rows with clickstream (incident shape)",+ estimateUsd: dataforseoPricing.keywords.related({+ keyword: "seo",+ ...location,+ limit: 500,+ includeClickstreamData: true,+ }),+ rawUsd: 0.144,+ credits: 185,+ },+ {+ name: "Labs research, default 150 rows",+ estimateUsd: dataforseoPricing.keywords.suggestions({+ keyword: "seo",+ ...location,+ limit: 150,+ }),+ rawUsd: 0.03,+ credits: 39,+ },+ {+ name: "live SERP at the default depth (2 pages)",+ estimateUsd: dataforseoPricing.serp.live({ keyword: "seo", ...location }),+ rawUsd: 0.0035,+ credits: 5,+ },+ {+ name: "Lighthouse run",+ estimateUsd: dataforseoPricing.lighthouse.live({+ url: "https://example.com",+ strategy: "mobile",+ }),+ rawUsd: 0.005,+ credits: 7,+ },+ {+ name: "backlinks history over one year",+ estimateUsd: dataforseoPricing.backlinks.history({+ target: "example.com",+ dateFrom: "2025-09-09",+ dateTo: "2026-09-08",+ }),+ rawUsd: 0.024 + 365 * 0.000036,+ credits: 48,+ },+ ])("$name", ({ estimateUsd, rawUsd, credits }) => {+ expect(estimateUsd).toBeCloseTo(rawUsd, 10);+ expect(creditsForProviderUsd(estimateUsd)).toBe(credits);+ });++ it.each([+ { includeOtherSources: false, billedUsd: 0.00375 },+ { includeOtherSources: true, billedUsd: 0.01 },+ ])(+ "holds at least the billed cost of a depth-20 reviews post (other sources: $includeOtherSources)",+ ({ includeOtherSources, billedUsd }) => {+ const estimateUsd = dataforseoPricing.business.reviewsTaskPost({+ cid: "123",+ ...location,+ depth: 20,+ sortBy: "newest",+ includeOtherSources,+ });+ expect(creditsForProviderUsd(estimateUsd)).toBeGreaterThanOrEqual(+ creditsForProviderUsd(billedUsd),+ );+ },+ );++ // Real bills read from DataForSEO's id_list, each above the earlier estimate.+ const near = { locationCoordinate: "40.74,-73.98", languageCode: "en" };+ it.each([+ {+ name: "Q&A at depth 10",+ estimateUsd: dataforseoPricing.business.questionsAnswers({+ keyword: "x",+ ...near,+ depth: 10,+ }),+ billedUsd: 0.0054,+ },+ {+ name: "Q&A at depth 30",+ estimateUsd: dataforseoPricing.business.questionsAnswers({+ keyword: "x",+ ...near,+ depth: 30,+ }),+ billedUsd: 0.0108,+ },+ {+ name: "Local Finder at depth 100",+ estimateUsd: dataforseoPricing.serp.local({+ keyword: "x",+ ...near,+ searchType: "local_finder",+ device: "mobile",+ depth: 100,+ }),+ billedUsd: 0.02,+ },+ {+ name: "Claude response with web search",+ estimateUsd: dataforseoPricing.aiSearch.llmResponse({+ userPrompt: "x",+ modelSlug: "claude",+ modelName: "claude-sonnet-4-5",+ webSearch: true,+ }),+ billedUsd: 0.142357,+ },+ ])(+ "holds at least the measured bill: $name",+ ({ estimateUsd, billedUsd }) => {+ expect(estimateUsd).toBeGreaterThanOrEqual(billedUsd);+ },+ );++ it("prices a queued task_post batch the way the rank check estimate does", () => {+ const tasks = Array.from({ length: 100 }, (_, i) => ({+ keyword: `kw ${i}`,+ keywordId: `id-${i}`,+ device: "desktop" as const,+ }));+ const estimateUsd = dataforseoPricing.serp.rankCheckTaskPost({+ tasks,+ ...location,+ depth: 20,+ targetDomain: "example.com",+ });+ expect(creditsForProviderUsd(estimateUsd)).toBe(+ estimateRankCheckCredits(100, "desktop", 20, "queued").costCredits,+ );+ });+});diff --git a/src/server/lib/dataforseo/pricing.ts b/src/server/lib/dataforseo/pricing.tsnew file mode 100644index 00000000..546ba40b--- /dev/null+++ b/src/server/lib/dataforseo/pricing.ts@@ -0,0 +1,279 @@+import {+ fetchBusinessListingsSearch,+ fetchMyBusinessInfo,+ fetchQuestionsAnswers,+ postGoogleReviewsTask,+ postMyBusinessUpdatesTask,+} from "@/server/lib/dataforseo/business";+import {+ BACKLINKS_DEFAULT_LIMIT,+ fetchBacklinksHistory,+ fetchBacklinksRows,+ fetchBacklinksSummary,+ fetchDomainPagesSummary,+ fetchReferringDomains,+} from "@/server/lib/dataforseo/backlinks";+import {+ fetchDomainRankOverview,+ fetchKeywordIdeas,+ fetchKeywordOverview,+ fetchKeywordSuggestions,+ fetchRankedKeywords,+ fetchRelatedKeywords,+ fetchRelevantPages,+ fetchSerpCompetitors,+} from "@/server/lib/dataforseo/labs";+import {+ fetchAdsKeywordIdeas,+ fetchAdsSearchVolume,+} from "@/server/lib/dataforseo/google-ads";+import {+ clampSerpDepth,+ fetchLiveSerp,+ fetchLocalSerp,+ fetchRankCheckSerp,+ postRankCheckTasks,+ SERP_ANALYSIS_DEPTH,+} from "@/server/lib/dataforseo/serp";+import { fetchLighthouseResult } from "@/server/lib/dataforseo/lighthouse";+import {+ fetchLlmAggregatedMetrics,+ fetchLlmCrossAggregatedMetrics,+ fetchLlmMentionsSearch,+ fetchLlmResponse,+ fetchLlmTopPages,+ LLM_RESPONSE_WEB_SEARCH_DEFAULT,+ type LlmResponseModelSlug,+ resolveLlmMentionsLimit,+} from "@/server/lib/dataforseo/ai";+import { costPerSerpAtDepth } from "@/shared/rank-tracking";++/**+ * Raw DataForSEO USD upper bound for one metered call, computed from the+ * fetcher's input before the call is made. The metering seam reserves+ * `creditsForProviderUsd(estimate)` and settles on the provider's real+ * `cost`, so every number here must be >= what DataForSEO actually charges+ * for that input. Overestimating only refuses a call slightly early at the+ * tail of a balance; underestimating lets spend past the balance.+ *+ * Prices are raw (pre-markup) USD from DataForSEO's per-account price table+ * (the `price` object on the free GET /v3/appendix/user_data), read Sep 2026.+ * That table has only each endpoint's base price, so per-page, per-depth and+ * token-priced shapes are "measured": set from real billed costs, which the+ * free POST /v3/<api>/id_list returns per task alongside the request+ * parameters for the last month. Re-check a price against id_list, not a+ * one-off fixture.+ */++// DataForSEO Labs (dataforseo.com/pricing/dataforseo-labs/dataforseo-google-api):+// per task + per returned row, doubled with include_clickstream_data. The+// spec 0004 figures ($0.01 + $0.0001) predate a price rise; web/pricing.tsx+// ("150-300 rows = $0.030-$0.048 raw", Jul 2026) matches these.+const LABS_TASK_USD = 0.012;+const LABS_ROW_USD = 0.00012;++// Keywords Data Google Ads, live mode (dataforseo.com/pricing/keywords-data/google-ads).+const GOOGLE_ADS_LIVE_TASK_USD = 0.09;++// Backlinks API, uniform across endpoints (dataforseo.com/pricing/backlinks/backlinks).+const BACKLINKS_TASK_USD = 0.024;+const BACKLINKS_ROW_USD = 0.000036;++// Business Data (dataforseo.com/pricing/business-data/*). Task-queue posts+// run at priority 2 (business.ts TASK_PRIORITY_HIGH), which doubles the+// standard-queue rates quoted on the pricing pages.+const BUSINESS_LISTINGS_TASK_USD = 0.012;+const BUSINESS_LISTINGS_ROW_USD = 0.00036;+const MY_BUSINESS_INFO_LIVE_USD = 0.0054;+// measured: billed per 20 rows of depth ($0.0054 at depth 10 and 20, $0.0108+// at 30, $0.027 at 100).+const QUESTIONS_ANSWERS_PER_20_USD = 0.0054;+// uncalibrated: the list prices undershoot the fixtures, which bill $0.00375+// (regular) and $0.01 (extended_reviews) for one depth-20 priority post.+const REVIEWS_PRIORITY_TASK_USD = 0.001;+const REVIEWS_PRIORITY_PER_10_USD = 0.0015;+const EXTENDED_REVIEWS_PRIORITY_PER_20_USD = 0.01;+const UPDATES_PRIORITY_TASK_USD = 0.003;+const UPDATES_PRIORITY_PER_10_USD = 0.0015;++// OnPage Lighthouse, live (dataforseo.com/pricing/on-page/lighthouse-api);+// fixtures show $0.00425 billed.+const LIGHTHOUSE_LIVE_USD = 0.005;++// AI Optimization (dataforseo.com/pricing/ai-optimization/llm-mentions):+// $0.1 per request + $0.001 per row on every llm_mentions endpoint.+const LLM_MENTIONS_TASK_USD = 0.1;+const LLM_MENTIONS_ROW_USD = 0.001;+// measured: the aggregate endpoints and top_pages return one result row, and+// every observed call billed $0.101.+const LLM_MENTIONS_ONE_ROW_USD = LLM_MENTIONS_TASK_USD + LLM_MENTIONS_ROW_USD;+// measured, token-priced: $0.0006 + the model's own bill. Measured with a+// long-answer prompt at the 4096-token output cap on the model Prompt Explorer+// sends per slug, then padded ~1.25x without web search and ~1.3x with it,+// where the searched pages add a variable input bill. Measured bills: gpt-5+// $0.072 / $0.042, claude-sonnet-4-5 $0.142 / $0.062, gemini-2.5-pro+// $0.085 / $0.042, sonar-reasoning-pro $0.028 (it always searches).+const LLM_RESPONSE_USD: Record<+ LlmResponseModelSlug,+ { webSearch: number; noSearch: number }+> = {+ chat_gpt: { webSearch: 0.09, noSearch: 0.05 },+ claude: { webSearch: 0.18, noSearch: 0.08 },+ gemini: { webSearch: 0.11, noSearch: 0.05 },+ perplexity: { webSearch: 0.04, noSearch: 0.04 },+};++// SERP Google Maps and Local Finder, live. measured: Maps bills one request+// through depth 100 ($0.002 at depth 20 and 100), and no caller asks for+// more. Local Finder bills every page of 10 at the first-page rate ($0.02 at+// depth 100).+const LOCAL_SERP_PAGE_USD = 0.002;++type ProviderUsdEstimator<I> = (input: I) => number;++/** Ties an estimator to a fetcher so it is typed against that fetcher's input. */+function priced<I>(+ _fetcher: (input: I) => unknown,+ estimate: ProviderUsdEstimator<I>,+): ProviderUsdEstimator<I> {+ return estimate;+}++function labsUsd(rows: number, clickstream?: boolean) {+ return (LABS_TASK_USD + rows * LABS_ROW_USD) * (clickstream ? 2 : 1);+}++function backlinksUsd(rows: number) {+ return BACKLINKS_TASK_USD + rows * BACKLINKS_ROW_USD;+}++/** SERP endpoints bill per page of 10; a partial page is a full page. */+function serpUsd(depth: number, method: "live" | "queued") {+ return costPerSerpAtDepth(Math.ceil(depth / 10) * 10, method);+}++function daysInclusive(from: string, to: string) {+ const ms = new Date(to).getTime() - new Date(from).getTime();+ return Math.max(1, Math.floor(ms / 86_400_000) + 1);+}++/** One raw-USD upper-bound estimator per entry in createDataforseoClient. */+export const dataforseoPricing = {+ business: {+ businessListings: priced(+ fetchBusinessListingsSearch,+ (input) =>+ BUSINESS_LISTINGS_TASK_USD + input.limit * BUSINESS_LISTINGS_ROW_USD,+ ),+ questionsAnswers: priced(+ fetchQuestionsAnswers,+ (input) => Math.ceil(input.depth / 20) * QUESTIONS_ANSWERS_PER_20_USD,+ ),+ myBusinessInfo: priced(+ fetchMyBusinessInfo,+ () => MY_BUSINESS_INFO_LIVE_USD,+ ),+ reviewsTaskPost: priced(postGoogleReviewsTask, (input) =>+ input.includeOtherSources+ ? Math.ceil(input.depth / 20) * EXTENDED_REVIEWS_PRIORITY_PER_20_USD+ : REVIEWS_PRIORITY_TASK_USD ++ Math.ceil(input.depth / 10) * REVIEWS_PRIORITY_PER_10_USD,+ ),+ updatesTaskPost: priced(+ postMyBusinessUpdatesTask,+ (input) =>+ UPDATES_PRIORITY_TASK_USD ++ Math.ceil(input.depth / 10) * UPDATES_PRIORITY_PER_10_USD,+ ),+ },+ backlinks: {+ summary: priced(fetchBacklinksSummary, () => backlinksUsd(1)),+ rows: priced(fetchBacklinksRows, (input) =>+ backlinksUsd(input.limit ?? BACKLINKS_DEFAULT_LIMIT),+ ),+ referringDomains: priced(fetchReferringDomains, (input) =>+ backlinksUsd(input.limit ?? BACKLINKS_DEFAULT_LIMIT),+ ),+ domainPages: priced(fetchDomainPagesSummary, (input) =>+ backlinksUsd(input.limit ?? BACKLINKS_DEFAULT_LIMIT),+ ),+ history: priced(fetchBacklinksHistory, (input) =>+ backlinksUsd(daysInclusive(input.dateFrom, input.dateTo)),+ ),+ },+ keywords: {+ related: priced(fetchRelatedKeywords, (input) =>+ labsUsd(input.limit, input.includeClickstreamData),+ ),+ suggestions: priced(fetchKeywordSuggestions, (input) =>+ labsUsd(input.limit, input.includeClickstreamData),+ ),+ ideas: priced(fetchKeywordIdeas, (input) =>+ labsUsd(input.limit, input.includeClickstreamData),+ ),+ adsIdeas: priced(fetchAdsKeywordIdeas, () => GOOGLE_ADS_LIVE_TASK_USD),+ adsSearchVolume: priced(+ fetchAdsSearchVolume,+ () => GOOGLE_ADS_LIVE_TASK_USD,+ ),+ },+ domain: {+ rankOverview: priced(fetchDomainRankOverview, () => labsUsd(1)),+ rankedKeywords: priced(fetchRankedKeywords, (input) =>+ labsUsd(input.limit),+ ),+ relevantPages: priced(fetchRelevantPages, (input) => labsUsd(input.limit)),+ },+ serp: {+ live: priced(fetchLiveSerp, (input) =>+ serpUsd(clampSerpDepth(input.depth ?? SERP_ANALYSIS_DEPTH), "live"),+ ),+ rankCheck: priced(fetchRankCheckSerp, (input) =>+ serpUsd(clampSerpDepth(input.depth), "live"),+ ),+ rankCheckTaskPost: priced(+ postRankCheckTasks,+ (input) =>+ input.tasks.length * serpUsd(clampSerpDepth(input.depth), "queued"),+ ),+ local: priced(fetchLocalSerp, (input) =>+ input.searchType === "maps"+ ? LOCAL_SERP_PAGE_USD+ : Math.ceil(input.depth / 10) * LOCAL_SERP_PAGE_USD,+ ),+ },+ labs: {+ keywordOverview: priced(fetchKeywordOverview, (input) =>+ labsUsd(input.keywords.length, input.includeClickstreamData),+ ),+ serpCompetitors: priced(fetchSerpCompetitors, (input) =>+ labsUsd(input.limit),+ ),+ },+ lighthouse: {+ live: priced(fetchLighthouseResult, () => LIGHTHOUSE_LIVE_USD),+ },+ aiSearch: {+ mentionsSearch: priced(+ fetchLlmMentionsSearch,+ (input) =>+ LLM_MENTIONS_TASK_USD ++ resolveLlmMentionsLimit(input.limit) * LLM_MENTIONS_ROW_USD,+ ),+ aggregatedMetrics: priced(+ fetchLlmAggregatedMetrics,+ () => LLM_MENTIONS_ONE_ROW_USD,+ ),+ topPages: priced(fetchLlmTopPages, () => LLM_MENTIONS_ONE_ROW_USD),+ crossAggregatedMetrics: priced(+ fetchLlmCrossAggregatedMetrics,+ () => LLM_MENTIONS_ONE_ROW_USD,+ ),+ llmResponse: priced(fetchLlmResponse, (input) => {+ const price = LLM_RESPONSE_USD[input.modelSlug];+ return (input.webSearch ?? LLM_RESPONSE_WEB_SEARCH_DEFAULT)+ ? price.webSearch+ : price.noSearch;+ }),+ },+} as const;diff --git a/src/server/lib/dataforseo/serp.ts b/src/server/lib/dataforseo/serp.tsindex b78ebb14..8ad01c20 100644--- a/src/server/lib/dataforseo/serp.ts+++ b/src/server/lib/dataforseo/serp.ts@@ -23,7 +23,7 @@ import { AppError } from "@/server/lib/errors";export const SERP_ANALYSIS_DEPTH = 20;/** DataForSEO bills SERPs in pages of 10; depth outside 10-100 is rejected. */-function clampSerpDepth(depth: number): number {+export function clampSerpDepth(depth: number): number {return Math.min(100, Math.max(10, depth));}diff --git a/src/shared/billing.ts b/src/shared/billing.tsindex 100bc3dc..0be8f47d 100644--- a/src/shared/billing.ts+++ b/src/shared/billing.ts@@ -15,7 +15,7 @@ export const AUTUMN_MANAGED_ACCESS_FEATURE_ID = "managed_service_access";export const AUTUMN_SEO_DATA_BALANCE_FEATURE_ID = "usage_credits";export const AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID = "topup_credits";export const AUTUMN_SEO_DATA_CREDITS_PER_USD = 1000;-export const SEO_DATA_COST_MARKUP = 1.28;+const SEO_DATA_COST_MARKUP = 1.28;export const LOW_CREDITS_THRESHOLD_USD = 0.25;// DataForSEO's raw price for one Google Ads search_volume live call (up to// 1,000 keywords). Local keyword research adds one call to each search.@@ -57,3 +57,14 @@ export function autumnSeoDataCreditsToUsd(credits: number) {export function applyBillingMarkupUsd(rawUsd: number): number {return roundUsdForBilling(rawUsd * SEO_DATA_COST_MARKUP);}++/**+ * Credits charged for one raw provider (DataForSEO) USD cost: marked-up,+ * rounded, then ceiled per call. This is the single charging formula, so a+ * pre-call estimate and the post-call deduction cannot drift apart.+ */+export function creditsForProviderUsd(rawUsd: number): number {+ return Math.ceil(+ applyBillingMarkupUsd(rawUsd) * AUTUMN_SEO_DATA_CREDITS_PER_USD,+ );+}diff --git a/src/shared/rank-tracking.ts b/src/shared/rank-tracking.tsindex 3f957485..af49eb9f 100644--- a/src/shared/rank-tracking.ts+++ b/src/shared/rank-tracking.ts@@ -1,6 +1,6 @@import {- AUTUMN_SEO_DATA_CREDITS_PER_USD,- SEO_DATA_COST_MARKUP,+ applyBillingMarkupUsd,+ creditsForProviderUsd,roundUsdForBilling,} from "./billing";import type {@@ -60,7 +60,10 @@ export const rankCheckCostApprovalError = (// ---------------------------------------------------------------------------/** DataForSEO cost for a single SERP request at the given depth. */-function costPerSerpAtDepth(depth: number, method: RankCheckMethod): number {+export function costPerSerpAtDepth(+ depth: number,+ method: RankCheckMethod,+): number {const pages = depth / 10;return method === "queued"? QUEUED_BASE_PAGE_COST_USD + (pages - 1) * QUEUED_EXTRA_PAGE_COST_USD@@ -92,11 +95,9 @@ export function estimateRankCheckCredits(// once can therefore understate the credits that will actually be charged.for (let offset = 0; offset < totalChecks; offset += checksPerMeteredCall) {const checksInCall = Math.min(checksPerMeteredCall, totalChecks - offset);- const callCostUsd = roundUsdForBilling(- checksInCall * costPerSerpAtDepth(depth, method) * SEO_DATA_COST_MARKUP,- );- costUsd += callCostUsd;- costCredits += Math.ceil(callCostUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD);+ const callRawUsd = checksInCall * costPerSerpAtDepth(depth, method);+ costUsd += applyBillingMarkupUsd(callRawUsd);+ costCredits += creditsForProviderUsd(callRawUsd);}// This is the nominal queued task_post estimate. Rejected, failed, or