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
feat(audit-log-stream): emit delivery-failed event when a stream starts dropping logs
Calvin33511e5f8e82
diff --git a/backend/src/db/migrations/20261007120000_audit-log-stream-health.ts b/backend/src/db/migrations/20261007120000_audit-log-stream-health.tsnew file mode 100644index 0000000000..67e9e14c51--- /dev/null+++ b/backend/src/db/migrations/20261007120000_audit-log-stream-health.ts@@ -0,0 +1,27 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasFailingSince = await knex.schema.hasColumn(TableName.AuditLogStream, "failingSince");+ const hasLastDeliveryError = await knex.schema.hasColumn(TableName.AuditLogStream, "lastDeliveryError");++ if (!hasFailingSince || !hasLastDeliveryError) {+ await knex.schema.alterTable(TableName.AuditLogStream, (t) => {+ if (!hasFailingSince) t.timestamp("failingSince", { useTz: true }).nullable();+ if (!hasLastDeliveryError) t.text("lastDeliveryError").nullable();+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasFailingSince = await knex.schema.hasColumn(TableName.AuditLogStream, "failingSince");+ const hasLastDeliveryError = await knex.schema.hasColumn(TableName.AuditLogStream, "lastDeliveryError");++ if (hasFailingSince || hasLastDeliveryError) {+ await knex.schema.alterTable(TableName.AuditLogStream, (t) => {+ if (hasFailingSince) t.dropColumn("failingSince");+ if (hasLastDeliveryError) t.dropColumn("lastDeliveryError");+ });+ }+}diff --git a/backend/src/db/schemas/audit-log-streams.ts b/backend/src/db/schemas/audit-log-streams.tsindex 9e588e55e6..692d60b9ec 100644--- a/backend/src/db/schemas/audit-log-streams.ts+++ b/backend/src/db/schemas/audit-log-streams.ts@@ -23,7 +23,9 @@ export const AuditLogStreamsSchema = z.object({provider: z.string().default("custom"),encryptedCredentials: zodBuffer,streamMode: z.string().default("batch"),- filters: z.unknown().nullable().optional()+ filters: z.unknown().nullable().optional(),+ failingSince: z.date().nullable().optional(),+ lastDeliveryError: z.string().nullable().optional()});export type TAuditLogStreams = z.infer<typeof AuditLogStreamsSchema>;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 8ed74ff254..dd4559b276 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@@ -10,6 +10,8 @@ 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;@@ -134,9 +136,16 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {successIds: number[];retriable: { groups: { ids: number[]; nextRetryDelayMs: number }[] } | null;exhaustedIds: number[];+ inTransaction?: (tx: Knex) => Promise<void>;}) => {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) return;+ if (+ input.successIds.length === 0 &&+ retriableCount === 0 &&+ input.exhaustedIds.length === 0 &&+ !input.inTransaction+ )+ return;try {await db.transaction(async (tx) => {if (input.successIds.length > 0) {@@ -151,6 +160,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {if (input.exhaustedIds.length > 0) {await tx(TableName.AuditLogStreamOutbox).whereIn("id", input.exhaustedIds).del();}+ if (input.inTransaction) await input.inTransaction(tx);});} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: commitDeliveryResult" });@@ -166,8 +176,9 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {// emits a metric for the dropped count.const recoverStaleClaims = async (thresholdMs: number,- maxAttempts: number- ): Promise<{ retried: number; dropped: { streamId: string; orgId: string; provider: string | null }[] }> => {+ maxAttempts: number,+ onDropped?: (dropped: TDroppedStreamRow[], tx: Knex) => Promise<void>+ ): Promise<{ retried: number; dropped: TDroppedStreamRow[] }> => {try {return await db.transaction(async (tx) => {const staleRows = await tx(TableName.AuditLogStreamOutbox)@@ -217,14 +228,14 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {.select<{ id: string; provider: string }[]>("id", "provider");const providerByStreamId = new Map(streams.map((stream) => [stream.id, stream.provider]));- return {- retried: retriable.length,- dropped: exhausted.map((row) => ({- streamId: row.streamId,- orgId: row.orgId,- provider: providerByStreamId.get(row.streamId) ?? null- }))- };+ const dropped = exhausted.map((row) => ({+ streamId: row.streamId,+ orgId: row.orgId,+ provider: providerByStreamId.get(row.streamId) ?? null+ }));+ if (onDropped) await onDropped(dropped, tx);++ return { retried: retriable.length, dropped };});} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: recoverStaleClaims" });@@ -286,8 +297,37 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {}};+ // Flips the stream to failing only if it was healthy, so the caller emits the alert event on+ // the null -> set edge exactly once even when two workers race. Returns the timestamp it set,+ // or null when the stream was already failing (or no longer exists).+ const markStreamFailing = async (+ { streamId, errorMessage }: { streamId: string; errorMessage: string },+ tx: Knex+ ): Promise<Date | null> => {+ try {+ const [row] = await tx(TableName.AuditLogStream)+ .where("id", streamId)+ .whereNull("failingSince")+ .update({ failingSince: new Date(), lastDeliveryError: errorMessage })+ .returning<{ failingSince: Date }[]>("failingSince");+ return row?.failingSince ?? null;+ } catch (error) {+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markStreamFailing" });+ }+ };++ const clearStreamFailing = async (streamId: string, tx: Knex) => {+ try {+ await tx(TableName.AuditLogStream).where("id", streamId).update({ failingSince: null, lastDeliveryError: null });+ } catch (error) {+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: clearStreamFailing" });+ }+ };+return {batchInsert,+ markStreamFailing,+ clearStreamFailing,claimBatchForStream,commitDeliveryResult,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 8d2c8204bf..01c955dca3 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@@ -40,9 +40,13 @@ vi.mock("@app/lib/telemetry/metrics", () => ({// Keep the real product-filter helpers (auditLogMatchesStreamFilter, resolveAuditLogProduct) so// the fanout filtering tests exercise actual behavior; only credential decryption is stubbed.+const { decryptLogStreamCredentials } = vi.hoisted(() => ({+ decryptLogStreamCredentials: vi.fn<() => Promise<unknown>>(async () => ({}))+}));+vi.mock("@app/ee/services/audit-log-stream/audit-log-stream-fns", async (importOriginal) => ({...(await importOriginal<typeof import("@app/ee/services/audit-log-stream/audit-log-stream-fns")>()),- decryptLogStreamCredentials: async () => ({})+ decryptLogStreamCredentials}));// Every provider lookup returns the same shared batchStreamLog mock so tests can@@ -81,22 +85,38 @@ const createService = () => {batchInsert: vi.fn(async () => undefined),claimBatchForStream: vi.fn<(...args: unknown[]) => Promise<TAuditLogStreamOutboxRow[]>>(async () => []),commitDeliveryResult: vi.fn<(input: unknown) => Promise<void>>(async () => undefined),- recoverStaleClaims: vi.fn(async () => ({ retried: 0, dropped: [] })),+ 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 () => ({+ retried: 0,+ dropped: []+ })),findStreamsWithOverdueRows: vi.fn(async () => []),deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)};const auditLogStreamDAL = {find: vi.fn(async () => []),- findById: vi.fn(async () => ({- id: STREAM_ID,- provider: PROVIDER,- orgId: ORG_ID,- encryptedCredentials: Buffer.from("x"),- streamMode: StreamMode.Batch as StreamMode- }))+ findById: vi.fn(+ async (): Promise<{+ id: string;+ provider: LogProvider;+ orgId: string;+ encryptedCredentials: Buffer;+ streamMode: StreamMode;+ failingSince?: Date | null;+ }> => ({+ id: STREAM_ID,+ provider: PROVIDER,+ orgId: ORG_ID,+ encryptedCredentials: Buffer.from("x"),+ streamMode: StreamMode.Batch+ })+ )};+ const eventEmitter = { emit: vi.fn<(event: unknown, tx?: unknown) => Promise<void>>(async () => undefined) };+const projectDAL = {findProjectTypesByIds: vi.fn(async () => [])};@@ -107,10 +127,11 @@ const createService = () => {projectDAL: projectDAL as never,kmsService: {} as never,keyStore: {} as never,- queueService: {} as never+ queueService: {} as never,+ eventEmitter});- return { service, auditLogStreamOutboxDAL, auditLogStreamDAL, projectDAL };+ return { service, auditLogStreamOutboxDAL, auditLogStreamDAL, projectDAL, eventEmitter };};describe("audit-log-stream-outbox-service drainStream failure handling", () => {@@ -354,7 +375,8 @@ describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {projectDAL: projectDAL as never,kmsService: {} as never,keyStore: keyStore as never,- queueService: queueService as never+ queueService: queueService as never,+ eventEmitter: { emit: vi.fn(async () => undefined) }});return { service, auditLogStreamOutboxDAL, auditLogStreamDAL, projectDAL, keyStore, queueService };@@ -594,3 +616,167 @@ describe("audit-log-stream-outbox-service sweepStaleClaims", () => {expect(exhaustedCounterAdd).not.toHaveBeenCalled();});});++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;++ beforeEach(() => {+ vi.clearAllMocks();+ getProviderBatchLimit.mockReturnValue({ maxLogs: 1_000, maxBytes: 4 * 1024 * 1024 });+ decryptLogStreamCredentials.mockResolvedValue({});+ });++ test("emits one event with the drop when a healthy stream exhausts a row", async () => {+ const { service, auditLogStreamOutboxDAL, eventEmitter } = createService();+ auditLogStreamOutboxDAL.claimBatchForStream+ .mockResolvedValueOnce([buildRow({ attempts: 4 }), buildRow({ id: 2, attempts: 4 })])+ .mockResolvedValueOnce([]);+ auditLogStreamOutboxDAL.markStreamFailing.mockResolvedValueOnce(FAILING_SINCE);+ batchStreamLog.mockRejectedValueOnce(new Error(FAILURE_MESSAGE));++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ await lastCommit(auditLogStreamOutboxDAL).inTransaction?.(TX);++ expect(auditLogStreamOutboxDAL.markStreamFailing).toHaveBeenCalledWith(+ { streamId: STREAM_ID, errorMessage: FAILURE_MESSAGE },+ TX+ );+ expect(eventEmitter.emit).toHaveBeenCalledTimes(1);+ expect(eventEmitter.emit).toHaveBeenCalledWith(+ {+ eventType: "audit-log.stream.delivery-failed",+ payload: containing({+ orgId: ORG_ID,+ resourceType: "audit-log.stream",+ resourceId: STREAM_ID,+ targetIds: [STREAM_ID],+ provider: PROVIDER,+ errorMessage: FAILURE_MESSAGE,+ droppedCount: 2,+ failingSince: FAILING_SINCE.toISOString()+ })+ },+ TX+ );+ });++ test("does not emit when another worker already flipped the stream to failing", async () => {+ const { service, auditLogStreamOutboxDAL, eventEmitter } = createService();+ auditLogStreamOutboxDAL.claimBatchForStream+ .mockResolvedValueOnce([buildRow({ attempts: 4 })])+ .mockResolvedValueOnce([]);+ auditLogStreamOutboxDAL.markStreamFailing.mockResolvedValueOnce(null);+ 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();+ });++ test("does not touch stream health for a retriable failure", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();+ auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow()]).mockResolvedValueOnce([]);+ batchStreamLog.mockRejectedValueOnce(new Error(FAILURE_MESSAGE));++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ });++ test("does not touch stream health for a healthy stream that delivers", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();+ auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow()]).mockResolvedValueOnce([]);+ batchStreamLog.mockResolvedValueOnce(undefined);++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ });++ 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+ });+ auditLogStreamOutboxDAL.claimBatchForStream+ .mockResolvedValueOnce([buildRow({ attempts: 4 })])+ .mockResolvedValueOnce([]);+ batchStreamLog.mockRejectedValueOnce(new Error(FAILURE_MESSAGE));++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(lastCommit(auditLogStreamOutboxDAL).inTransaction).toBeUndefined();+ });++ 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+ });+ 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();+ });++ test("a credential decrypt failure claims the rows and fails them instead of throwing", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();+ decryptLogStreamCredentials.mockRejectedValueOnce(new Error("kms unreachable"));+ auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow()]).mockResolvedValueOnce([]);++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(batchStreamLog).not.toHaveBeenCalled();+ const call = auditLogStreamOutboxDAL.commitDeliveryResult.mock.calls[0][0] as {+ retriable: { groups: { ids: number[] }[] } | null;+ };+ 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();+ 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(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 6d63a03d54..8e1769e208 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@@ -1,3 +1,5 @@+import { Knex } from "knex";+import { TAuditLogs } from "@app/db/schemas";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { chunkArray } from "@app/lib/fn";@@ -7,12 +9,14 @@ import {auditLogStreamDeliveryExhaustedCounter} from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";+import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { chunkAuditLogsByBatchLimit } from "../audit-log-stream/audit-log-stream-batching";import { TAuditLogStreamDALFactory } from "../audit-log-stream/audit-log-stream-dal";import { LogProvider, StreamMode } from "../audit-log-stream/audit-log-stream-enums";+import { emitAuditLogStreamDeliveryFailed, truncateDeliveryError } from "../audit-log-stream/audit-log-stream-events";import { LOG_STREAM_FACTORY_MAP } from "../audit-log-stream/audit-log-stream-factory";import {auditLogMatchesStreamFilter,@@ -21,6 +25,7 @@ import {streamHasProductFilter} from "../audit-log-stream/audit-log-stream-fns";import { TAuditLogStreamFilters } from "../audit-log-stream/audit-log-stream-schemas";+import { TAuditLogStreamCredentials } from "../audit-log-stream/audit-log-stream-types";import { TAuditLogStreamOutboxDALFactory } from "./audit-log-stream-outbox-dal";import {TAuditLogStreamFlushJobData,@@ -74,6 +79,7 @@ export type TAuditLogStreamOutboxServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;queueService: TQueueServiceFactory;+ eventEmitter: TEventEmitter;};export type TAuditLogStreamOutboxServiceFactory = {@@ -89,7 +95,8 @@ export const auditLogStreamOutboxServiceFactory = ({projectDAL,kmsService,keyStore,- queueService+ queueService,+ eventEmitter}: TAuditLogStreamOutboxServiceFactoryDep): TAuditLogStreamOutboxServiceFactory => {// Try to win the 5s SETNX debounce for a stream and, on win, enqueue a delayed// flush job on the shared outbox queue (provider is carried in the payload and read@@ -214,11 +221,20 @@ export const auditLogStreamOutboxServiceFactory = ({return;}- const credentials = await decryptLogStreamCredentials({- encryptedCredentials: stream.encryptedCredentials,- orgId: stream.orgId,- kmsService- });+ // A stream whose credentials can't be decrypted (eg its org KMS key is broken) goes through the+ // same claim, retry, drop and alert path as a failing endpoint. Throwing here instead would leave+ // its rows unclaimed, so they would never use up their attempts and nobody would be told.+ let credentials: TAuditLogStreamCredentials = {} as TAuditLogStreamCredentials;+ let credentialsError: Error | null = null;+ try {+ credentials = await decryptLogStreamCredentials({+ encryptedCredentials: stream.encryptedCredentials,+ orgId: stream.orgId,+ kmsService+ });+ } catch (error) {+ credentialsError = new Error(`Failed to decrypt stream credentials: ${(error as Error)?.message}`);+ }const providerImpl = factory();@@ -226,6 +242,8 @@ export const auditLogStreamOutboxServiceFactory = ({// else gets a JSON array per request. Single mode treats each row as its own chunk.const isSingleMode = stream.streamMode === StreamMode.Single;+ let isFailing = Boolean(stream.failingSince);+for (let batchIdx = 0; batchIdx < MAX_BATCHES_PER_JOB; batchIdx += 1) {// eslint-disable-next-line no-await-in-loopconst claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE);@@ -243,6 +261,7 @@ export const auditLogStreamOutboxServiceFactory = ({"audit_log_stream.provider": provider};try {+ if (credentialsError) throw credentialsError;if (isSingleMode) {if (!providerImpl.streamLog) {throw new Error(`provider '${provider}' does not support single stream mode`);@@ -330,12 +349,39 @@ 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.+ 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-loopawait auditLogStreamOutboxDAL.commitDeliveryResult({successIds: streamSuccess.map((row) => row.id),retriable: retriableInput,- exhaustedIds: exhausted.map((failed) => failed.row.id)+ exhaustedIds: exhausted.map((failed) => failed.row.id),+ inTransaction});+ if (becameFailing) isFailing = true;+ if (recovered) isFailing = false;if (streamFail.length > 0) {// Each failed chunk is already logged with its error above; the rows are@@ -370,7 +416,28 @@ export const auditLogStreamOutboxServiceFactory = ({const sweepStaleClaims = async () => {const { retried, dropped } = await auditLogStreamOutboxDAL.recoverStaleClaims(STALE_CLAIM_THRESHOLD_MS,- MAX_ATTEMPTS+ 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+ );+ }+ }+ });if (retried > 0 || dropped.length > 0) {logger.warn(diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-events.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-events.tsnew file mode 100644index 0000000000..105502b9a2--- /dev/null+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-events.ts@@ -0,0 +1,53 @@+import { Knex } from "knex";+import { z } from "zod";++import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";++export const AUDIT_LOG_STREAM_RESOURCE_TYPE = "audit-log.stream";+export const AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT = "audit-log.stream.delivery-failed";++export const AUDIT_LOG_STREAM_ERROR_MAX_LENGTH = 500;++export const AuditLogStreamDeliveryFailedPayloadSchema = z.object({+ provider: z.string(),+ errorMessage: z.string(),+ droppedCount: z.number().int().positive(),+ failingSince: z.coerce.date()+});++export type TAuditLogStreamDeliveryFailedInput = {+ orgId: string;+ streamId: string;+ provider: string | null;+ errorMessage: string;+ droppedCount: number;+ failingSince: Date;+};++export const truncateDeliveryError = (message: string): string =>+ message.length > AUDIT_LOG_STREAM_ERROR_MAX_LENGTH+ ? `${message.slice(0, AUDIT_LOG_STREAM_ERROR_MAX_LENGTH)}...`+ : message;++export const emitAuditLogStreamDeliveryFailed = (+ eventEmitter: TEventEmitter,+ { orgId, streamId, provider, errorMessage, droppedCount, failingSince }: TAuditLogStreamDeliveryFailedInput,+ tx: Knex+): Promise<void> =>+ eventEmitter.emit(+ {+ eventType: AUDIT_LOG_STREAM_DELIVERY_FAILED_EVENT,+ payload: {+ orgId,+ projectId: null,+ resourceType: AUDIT_LOG_STREAM_RESOURCE_TYPE,+ resourceId: streamId,+ targetIds: [streamId],+ provider: provider ?? "unknown",+ errorMessage: truncateDeliveryError(errorMessage),+ droppedCount,+ failingSince: failingSince.toISOString()+ }+ },+ tx+ );diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.tsindex c2e7a64350..015d5bf648 100644--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts@@ -199,6 +199,10 @@ export const auditLogStreamServiceFactory = ({const updatedLogStream = await auditLogStreamDAL.updateById(logStreamId, {encryptedCredentials,+ // The credentials just passed validateCredentials, so start health tracking over. A stream that+ // is still broken then alerts again instead of staying silent behind its old failingSince.+ failingSince: null,+ lastDeliveryError: null,// Only persist a mode change when provided (the validated single -> batch upgrade)....(streamMode ? { streamMode } : {}),// `undefined` leaves the existing filter untouched; `null`/empty clears it (stream all).diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 3a9cd70be4..27c70e1983 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1234,7 +1234,8 @@ export const registerRoutes = async (projectDAL,kmsService,keyStore,- queueService+ queueService,+ eventEmitter: eventOutboxService});const auditLogStreamOutboxQueue = auditLogStreamOutboxQueueFactory({