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
refactor(audit-log-stream): pass tx to outbox DAL instead of in-transaction closures
Calvin7b6a17e2dd26
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.tsindex dd4559b276..93b924c882 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts@@ -132,36 +132,36 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {// 'delivered' but retriable rows still 'processing'); either every write// commits or none do, and the stale-claim sweeper picks up an un-applied// claim on the next pass.- const commitDeliveryResult = async (input: {- successIds: number[];- retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;- exhaustedIds: number[];- inTransaction?: (tx: Knex) => Promise<void>;- }) => {+ //+ // Pass `tx` to commit alongside other writes (eg the stream health flip and its alert event).+ const commitDeliveryResult = async (+ input: {+ successIds: number[];+ retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;+ exhaustedIds: number[];+ },+ tx?: Knex+ ) => {const retriableCount = input.retriable?.groups.reduce((n, g) => n + g.ids.length, 0) ?? 0;- if (- input.successIds.length === 0 &&- retriableCount === 0 &&- input.exhaustedIds.length === 0 &&- !input.inTransaction- )- return;+ if (input.successIds.length === 0 && retriableCount === 0 && input.exhaustedIds.length === 0) return;try {- await db.transaction(async (tx) => {+ const applyResult = async (trx: Knex) => {if (input.successIds.length > 0) {- await markBatchAsDelivered(input.successIds, tx);+ await markBatchAsDelivered(input.successIds, trx);}if (input.retriable) {for (const group of input.retriable.groups) {// eslint-disable-next-line no-await-in-loop- await markBatchForRetry(group.ids, group.nextRetryDelayMs, tx);+ await markBatchForRetry(group.ids, group.nextRetryDelayMs, trx);}}if (input.exhaustedIds.length > 0) {- await tx(TableName.AuditLogStreamOutbox).whereIn("id", input.exhaustedIds).del();+ await trx(TableName.AuditLogStreamOutbox).whereIn("id", input.exhaustedIds).del();}- if (input.inTransaction) await input.inTransaction(tx);- });+ };++ if (tx) await applyResult(tx);+ else await db.transaction(applyResult);} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: commitDeliveryResult" });}@@ -177,11 +177,11 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {const recoverStaleClaims = async (thresholdMs: number,maxAttempts: number,- onDropped?: (dropped: TDroppedStreamRow[], tx: Knex) => Promise<void>+ tx?: Knex): Promise<{ retried: number; dropped: TDroppedStreamRow[] }> => {try {- return await db.transaction(async (tx) => {- const staleRows = await tx(TableName.AuditLogStreamOutbox)+ const recover = async (trx: Knex) => {+ const staleRows = await trx(TableName.AuditLogStreamOutbox).where("status", AuditLogStreamOutboxStatus.Processing).andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs]).forUpdate()@@ -201,7 +201,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {}if (retriable.length > 0) {- await tx(TableName.AuditLogStreamOutbox)+ await trx(TableName.AuditLogStreamOutbox).whereIn("id",retriable.map((row) => row.id)@@ -209,21 +209,21 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {.update({status: AuditLogStreamOutboxStatus.Retry,attempts: db.raw('"attempts" + 1'),- nextRetryAt: tx.fn.now(),+ nextRetryAt: trx.fn.now(),lockedAt: null});}if (exhausted.length === 0) return { retried: retriable.length, dropped: [] };- await tx(TableName.AuditLogStreamOutbox)+ await trx(TableName.AuditLogStreamOutbox).whereIn("id",exhausted.map((row) => row.id)).del();- const streams = await tx(TableName.AuditLogStream)+ const streams = await trx(TableName.AuditLogStream).whereIn("id", [...new Set(exhausted.map((row) => row.streamId))]).select<{ id: string; provider: string }[]>("id", "provider");const providerByStreamId = new Map(streams.map((stream) => [stream.id, stream.provider]));@@ -233,10 +233,11 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {orgId: row.orgId,provider: providerByStreamId.get(row.streamId) ?? null}));- if (onDropped) await onDropped(dropped, tx);return { retried: retriable.length, dropped };- });+ };++ return tx ? await recover(tx) : await db.transaction(recover);} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: recoverStaleClaims" });}@@ -324,7 +325,10 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {}};+ const transaction = async <T>(cb: (tx: Knex) => Promise<T>) => db.transaction(cb);+return {+ transaction,batchInsert,markStreamFailing,clearStreamFailing,diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.tsindex 01c955dca3..3e49d9b309 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts@@ -80,11 +80,14 @@ const buildRow = (overrides: Partial<TAuditLogStreamOutboxRow> = {}): TAuditLogS...overrides});+const TX = { tx: true };+const createService = () => {const auditLogStreamOutboxDAL = {+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(TX)),batchInsert: vi.fn(async () => undefined),claimBatchForStream: vi.fn<(...args: unknown[]) => Promise<TAuditLogStreamOutboxRow[]>>(async () => []),- commitDeliveryResult: vi.fn<(input: unknown) => Promise<void>>(async () => undefined),+ commitDeliveryResult: vi.fn<(input: unknown, tx?: unknown) => Promise<void>>(async () => undefined),markStreamFailing: vi.fn<(input: unknown, tx: unknown) => Promise<Date | null>>(async () => new Date()),clearStreamFailing: vi.fn<(streamId: string, tx: unknown) => Promise<void>>(async () => undefined),recoverStaleClaims: vi.fn<(...args: unknown[]) => Promise<{ retried: number; dropped: unknown[] }>>(async () => ({@@ -620,13 +623,16 @@ describe("audit-log-stream-outbox-service sweepStaleClaims", () => {const containing = (fields: Record<string, unknown>): unknown => expect.objectContaining(fields);describe("audit-log-stream-outbox-service delivery failure alerting", () => {- const TX = { tx: true };const FAILING_SINCE = new Date("2026-10-07T10:00:00.000Z");- type TInTransactionInput = { inTransaction?: (tx: unknown) => Promise<void> };-- const lastCommit = (dal: ReturnType<typeof createService>["auditLogStreamOutboxDAL"]) =>- dal.commitDeliveryResult.mock.calls[0][0] as TInTransactionInput;+ const failingStream = {+ id: STREAM_ID,+ provider: PROVIDER,+ orgId: ORG_ID,+ encryptedCredentials: Buffer.from("x"),+ streamMode: StreamMode.Batch,+ failingSince: FAILING_SINCE+ };beforeEach(() => {vi.clearAllMocks();@@ -644,8 +650,7 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- await lastCommit(auditLogStreamOutboxDAL).inTransaction?.(TX);-+ expect(auditLogStreamOutboxDAL.commitDeliveryResult).toHaveBeenCalledWith(expect.anything(), TX);expect(auditLogStreamOutboxDAL.markStreamFailing).toHaveBeenCalledWith({ streamId: STREAM_ID, errorMessage: FAILURE_MESSAGE },TX@@ -678,7 +683,6 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {batchStreamLog.mockRejectedValueOnce(new Error(FAILURE_MESSAGE));await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- await lastCommit(auditLogStreamOutboxDAL).inTransaction?.(TX);expect(eventEmitter.emit).not.toHaveBeenCalled();});@@ -690,7 +694,8 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ expect(auditLogStreamOutboxDAL.markStreamFailing).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.clearStreamFailing).not.toHaveBeenCalled();});test("does not touch stream health for a healthy stream that delivers", async () => {@@ -700,19 +705,13 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ expect(auditLogStreamOutboxDAL.markStreamFailing).not.toHaveBeenCalled();+ expect(auditLogStreamOutboxDAL.clearStreamFailing).not.toHaveBeenCalled();});test("stays quiet when a stream that is already failing exhausts more rows", async () => {- const { service, auditLogStreamOutboxDAL, auditLogStreamDAL } = createService();- auditLogStreamDAL.findById.mockResolvedValueOnce({- id: STREAM_ID,- provider: PROVIDER,- orgId: ORG_ID,- encryptedCredentials: Buffer.from("x"),- streamMode: StreamMode.Batch,- failingSince: FAILING_SINCE- });+ const { service, auditLogStreamOutboxDAL, auditLogStreamDAL, eventEmitter } = createService();+ auditLogStreamDAL.findById.mockResolvedValueOnce(failingStream);auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow({ attempts: 4 })]).mockResolvedValueOnce([]);@@ -720,24 +719,17 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ expect(auditLogStreamOutboxDAL.markStreamFailing).not.toHaveBeenCalled();+ expect(eventEmitter.emit).not.toHaveBeenCalled();});test("clears the failing state when a failing stream delivers again", async () => {const { service, auditLogStreamOutboxDAL, auditLogStreamDAL, eventEmitter } = createService();- auditLogStreamDAL.findById.mockResolvedValueOnce({- id: STREAM_ID,- provider: PROVIDER,- orgId: ORG_ID,- encryptedCredentials: Buffer.from("x"),- streamMode: StreamMode.Batch,- failingSince: FAILING_SINCE- });+ auditLogStreamDAL.findById.mockResolvedValueOnce(failingStream);auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow()]).mockResolvedValueOnce([]);batchStreamLog.mockResolvedValueOnce(undefined);await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });- await lastCommit(auditLogStreamOutboxDAL).inTransaction?.(TX);expect(auditLogStreamOutboxDAL.clearStreamFailing).toHaveBeenCalledWith(STREAM_ID, TX);expect(eventEmitter.emit).not.toHaveBeenCalled();@@ -759,17 +751,16 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {test("stale-claim drops emit once per stream with the dropped count", async () => {const { service, auditLogStreamOutboxDAL, eventEmitter } = createService();+ const row = { streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER as string | null };+ auditLogStreamOutboxDAL.recoverStaleClaims.mockResolvedValueOnce({+ retried: 0,+ dropped: [row, row, { ...row, streamId: "stream-2" }]+ });auditLogStreamOutboxDAL.markStreamFailing.mockResolvedValue(FAILING_SINCE);await service.sweepStaleClaims();- const onDropped = auditLogStreamOutboxDAL.recoverStaleClaims.mock.calls[0][2] as (- dropped: { streamId: string; orgId: string; provider: string | null }[],- tx: unknown- ) => Promise<void>;- const row = { streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER as string | null };- await onDropped([row, row, { ...row, streamId: "stream-2" }], TX);-+ expect(auditLogStreamOutboxDAL.recoverStaleClaims.mock.calls[0][2]).toBe(TX);expect(eventEmitter.emit).toHaveBeenCalledTimes(2);expect(eventEmitter.emit).toHaveBeenCalledWith({diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.tsindex 8e1769e208..6b1921a513 100644--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts@@ -204,6 +204,32 @@ export const auditLogStreamOutboxServiceFactory = ({);};+ // Only the healthy -> failing edge emits: markStreamFailing returns null when the stream is already+ // failing (or gone), so a stream that stays down does not page again on every drain.+ const flagStreamFailing = async (+ {+ streamId,+ orgId,+ provider,+ errorMessage,+ droppedCount+ }: { streamId: string; orgId: string; provider: string | null; errorMessage: string; droppedCount: number },+ tx: Knex+ ) => {+ const truncatedError = truncateDeliveryError(errorMessage);+ const failingSince = await auditLogStreamOutboxDAL.markStreamFailing(+ { streamId, errorMessage: truncatedError },+ tx+ );+ if (!failingSince) return;++ await emitAuditLogStreamDeliveryFailed(+ eventEmitter,+ { orgId, streamId, provider, errorMessage: truncatedError, droppedCount, failingSince },+ tx+ );+ };+// Worker entrypoint. Loops claim→send→ack while there are still rows pending// for this stream, but bounded by MAX_BATCHES_PER_JOB so one wedged stream// can't hold the worker hostage. If rows remain when we bail, the next event@@ -350,35 +376,27 @@ export const auditLogStreamOutboxServiceFactory = ({}// The state flip and the alert event commit with the drop itself, so an alert is never lost- // or sent for rows that are still retrying. Only the healthy -> failing edge emits: a stream- // that stays down keeps its first error rather than paging again on every drain.+ // or sent for rows that are still retrying.const becameFailing = exhausted.length > 0 && !isFailing;const recovered = isFailing && streamFail.length === 0 && streamSuccess.length > 0;- const inTransaction =- becameFailing || recovered- ? async (tx: Knex) => {- if (recovered) {- await auditLogStreamOutboxDAL.clearStreamFailing(streamId, tx);- return;- }- const errorMessage = truncateDeliveryError(exhausted[0].errorMessage);- const failingSince = await auditLogStreamOutboxDAL.markStreamFailing({ streamId, errorMessage }, tx);- if (failingSince) {- await emitAuditLogStreamDeliveryFailed(- eventEmitter,- { orgId, streamId, provider, errorMessage, droppedCount: exhausted.length, failingSince },- tx- );- }- }- : undefined;-// eslint-disable-next-line no-await-in-loop- await auditLogStreamOutboxDAL.commitDeliveryResult({- successIds: streamSuccess.map((row) => row.id),- retriable: retriableInput,- exhaustedIds: exhausted.map((failed) => failed.row.id),- inTransaction+ await auditLogStreamOutboxDAL.transaction(async (tx) => {+ await auditLogStreamOutboxDAL.commitDeliveryResult(+ {+ successIds: streamSuccess.map((row) => row.id),+ retriable: retriableInput,+ exhaustedIds: exhausted.map((failed) => failed.row.id)+ },+ tx+ );+ if (becameFailing) {+ await flagStreamFailing(+ { streamId, orgId, provider, errorMessage: exhausted[0].errorMessage, droppedCount: exhausted.length },+ tx+ );+ } else if (recovered) {+ await auditLogStreamOutboxDAL.clearStreamFailing(streamId, tx);+ }});if (becameFailing) isFailing = true;if (recovered) isFailing = false;@@ -414,31 +432,31 @@ export const auditLogStreamOutboxServiceFactory = ({// - claimBatchForStream's FOR UPDATE SKIP LOCKED + atomic flip to 'processing'// so even concurrent workers claim disjoint rows.const sweepStaleClaims = async () => {- const { retried, dropped } = await auditLogStreamOutboxDAL.recoverStaleClaims(- STALE_CLAIM_THRESHOLD_MS,- MAX_ATTEMPTS,- async (droppedRows, tx) => {- const droppedByStream = new Map<string, { orgId: string; provider: string | null; count: number }>();- for (const { streamId, orgId, provider } of droppedRows) {- const existing = droppedByStream.get(streamId);- if (existing) existing.count += 1;- else droppedByStream.set(streamId, { orgId, provider, count: 1 });- }- for (const [streamId, { orgId, provider, count }] of droppedByStream) {- const errorMessage = "The delivery worker stopped before finishing and the retry limit was reached";- // eslint-disable-next-line no-await-in-loop- const failingSince = await auditLogStreamOutboxDAL.markStreamFailing({ streamId, errorMessage }, tx);- if (failingSince) {- // eslint-disable-next-line no-await-in-loop- await emitAuditLogStreamDeliveryFailed(- eventEmitter,- { orgId, streamId, provider, errorMessage, droppedCount: count, failingSince },- tx- );- }- }+ const { retried, dropped } = await auditLogStreamOutboxDAL.transaction(async (tx) => {+ const result = await auditLogStreamOutboxDAL.recoverStaleClaims(STALE_CLAIM_THRESHOLD_MS, MAX_ATTEMPTS, tx);++ const droppedByStream = new Map<string, { orgId: string; provider: string | null; count: number }>();+ for (const { streamId, orgId, provider } of result.dropped) {+ const existing = droppedByStream.get(streamId);+ if (existing) existing.count += 1;+ else droppedByStream.set(streamId, { orgId, provider, count: 1 });}- );+ for (const [streamId, { orgId, provider, count }] of droppedByStream) {+ // eslint-disable-next-line no-await-in-loop+ await flagStreamFailing(+ {+ streamId,+ orgId,+ provider,+ errorMessage: "The delivery worker stopped before finishing and the retry limit was reached",+ droppedCount: count+ },+ tx+ );+ }++ return result;+ });if (retried > 0 || dropped.length > 0) {logger.warn(`audit-log-stream-outbox: recovered stale claims [retried=${retried}] [dropped=${dropped.length}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`