Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
lock consumer to avoid time bound issues
Thiago Araujo da Silvae21a78e7880f
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.tsindex 49679b11e3..c9b2097d43 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts@@ -53,6 +53,7 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}upsertJobScheduler: vi.fn(async () => undefined)};+ const release = vi.fn(async () => undefined);const keyStore = {streamAdd: vi.fn<(key: string, id: string, fieldValue: { data: string }, maxLen?: number) => Promise<string | null>@@ -61,7 +62,14 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}entries: [],lastId: null})),- streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0)+ streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0),+ acquireLock: vi.fn<+ (+ resources: string[],+ duration: number,+ settings?: { retryCount?: number }+ ) => Promise<{ release: typeof release }>+ >(async () => ({ release }))};const auditLogDAL = { batchCreate: vi.fn<(logs: Record<string, unknown>[]) => Promise<void>>(async () => undefined) };@@ -98,6 +106,7 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false } = {}service,queueService,keyStore,+ release,auditLogDAL,projectDAL,licenseService,@@ -322,4 +331,25 @@ describe("audit-log-queue unified consumer", () => {expect(rows).toHaveLength(1);expect(rows[0].id).toBe("ok");});++ test("skips the tick when the consumer lock is already held by another runner", async () => {+ const { consumer, auditLogDAL, keyStore, release } = await createHarness();+ keyStore.acquireLock.mockRejectedValueOnce(new Error("ResourceLockedError"));+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([streamEntry()]));++ await consumer();++ expect(keyStore.streamCollect).not.toHaveBeenCalled();+ expect(auditLogDAL.batchCreate).not.toHaveBeenCalled();+ expect(release).not.toHaveBeenCalled();+ });++ test("releases the consumer lock even when the drain throws", async () => {+ const { consumer, keyStore, release } = await createHarness();+ keyStore.streamCollect.mockRejectedValueOnce(new Error("redis hiccup"));++ await expect(consumer()).rejects.toThrow("redis hiccup");++ expect(release).toHaveBeenCalledTimes(1);+ });});diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 9137c435db..0753f13459 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -4,7 +4,7 @@ import { v7 as uuidv7 } from "uuid";import type { TAuditLogs, TProjects } from "@app/db/schemas";import { TAuditLogStreamOutboxServiceFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service";-import { TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";@@ -21,7 +21,7 @@ type TAuditLogQueueServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;clickhouseClient: ClickHouseClient | null;- keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamCollect" | "streamTrim">;+ keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamCollect" | "streamTrim" | "acquireLock">;};export type TAuditLogQueueServiceFactory = {@@ -55,12 +55,10 @@ export const AUDIT_LOG_STREAM_TIMEOUT = 5 * 1000;export const AUDIT_LOG_STREAM_BATCH_TIMEOUT = 30 * 1000;const MS_IN_DAY = 24 * 60 * 60 * 1000;-// Redis ingest stream shared by both storage backends. `pushToLog` appends raw-ish entries-// here; a single scheduled consumer drains, enriches, batch-inserts, fans out to the outbox,-// and trims. Keep the key literal stable so a rolling deploy doesn't strand in-flight entries.const AUDIT_LOG_STREAM_KEY = "audit-log-stream";const AUDIT_LOG_STREAM_BATCH_SIZE = 10_000;const AUDIT_LOG_STREAM_MAX_ENTRIES = 50_000;+const AUDIT_LOG_STREAM_CONSUMER_LOCK_TTL_MS = 60_000;export const auditLogQueueServiceFactory = async ({auditLogDAL,@@ -127,7 +125,7 @@ export const auditLogQueueServiceFactory = async ({// into the active backend, fan out to the stream outbox, and trim. Trim happens only after a// successful insert so a failed batch is retried on the next tick (re-inserts are idempotent:// ClickHouse ReplacingMergeTree dedups on id, Postgres uses ON CONFLICT (id) DO NOTHING).- const consumeAuditLogStream = async () => {+ const drainAuditLogStream = async () => {const { entries, lastId } = await keyStore.streamCollect(AUDIT_LOG_STREAM_KEY,AUDIT_LOG_STREAM_BATCH_SIZE,@@ -271,6 +269,34 @@ export const auditLogQueueServiceFactory = async ({await keyStore.streamTrim(AUDIT_LOG_STREAM_KEY, lastId, true);};+ // Cron fires every 5 s but a tick can run longer under load (big batch, slow DB). Multiple+ // pods all subscribe to the scheduler so two ticks can overlap. The work is idempotent, but+ // overlap doubles DB / Redis pressure when we're already behind. Guard the body with redlock+ // (`retryCount: 0` makes it non-blocking): if another runner holds the lock we just skip —+ // the next scheduled tick will pick up where it left off. The TTL is a safety net for a+ // crashed consumer; release uses a fencing-token Lua script so a slow runner whose lock+ // already expired can't accidentally release a successor's lock.+ const consumeAuditLogStream = async () => {+ let lock;+ try {+ lock = await keyStore.acquireLock(+ [KeyStorePrefixes.AuditLogIngestConsumerLock],+ AUDIT_LOG_STREAM_CONSUMER_LOCK_TTL_MS,+ {+ retryCount: 0+ }+ );+ } catch {+ // Another runner holds the lock — skip this tick.+ return;+ }+ try {+ await drainAuditLogStream();+ } finally {+ await lock.release();+ }+ };+// Single scheduled consumer for both backends, every 5 seconds. Registered unconditionally// now that Postgres also batches through the stream. The scheduler id is kept as the historical// "audit-log-clickhouse-batch" so the existing Redis scheduler key isn't orphaned on upgrade.diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 597369a958..63a40c2e44 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -141,7 +141,8 @@ export const KeyStorePrefixes = {`telemetry-event-${event}-${bucketId}-${distinctId}-${uuid}` as const,TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const,- AuditLogStreamFlushDebounce: (streamId: string) => `audit-log-stream:${streamId}:flush-debounce` as const+ AuditLogStreamFlushDebounce: (streamId: string) => `audit-log-stream:${streamId}:flush-debounce` as const,+ AuditLogIngestConsumerLock: "audit-log-ingest:consumer-lock" as const};export const KeyStoreTtls = {