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
perf(api): skip the monolith's Autumn provisioning prefix on the firebill route (#4597)
Rakshith Ramprakash5e57a065ac4d
diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex f6b8cad49..d6a514f15 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -1999,3 +1999,297 @@ describe("inline provisioning counters", () => {expect(await customerCalls()).toBe(1);});});++// ---------------------------------------------------------------------------+// Who provisions, by route (Β§2 of the middleware credit-check spec). On the+// firebill route the monolith no longer runs its own customer/entity prefix:+// firebill creates a missing entity itself, off the 404 Autumn answers the+// billing call with. The direct route keeps provisioning exactly as it did.+// ---------------------------------------------------------------------------++describe("provisioning by route", () => {+ const mockFetch = vi.fn<(url: any, init?: any) => Promise<Response>>();++ const firebillConfig = () => ({+ FIREBILL_URL: "http://firebill.test",+ FIREBILL_SECRET: "fb-secret",+ FIREBILL_ORG_IDS: ["org-1"],+ });++ // The same team, off the allowlist and at 0 percent, so it bills straight to+ // Autumn. The route is the only thing that differs between the two halves.+ const directConfig = () => ({+ ...firebillConfig(),+ FIREBILL_ORG_IDS: ["some-other-org"],+ FIREBILL_ROLLOUT_PERCENT: 0,+ });++ // A fresh Response per call: firebill reads the body, and a reused one looks+ // like a failure and triggers its retry.+ const answers = (body: Record<string, unknown>) => () =>+ Promise.resolve(new Response(JSON.stringify(body), { status: 200 }));++ const expectNoProvisioning = () => {+ expect(mockGetOrCreate).not.toHaveBeenCalled();+ expect(mockEntityGet).not.toHaveBeenCalled();+ expect(mockEntityCreate).not.toHaveBeenCalled();+ };++ beforeEach(() => {+ mockFetch.mockReset();+ mockFetch.mockImplementation(+ answers({+ success: true,+ allowed: true,+ remaining: 500,+ lock_id: "lock-1",+ }),+ );+ vi.stubGlobal("fetch", mockFetch);+ state.gatewayStubRow = null;+ state.gatewayStubThrows = false;+ state.configRef = firebillConfig();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("check asks firebill the same question, and provisions nothing", async () => {+ const svc = makeService();++ const result = await svc.checkCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 100,+ properties: { source: "checkCreditsMiddleware" },+ });++ expect(result).toEqual({ allowed: true, remaining: 500 });+ expectNoProvisioning();+ expect(mockCheck).not.toHaveBeenCalled();+ const [url, init] = mockFetch.mock.calls[0]!;+ expect(String(url)).toBe("http://firebill.test/v1/check");+ expect(JSON.parse(init.body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ value: 100,+ properties: { source: "checkCreditsMiddleware" },+ });+ });++ it("lock holds through firebill unchanged, and provisions nothing", async () => {+ const svc = makeService();++ const result = await svc.lockCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 10,+ lockId: "lock-1",+ expiresAt: 1_700_000_000_000,+ properties: { source: "monitorCheck" },+ });++ expect(result).toEqual({ status: "locked", lockId: "lock-1" });+ expectNoProvisioning();+ const [url, init] = mockFetch.mock.calls[0]!;+ expect(String(url)).toBe("http://firebill.test/v1/lock");+ expect(JSON.parse(init.body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ value: 10,+ lock_id: "lock-1",+ expires_at: 1_700_000_000_000,+ properties: { source: "monitorCheck" },+ });+ });++ it("a gated lock still arms the partner gate, and provisions nothing", async () => {+ mockFetch.mockImplementation(+ answers({+ success: true,+ allowed: true,+ lock_id: "lock-1",+ operation_token: "run-42",+ }),+ );+ const svc = makeService();++ const result = await svc.lockCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 10,+ lockId: "lock-1",+ expiresAt: 1_700_000_000_000,+ partnerJobToken: "pjt-1",+ });++ expect(result).toEqual({+ status: "locked",+ lockId: "lock-1",+ operationToken: "run-42",+ });+ expectNoProvisioning();+ expect(JSON.parse(mockFetch.mock.calls[0]![1].body).partner_job_token).toBe(+ "pjt-1",+ );+ });++ it("track forwards the same event, and provisions nothing", async () => {+ const svc = makeService();++ await expect(+ svc.trackCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 42,+ properties: { source: "billScrapeJob", endpoint: "scrape" },+ idempotencyKey: "fc:track:scrape:job-1",+ }),+ ).resolves.toBe(true);++ expectNoProvisioning();+ expect(mockTrack).not.toHaveBeenCalled();+ const [url, init] = mockFetch.mock.calls[0]!;+ expect(String(url)).toBe("http://firebill.test/v1/track");+ expect(JSON.parse(init.body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ value: 42,+ properties: { source: "billScrapeJob", endpoint: "scrape" },+ idempotency_key: "fc:track:scrape:job-1",+ });+ });++ it("refund forwards the same event, and provisions nothing", async () => {+ const svc = makeService();++ await svc.refundCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 30,+ properties: { endpoint: "extract" },+ idempotencyKey: "fc:refund:extract:job-1",+ });++ expectNoProvisioning();+ expect(mockTrack).not.toHaveBeenCalled();+ const [url, init] = mockFetch.mock.calls[0]!;+ expect(String(url)).toBe("http://firebill.test/v1/refund");+ expect(JSON.parse(init.body)).toEqual({+ customer_id: "org-1",+ entity_id: "team-1",+ feature_id: "CREDITS",+ // firebill negates a refund itself, so the positive value goes on the wire.+ value: 30,+ properties: { endpoint: "extract", source: "autumn_refund" },+ idempotency_key: "fc:refund:extract:job-1",+ });+ });++ // The gated settle needs the org named β that is the whole reason it resolves+ // one β so this is the case where skipping the prefix must not cost the label.+ it("a gated finalize still names the org, and provisions nothing", async () => {+ const svc = makeService();++ await expect(+ svc.finalizeCreditsLock({+ lockId: "monitor_check-1",+ action: "confirm",+ overrideValue: 7,+ team: { teamId: "team-1", orgId: "org-1" },+ externalRequestId: "run-42",+ heldValue: 12,+ }),+ ).resolves.toBe(true);++ expectNoProvisioning();+ expect(mockFinalize).not.toHaveBeenCalled();+ const [url, init] = mockFetch.mock.calls[0]!;+ expect(String(url)).toBe("http://firebill.test/v1/finalize");+ const body = JSON.parse(init.body);+ expect(body.customer_id).toBe("org-1");+ expect(body.external_request_id).toBe("run-42");+ expect(body.feature_id).toBe("CREDITS");+ expect(body.held_value).toBe(12);+ });++ // Skipping the prefix must not also claim the team is provisioned: nothing+ // here checked the entity, so a later direct-route operation still has to.+ it("leaves ensuredTeams cold, so the direct route still provisions", async () => {+ const svc = makeService();++ await svc.checkCredits({ teamId: "team-1", orgId: "org-1", value: 1 });+ expectNoProvisioning();++ state.configRef = directConfig();+ await svc.checkCredits({ teamId: "team-1", orgId: "org-1", value: 1 });++ expect(mockGetOrCreate).toHaveBeenCalledTimes(1);+ expect(mockEntityGet).toHaveBeenCalledTimes(1);+ });++ const operations: Record<string, (svc: AutumnService) => Promise<unknown>> = {+ check: svc =>+ svc.checkCredits({ teamId: "team-1", orgId: "org-1", value: 1 }),+ lock: svc =>+ svc.lockCredits({+ teamId: "team-1",+ orgId: "org-1",+ value: 1,+ lockId: "lock-1",+ }),+ track: svc =>+ svc.trackCredits({ teamId: "team-1", orgId: "org-1", value: 1 }),+ refund: svc =>+ svc.refundCredits({ teamId: "team-1", orgId: "org-1", value: 1 }),+ };++ describe.each(Object.entries(operations))(+ "the direct route's %s",+ (_name, run) => {+ beforeEach(() => {+ state.configRef = directConfig();+ });++ it("provisions a cold team: getOrCreate then get, no create", async () => {+ const svc = makeService();++ await run(svc);++ expect(mockGetOrCreate).toHaveBeenCalledTimes(1);+ expect(mockEntityGet).toHaveBeenCalledTimes(1);+ expect(mockEntityCreate).not.toHaveBeenCalled();+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it("creates the entity Autumn answers 404 for", async () => {+ mockEntityGet.mockRejectedValue({ statusCode: 404 });+ const svc = makeService();++ await run(svc);++ expect(mockEntityCreate).toHaveBeenCalledTimes(1);+ expect(mockEntityCreate).toHaveBeenCalledWith({+ customerId: "org-1",+ entityId: "team-1",+ featureId: "TEAM",+ });+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it("provisions nothing once the team is ensured", async () => {+ const svc = makeService();++ await run(svc);+ vi.clearAllMocks();+ await run(svc);++ expectNoProvisioning();+ });+ },+ );+});diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex 5b4c15d2c..522a437c4 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -298,24 +298,28 @@ export class AutumnService {}}- private async track({- customerId,- entityId,- featureId,- value,- properties,- idempotencyKey,- }: TrackParams): Promise<boolean> {+ /**+ * `routed` is decided by the caller (see {@link resolveBillingRoute}) rather+ * than asked again here: the answer costs a `partner_provisioned_accounts`+ * read on a cold team, and the caller already needed it to know whether to+ * provision.+ */+ private async track(+ {+ customerId,+ entityId,+ featureId,+ value,+ properties,+ idempotencyKey,+ }: TrackParams,+ routed: boolean,+ ): Promise<boolean> {// Gradual rollout: allowlisted orgs, partner-provisioned orgs, and those in// sticky FIREBILL_ROLLOUT_PERCENT bucket bill through firebill. No fallback// to Autumn on failure β firebill may already own the event, and the SDK// sends no idempotency key, so the pair could not be deduped.- // No entity means no team, and every provisioned account has one β so there- // is nothing to look up.- const gatewayProvisioned = entityId- ? await this.isGatewayProvisioned(entityId)- : false;- if (shouldRouteToFirebill(customerId, { gatewayProvisioned })) {+ if (routed) {billingRouteTotal.labels("firebill").inc();return await firebillTrack({customerId,@@ -432,19 +436,30 @@ export class AutumnService {}/**- * Warms the Autumn customer/entity context needed before tracking usage and- * answers with the customer to bill β the caller's org, which this service- * never looks up for itself. A team already provisioned under this org skips- * ensureTeamProvisioned entirely.+ * Decides the route a team's billing takes, and warms the customer/entity+ * context the direct route needs. The customer is the caller's own org,+ * which this service never looks up for itself.+ *+ * **Provisioning runs on the direct route only.** firebill creates a missing+ * entity itself now, off the 404 `entity_not_found` Autumn answers the+ * billing call with, so the get/create prefix here would be a second,+ * redundant round trip β one that cannot change the answer either way,+ * because its failure is caught and the operation proceeds regardless.+ *+ * A team already provisioned under this org skips ensureTeamProvisioned+ * entirely.*/- private async ensureTrackingContext(+ private async resolveBillingRoute(teamId: string,orgId: string,- ): Promise<string> {- if (!this.ensuredTeams.has(this.ensuredTeamKey(orgId, teamId))) {+ ): Promise<{ customerId: string; routed: boolean }> {+ const routed = shouldRouteToFirebill(orgId, {+ gatewayProvisioned: await this.isGatewayProvisioned(teamId),+ });+ if (!routed && !this.ensuredTeams.has(this.ensuredTeamKey(orgId, teamId))) {await this.ensureTeamProvisioned({ teamId, orgId });}- return orgId;+ return { customerId: orgId, routed };}/**@@ -465,7 +480,10 @@ export class AutumnService {return null;}try {- const customerId = await this.ensureTrackingContext(teamId, orgId);+ const { customerId, routed } = await this.resolveBillingRoute(+ teamId,+ orgId,+ );// Mirrors track() and lockCredits(). Without this branch the gate reads// the ghost's balance alone, and a gateway ghost is designed to spend@@ -483,11 +501,7 @@ export class AutumnService {// outright, because Autumn is asked about a balance the org was never// meant to pay from. So the org this most needs to reach firebill is// exactly the one a sampling bucket might leave behind.- if (- shouldRouteToFirebill(customerId, {- gatewayProvisioned: await this.isGatewayProvisioned(teamId),- })- ) {+ if (routed) {const result = await firebillCheck({customerId,entityId: teamId,@@ -560,7 +574,10 @@ export class AutumnService {: { status: "skipped" };try {- const customerId = await this.ensureTrackingContext(teamId, orgId);+ const { customerId, routed } = await this.resolveBillingRoute(+ teamId,+ orgId,+ );// Gradual firebill rollout, mirroring track(): allowlisted orgs take// their holds through firebill. The hold still lives in Autumn (firebill@@ -568,11 +585,7 @@ export class AutumnService {// around the call. An unavailable answer maps to "skipped" β proceed// unlocked β like a direct-Autumn check failure below, except when a// partner gate is involved; see `unreachable` above.- if (- shouldRouteToFirebill(customerId, {- gatewayProvisioned: await this.isGatewayProvisioned(teamId),- })- ) {+ if (routed) {const result = await firebillLock({customerId,entityId: teamId,@@ -689,29 +702,21 @@ export class AutumnService {gated ||(team && (await this.isRoutedThroughFirebill(team.teamId, team.orgId)))) {- // Only resolved for a gated settle: firebill needs the org to split the+ // Named only for a gated settle: firebill needs the org to split the// settle and to find the integration to report to. An ordinary finalize- // does neither, so it does not pay for the lookup.+ // does neither, so it does not carry one. Nothing is provisioned here β+ // every settle on this branch goes through firebill, which provisions+ // what it needs (see resolveBillingRoute).//- // A failure degrades to omitting it rather than throwing. There is no- // durable retry on this path β `billMonitorCheck`'s only caller catches,- // writes `billing_status: "failed"`, and moves on, and nothing ever reads- // that back β so throwing would abandon the finalize entirely: the hold+ // A caller that cannot name the org passes no team and the settle still+ // lands, without the label. There is no durable retry on this path β+ // `billMonitorCheck`'s only caller catches, writes+ // `billing_status: "failed"`, and moves on, and nothing ever reads that+ // back β so refusing would abandon the finalize entirely: the hold// expires and the run goes unbilled at Autumn as well as unreported.// Settling and losing the label is the lesser loss, and firebill counts// the lost label as `partner_events_total{outcome="no_customer"}`.- const customerId =- externalRequestId && team- ? await this.ensureTrackingContext(team.teamId, team.orgId).catch(- error => {- logger.error(- "Could not provision the customer for a gated settle; finalizing anyway, but this run cannot be reported to its partner",- { teamId: team.teamId, lockId, error },- );- return null;- },- )- : null;+ const customerId = externalRequestId && team ? team.orgId : null;// Surfaced, not discarded. firebill answers `false` for a refusal, a// timeout, or a non-OK β none of which throw β so a caller that ignores// this records a run as billed that nobody billed.@@ -773,15 +778,21 @@ export class AutumnService {if (this.isPreviewTeam(teamId)) return false;try {- const customerId = await this.ensureTrackingContext(teamId, orgId);- return await this.track({- customerId,- entityId: teamId,- featureId,- value,- properties,- idempotencyKey,- });+ const { customerId, routed } = await this.resolveBillingRoute(+ teamId,+ orgId,+ );+ return await this.track(+ {+ customerId,+ entityId: teamId,+ featureId,+ value,+ properties,+ idempotencyKey,+ },+ routed,+ );} catch (error) {logger.error("Autumn trackCredits failed β billing API may be unavailable",@@ -965,15 +976,21 @@ export class AutumnService {if (this.isPreviewTeam(teamId)) return;try {- const customerId = await this.ensureTrackingContext(teamId, orgId);- await this.track({- customerId,- entityId: teamId,- featureId,- value: -value,- properties: { ...properties, source: "autumn_refund" },- idempotencyKey,- });+ const { customerId, routed } = await this.resolveBillingRoute(+ teamId,+ orgId,+ );+ await this.track(+ {+ customerId,+ entityId: teamId,+ featureId,+ value: -value,+ properties: { ...properties, source: "autumn_refund" },+ idempotencyKey,+ },+ routed,+ );} catch (error) {logger.error("Autumn refundCredits failed β billing API may be unavailable",