AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(billing): wait 400ms for the credits read outside sync webhooks and log read times (#16995)
Abduld27bcea5668a
diff --git a/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-billing.ts b/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-billing.tsindex 2988c971153..11083aebbfc 100644--- a/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-billing.ts+++ b/packages/server/api/src/app/ee/platform/platform-plan/billing-providers/autumn-billing.ts@@ -1,12 +1,12 @@import { isNil, tryCatch } from '@activepieces/core-utils'-import { apDayjs } from '@activepieces/server-utils'+import { apDayjs, wideEvent } from '@activepieces/server-utils'import { AiCreditsAutoTopUpState, AppSumoCreditsBillableFeature, AutoTopUpConfig, ConsumableFeatureId, CreditsBillableFeature, FeatureId, isConsumableFeatureId, PlanName, SeatsBillableFeature, UnconsumableFeatureId } from '@activepieces/shared'import { AutumnError, type GetCustomerResponse } from 'autumn-js'import { FastifyBaseLogger } from 'fastify'import { AUTUMN_ENROLL_LOCK_TIMEOUT_SECONDS, getAutumnEnrollLockKey, getBillingEnforcedKey, getBillingOverviewFetchLockKey, getBillingOverviewKey, getCustomerStateFetchLockKey, getCustomerStateMissKey, getCustomerStateRefreshKey } from '../../../../database/redis/keys'import { distributedLock, distributedStore } from '../../../../database/redis-connections'import { rejectedPromiseHandler } from '../../../../helper/promise-handler'-import { ActivateLicenseParams, ApplyAppSumoPlanParams, AppSumoAiCreditsUsage, BillingInfo, BillingOverview, BillingProvider, CreditsAndAppSumoState, CreditsGateState, CreditsUsage, emptyBillingOverview, TrackFeatureParams } from '../../../../platform/billing-provider'+import { ActivateLicenseParams, ApplyAppSumoPlanParams, AppSumoAiCreditsUsage, BillingInfo, BillingOverview, BillingProvider, CreditsAndAppSumoState, CreditsGateState, CreditsUsage, emptyBillingOverview, ShouldBlockOnCreditsParams, TrackFeatureParams } from '../../../../platform/billing-provider'import { assertSeatsNotBelowActiveUsers, platformPlanService } from '../platform-plan.service'import { autumnConsole, autumnUtils, BalanceCacheSnapshot, ConsoleCustomerCall, CreditsBalanceCache } from './autumn-utils'@@ -14,7 +14,9 @@ const CREDITS_REFETCH_PERIOD_MS = 180 * 1000const CUSTOMER_STATE_REFRESH_DEBOUNCE_SECONDS = 15const CUSTOMER_STATE_MISS_DEBOUNCE_SECONDS = 60const CUSTOMER_STATE_FETCH_LOCK_TIMEOUT_SECONDS = 15-const CREDITS_CACHE_READ_TIMEOUT_MS = 25+const CREDITS_CACHE_READ_TIMEOUT_MS = 400+const FAST_CREDIT_CHECK_READ_TIMEOUT_MS = 25+const SLOW_CREDITS_CACHE_READ_LOG_MS = 25const BILLING_OVERVIEW_TTL_SECONDS = 5 * 60const TRIAL_DURATION_UNITS: Partial<Record<string, 'day' | 'month' | 'year'>> = { day: 'day', month: 'month', year: 'year' }@@ -154,11 +156,12 @@ export const autumnBillingProvider = (log: FastifyBaseLogger): BillingProvider =isBillingEnforced: async (platformId: string) => {return (await distributedStore.get<boolean>(getBillingEnforcedKey(platformId))) ?? false},- shouldBlockOnCredits: async (platformId: string) => {- return (await computeCreditsAndAppSumoState(log, platformId)).credits.blocked+ shouldBlockOnCredits: async ({ platformId, fastCreditCheck }: ShouldBlockOnCreditsParams) => {+ const readTimeoutMs = fastCreditCheck ? FAST_CREDIT_CHECK_READ_TIMEOUT_MS : CREDITS_CACHE_READ_TIMEOUT_MS+ return (await computeCreditsAndAppSumoState({ log, platformId, readTimeoutMs })).credits.blocked},getCreditsAndAppSumoState: async (platformId: string) => {- return computeCreditsAndAppSumoState(log, platformId)+ return computeCreditsAndAppSumoState({ log, platformId, readTimeoutMs: CREDITS_CACHE_READ_TIMEOUT_MS })},getConsumablesUsage: async (platformId: string) => {const { credits, appSumo } = await resolveCreditsCache(log, platformId)@@ -302,10 +305,15 @@ function msToIso(ms: number | null | undefined): string | null {return isNil(ms) ? null : apDayjs(ms).toISOString()}-async function computeCreditsAndAppSumoState(log: FastifyBaseLogger, platformId: string): Promise<CreditsAndAppSumoState> {- const { data: snapshot, error } = await tryCatch(() => withTimeout(readCreditsCaches(platformId), CREDITS_CACHE_READ_TIMEOUT_MS))+async function computeCreditsAndAppSumoState({ log, platformId, readTimeoutMs }: ComputeCreditsAndAppSumoStateParams): Promise<CreditsAndAppSumoState> {+ const startedAt = performance.now()+ const read = readCreditsCaches(platformId)+ const { data: snapshot, error } = await tryCatch(() => withTimeout(read, readTimeoutMs))+ const readMs = elapsedMs(startedAt)+ wideEvent.set({ creditsGate: { readMs, readTimeoutMs, timedOut: error instanceof CreditsReadTimeoutError } })if (isNil(snapshot)) {- log.warn({ error, platform: { id: platformId } }, 'Credits gate cache read timed out or failed; failing open without gating this request')+ log.warn({ error, platform: { id: platformId }, creditsGate: { readMs, readTimeoutMs } }, 'Credits gate cache read timed out or failed; failing open without gating this request')+ read.then(() => log.info({ platform: { id: platformId }, creditsGate: { readMs: elapsedMs(startedAt), readTimeoutMs } }, 'Credits gate cache read finished after the timeout')).catch(() => undefined)return {credits: computeCreditState({ balance: null, enforced: false }),appSumo: computeCreditState({ balance: null, enforced: true }),@@ -315,10 +323,17 @@ async function computeCreditsAndAppSumoState(log: FastifyBaseLogger, platformId:credits: computeCreditState({ balance: snapshot.credits, enforced: snapshot.billingEnforced }),appSumo: computeCreditState({ balance: snapshot.appSumo, enforced: true }),}+ if (isNil(wideEvent.current()) && readMs >= SLOW_CREDITS_CACHE_READ_LOG_MS) {+ log.info({ platform: { id: platformId }, creditsGate: { readMs, readTimeoutMs } }, 'Credits gate cache read was slow')+ }scheduleCreditsCacheMaintenance({ log, platformId, snapshot, state })return state}+function elapsedMs(startedAt: number): number {+ return Math.round(performance.now() - startedAt)+}+function scheduleCreditsCacheMaintenance({ log, platformId, snapshot, state }: CreditsCacheMaintenanceParams): void {const stale = isNil(snapshot.credits) || isCreditsStale(snapshot.credits)if (!stale && !state.credits.blocked && !state.appSumo.blocked) {@@ -335,9 +350,11 @@ async function readCreditsCaches(platformId: string): Promise<CreditsCacheSnapshreturn { billingEnforced: billingEnforced ?? false, credits, appSumo }}+class CreditsReadTimeoutError extends Error {}+function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {return new Promise<T>((resolve, reject) => {- const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms`)), timeoutMs)+ const timer = setTimeout(() => reject(new CreditsReadTimeoutError(`Timed out after ${timeoutMs}ms`)), timeoutMs)promise.then((value) => {clearTimeout(timer)@@ -491,6 +508,12 @@ type CurrentPlanSelection = {plan: AutumnPlan | null}+type ComputeCreditsAndAppSumoStateParams = {+ log: FastifyBaseLogger+ platformId: string+ readTimeoutMs: number+}+type ComputeCreditStateParams = {balance: CreditsBalanceCache | nullenforced: booleandiff --git a/packages/server/api/src/app/platform/billing-provider.ts b/packages/server/api/src/app/platform/billing-provider.tsindex ef437653be8..7730f888a59 100644--- a/packages/server/api/src/app/platform/billing-provider.ts+++ b/packages/server/api/src/app/platform/billing-provider.ts@@ -112,14 +112,14 @@ export async function hasCreditsLeft({ platformId, log }: { platformId: string,return isNil(left) || left > 0}-export async function shouldBlockRunOnCredits({ platformId, environment, log }: RunCreditsGateParams): Promise<boolean> {+export async function shouldBlockRunOnCredits({ platformId, environment, fastCreditCheck = false, log }: RunCreditsGateParams): Promise<boolean> {if (system.getEdition() === ApEdition.ENTERPRISE) {return false}if (environment !== RunEnvironment.PRODUCTION) {return false}- return billingProvider.get(log).shouldBlockOnCredits(platformId)+ return billingProvider.get(log).shouldBlockOnCredits({ platformId, fastCreditCheck })}export async function assertRunCreditsNotExceeded({ platformId, environment, log }: RunCreditsGateParams): Promise<void> {@@ -186,9 +186,15 @@ type EmptyBillingOverviewParams = {type RunCreditsGateParams = {platformId: stringenvironment: RunEnvironment+ fastCreditCheck?: booleanlog: FastifyBaseLogger}+export type ShouldBlockOnCreditsParams = {+ platformId: string+ fastCreditCheck: boolean+}+export type CreditEventBreakdownEntry = {provider: stringmodel: string@@ -415,7 +421,7 @@ export type BillingProvider = {applyAppSumoPlan(params: ApplyAppSumoPlanParams): Promise<void>activateLicense(params: ActivateLicenseParams): Promise<void>isBillingEnforced(platformId: string): Promise<boolean>- shouldBlockOnCredits(platformId: string): Promise<boolean>+ shouldBlockOnCredits(params: ShouldBlockOnCreditsParams): Promise<boolean>getCreditsAndAppSumoState(platformId: string): Promise<CreditsAndAppSumoState>getConsumablesUsage(platformId: string): Promise<ConsumablesUsage>getCreditUsage(params: CreditUsageByProjectParams): Promise<CreditUsage>diff --git a/packages/server/api/src/app/webhooks/webhook.service.ts b/packages/server/api/src/app/webhooks/webhook.service.tsindex 1817a690c54..448629357da 100644--- a/packages/server/api/src/app/webhooks/webhook.service.ts+++ b/packages/server/api/src/app/webhooks/webhook.service.ts@@ -274,6 +274,7 @@ async function handleSync(params: SyncWebhookParams): Promise<EngineHttpResponseconst creditsExhausted = await shouldBlockRunOnCredits({platformId,environment: runEnvironment,+ fastCreditCheck: true,log: logger,})diff --git a/packages/server/api/test/unit/app/ee/platform-plan/credits-gate.test.ts b/packages/server/api/test/unit/app/ee/platform-plan/credits-gate.test.tsindex a567d5a4596..5af3cc2ae67 100644--- a/packages/server/api/test/unit/app/ee/platform-plan/credits-gate.test.ts+++ b/packages/server/api/test/unit/app/ee/platform-plan/credits-gate.test.ts@@ -1,3 +1,4 @@+import { createLogger, wideEvent } from '@activepieces/server-utils'import { FastifyBaseLogger } from 'fastify'import { beforeEach, describe, expect, it, vi } from 'vitest'import { autumnBillingProvider, computeCreditState } from '../../../../../src/app/ee/platform/platform-plan/billing-providers/autumn-billing'@@ -244,4 +245,69 @@ describe('credits gate decides from the cache and refreshes in the background',expect(mockResolveClientForPlatform).not.toHaveBeenCalled()expect(log.warn).toHaveBeenCalled()})++ it('waits longer than a fast credit check for a slow cache read before failing open', async () => {+ storedCredits = fresh({ remaining: 0 })+ mockBillingEnforced.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(true), 100)))+ const provider = autumnBillingProvider(log)++ await expect(provider.shouldBlockOnCredits({ platformId: 'platform-1', fastCreditCheck: true })).resolves.toBe(false)+ await expect(provider.shouldBlockOnCredits({ platformId: 'platform-1', fastCreditCheck: false })).resolves.toBe(true)+ })++ it('records the read time on the request row instead of a separate log line', async () => {+ storedCredits = fresh({ remaining: 0 })+ mockBillingEnforced.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(true), 40)))+ const requestLogger = createLogger()++ await wideEvent.run({ logger: requestLogger, fn: () => gateState() })++ expect(requestLogger.getContext()).toMatchObject({ creditsGate: { readMs: expect.any(Number), readTimeoutMs: 400, timedOut: false } })+ expect(log.info).not.toHaveBeenCalledWith(expect.anything(), 'Credits gate cache read was slow')+ })++ it('logs a slow read made outside a request', async () => {+ storedCredits = fresh({ remaining: 0 })+ mockBillingEnforced.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(true), 40)))++ await gateState()++ expect(log.info).toHaveBeenCalledWith(+ { platform: { id: 'platform-1' }, creditsGate: { readMs: expect.any(Number), readTimeoutMs: 400 } },+ 'Credits gate cache read was slow',+ )+ })++ it('marks only a read that ran out of time as timed out, not a read that failed', async () => {+ mockBillingEnforced.mockRejectedValueOnce(new Error('redis unreachable'))+ const failedRead = createLogger()+ await wideEvent.run({ logger: failedRead, fn: () => gateState() })++ mockBillingEnforced.mockImplementationOnce(() => new Promise((resolve) => setTimeout(() => resolve(true), 100)))+ const slowRead = createLogger()+ await wideEvent.run({ logger: slowRead, fn: () => autumnBillingProvider(log).shouldBlockOnCredits({ platformId: 'platform-1', fastCreditCheck: true }) })++ expect(failedRead.getContext()).toMatchObject({ creditsGate: { timedOut: false } })+ expect(slowRead.getContext()).toMatchObject({ creditsGate: { timedOut: true, readTimeoutMs: 25 } })+ })++ it('does not log a fast read', async () => {+ storedCredits = fresh({ remaining: 0 })++ await gateState()++ expect(log.info).not.toHaveBeenCalledWith(expect.anything(), 'Credits gate cache read was slow')+ })++ it('logs how long a timed-out read really took once it finishes', async () => {+ storedCredits = fresh({ remaining: 0 })+ mockBillingEnforced.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(true), 100)))++ await autumnBillingProvider(log).shouldBlockOnCredits({ platformId: 'platform-1', fastCreditCheck: true })+ await new Promise((resolve) => setTimeout(resolve, 150))++ const lateRead = vi.mocked(log.info).mock.calls.find(([, msg]) => msg === 'Credits gate cache read finished after the timeout')+ expect(lateRead?.[0]).toMatchObject({ platform: { id: 'platform-1' }, creditsGate: { readTimeoutMs: 25 } })+ expect(lateRead?.[0]).toHaveProperty('creditsGate.readMs', expect.any(Number))+ })})diff --git a/packages/server/api/test/unit/app/platform/run-credits-gate.test.ts b/packages/server/api/test/unit/app/platform/run-credits-gate.test.tsindex 63173e9dcfb..710d569aeb0 100644--- a/packages/server/api/test/unit/app/platform/run-credits-gate.test.ts+++ b/packages/server/api/test/unit/app/platform/run-credits-gate.test.ts@@ -16,8 +16,8 @@ import { billingProvider, shouldBlockRunOnCredits } from '../../../../src/app/plconst log = { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } as unknown as FastifyBaseLoggerconst noopProvider = billingProvider.get(log)-function gate(environment: RunEnvironment) {- return shouldBlockRunOnCredits({ platformId: 'platform-1', environment, log })+function gate(environment: RunEnvironment, fastCreditCheck?: boolean) {+ return shouldBlockRunOnCredits({ platformId: 'platform-1', environment, fastCreditCheck, log })}describe('shouldBlockRunOnCredits', () => {@@ -38,7 +38,14 @@ describe('shouldBlockRunOnCredits', () => {mockGetEdition.mockReturnValue(ApEdition.CLOUD)await expect(gate(RunEnvironment.PRODUCTION)).resolves.toBe(true)- expect(mockShouldBlockOnCredits).toHaveBeenCalledWith('platform-1')+ expect(mockShouldBlockOnCredits).toHaveBeenCalledWith({ platformId: 'platform-1', fastCreditCheck: false })+ })++ it('tells the provider when the check must be fast', async () => {+ mockGetEdition.mockReturnValue(ApEdition.CLOUD)++ await gate(RunEnvironment.PRODUCTION, true)+ expect(mockShouldBlockOnCredits).toHaveBeenCalledWith({ platformId: 'platform-1', fastCreditCheck: true })})it('never gates a testing run', async () => {diff --git a/packages/server/api/test/unit/app/webhooks/webhook-credit-gate.test.ts b/packages/server/api/test/unit/app/webhooks/webhook-credit-gate.test.tsindex 188f2bdbb6c..8a7e8bb5c84 100644--- a/packages/server/api/test/unit/app/webhooks/webhook-credit-gate.test.ts+++ b/packages/server/api/test/unit/app/webhooks/webhook-credit-gate.test.ts@@ -160,6 +160,7 @@ describe('sync webhook credit gate', () => {expect(mockShouldBlockRunOnCredits.mock.calls[0][0]).toMatchObject({platformId: 'plat-1',environment: RunEnvironment.PRODUCTION,+ fastCreditCheck: true,})})})