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): stop flagging streams from the stale-claim sweeper
Calvinc453401b6b42
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 54b8310f4a..75d73ab1d8 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@@ -11,8 +11,6 @@ import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-loexport type TAuditLogStreamOutboxDALFactory = ReturnType<typeof auditLogStreamOutboxDALFactory>;-export type TDroppedStreamRow = { streamId: string; orgId: string; provider: string | null };-export type TInsertOutboxRow = {streamId: string;orgId: string;@@ -172,64 +170,66 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {// emits a metric for the dropped count.const recoverStaleClaims = async (thresholdMs: number,- maxAttempts: number,- tx: Knex- ): Promise<{ retried: number; dropped: TDroppedStreamRow[] }> => {+ maxAttempts: number+ ): Promise<{ retried: number; dropped: { streamId: string; orgId: string; provider: string | null }[] }> => {try {- const staleRows = await tx(TableName.AuditLogStreamOutbox)- .where("status", AuditLogStreamOutboxStatus.Processing)- .andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])- .forUpdate()- .skipLocked()- .select<TAuditLogStreamOutboxRow[]>("*");+ return await db.transaction(async (tx) => {+ const staleRows = await tx(TableName.AuditLogStreamOutbox)+ .where("status", AuditLogStreamOutboxStatus.Processing)+ .andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])+ .forUpdate()+ .skipLocked()+ .select<TAuditLogStreamOutboxRow[]>("*");- if (staleRows.length === 0) return { retried: 0, dropped: [] };+ if (staleRows.length === 0) return { retried: 0, dropped: [] };- const exhausted: TAuditLogStreamOutboxRow[] = [];- const retriable: TAuditLogStreamOutboxRow[] = [];- for (const row of staleRows) {- if (row.attempts + 1 >= maxAttempts) {- exhausted.push(row);- } else {- retriable.push(row);+ const exhausted: TAuditLogStreamOutboxRow[] = [];+ const retriable: TAuditLogStreamOutboxRow[] = [];+ for (const row of staleRows) {+ if (row.attempts + 1 >= maxAttempts) {+ exhausted.push(row);+ } else {+ retriable.push(row);+ }+ }++ if (retriable.length > 0) {+ await tx(TableName.AuditLogStreamOutbox)+ .whereIn(+ "id",+ retriable.map((row) => row.id)+ )+ .update({+ status: AuditLogStreamOutboxStatus.Retry,+ attempts: db.raw('"attempts" + 1'),+ nextRetryAt: tx.fn.now(),+ lockedAt: null+ });}- }- if (retriable.length > 0) {+ if (exhausted.length === 0) return { retried: retriable.length, dropped: [] };+await tx(TableName.AuditLogStreamOutbox).whereIn("id",- retriable.map((row) => row.id)+ exhausted.map((row) => row.id))- .update({- status: AuditLogStreamOutboxStatus.Retry,- attempts: db.raw('"attempts" + 1'),- nextRetryAt: tx.fn.now(),- lockedAt: null- });- }-- if (exhausted.length === 0) return { retried: retriable.length, dropped: [] };-- await tx(TableName.AuditLogStreamOutbox)- .whereIn(- "id",- exhausted.map((row) => row.id)- )- .del();+ .del();- const streams = await tx(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]));+ const streams = await tx(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]));- const dropped = exhausted.map((row) => ({- streamId: row.streamId,- orgId: row.orgId,- provider: providerByStreamId.get(row.streamId) ?? null- }));-- return { retried: retriable.length, dropped };+ return {+ retried: retriable.length,+ dropped: exhausted.map((row) => ({+ streamId: row.streamId,+ orgId: row.orgId,+ provider: providerByStreamId.get(row.streamId) ?? null+ }))+ };+ });} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: recoverStaleClaims" });}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 90a99239cc..f985a7f7d1 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@@ -747,26 +747,4 @@ describe("audit-log-stream-outbox-service delivery failure alerting", () => {};expect(call.retriable?.groups.flatMap((g) => g.ids)).toEqual([1]);});-- 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();-- expect(auditLogStreamOutboxDAL.recoverStaleClaims.mock.calls[0][2]).toBe(TX);- expect(eventEmitter.emit).toHaveBeenCalledTimes(2);- expect(eventEmitter.emit).toHaveBeenCalledWith(- {- eventType: "audit-log.stream.delivery-failed",- payload: containing({ resourceId: STREAM_ID, droppedCount: 2 })- },- TX- );- });});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 dcbf2fa858..4d6165da10 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@@ -432,31 +432,10 @@ 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.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;- });+ const { retried, dropped } = await auditLogStreamOutboxDAL.recoverStaleClaims(+ STALE_CLAIM_THRESHOLD_MS,+ MAX_ATTEMPTS+ );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}]`