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
fix(api/autumn): expire team→org cache and key provisioning by org (#4561)
Rakshith Ramprakash7a1e57ce537c
diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex ac6ee4edd..5ecce4076 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -171,6 +171,16 @@ const configSchema = z.object({LLAMAPARSE_API_KEY: z.string().optional(),STRIPE_SECRET_KEY: z.string().optional(),AUTUMN_SECRET_KEY: z.string().optional(),+ // How long a team → org mapping is trusted in-process before it is re-read+ // from the DB. Bounded because a team's org changes when accounts are merged+ // or moved: every warm pod otherwise keeps billing the old Autumn customer+ // (and 404s on the entity that no longer lives there) until it restarts.+ AUTUMN_ORG_CACHE_TTL_SECONDS: z.coerce+ .number()+ .int()+ .min(0)+ .max(3600)+ .default(300),RESEND_API_KEY: z.string().optional(),PREVIEW_TOKEN: z.string().optional(),SEARCH_PREVIEW_TOKEN: z.string().optional(),diff --git a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts b/apps/api/src/services/autumn/__tests__/autumn.service.test.tsindex e1e63f9c4..67ff4b401 100644--- a/apps/api/src/services/autumn/__tests__/autumn.service.test.ts+++ b/apps/api/src/services/autumn/__tests__/autumn.service.test.ts@@ -72,7 +72,10 @@ const {return {from: () => ({where: () => ({- limit: () => Promise.resolve(rows),+ limit: () =>+ !isGatewayLookup && state.dbLimitOverride+ ? state.dbLimitOverride()+ : Promise.resolve(rows),}),}),};@@ -101,6 +104,9 @@ const {gatewayStubRow: null as unknown,// Makes the gateway lookup throw, to prove a failure is never cached.gatewayStubThrows: false,+ // When set, replaces the team → org_id query result (e.g. to hold a+ // lookup open and observe how many are issued).+ dbLimitOverride: null as (() => Promise<unknown[]>) | null,configRef: {} as Record<string, unknown>,},};@@ -367,6 +373,136 @@ describe("ensureTrackingContext warm-cache short-circuit", () => {});});+// ---------------------------------------------------------------------------+// Org moves: the team → org cache must expire and re-provision under the new org+// ---------------------------------------------------------------------------++describe("team org change", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("keeps billing the cached org while the mapping is fresh", async () => {+ vi.useFakeTimers();+ const svc = makeService();++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ expect(mockTrack).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-1" }),+ );++ // Org moves in the DB, but the cache has not expired yet (default 300s).+ state.supabaseStubData = { data: { org_id: "org-2" }, error: null };+ vi.advanceTimersByTime(299_000);++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ expect(mockTrack).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-1" }),+ );+ });++ it("re-reads the org after the TTL and provisions the entity under the new org", async () => {+ vi.useFakeTimers();+ const svc = makeService();++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ expect(mockTrack).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-1", entityId: "team-1" }),+ );+ const entityGetsBefore = mockEntityGet.mock.calls.length;++ state.supabaseStubData = { data: { org_id: "org-2" }, error: null };+ // The entity does not exist under the new customer yet.+ mockEntityGet.mockResolvedValue(null);+ vi.advanceTimersByTime(301_000);++ await svc.trackCredits({ teamId: "team-1", value: 1 });++ // Provisioning ran again for the (org-2, team-1) pair...+ expect(mockEntityGet.mock.calls.length).toBe(entityGetsBefore + 1);+ expect(mockEntityGet).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-2", entityId: "team-1" }),+ );+ expect(mockEntityCreate).toHaveBeenCalledWith(+ expect.objectContaining({ customerId: "org-2", entityId: "team-1" }),+ );+ // ...and usage is billed to the new org.+ expect(mockTrack).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-2", entityId: "team-1" }),+ );++ // Warm again under org-2: no further provisioning calls.+ await svc.trackCredits({ teamId: "team-1", value: 1 });+ expect(mockEntityGet.mock.calls.length).toBe(entityGetsBefore + 1);+ });++ it("checkCredits follows the org move too", async () => {+ vi.useFakeTimers();+ const svc = makeService();++ await svc.checkCredits({ teamId: "team-1", value: 1 });+ expect(mockCheck).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-1" }),+ );++ state.supabaseStubData = { data: { org_id: "org-2" }, error: null };+ vi.advanceTimersByTime(301_000);++ await svc.checkCredits({ teamId: "team-1", value: 1 });+ expect(mockCheck).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-2" }),+ );+ });++ it("collapses concurrent expired-cache refreshes into one DB lookup", async () => {+ vi.useFakeTimers();+ const svc = makeService();++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ vi.advanceTimersByTime(301_000);++ // Make the org lookup observable and slow.+ let resolveLookup!: (rows: unknown[]) => void;+ let lookups = 0;+ state.dbLimitOverride = () => {+ lookups++;+ return new Promise<unknown[]>(resolve => {+ resolveLookup = resolve;+ });+ };++ const a = svc.trackCredits({ teamId: "team-1", value: 1 });+ const b = svc.trackCredits({ teamId: "team-1", value: 1 });+ const c = svc.trackCredits({ teamId: "team-1", value: 1 });+ await Promise.resolve();+ expect(lookups).toBe(1);++ state.dbLimitOverride = null;+ resolveLookup([{ org_id: "org-2" }]);+ await Promise.all([a, b, c]);++ expect(lookups).toBe(1);+ for (const call of mockTrack.mock.calls.slice(-3)) {+ expect(call[0]).toEqual(expect.objectContaining({ customerId: "org-2" }));+ }+ });++ it("honours AUTUMN_ORG_CACHE_TTL_SECONDS", async () => {+ vi.useFakeTimers();+ state.configRef = { AUTUMN_ORG_CACHE_TTL_SECONDS: 10 };+ const svc = makeService();++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ state.supabaseStubData = { data: { org_id: "org-2" }, error: null };+ vi.advanceTimersByTime(11_000);++ await svc.trackCredits({ teamId: "team-1", value: 1 });+ expect(mockTrack).toHaveBeenLastCalledWith(+ expect.objectContaining({ customerId: "org-2" }),+ );+ });+});+// ---------------------------------------------------------------------------// lockCredits// ---------------------------------------------------------------------------@@ -764,6 +900,7 @@ describe("firebill routing", () => {// Default every test to not partner-provisioned, which almost every team is.state.gatewayStubRow = null;state.gatewayStubThrows = false;+ state.dbLimitOverride = null;});afterEach(() => {diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex 4b0a17b5f..a24cdf9ca 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -98,12 +98,39 @@ export class BoundedSet<V> extends Set<V> {* Wraps Autumn customer/entity provisioning and usage tracking for team credit billing.*/export class AutumnService {- private customerOrgCache = new BoundedMap<string, string>(50_000);+ // team → org, trusted only until `expiresAt`. A team's org changes when an+ // account is merged or moved; without a bound every warm pod keeps billing+ // the old Autumn customer until it restarts.+ private customerOrgCache = new BoundedMap<+ string,+ { orgId: string; expiresAt: number }+ >(50_000);+ // One DB lookup in flight per team. Without this, N requests that all see+ // an expired entry each read the DB, and if the org moved mid-flight an+ // older read can land last and overwrite the newer org for another TTL.+ private pendingOrgLookups = new Map<string, Promise<string>>();private gatewayTeams = new BoundedSet<string>(50_000);private nonGatewayTeamsUntil = new BoundedMap<string, number>(50_000);private ensuredOrgs = new BoundedSet<string>(50_000);+ // Keyed by org AND team: an entity lives under one customer, so a team that+ // moves orgs has to be provisioned again under the new one.private ensuredTeams = new BoundedSet<string>(50_000);+ private ensuredTeamKey(orgId: string, teamId: string): string {+ return `${orgId}:${teamId}`;+ }++ private orgCacheTtlMs(): number {+ return (config.AUTUMN_ORG_CACHE_TTL_SECONDS ?? 300) * 1000;+ }++ private cacheOrgId(teamId: string, orgId: string): void {+ this.customerOrgCache.set(teamId, {+ orgId,+ expiresAt: Date.now() + this.orgCacheTtlMs(),+ });+ }+private isPreviewTeam(teamId: string): boolean {return teamId === "preview" || teamId.startsWith("preview_");}@@ -381,8 +408,9 @@ export class AutumnService {/*** Ensures the Autumn entity exists for a team under its org customer.*- * The `ensuredTeams` check is performed first so that already-provisioned- * teams incur no HTTP calls — not even the `ensureOrgProvisioned` round-trip.+ * The `ensuredTeams` check runs before any Autumn call so that a team already+ * provisioned under its current org incurs no HTTP round-trips — not even+ * `ensureOrgProvisioned`.*/async ensureTeamProvisioned({teamId,@@ -391,12 +419,14 @@ export class AutumnService {}: EnsureTeamProvisionedParams): Promise<void> {if (!autumnClient) return;if (this.isPreviewTeam(teamId)) return;- // Fast path: team is already fully provisioned.- if (this.ensuredTeams.has(teamId)) return;try {- const resolvedOrgId = orgId ?? (await this.lookupOrgIdForTeam(teamId));- this.customerOrgCache.set(teamId, resolvedOrgId);+ const resolvedOrgId = orgId ?? (await this.resolveOrgId(teamId));+ // Fast path: team is already fully provisioned under this org.+ if (this.ensuredTeams.has(this.ensuredTeamKey(resolvedOrgId, teamId))) {+ return;+ }+ if (orgId) this.cacheOrgId(teamId, orgId);await this.ensureOrgProvisioned({ orgId: resolvedOrgId });const entity = await this.getEntity({@@ -414,13 +444,13 @@ export class AutumnService {if (result.ok || ("conflict" in result && result.conflict)) {// Entity was just created, or already existed (409 race) — either way// it's present. No need for a second getEntity confirmation call.- this.ensuredTeams.add(teamId);+ this.ensuredTeams.add(this.ensuredTeamKey(resolvedOrgId, teamId));}// Genuine error: leave ensuredTeams empty so the next request retries.return;}- this.ensuredTeams.add(teamId);+ this.ensuredTeams.add(this.ensuredTeamKey(resolvedOrgId, teamId));} catch (error) {logger.error("Autumn ensureTeamProvisioned failed — billing API may be unavailable",@@ -430,15 +460,27 @@ export class AutumnService {}/**- * Resolves the orgId for a team, returning the cached value when available- * and populating the cache on miss. Does NOT provision anything.+ * Resolves the orgId for a team, returning the cached value while it is+ * fresh and re-reading the DB once it has expired. Does NOT provision+ * anything.*/private async resolveOrgId(teamId: string): Promise<string> {const cached = this.customerOrgCache.get(teamId);- if (cached) return cached;- const orgId = await this.lookupOrgIdForTeam(teamId);- this.customerOrgCache.set(teamId, orgId);- return orgId;+ if (cached && cached.expiresAt > Date.now()) return cached.orgId;++ const pending = this.pendingOrgLookups.get(teamId);+ if (pending) return pending;++ const lookup = this.lookupOrgIdForTeam(teamId)+ .then(orgId => {+ this.cacheOrgId(teamId, orgId);+ return orgId;+ })+ .finally(() => {+ this.pendingOrgLookups.delete(teamId);+ });+ this.pendingOrgLookups.set(teamId, lookup);+ return lookup;}/**@@ -450,7 +492,7 @@ export class AutumnService {*/private async ensureTrackingContext(teamId: string): Promise<string> {const orgId = await this.resolveOrgId(teamId);- if (!this.ensuredTeams.has(teamId)) {+ if (!this.ensuredTeams.has(this.ensuredTeamKey(orgId, teamId))) {await this.ensureTeamProvisioned({ teamId, orgId });}return orgId;