Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Route monitor credit locks and finalizes through firebill for rollout orgs
Rakshith Ramprakash8fae7cadb5d2
diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex 42249c36c..c70ce2811 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -890,4 +890,190 @@ describe("firebill routing", () => {expect(result).toBe(false);expect(mockTrack).not.toHaveBeenCalled();});++ // -------------------------------------------------------------------------+ // lockCredits / finalizeCreditsLock (the monitor check flow)+ // -------------------------------------------------------------------------++ const lockResponse = (body: Record<string, unknown>) =>+ new Response(JSON.stringify(body), { status: 200 });++ it("routes lockCredits for an allowlisted org to /v1/lock, not Autumn", async () => {+ state.configRef = firebillConfig();+ mockFetch.mockResolvedValue(+ lockResponse({+ success: true,+ allowed: true,+ lock_id: "monitor_check-1",+ }),+ );+ const svc = makeService();++ const expiresAt = Date.now() + 60 * 60 * 1000;+ const result = await svc.lockCredits({+ teamId: "team-1",+ value: 10,+ lockId: "monitor_check-1",+ expiresAt,+ properties: { source: "monitorCheck", endpoint: "monitor" },+ });++ expect(result).toEqual({ status: "locked", lockId: "monitor_check-1" });+ expect(mockCheck).not.toHaveBeenCalled();++ const lockCall = mockFetch.mock.calls.find(([url]) =>+ String(url).endsWith("/v1/lock"),+ );+ expect(lockCall).toBeDefined();+ expect(lockCall![1].headers.authorization).toBe("Bearer fb-secret");+ expect(JSON.parse(lockCall![1].body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ value: 10,+ lock_id: "monitor_check-1",+ expires_at: expiresAt,+ properties: { source: "monitorCheck", endpoint: "monitor" },+ });+ });++ it("defaults the lock expiry when the caller sets none β firebill requires one", async () => {+ state.configRef = firebillConfig();+ mockFetch.mockResolvedValue(+ lockResponse({ success: true, allowed: true, lock_id: "lock-1" }),+ );+ const svc = makeService();++ const before = Date.now();+ await svc.lockCredits({ teamId: "team-1", value: 1, lockId: "lock-1" });++ const lockCall = mockFetch.mock.calls.find(([url]) =>+ String(url).endsWith("/v1/lock"),+ );+ const body = JSON.parse(lockCall![1].body);+ expect(body.expires_at).toBeGreaterThanOrEqual(before + 60 * 60 * 1000);+ });++ it("maps a firebill lock denial to denied", async () => {+ state.configRef = firebillConfig();+ mockFetch.mockResolvedValue(+ lockResponse({ success: true, allowed: false }),+ );+ const svc = makeService();++ const result = await svc.lockCredits({+ teamId: "team-1",+ value: 10,+ lockId: "lock-1",+ });++ expect(result).toEqual({ status: "denied" });+ expect(mockCheck).not.toHaveBeenCalled();+ });++ it("maps firebill lock unavailability to skipped β proceed unlocked, no Autumn fallback", async () => {+ state.configRef = firebillConfig();+ const svc = makeService();++ mockFetch.mockResolvedValueOnce(lockResponse({ success: false }));+ expect(+ await svc.lockCredits({ teamId: "team-1", value: 10, lockId: "lock-1" }),+ ).toEqual({ status: "skipped" });++ mockFetch.mockRejectedValueOnce(new Error("ECONNREFUSED"));+ expect(+ await svc.lockCredits({ teamId: "team-1", value: 10, lockId: "lock-1" }),+ ).toEqual({ status: "skipped" });++ // A firebill-side hold may exist under this lock id; a direct-Autumn+ // retry of the same lock must never be attempted.+ expect(mockCheck).not.toHaveBeenCalled();+ });++ it("uses the direct Autumn lock path for orgs NOT on the allowlist", async () => {+ state.configRef = {+ ...firebillConfig(),+ FIREBILL_ORG_IDS: ["some-other-org"],+ };+ const svc = makeService();++ const result = await svc.lockCredits({+ teamId: "team-1",+ value: 10,+ lockId: "lock-1",+ });++ expect(result).toEqual({ status: "locked", lockId: "lock-1" });+ expect(mockFetch).not.toHaveBeenCalled();+ expect(mockCheck).toHaveBeenCalledTimes(1);+ });++ it("routes finalizeCreditsLock through /v1/finalize when teamId is on the rollout", async () => {+ state.configRef = firebillConfig();+ const svc = makeService();++ await svc.finalizeCreditsLock({+ lockId: "monitor_check-1",+ action: "confirm",+ overrideValue: 7,+ properties: { source: "monitorCheck", endpoint: "monitor" },+ teamId: "team-1",+ });++ expect(mockFinalize).not.toHaveBeenCalled();+ const finalizeCall = mockFetch.mock.calls.find(([url]) =>+ String(url).endsWith("/v1/finalize"),+ );+ expect(finalizeCall).toBeDefined();+ expect(JSON.parse(finalizeCall![1].body)).toEqual({+ lock_id: "monitor_check-1",+ action: "confirm",+ override_value: 7,+ properties: { source: "monitorCheck", endpoint: "monitor" },+ // Deterministic per (lock, action) so a reconciler re-finalize dedupes.+ idempotency_key: "fc:finalize:confirm:monitor_check-1",+ });+ });++ it("omits override_value on a release and keys it separately from a confirm", async () => {+ state.configRef = firebillConfig();+ const svc = makeService();++ await svc.finalizeCreditsLock({+ lockId: "monitor_check-1",+ action: "release",+ teamId: "team-1",+ });++ const body = JSON.parse(mockFetch.mock.calls[0]![1].body);+ expect("override_value" in body).toBe(false);+ expect(body.idempotency_key).toBe("fc:finalize:release:monitor_check-1");+ });++ it("finalizes directly in Autumn when no teamId is supplied", async () => {+ state.configRef = firebillConfig();+ const svc = makeService();++ await svc.finalizeCreditsLock({ lockId: "lock-1", action: "release" });++ expect(mockFetch).not.toHaveBeenCalled();+ expect(mockFinalize).toHaveBeenCalledTimes(1);+ });++ it("finalizes directly in Autumn when the team's org is NOT on the allowlist", async () => {+ state.configRef = {+ ...firebillConfig(),+ FIREBILL_ORG_IDS: ["some-other-org"],+ };+ const svc = makeService();++ await svc.finalizeCreditsLock({+ lockId: "lock-1",+ action: "confirm",+ teamId: "team-1",+ });++ expect(mockFetch).not.toHaveBeenCalled();+ expect(mockFinalize).toHaveBeenCalledTimes(1);+ });});diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex 020d44427..4e751bc70 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -4,7 +4,12 @@ import { eq } from "drizzle-orm";import { dbRr } from "../../db/connection";import * as schema from "../../db/schema";import { autumnClient } from "./client";-import { firebillTrack, shouldRouteToFirebill } from "./firebill";+import {+ firebillFinalize,+ firebillLock,+ firebillTrack,+ shouldRouteToFirebill,+} from "./firebill";import type {CreateEntityParams,CreateEntityResult,@@ -445,6 +450,34 @@ export class AutumnService {try {const customerId = await this.ensureTrackingContext(teamId);++ // Gradual firebill rollout, mirroring track(): allowlisted orgs take+ // their holds through firebill. The hold still lives in Autumn (firebill+ // keeps no lock state), but only firebill pins the retry/timeout budget+ // around the call. An unavailable answer maps to "skipped" β proceed+ // unlocked β exactly like a direct-Autumn check failure below.+ if (shouldRouteToFirebill(customerId)) {+ const result = await firebillLock({+ customerId,+ entityId: teamId,+ featureId,+ value,+ lockId: resolvedLockId,+ // firebill requires an expiry (Autumn releasing the hold by itself+ // is what makes firebill lock-table-free); default to an hour, the+ // monitor runner's convention, when the caller sets none.+ expiresAt: expiresAt ?? Date.now() + 60 * 60 * 1000,+ properties,+ });+ if (result.status === "locked") {+ return { status: "locked", lockId: result.lockId };+ }+ if (result.status === "denied") {+ return { status: "denied" };+ }+ return { status: "skipped" };+ }+const { allowed } = await autumnClient.check({customerId,entityId: teamId,@@ -492,13 +525,25 @@ export class AutumnService {/*** Finalizes a previously-acquired Autumn lock.+ *+ * When the caller supplies the lock's teamId and that team's org is on the+ * firebill rollout, the settle goes through firebill, which queues it+ * durably and retries delivery β a dropped direct finalize means the hold+ * just expires, leaving a confirm's work unbilled. Either route lands on the+ * same Autumn lock, so routing is a durability choice, not a correctness one.*/async finalizeCreditsLock({lockId,action,overrideValue,properties,+ teamId,}: FinalizeCreditsLockParams): Promise<void> {+ if (teamId && (await this.isRoutedThroughFirebill(teamId))) {+ await firebillFinalize({ lockId, action, overrideValue, properties });+ return;+ }+if (!autumnClient) return;try {diff --git a/apps/api/src/services/autumn/firebill.ts b/apps/api/src/services/autumn/firebill.tsindex 12714a17b..7d14b1de3 100644--- a/apps/api/src/services/autumn/firebill.ts+++ b/apps/api/src/services/autumn/firebill.ts@@ -2,6 +2,17 @@ import { config } from "../../config";import { logger } from "../../lib/logger";import type { TrackParams } from "./types";+/**+ * Outcome of a firebill `/v1/lock` call, mirroring firebill's three-state+ * answer: `denied` is Autumn saying no (a real answer β the caller must not+ * proceed), while `unavailable` means firebill couldn't get an answer out of+ * Autumn at all and the caller decides how its endpoint fails.+ */+type FirebillLockResult =+ | { status: "locked"; lockId: string }+ | { status: "denied" }+ | { status: "unavailable" };+// firebill's own internal budget (durable write + forward attempt) is up to// ~3.5s worst case, so this is deliberately looser than the 2s timeout on the// direct Autumn client.@@ -35,6 +46,12 @@ export function shouldRouteToFirebill(orgId: string): boolean {return firebillOrgIds().has(orgId);}+// Plain concatenation rather than new URL(path, base): a leading-slash path+// would drop any base-path prefix (e.g. a reverse proxy at /firebill).+function firebillUrl(path: string): string {+ return `${config.FIREBILL_URL!.replace(/\/+$/, "")}${path}`;+}+/*** Sends a usage event to firebill, which records it durably in Postgres and* forwards it to Autumn (replaying failed deliveries instead of losing them).@@ -56,9 +73,7 @@ export async function firebillTrack({idempotencyKey,}: TrackParams): Promise<boolean> {const path = value < 0 ? "/v1/refund" : "/v1/track";- // Plain concatenation rather than new URL(path, base): a leading-slash path- // would drop any base-path prefix (e.g. a reverse proxy at /firebill).- const url = `${config.FIREBILL_URL!.replace(/\/+$/, "")}${path}`;+ const url = firebillUrl(path);try {const response = await fetch(url, {method: "POST",@@ -133,3 +148,199 @@ export async function firebillTrack({return false;}}++/**+ * Holds balance via firebill's `/v1/lock`, the one synchronous firebill route:+ * firebill calls Autumn inline (it keeps no lock state of its own β Autumn+ * expires the hold by itself at `expiresAt`) and answers in three states.+ *+ * `unavailable` covers everything that isn't a real answer β firebill down,+ * non-OK response, or firebill reporting it couldn't reach Autumn. As with+ * track, there is deliberately no direct-Autumn fallback here: splitting one+ * lock's lifecycle across two routes would let a firebill-side hold and a+ * fallback hold coexist under retries.+ */+export async function firebillLock({+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ expiresAt,+ properties,+}: {+ customerId: string;+ entityId: string;+ featureId: string;+ value: number;+ lockId: string;+ expiresAt: number;+ properties?: Record<string, unknown>;+}): Promise<FirebillLockResult> {+ const url = firebillUrl("/v1/lock");+ try {+ const response = await fetch(url, {+ method: "POST",+ headers: {+ authorization: `Bearer ${config.FIREBILL_SECRET}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ customer_id: customerId,+ entity_id: entityId,+ feature_id: featureId,+ value,+ // Caller-chosen and deterministic β firebill never mints one, because+ // a minted id would be lost on a timeout, leaving a hold nobody can+ // finalize. Autumn enforces it as the lock's idempotency key.+ lock_id: lockId,+ expires_at: expiresAt,+ properties,+ }),+ signal: AbortSignal.timeout(FIREBILL_TIMEOUT_MS),+ });++ if (!response.ok) {+ logger.error("firebill lock failed β non-OK response", {+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ status: response.status,+ });+ return { status: "unavailable" };+ }++ const body = (await response.json()) as {+ success?: boolean;+ allowed?: boolean;+ lock_id?: string;+ };++ if (body.success !== true) {+ logger.error("firebill lock did not succeed", {+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ });+ return { status: "unavailable" };+ }++ if (body.allowed !== true) {+ logger.info("firebill lock denied", {+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ });+ return { status: "denied" };+ }++ logger.info("firebill lock succeeded", {+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ });+ return { status: "locked", lockId: body.lock_id ?? lockId };+ } catch (error) {+ logger.error("firebill lock failed β firebill may be unavailable", {+ customerId,+ entityId,+ featureId,+ value,+ lockId,+ error,+ });+ return { status: "unavailable" };+ }+}++/**+ * Settles a lock via firebill's `/v1/finalize`: `confirm` bills the hold,+ * `release` gives the balance back. firebill queues the settle durably and+ * retries it until it lands in Autumn, instead of dropping it when Autumn+ * blinks (the direct-Autumn path's failure mode β the lock then just expires,+ * which for a confirm means the work goes unbilled).+ *+ * Returns true when firebill accepted the settle for delivery, mirroring the+ * void-and-log contract of the direct finalize path. No direct-Autumn+ * fallback, for the same reason as track: firebill may have durably queued+ * the settle before the call failed.+ */+export async function firebillFinalize({+ lockId,+ action,+ overrideValue,+ properties,+}: {+ lockId: string;+ action: "confirm" | "release";+ overrideValue?: number;+ properties?: Record<string, unknown>;+}): Promise<boolean> {+ const url = firebillUrl("/v1/finalize");+ try {+ const response = await fetch(url, {+ method: "POST",+ headers: {+ authorization: `Bearer ${config.FIREBILL_SECRET}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ lock_id: lockId,+ action,+ ...(overrideValue !== undefined+ ? { override_value: overrideValue }+ : {}),+ properties,+ // Deterministic per (lock, action): the lock id is itself caller-chosen+ // and stable (`monitor_${check.id}`), so a re-finalize of the same+ // settle β e.g. the reconciler re-running a check it raced β dedupes+ // upstream instead of settling twice.+ idempotency_key: `fc:finalize:${action}:${lockId}`,+ }),+ signal: AbortSignal.timeout(FIREBILL_TIMEOUT_MS),+ });++ if (!response.ok) {+ logger.error("firebill finalize failed β non-OK response", {+ lockId,+ action,+ overrideValue,+ status: response.status,+ });+ return false;+ }++ const body = (await response.json()) as { success?: boolean };+ if (body.success !== true) {+ logger.error("firebill finalize did not succeed", {+ lockId,+ action,+ overrideValue,+ });+ return false;+ }++ logger.info("firebill finalize succeeded", {+ lockId,+ action,+ overrideValue,+ });+ return true;+ } catch (error) {+ logger.error("firebill finalize failed β firebill may be unavailable", {+ lockId,+ action,+ overrideValue,+ error,+ });+ return false;+ }+}diff --git a/apps/api/src/services/autumn/types.ts b/apps/api/src/services/autumn/types.tsindex 564c6b086..18859d1bb 100644--- a/apps/api/src/services/autumn/types.ts+++ b/apps/api/src/services/autumn/types.ts@@ -72,6 +72,14 @@ export type FinalizeCreditsLockParams = {action: "confirm" | "release";overrideValue?: number;properties?: Record<string, unknown>;+ /**+ * The team the lock was taken for. Needed to route the settle through+ * firebill for allowlisted orgs β a finalize carries no customer context of+ * its own. When omitted, the settle goes directly to Autumn (which also+ * works for a firebill-taken lock: the hold lives in Autumn either way, but+ * loses firebill's durable retry).+ */+ teamId?: string;};export type TrackCreditsParams = {diff --git a/apps/api/src/services/monitoring/runner.ts b/apps/api/src/services/monitoring/runner.tsindex c3cd12dfe..ca4c271b2 100644--- a/apps/api/src/services/monitoring/runner.ts+++ b/apps/api/src/services/monitoring/runner.ts@@ -358,6 +358,7 @@ async function billMonitorCheck(params: {endpoint: "monitor",jobId: params.check.id,},+ teamId: params.monitor.team_id,});}@@ -1057,6 +1058,7 @@ export async function processMonitorCheckJob(endpoint: "monitor",jobId: check.id,},+ teamId: monitor.team_id,});}@@ -1232,6 +1234,7 @@ async function failStaleMonitorCheck(params: {endpoint: "monitor",jobId: params.check.id,},+ teamId: params.monitor.team_id,}).catch(releaseError => {logger.warn("Failed to release stale monitor check credit lock", {@@ -1338,6 +1341,7 @@ export async function reconcileRunningMonitorChecks(endpoint: "monitor",jobId: check.id,},+ teamId: check.team_id,}).catch(error => {logger.warn(diff --git a/apps/api/src/services/monitoring/scheduler.ts b/apps/api/src/services/monitoring/scheduler.tsindex 0994d1fec..20c3855e7 100644--- a/apps/api/src/services/monitoring/scheduler.ts+++ b/apps/api/src/services/monitoring/scheduler.ts@@ -202,6 +202,7 @@ async function clearFinishedOrStaleCurrentCheck(endpoint: "monitor",jobId: current.id,},+ teamId: monitor.team_id,}).catch(error => {logger.warn("Failed to release stale monitor check credit lock", {