Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

add outbox pattern for audit log streaming

Thiago Araujo da Silva0692ee6a5987
diff --git a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
new file mode 100644
index 0000000000..04365a4ab9
--- /dev/null
+++ b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
@@ -0,0 +1,67 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.AuditLogStreamOutbox))) {
+ await knex.schema.createTable(TableName.AuditLogStreamOutbox, (t) => {
+ t.bigIncrements("id").primary();
+ t.uuid("streamId").notNullable();
+ t.uuid("orgId").notNullable();
+ t.jsonb("payload").notNullable();
+ t.string("status").notNullable().defaultTo("pending");
+ t.check(`"status" IN ('pending', 'processing', 'retry')`);
+ t.integer("attempts").notNullable().defaultTo(0);
+ t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
+ t.timestamp("lockedAt", { useTz: true });
+ t.string("workerId");
+ t.text("lastError");
+ t.timestamps(true, true, true);
+
+ t.foreign("streamId").references("id").inTable(TableName.AuditLogStream).onDelete("CASCADE");
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ });
+
+ // Worker drain query: WHERE streamId = ? AND status IN ('pending','retry') AND nextRetryAt <= NOW() ORDER BY id LIMIT N FOR UPDATE SKIP LOCKED
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_drain_idx"
+ ON "${TableName.AuditLogStreamOutbox}" ("streamId", "nextRetryAt", "id")
+ WHERE status IN ('pending', 'retry')
+ `);
+
+ // Stale lock recovery: surface rows stuck in 'processing' (worker crashed mid-batch).
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_processing_idx"
+ ON "${TableName.AuditLogStreamOutbox}" ("lockedAt")
+ WHERE status = 'processing'
+ `);
+ }
+
+ await createOnUpdateTrigger(knex, TableName.AuditLogStreamOutbox);
+
+ if (!(await knex.schema.hasTable(TableName.AuditLogStreamOutboxDlq))) {
+ await knex.schema.createTable(TableName.AuditLogStreamOutboxDlq, (t) => {
+ t.bigIncrements("id").primary();
+ t.bigInteger("originalAuditLogStreamOutboxId").notNullable();
+ t.uuid("streamId").notNullable();
+ t.uuid("orgId").notNullable();
+ t.jsonb("payload").notNullable();
+ t.integer("attempts").notNullable();
+ t.text("lastError");
+ t.timestamp("originalCreatedAt", { useTz: true }).notNullable();
+ t.timestamp("failedAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
+
+ t.foreign("streamId").references("id").inTable(TableName.AuditLogStream).onDelete("CASCADE");
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ t.index(["streamId", "failedAt"]);
+ t.index(["orgId", "failedAt"]);
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await dropOnUpdateTrigger(knex, TableName.AuditLogStreamOutbox);
+ await knex.schema.dropTableIfExists(TableName.AuditLogStreamOutboxDlq);
+ await knex.schema.dropTableIfExists(TableName.AuditLogStreamOutbox);
+}
diff --git a/backend/src/db/schemas/approval-policies.ts b/backend/src/db/schemas/approval-policies.ts
index f358b620a4..7833dc4ec7 100644
--- a/backend/src/db/schemas/approval-policies.ts
+++ b/backend/src/db/schemas/approval-policies.ts
@@ -20,9 +20,9 @@ export const ApprovalPoliciesSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
bypassForMachineIdentities: z.boolean().default(false).nullable().optional(),
- enforcementLevel: z.string().default("hard"),
scopeType: z.string().nullable().optional(),
- scopeId: z.string().uuid().nullable().optional()
+ scopeId: z.string().uuid().nullable().optional(),
+ enforcementLevel: z.string().default("hard")
});
export type TApprovalPolicies = z.infer<typeof ApprovalPoliciesSchema>;
diff --git a/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts b/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts
new file mode 100644
index 0000000000..d9c0db63a9
--- /dev/null
+++ b/backend/src/db/schemas/audit-log-stream-outbox-dlq.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AuditLogStreamOutboxDlqSchema = z.object({
+ id: z.coerce.number(),
+ originalAuditLogStreamOutboxId: z.coerce.number(),
+ streamId: z.string().uuid(),
+ orgId: z.string().uuid(),
+ payload: z.unknown(),
+ attempts: z.number(),
+ lastError: z.string().nullable().optional(),
+ originalCreatedAt: z.date(),
+ failedAt: z.date()
+});
+
+export type TAuditLogStreamOutboxDlq = z.infer<typeof AuditLogStreamOutboxDlqSchema>;
+export type TAuditLogStreamOutboxDlqInsert = Omit<z.input<typeof AuditLogStreamOutboxDlqSchema>, TImmutableDBKeys>;
+export type TAuditLogStreamOutboxDlqUpdate = Partial<
+ Omit<z.input<typeof AuditLogStreamOutboxDlqSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/audit-log-stream-outbox.ts b/backend/src/db/schemas/audit-log-stream-outbox.ts
new file mode 100644
index 0000000000..56ed9b182a
--- /dev/null
+++ b/backend/src/db/schemas/audit-log-stream-outbox.ts
@@ -0,0 +1,27 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const AuditLogStreamOutboxSchema = z.object({
+ id: z.coerce.number(),
+ streamId: z.string().uuid(),
+ orgId: z.string().uuid(),
+ payload: z.unknown(),
+ status: z.string().default("pending"),
+ attempts: z.number().default(0),
+ nextRetryAt: z.date(),
+ lockedAt: z.date().nullable().optional(),
+ workerId: z.string().nullable().optional(),
+ lastError: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TAuditLogStreamOutbox = z.infer<typeof AuditLogStreamOutboxSchema>;
+export type TAuditLogStreamOutboxInsert = Omit<z.input<typeof AuditLogStreamOutboxSchema>, TImmutableDBKeys>;
+export type TAuditLogStreamOutboxUpdate = Partial<Omit<z.input<typeof AuditLogStreamOutboxSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/audit-log-streams.ts b/backend/src/db/schemas/audit-log-streams.ts
index a3f6bafba8..3c961734eb 100644
--- a/backend/src/db/schemas/audit-log-streams.ts
+++ b/backend/src/db/schemas/audit-log-streams.ts
@@ -21,7 +21,8 @@ export const AuditLogStreamsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
provider: z.string().default("custom"),
- encryptedCredentials: zodBuffer
+ encryptedCredentials: zodBuffer,
+ streamMode: z.string().default("batch")
});
export type TAuditLogStreams = z.infer<typeof AuditLogStreamsSchema>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index a381a4e19e..8445b4aabb 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -22,6 +22,8 @@ export * from "./approval-request-grants";
export * from "./approval-request-step-eligible-approvers";
export * from "./approval-request-steps";
export * from "./approval-requests";
+export * from "./audit-log-stream-outbox";
+export * from "./audit-log-stream-outbox-dlq";
export * from "./audit-log-streams";
export * from "./audit-logs";
export * from "./auth-token-sessions";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index ef68f60760..d8517c4a79 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -140,6 +140,8 @@ export enum TableName {
LdapGroupMap = "ldap_group_maps",
AuditLog = "audit_logs",
AuditLogStream = "audit_log_streams",
+ AuditLogStreamOutbox = "audit_log_stream_outbox",
+ AuditLogStreamOutboxDlq = "audit_log_stream_outbox_dlq",
GitAppInstallSession = "git_app_install_sessions",
GitAppOrg = "git_app_org",
SecretScanningGitRisk = "secret_scanning_git_risks",
diff --git a/backend/src/db/schemas/org-github-apps.ts b/backend/src/db/schemas/org-github-apps.ts
new file mode 100644
index 0000000000..4b9816b502
--- /dev/null
+++ b/backend/src/db/schemas/org-github-apps.ts
@@ -0,0 +1,28 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const OrgGithubAppsSchema = z.object({
+ id: z.string().uuid(),
+ orgId: z.string().uuid(),
+ name: z.string(),
+ encryptedAppId: zodBuffer,
+ encryptedClientId: zodBuffer,
+ encryptedClientSecret: zodBuffer,
+ encryptedPrivateKey: zodBuffer,
+ encryptedSlug: zodBuffer,
+ encryptedWebhookSecret: zodBuffer.nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TOrgGithubApps = z.infer<typeof OrgGithubAppsSchema>;
+export type TOrgGithubAppsInsert = Omit<z.input<typeof OrgGithubAppsSchema>, TImmutableDBKeys>;
+export type TOrgGithubAppsUpdate = Partial<Omit<z.input<typeof OrgGithubAppsSchema>, TImmutableDBKeys>>;
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.ts
new file mode 100644
index 0000000000..23afa8be3b
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
@@ -0,0 +1,144 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName, TAuditLogs } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+import { AuditLogStreamOutboxStatus, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";
+
+export type TAuditLogStreamOutboxDALFactory = ReturnType<typeof auditLogStreamOutboxDALFactory>;
+
+export type TInsertOutboxRow = {
+ streamId: string;
+ orgId: string;
+ payload: TAuditLogs;
+};
+
+export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
+ const batchInsert = async (rows: TInsertOutboxRow[], tx?: Knex) => {
+ if (rows.length === 0) return;
+ try {
+ const records = rows.map((row) => ({
+ streamId: row.streamId,
+ orgId: row.orgId,
+ // Store as native JSONB; Knex serializes JS objects when the column type is jsonb.
+ payload: JSON.stringify(row.payload),
+ status: AuditLogStreamOutboxStatus.Pending
+ }));
+ await (tx || db).batchInsert(TableName.AuditLogStreamOutbox, records);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: batchInsert" });
+ }
+ };
+
+ // Atomically claim up to `limit` ready rows for `streamId`: lock them with
+ // FOR UPDATE SKIP LOCKED, mark them processing, and return them to the worker.
+ // Runs inside a single transaction so the lock and the status flip commit together.
+ const claimBatchForStream = async (
+ streamId: string,
+ limit: number,
+ workerId: string
+ ): Promise<TAuditLogStreamOutboxRow[]> => {
+ try {
+ return await db.transaction(async (tx) => {
+ const lockedRows = await tx(TableName.AuditLogStreamOutbox)
+ .where({ streamId })
+ .whereIn("status", [AuditLogStreamOutboxStatus.Pending, AuditLogStreamOutboxStatus.Retry])
+ .andWhere("nextRetryAt", "<=", tx.fn.now())
+ .orderBy("id", "asc")
+ .limit(limit)
+ .forUpdate()
+ .skipLocked()
+ .select<{ id: number }[]>("id");
+
+ if (lockedRows.length === 0) return [];
+
+ const ids = lockedRows.map((row) => row.id);
+ const claimed = await tx(TableName.AuditLogStreamOutbox)
+ .whereIn("id", ids)
+ .update({
+ status: AuditLogStreamOutboxStatus.Processing,
+ lockedAt: tx.fn.now(),
+ workerId
+ })
+ .returning("*");
+
+ return claimed as unknown as TAuditLogStreamOutboxRow[];
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: claimBatchForStream" });
+ }
+ };
+
+ const deleteByIds = async (ids: number[], tx?: Knex) => {
+ if (ids.length === 0) return;
+ try {
+ await (tx || db)(TableName.AuditLogStreamOutbox).whereIn("id", ids).del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: deleteByIds" });
+ }
+ };
+
+ // Release a claim by flipping rows back to 'retry' with an updated attempt count
+ // and a future nextRetryAt. Used when the provider call fails for the whole batch.
+ const markBatchForRetry = async (ids: number[], nextRetryAt: Date, errorMessage: string, tx?: Knex) => {
+ if (ids.length === 0) return;
+ try {
+ await (tx || db)(TableName.AuditLogStreamOutbox)
+ .whereIn("id", ids)
+ .update({
+ status: AuditLogStreamOutboxStatus.Retry,
+ attempts: db.raw('"attempts" + 1'),
+ nextRetryAt,
+ lockedAt: null,
+ workerId: null,
+ lastError: errorMessage
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markBatchForRetry" });
+ }
+ };
+
+ // Move exhausted rows out of the hot table into the DLQ in one transaction —
+ // copies the payload + audit history, then deletes the original rows so the
+ // worker never picks them up again.
+ const moveToDlq = async (rows: TAuditLogStreamOutboxRow[], errorMessage: string, tx?: Knex) => {
+ if (rows.length === 0) return;
+ try {
+ const exec = async (trx: Knex) => {
+ const dlqRows = rows.map((row) => ({
+ originalAuditLogStreamOutboxId: row.id,
+ streamId: row.streamId,
+ orgId: row.orgId,
+ payload: JSON.stringify(row.payload),
+ attempts: row.attempts,
+ lastError: errorMessage,
+ originalCreatedAt: row.createdAt
+ }));
+ await trx.batchInsert(TableName.AuditLogStreamOutboxDlq, dlqRows);
+ await trx(TableName.AuditLogStreamOutbox)
+ .whereIn(
+ "id",
+ rows.map((row) => row.id)
+ )
+ .del();
+ };
+
+ if (tx) {
+ await exec(tx);
+ } else {
+ await db.transaction(exec);
+ }
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: moveToDlq" });
+ }
+ };
+
+ return {
+ batchInsert,
+ claimBatchForStream,
+ deleteByIds,
+ markBatchForRetry,
+ moveToDlq
+ };
+};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
new file mode 100644
index 0000000000..dfd10afbdc
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
@@ -0,0 +1,38 @@
+import { logger } from "@app/lib/logger";
+import { QueueName, TQueueServiceFactory } from "@app/queue";
+
+import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";
+import { TAuditLogStreamOutboxServiceFactory } from "./audit-log-stream-outbox-service";
+
+export type TAuditLogStreamOutboxQueueDep = {
+ queueService: TQueueServiceFactory;
+ auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "drainStream">;
+};
+
+// Boots one BullMQ worker per provider so a slow upstream (e.g. a wedged
+// Splunk HEC) can't block deliveries to a healthy one (e.g. Datadog).
+export const auditLogStreamOutboxQueueFactory = ({
+ queueService,
+ auditLogStreamOutboxService
+}: TAuditLogStreamOutboxQueueDep) => {
+ const registerWorker = <T extends QueueName>(queueName: T, provider: LogProvider) => {
+ queueService.start(queueName, async (job) => {
+ const { streamId, orgId } = job.data as { streamId: string; orgId: string };
+ try {
+ await auditLogStreamOutboxService.drainStream({ streamId, orgId, provider });
+ } catch (error) {
+ logger.error(
+ error,
+ `audit-log-stream-outbox: flush worker crashed [provider=${provider}] [streamId=${streamId}] [orgId=${orgId}]`
+ );
+ throw error;
+ }
+ });
+ };
+
+ registerWorker(QueueName.AuditLogStreamAzure, LogProvider.Azure);
+ registerWorker(QueueName.AuditLogStreamCribl, LogProvider.Cribl);
+ registerWorker(QueueName.AuditLogStreamCustom, LogProvider.Custom);
+ registerWorker(QueueName.AuditLogStreamDatadog, LogProvider.Datadog);
+ registerWorker(QueueName.AuditLogStreamSplunk, LogProvider.Splunk);
+};
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.ts
new file mode 100644
index 0000000000..890bb84425
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
@@ -0,0 +1,230 @@
+import { isAxiosError } from "axios";
+import { randomUUID } from "crypto";
+
+import { TAuditLogs } from "@app/db/schemas";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TAuditLogStreamDALFactory } from "../audit-log-stream/audit-log-stream-dal";
+import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";
+import { LOG_STREAM_FACTORY_MAP } from "../audit-log-stream/audit-log-stream-factory";
+import { decryptLogStreamCredentials } from "../audit-log-stream/audit-log-stream-fns";
+import { TAuditLogStreamOutboxDALFactory } from "./audit-log-stream-outbox-dal";
+import { TAuditLogStreamFlushJobData, TAuditLogStreamOutboxRow } from "./audit-log-stream-outbox-types";
+
+// Debounce window: first writer for a stream enqueues a flush job delayed by this many ms.
+// Subsequent writers within the window are absorbed by the same job (SETNX is a no-op for them).
+const FLUSH_DEBOUNCE_MS = 5_000;
+const FLUSH_DEBOUNCE_SECONDS = Math.ceil(FLUSH_DEBOUNCE_MS / 1_000);
+
+// Worker drain settings.
+const BATCH_SIZE = 1_000;
+const MAX_BATCHES_PER_JOB = 10; // hard cap so one job can't monopolize the worker
+const MAX_ATTEMPTS = 5;
+// Exponential backoff with jitter, capped — keeps a wedged provider from hot-looping.
+const BACKOFF_BASE_MS = 30_000;
+const BACKOFF_MAX_MS = 15 * 60_000;
+
+const PROVIDER_QUEUE_MAP: Record<LogProvider, QueueName> = {
+ [LogProvider.Azure]: QueueName.AuditLogStreamAzure,
+ [LogProvider.Cribl]: QueueName.AuditLogStreamCribl,
+ [LogProvider.Custom]: QueueName.AuditLogStreamCustom,
+ [LogProvider.Datadog]: QueueName.AuditLogStreamDatadog,
+ [LogProvider.Splunk]: QueueName.AuditLogStreamSplunk
+};
+
+const LAST_ERROR_MAX_LENGTH = 1_000;
+
+const computeBackoff = (attemptsAfterIncrement: number): Date => {
+ const exponent = Math.min(attemptsAfterIncrement - 1, 10);
+ const base = Math.min(BACKOFF_BASE_MS * 2 ** exponent, BACKOFF_MAX_MS);
+ const jitter = Math.floor(Math.random() * Math.min(base / 2, 30_000));
+ return new Date(Date.now() + base + jitter);
+};
+
+const truncateError = (error: unknown): string => {
+ let message: string;
+ if (isAxiosError(error)) {
+ message = `${error.message ?? "Request failed"} — ${JSON.stringify(error.response?.data ?? null)}`;
+ } else {
+ message = (error as Error)?.message ?? "Unknown error";
+ }
+ if (message.length > LAST_ERROR_MAX_LENGTH) {
+ return `${message.slice(0, LAST_ERROR_MAX_LENGTH)}...`;
+ }
+ return message;
+};
+
+const formatErrorMessage = (error: unknown): string => {
+ if (isAxiosError(error)) {
+ return `${error.message ?? "Request failed"} — ${JSON.stringify(error.response?.data ?? null)}`;
+ }
+ return (error as Error)?.message ?? "Unknown error";
+};
+
+export type TAuditLogStreamOutboxServiceFactoryDep = {
+ auditLogStreamOutboxDAL: TAuditLogStreamOutboxDALFactory;
+ auditLogStreamDAL: Pick<TAuditLogStreamDALFactory, "find" | "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
+ queueService: TQueueServiceFactory;
+ onStreamFailure?: (input: {
+ orgId: string;
+ streamId: string;
+ provider: LogProvider;
+ errorMessage: string;
+ }) => Promise<void> | void;
+};
+
+export type TAuditLogStreamOutboxServiceFactory = {
+ enqueueForOrg: (orgId: string, auditLog: TAuditLogs) => Promise<void>;
+ drainStream: (data: TAuditLogStreamFlushJobData) => Promise<void>;
+};
+
+export const auditLogStreamOutboxServiceFactory = ({
+ auditLogStreamOutboxDAL,
+ auditLogStreamDAL,
+ kmsService,
+ keyStore,
+ queueService,
+ onStreamFailure
+}: TAuditLogStreamOutboxServiceFactoryDep): TAuditLogStreamOutboxServiceFactory => {
+ // Per-audit-log fanout:
+ // 1. Look up active streams for the org.
+ // 2. Insert one outbox row per stream (payload is self-contained).
+ // 3. For each stream, try to win the 5s debounce SETNX. The winner enqueues
+ // the flush job (delayed by FLUSH_DEBOUNCE_MS) on the provider queue;
+ // losers do nothing because their event is already covered by the winner's job.
+ const enqueueForOrg = async (orgId: string, auditLog: TAuditLogs) => {
+ const streams = await auditLogStreamDAL.find({ orgId });
+ if (streams.length === 0) return;
+
+ await auditLogStreamOutboxDAL.batchInsert(
+ streams.map((stream) => ({ streamId: stream.id, orgId, payload: auditLog }))
+ );
+
+ await Promise.allSettled(
+ streams.map(async (stream) => {
+ const provider = stream.provider as LogProvider;
+ const queueName = PROVIDER_QUEUE_MAP[provider];
+ if (!queueName) {
+ logger.warn(
+ `audit-log-stream-outbox: unknown provider, skipping flush enqueue [provider=${provider}] [streamId=${stream.id}]`
+ );
+ return;
+ }
+
+ const debounceKey = KeyStorePrefixes.AuditLogStreamFlushDebounce(stream.id);
+ const acquired = await keyStore.setItemWithExpiryNX(debounceKey, FLUSH_DEBOUNCE_SECONDS, "1");
+ if (!acquired) return;
+
+ // Job ID matches the debounce key so BullMQ collapses any in-flight duplicates.
+ await queueService.queue(
+ queueName,
+ QueueJobs.AuditLogStreamFlush,
+ { streamId: stream.id, orgId, provider },
+ {
+ jobId: `flush:${stream.id}`,
+ delay: FLUSH_DEBOUNCE_MS,
+ removeOnComplete: true,
+ removeOnFail: { count: 50 }
+ }
+ );
+ })
+ );
+ };
+
+ // 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
+ // for the stream will debounce-enqueue another flush.
+ const drainStream = async ({ streamId, orgId, provider }: TAuditLogStreamFlushJobData) => {
+ const stream = await auditLogStreamDAL.findById(streamId);
+ if (!stream) {
+ logger.warn(`audit-log-stream-outbox: stream deleted, dropping flush [streamId=${streamId}]`);
+ return;
+ }
+
+ const factory = LOG_STREAM_FACTORY_MAP[provider];
+ if (!factory) {
+ logger.error(`audit-log-stream-outbox: unknown provider [provider=${provider}] [streamId=${streamId}]`);
+ return;
+ }
+
+ const credentials = await decryptLogStreamCredentials({
+ encryptedCredentials: stream.encryptedCredentials,
+ orgId: stream.orgId,
+ kmsService
+ });
+
+ const workerId = randomUUID();
+ const providerImpl = factory();
+
+ for (let batchIdx = 0; batchIdx < MAX_BATCHES_PER_JOB; batchIdx += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE, workerId);
+ if (claimed.length === 0) return;
+
+ const auditLogs = claimed.map((row) => row.payload);
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await providerImpl.batchStreamLog({ credentials, auditLogs });
+ // eslint-disable-next-line no-await-in-loop
+ await auditLogStreamOutboxDAL.deleteByIds(claimed.map((row) => row.id));
+ } catch (error) {
+ const errorMessage = truncateError(error);
+ const logMessage = formatErrorMessage(error);
+ logger.error(
+ error,
+ `audit-log-stream-outbox: batch delivery failed [streamId=${streamId}] [orgId=${orgId}] [provider=${provider}] [batchSize=${claimed.length}]: ${logMessage}`
+ );
+
+ const exhausted: TAuditLogStreamOutboxRow[] = [];
+ const retriable: TAuditLogStreamOutboxRow[] = [];
+ // attempts on the row is pre-increment. The +1 reflects this failure.
+ for (const row of claimed) {
+ if (row.attempts + 1 >= MAX_ATTEMPTS) {
+ exhausted.push(row);
+ } else {
+ retriable.push(row);
+ }
+ }
+
+ if (retriable.length > 0) {
+ // Use the same nextRetryAt for the whole retriable batch — they share
+ // a failure cause, so they should re-enter together. Each row's own
+ // attempts count is incremented atomically in DAL.
+ const maxAttemptsInBatch = Math.max(...retriable.map((row) => row.attempts + 1));
+ const nextRetryAt = computeBackoff(maxAttemptsInBatch);
+ // eslint-disable-next-line no-await-in-loop
+ await auditLogStreamOutboxDAL.markBatchForRetry(
+ retriable.map((row) => row.id),
+ nextRetryAt,
+ errorMessage
+ );
+ }
+
+ if (exhausted.length > 0) {
+ // eslint-disable-next-line no-await-in-loop
+ await auditLogStreamOutboxDAL.moveToDlq(exhausted, errorMessage);
+ }
+
+ if (onStreamFailure) {
+ // eslint-disable-next-line no-await-in-loop
+ await Promise.resolve(onStreamFailure({ orgId, streamId, provider, errorMessage }));
+ }
+
+ // Stop draining on the first failure — let backoff govern the retry cadence
+ // instead of hammering a failing endpoint with the next batch.
+ return;
+ }
+ }
+ };
+
+ return {
+ enqueueForOrg,
+ drainStream
+ };
+};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
new file mode 100644
index 0000000000..b0b2cc3e9a
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
@@ -0,0 +1,30 @@
+import { TAuditLogs } from "@app/db/schemas";
+
+import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";
+
+export enum AuditLogStreamOutboxStatus {
+ Pending = "pending",
+ Processing = "processing",
+ Retry = "retry"
+}
+
+export type TAuditLogStreamOutboxRow = {
+ id: number;
+ streamId: string;
+ orgId: string;
+ payload: TAuditLogs;
+ status: AuditLogStreamOutboxStatus;
+ attempts: number;
+ nextRetryAt: Date;
+ lockedAt: Date | null;
+ workerId: string | null;
+ lastError: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+export type TAuditLogStreamFlushJobData = {
+ streamId: string;
+ orgId: string;
+ provider: LogProvider;
+};
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.ts
index 56f1c906fa..ffd3f31be8 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
@@ -1,5 +1,4 @@
import { ForbiddenError } from "@casl/ability";
-import { isAxiosError } from "axios";
import { OrganizationActionScope, TAuditLogs } from "@app/db/schemas";
import {
@@ -279,7 +278,6 @@ export const auditLogStreamServiceFactory = ({
deleteById,
getById,
list,
- listProviderOptions,
- streamLog
+ listProviderOptions
};
};
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
index 5983e50bf9..c1e8ac85aa 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
@@ -31,12 +31,12 @@ export type TLogStreamFactoryValidateCredentials<C extends TAuditLogStreamCreden
credentials: C;
}) => Promise<C>;
-export type TLogStreamFactoryStreamLog<C extends TAuditLogStreamCredentials> = (input: {
+export type TLogStreamFactoryBatchStreamLog<C extends TAuditLogStreamCredentials> = (input: {
credentials: C;
- auditLog: TAuditLogs;
+ auditLogs: TAuditLogs[];
}) => Promise<void>;
export type TLogStreamFactory<C extends TAuditLogStreamCredentials> = () => {
validateCredentials: TLogStreamFactoryValidateCredentials<C>;
- streamLog: TLogStreamFactoryStreamLog<C>;
+ batchStreamLog: TLogStreamFactoryBatchStreamLog<C>;
};
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
index ecba115f69..43778a9902 100644
--- a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
@@ -4,17 +4,19 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
-import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
-import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
import { TAzureProviderCredentials } from "./azure-provider-types";
+function buildAzureEvent(event: { createdAt?: Date | string } & Record<string, unknown>) {
+ return {
+ ...event,
+ TimeGenerated: (event.createdAt ? new Date(event.createdAt) : new Date()).toISOString()
+ };
+}
+
function createPayload(event: { createdAt?: Date | string } & Record<string, unknown>) {
- return [
- {
- ...event,
- TimeGenerated: (event.createdAt ? new Date(event.createdAt) : new Date()).toISOString()
- }
- ];
+ return [buildAzureEvent(event)];
}
async function getAzureToken(tenantId: string, clientId: string, clientSecret: string) {
@@ -67,7 +69,13 @@ export const AzureProviderFactory = () => {
return credentials;
};
- const streamLog: TLogStreamFactoryStreamLog<TAzureProviderCredentials> = async ({ credentials, auditLog }) => {
+ // Azure Logs Ingestion API natively accepts a JSON array of events per request.
+ const batchStreamLog: TLogStreamFactoryBatchStreamLog<TAzureProviderCredentials> = async ({
+ credentials,
+ auditLogs
+ }) => {
+ if (auditLogs.length === 0) return;
+
const { tenantId, clientId, clientSecret, dceUrl, dcrId, cltName } = credentials;
await blockLocalAndPrivateIpAddresses(dceUrl);
@@ -81,16 +89,16 @@ export const AzureProviderFactory = () => {
await request.post(
`${dceUrl}/dataCollectionRules/${dcrId}/streams/Custom-${cltName}_CL?api-version=2023-01-01`,
- createPayload(auditLog),
+ auditLogs.map(buildAzureEvent),
{
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_BATCH_TIMEOUT
}
);
};
return {
validateCredentials,
- streamLog
+ batchStreamLog
};
};
diff --git a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
index d0d2724f8c..5ed85a199a 100644
--- a/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/cribl/cribl-provider-factory.ts
@@ -4,8 +4,8 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
-import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
-import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
import { TCriblProviderCredentials } from "./cribl-provider-types";
export const CriblProviderFactory = () => {
@@ -33,24 +33,32 @@ export const CriblProviderFactory = () => {
return credentials;
};
- const streamLog: TLogStreamFactoryStreamLog<TCriblProviderCredentials> = async ({ credentials, auditLog }) => {
+ // Cribl HTTP source ingests newline-delimited JSON for batch payloads.
+ const batchStreamLog: TLogStreamFactoryBatchStreamLog<TCriblProviderCredentials> = async ({
+ credentials,
+ auditLogs
+ }) => {
+ if (auditLogs.length === 0) return;
+
const { url, token } = credentials;
await blockLocalAndPrivateIpAddresses(url);
const streamHeaders: RawAxiosRequestHeaders = {
- "Content-Type": "application/json",
+ "Content-Type": "application/x-ndjson",
Authorization: `Bearer ${token}`
};
- await request.post(url, JSON.stringify(auditLog), {
+ const body = auditLogs.map((auditLog) => JSON.stringify(auditLog)).join("\n");
+
+ await request.post(url, body, {
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_BATCH_TIMEOUT
});
};
return {
validateCredentials,
- streamLog
+ batchStreamLog
};
};
diff --git a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
index 47dc1a24ee..95899526d0 100644
--- a/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/custom/custom-provider-factory.ts
@@ -4,8 +4,8 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
-import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
-import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
import { TCustomProviderCredentials } from "./custom-provider-types";
export const CustomProviderFactory = () => {
@@ -40,7 +40,13 @@ export const CustomProviderFactory = () => {
return credentials;
};
- const streamLog: TLogStreamFactoryStreamLog<TCustomProviderCredentials> = async ({ credentials, auditLog }) => {
+ // Custom webhook receivers get a JSON array of events per batch POST.
+ const batchStreamLog: TLogStreamFactoryBatchStreamLog<TCustomProviderCredentials> = async ({
+ credentials,
+ auditLogs
+ }) => {
+ if (auditLogs.length === 0) return;
+
const { url, headers } = credentials;
await blockLocalAndPrivateIpAddresses(url);
@@ -53,14 +59,14 @@ export const CustomProviderFactory = () => {
});
}
- await request.post(url, auditLog, {
+ await request.post(url, auditLogs, {
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_BATCH_TIMEOUT
});
};
return {
validateCredentials,
- streamLog
+ batchStreamLog
};
};
diff --git a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
index bec5b00ffc..8e5bafe44b 100644
--- a/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/datadog/datadog-provider-factory.ts
@@ -5,8 +5,8 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
-import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
-import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
import { TDatadogProviderCredentials } from "./datadog-provider-types";
function createPayload(event: Record<string, unknown>) {
@@ -45,21 +45,27 @@ export const DatadogProviderFactory = () => {
return credentials;
};
- const streamLog: TLogStreamFactoryStreamLog<TDatadogProviderCredentials> = async ({ credentials, auditLog }) => {
+ // Datadog v2 logs intake accepts a JSON array of events in a single POST.
+ const batchStreamLog: TLogStreamFactoryBatchStreamLog<TDatadogProviderCredentials> = async ({
+ credentials,
+ auditLogs
+ }) => {
+ if (auditLogs.length === 0) return;
+
const { url, token } = credentials;
await blockLocalAndPrivateIpAddresses(url);
const streamHeaders: RawAxiosRequestHeaders = { "Content-Type": "application/json", "DD-API-KEY": token };
- await request.post(url, createPayload(auditLog), {
+ await request.post(url, auditLogs.map(createPayload), {
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_BATCH_TIMEOUT
});
};
return {
validateCredentials,
- streamLog
+ batchStreamLog
};
};
diff --git a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
index 0baec037ef..40fe4f8879 100644
--- a/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/splunk/splunk-provider-factory.ts
@@ -5,8 +5,8 @@ import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
-import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
-import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { AUDIT_LOG_STREAM_BATCH_TIMEOUT, AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryBatchStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
import { TSplunkProviderCredentials } from "./splunk-provider-types";
function createPayload(event: Record<string, unknown>) {
@@ -59,7 +59,13 @@ export const SplunkProviderFactory = () => {
return credentials;
};
- const streamLog: TLogStreamFactoryStreamLog<TSplunkProviderCredentials> = async ({ credentials, auditLog }) => {
+ // Splunk HEC accepts multiple events in a single POST as concatenated JSON objects (no separator required).
+ const batchStreamLog: TLogStreamFactoryBatchStreamLog<TSplunkProviderCredentials> = async ({
+ credentials,
+ auditLogs
+ }) => {
+ if (auditLogs.length === 0) return;
+
const { hostname, token } = credentials;
const url = await createSplunkUrl(hostname);
@@ -69,14 +75,16 @@ export const SplunkProviderFactory = () => {
Authorization: `Splunk ${token}`
};
- await request.post(url, createPayload(auditLog), {
+ const body = auditLogs.map((auditLog) => JSON.stringify(createPayload(auditLog))).join("");
+
+ await request.post(url, body, {
headers: streamHeaders,
- timeout: AUDIT_LOG_STREAM_TIMEOUT
+ timeout: AUDIT_LOG_STREAM_BATCH_TIMEOUT
});
};
return {
validateCredentials,
- streamLog
+ batchStreamLog
};
};
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.ts
index 5454dd412a..887929e964 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts
@@ -3,7 +3,7 @@ import { randomUUID } from "crypto";
import { v7 as uuidv7 } from "uuid";
import type { TProjects } from "@app/db/schemas";
-import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";
+import { TAuditLogStreamOutboxServiceFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
@@ -21,7 +21,7 @@ import { TCreateAuditLogDTO } from "./audit-log-types";
type TAuditLogQueueServiceFactoryDep = {
auditLogDAL: TAuditLogDALFactory;
- auditLogStreamService: Pick<TAuditLogStreamServiceFactory, "streamLog">;
+ auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "enqueueForOrg">;
queueService: TQueueServiceFactory;
projectDAL: Pick<TProjectDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -54,6 +54,10 @@ const normalizeEmptyValue = (value: string | undefined | null, isClickhouse: boo
// keep this timeout 5s it must be fast because else the queue will take time to finish
// audit log is a crowded queue thus needs to be fast
export const AUDIT_LOG_STREAM_TIMEOUT = 5 * 1000;
+
+// batch deliveries can carry up to AUDIT_LOG_STREAM_BATCH_SIZE events to remote intakes;
+// give them more headroom than the single-event ping timeout above.
+export const AUDIT_LOG_STREAM_BATCH_TIMEOUT = 30 * 1000;
const MS_IN_DAY = 24 * 60 * 60 * 1000;
const AUDIT_LOG_CLICKHOUSE_STREAM_KEY = "audit-log-stream";
const AUDIT_LOG_CLICKHOUSE_BATCH_SIZE = 10_000;
@@ -64,7 +68,7 @@ export const auditLogQueueServiceFactory = async ({
queueService,
projectDAL,
licenseService,
- auditLogStreamService,
+ auditLogStreamOutboxService,
clickhouseClient,
keyStore
}: TAuditLogQueueServiceFactoryDep): Promise<TAuditLogQueueServiceFactory> => {
@@ -183,7 +187,9 @@ export const auditLogQueueServiceFactory = async ({
});
if (getConfig().AUDIT_LOG_STREAMS_ENABLED) {
- await auditLogStreamService.streamLog(orgId, auditLog);
+ // Hand off to the outbox: fan out one row per active stream and let
+ // per-provider workers batch-drain in the background.
+ await auditLogStreamOutboxService.enqueueForOrg(orgId, auditLog);
}
}
} catch (error) {
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a1f6e08b47..2f32ab58a1 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -139,7 +139,9 @@ export const KeyStorePrefixes = {
TelemetryEvent: (event: string, bucketId: string, distinctId: string, uuid: string) =>
`telemetry-event-${event}-${bucketId}-${distinctId}-${uuid}` as const,
- TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const
+ TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const,
+
+ AuditLogStreamFlushDebounce: (streamId: string) => `audit-log-stream:${streamId}:flush-debounce` as const
};
export const KeyStoreTtls = {
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 7c7c2fddf1..4315f4882b 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -13,6 +13,7 @@ import {
import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";
import { TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";
+import { TAuditLogStreamFlushJobData } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types";
import { PamDiscoverySourceRunTrigger } from "@app/ee/services/pam-discovery/pam-discovery-enums";
import {
TSecretRotationRotateSecretsJobPayload,
@@ -108,6 +109,13 @@ export enum QueueName {
AppConnectionCredentialRotation = "app-connection-credential-rotation",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
+ // One queue per provider so a slow Splunk endpoint can't starve fast Datadog flushes (and vice versa).
+ // BullMQ disallows ':' in queue names, so use '-' as the separator.
+ AuditLogStreamAzure = "audit-stream-azure",
+ AuditLogStreamCribl = "audit-stream-cribl",
+ AuditLogStreamCustom = "audit-stream-custom",
+ AuditLogStreamDatadog = "audit-stream-datadog",
+ AuditLogStreamSplunk = "audit-stream-splunk",
PamDiscoveryScan = "pam-discovery-scan",
CaAutoRenewal = "ca-auto-renewal",
ProjectHardDelete = "project-hard-delete",
@@ -176,6 +184,7 @@ export enum QueueJobs {
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch-job",
+ AuditLogStreamFlush = "audit-log-stream-flush",
PamDiscoverySourceRunScan = "pam-discovery-run-scan",
PamDiscoveryScheduledScan = "pam-discovery-scheduled-scan",
CaDailyAutoRenewal = "ca-daily-auto-renewal",
@@ -478,6 +487,26 @@ export type TQueueJobTypes = {
name: QueueJobs.AuditLogClickHouseBatch;
payload: undefined;
};
+ [QueueName.AuditLogStreamAzure]: {
+ name: QueueJobs.AuditLogStreamFlush;
+ payload: TAuditLogStreamFlushJobData;
+ };
+ [QueueName.AuditLogStreamCribl]: {
+ name: QueueJobs.AuditLogStreamFlush;
+ payload: TAuditLogStreamFlushJobData;
+ };
+ [QueueName.AuditLogStreamCustom]: {
+ name: QueueJobs.AuditLogStreamFlush;
+ payload: TAuditLogStreamFlushJobData;
+ };
+ [QueueName.AuditLogStreamDatadog]: {
+ name: QueueJobs.AuditLogStreamFlush;
+ payload: TAuditLogStreamFlushJobData;
+ };
+ [QueueName.AuditLogStreamSplunk]: {
+ name: QueueJobs.AuditLogStreamFlush;
+ payload: TAuditLogStreamFlushJobData;
+ };
[QueueName.PamDiscoveryScan]:
| {
name: QueueJobs.PamDiscoverySourceRunScan;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 2165c49fbe..1003c75241 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -43,6 +43,9 @@ import { auditLogQueueServiceFactory } from "@app/ee/services/audit-log/audit-lo
import { auditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-service";
import { auditLogStreamDALFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-dal";
import { auditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";
+import { auditLogStreamOutboxDALFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal";
+import { auditLogStreamOutboxQueueFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue";
+import { auditLogStreamOutboxServiceFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service";
import { certificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { certificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-service";
import { certificateEstServiceFactory } from "@app/ee/services/certificate-est/certificate-est-service";
@@ -639,6 +642,7 @@ export const registerRoutes = async (
const auditLogDAL = auditLogDALFactory(auditLogDb ?? db);
const auditLogStreamDAL = auditLogStreamDALFactory(db);
+ const auditLogStreamOutboxDAL = auditLogStreamOutboxDALFactory(db);
const trustedIpDAL = trustedIpDALFactory(db);
const telemetryDAL = telemetryDALFactory(db);
const appConnectionDAL = appConnectionDALFactory(db);
@@ -913,12 +917,29 @@ export const registerRoutes = async (
kmsService
});
+ const auditLogStreamOutboxService = auditLogStreamOutboxServiceFactory({
+ auditLogStreamOutboxDAL,
+ auditLogStreamDAL,
+ kmsService,
+ keyStore,
+ queueService,
+ // Reuse the existing sliding-window alerting so a wedged provider still
+ // emails org admins after the failure threshold is crossed.
+ onStreamFailure: ({ orgId, streamId, provider, errorMessage }) =>
+ auditLogStreamService.recordStreamFailure(orgId, streamId, provider, errorMessage)
+ });
+
+ auditLogStreamOutboxQueueFactory({
+ queueService,
+ auditLogStreamOutboxService
+ });
+
const auditLogQueue = await auditLogQueueServiceFactory({
auditLogDAL,
queueService,
projectDAL,
licenseService,
- auditLogStreamService,
+ auditLogStreamOutboxService,
clickhouseClient: clickhouse,
keyStore
});