Skip to content

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

add event outbox and alert event type

Thiago Araujo da Silvafcf11ac91e82
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index f06cc92847..5ab73c3b74 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -610,11 +610,18 @@ See `src/services/health-alert/health-alert-queue.ts` for a minimal example, `sr
Adding a new alertable resource type:
-1. Implement `IResourceAlertProvider` (`alert-types.ts`) in `src/services/alert/providers/<name>-alert-provider.ts`, with its DAL alongside it. You supply: a dot-namespaced `resourceType` (e.g. `identity.authentication`), `eventTypes`, a `conditionSchema` for the "when", `findDueTargets`, `buildViewUrl` / `buildPayload` / `targetId` / `buildTestTargets`, and the two authorization hooks `assertPermission` + `assertResourceInScope`.
+1. Implement `IResourceAlertProvider` (`alert-types.ts`) in `src/services/alert/providers/<name>-alert-provider.ts`, with its DAL alongside it. You supply: a dot-namespaced `resourceType` (e.g. `identity.authentication`), an `events` list, a `conditionSchema` for the "when", `buildViewUrl` / `buildPayload` / `targetId`, one discovery method per trigger type you declare (below), and the two authorization hooks `assertPermission` + `assertResourceInScope`. Test sends do **not** need anything from you — they go through the generic `buildTestAlertPayload` (`alert-test-payload-fns.ts`).
2. Register it on the singleton registry in `src/server/routes/index.ts` (`alertProviderRegistry.register(...)`).
That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS encryption, dedup, history, retention pruning, test sends, and dispatch metrics all come for free, because the cron tick enumerates `alertProviderRegistry.resourceTypes()`. See `src/services/alert/providers/identity-credential-alert-provider.ts` for a complete example.
+**Each event declares how it fires**, and the trigger decides which discovery method the provider owes:
+
+- `AlertTriggerType.Scheduled` → **`findDueTargets`**. The daily cron asks what is currently due, and the engine dedups per `(channel, target)` so a target rediscovered tomorrow is not alerted on twice.
+- `AlertTriggerType.Event` → **`findTargetsByIds`**. The target is already known, so nothing is scanned for and **nothing is deduped** — an event that fired is one the customer asked to hear about, and unlike a daily scan it is never rediscovered. These reach the engine from the event outbox (below), never from the cron.
+
+`alertProviderRegistry.register` asserts that pairing at boot, so a provider that declares an event trigger without `findTargetsByIds` fails the process rather than silently no-op'ing in production. `triggerType` is derived from the provider's event definition inside `createAlert` and is never accepted from a request.
+
Invariants worth knowing before extending it:
- **The alert module owns no CASL subject.** Each provider reuses its own resource's existing permissions inside `assertPermission`, so authorization stays with the domain that owns the resource.
@@ -627,6 +634,121 @@ Invariants worth knowing before extending it:
Wire it into **every** path that deletes or detaches the resource, not just the obvious one. A resource usually has several (a hard delete, an org-membership removal, a project-membership removal), and each needs its own reap. Call it **inside the delete transaction** and pass `tx`; the reap is pure DB (no KMS or network), so it is safe there. The `(resourceType, resourceId)` index on `alerts` is what keeps the unscoped reap off a seq scan, so a provider whose resource is deleted in bulk depends on it.
+### Event Outbox (transactional, generic — alerting is its first consumer)
+
+`src/services/event-outbox/` records "this happened" as a row written **inside the caller's own
+transaction**, so an event is exactly as durable as the business write that produced it. Redis cannot
+participate in a Postgres commit, so the alternative — enqueueing after commit — loses the event
+whenever the pod dies or Redis is unreachable in that window, with nothing but a log line to show for
+it.
+
+It is deliberately **not** alert-specific. `src/services/alert/alert-event-consumer.ts` is one consumer
+registered on the shared registry; anything else that needs guaranteed at-least-once delivery of a
+domain event registers alongside it.
+
+**To emit:** `eventOutboxService.emit(event, tx)`. `tx` is required, not optional — that is the whole
+point, and there is deliberately no weaker path to reach for.
+
+```ts
+await someDAL.transaction(async (tx) => {
+ const request = await approvalRequestDAL.create({ ... }, tx);
+ await eventOutbox.emit(
+ {
+ eventType: "approval.workflow.request_opened",
+ resourceType: "approval.workflow",
+ resourceId: policyId,
+ orgId,
+ projectId,
+ payload: { targetIds: [request.id] }
+ },
+ tx
+ );
+});
+```
+
+**Only one thing is consulted before a row is written:** `subscribesTo(eventType)`, a pure in-memory
+check for "is this event type handled at all". Whether a customer has actually configured anything for
+*this* resource is settled later, in the worker. That is deliberate: `emit` adds exactly one statement
+to the caller's transaction and never calls back into a consumer, so a consumer cannot reach into a
+transaction it knows nothing about. The cost is a throwaway row when nobody was listening, which
+`handle` marks `Delivered` and the prune reaps within the day. If a high-volume event type ever makes
+that amplification matter, cache the answer *inside the consumer* rather than adding a read to the
+emit path.
+
+**The insert is not caught.** Postgres aborts a whole transaction on a failed statement, so swallowing
+it would hand the caller a poisoned transaction (`25P02` on its next statement) instead of the real
+error, and a row that cannot be written means the operation did not happen. A payload that fails its
+consumer's `payloadSchema` throws too: the emit site is statically wrong and fails on the first request
+in dev, and silently dropping a notification because a field was misspelled is the worse outcome. Both
+of those run before any database access, so neither can poison the transaction.
+
+**Who owns what, because this is the part that is easy to get wrong:**
+
+| Layer | Owns | Does not own |
+|---|---|---|
+| `emit` | validation, consumer matching, the insert on the caller's `tx` | anything after commit |
+| Relay ticker (~10s) | noticing due work | delivery, retry |
+| The flush job | parallelism. `attempts: 1`, no backoff | correctness — a lost job costs one interval |
+| Stale-claim cron | rescuing rows whose worker died | delivery |
+| The row + `drain` | the retry state machine: `attempts`, `nextRetryAt`, backoff, terminal `failed`; the claim heartbeat; the lag and exhausted metrics | what "delivered" means |
+| `consumer.handle` | delivery, and reporting per-row `Delivered`/`Retry`/`Failed` + `progress` | when the retry happens, outbox metrics |
+
+**A claim is a lease, and `drain` keeps it alive.** The sweeper treats any `processing` row whose
+`lockedAt` is older than `STALE_CLAIM_THRESHOLD_MS` as a dead worker and hands it back out. A batch can
+legitimately outlive that (one slow webhook endpoint times out on every row of a resource), so `drain`
+refreshes `lockedAt` on the claimed ids every quarter of the threshold while `handle` runs. Without it
+the sweeper re-queues rows a live worker is still delivering, and the customer is notified twice.
+
+**A consumer must not let one row's failure escape `handle`.** The outbox retries the whole batch when
+`handle` throws, because it has no way to know which rows already delivered. A consumer that processes
+rows one at a time catches per row and reports `Retry` for that row alone; see
+`alert-event-consumer.ts`. The batch-level catch in `drain` is the backstop, not the plan.
+
+**BullMQ owns latency here, never correctness.** `attempts: 1` on the flush job is intentional: retry
+lives on the outbox row, where an operator can query it and where it survives a Redis flush. If an
+enqueue fails outright, the row simply stays `pending` and the next relay tick picks it up.
+
+**The relay is a `setInterval`, not a cron registration**, which bends the rule above that all recurring
+work goes through the cron manager. The reason: that rule exists to prevent duplicate execution, and
+the cron manager answers it with slot election plus redlocks to get fleet-wide exactly-once. This relay
+does not need exactly-once — `claimBatch`'s `FOR UPDATE SKIP LOCKED` plus the flush `jobId` make
+concurrent pollers correct by construction. What it does need is a sub-minute cadence, and the cron
+manager's floor is sixty seconds. Every pod polling is the shape the outbox pattern assumes.
+
+**Ordering is per resource, and the claim must sort by `id`.** The flush `jobId` is keyed on
+`(consumer, resourceType, resourceId)`, so at most one flush per aggregate runs at a time, which is the
+standard rule for a polling relay: never parallelize publishing within one aggregate across workers,
+even though `SKIP LOCKED` makes it safe across different aggregates. Within a claim, order by the
+autoincrement `id` and never by a timestamp. `nextRetryAt` is a *filter*, not a sort key: a fresh row's
+`nextRetryAt` is its insert time, so it sorts ahead of a retried row's future one and a later event
+overtakes an earlier one that happened to fail once. `event_outbox_drain_idx` is shaped
+`(consumer, resourceType, resourceId, id, nextRetryAt)` so that ordering comes from the index with no
+sort node.
+
+One gap remains by choice: while an earlier row is still inside its backoff window it is not eligible,
+so a later row for the same resource can be delivered first. Closing that would mean blocking the whole
+aggregate behind its oldest undelivered row, which trades a rare reorder for one failing event stalling
+everything behind it. For notifications that is the wrong trade, so do not promise callers strict
+ordering.
+
+**Delivery is at-least-once.** A send that succeeds and whose `commitResults` then fails is redelivered.
+Consumers narrow the blast radius with `progress` (alerting stores the channels that already
+succeeded, and skips them on the retry), and an emitter that needs to dedupe its own retries passes an
+`idempotencyKey`.
+
+**Watch `infisical.event_outbox.oldest_pending_age`.** It is the canonical outbox canary — the one
+signal that catches a dead relay, a wedged consumer and a stuck claim alike. Alarm when it exceeds a
+small multiple of the relay interval. `infisical.event_outbox.lag` and `infisical.event_outbox.exhausted.count`
+are recorded by the outbox itself as it commits results, labelled by consumer, so a new consumer gets
+them without writing any telemetry code.
+
+**Adding an event-triggered alert** needs no outbox code at all. The provider declares the event with
+`triggerType: AlertTriggerType.Event` and implements `findTargetsByIds`; the emitter calls
+`eventOutbox.emit` with `resourceType` equal to the provider's and `payload: { targetIds }`. The alert
+consumer fails a row terminally, with both halves named, when the emitted `resourceType` does not
+declare that `eventType`, so a mismatched emit site shows up in the logs on its first event rather than
+being marked delivered as "no matching alert".
+
### Soft-Delete + Async Cleanup
Resources whose deletion cascades across many/large tables use a **soft-delete + paced async hard-delete** pattern instead of a synchronous cascade in the request path.
diff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.ts
new file mode 100644
index 0000000000..7854be6790
--- /dev/null
+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts
@@ -0,0 +1,75 @@
+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.EventOutbox))) {
+ await knex.schema.createTable(TableName.EventOutbox, (t) => {
+ // Ordering within a resource is read off this column, so it has to be monotonic.
+ t.bigIncrements("id").primary();
+ t.string("consumer").notNullable();
+ t.string("eventType").notNullable();
+ t.string("resourceType").notNullable();
+ t.string("resourceId").notNullable();
+ t.uuid("orgId").notNullable();
+ t.string("projectId");
+ // Opaque to the outbox: each consumer validates it against its own payloadSchema at emit.
+ t.jsonb("payload").notNullable();
+ t.string("idempotencyKey");
+ t.timestamp("occurredAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
+ t.string("status").notNullable().defaultTo("pending");
+ t.check(`"status" IN ('pending', 'processing', 'retry', 'delivered', 'failed')`);
+ t.integer("attempts").notNullable().defaultTo(0);
+ t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
+ t.timestamp("lockedAt", { useTz: true });
+ // Consumer-defined progress carried across attempts so a retry can skip what already landed.
+ t.jsonb("progress");
+ t.text("lastError");
+ t.timestamps(true, true, true);
+ });
+
+ // Backs both the relay's discovery query and the per-resource claim. Leads with the flush key,
+ // then `id` so the claim's ORDER BY is index-ordered with no sort, then `nextRetryAt` so
+ // discovery's MIN() can be answered from the index rather than the heap.
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"
+ ON "${TableName.EventOutbox}" ("consumer", "resourceType", "resourceId", "id", "nextRetryAt")
+ WHERE status IN ('pending', 'retry')
+ `);
+
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_processing_idx"
+ ON "${TableName.EventOutbox}" ("lockedAt")
+ WHERE status = 'processing'
+ `);
+
+ // Backs the oldest-pending health gauge, which runs on every relay tick forever. Without it that
+ // query seq-scans the whole table to find a handful of undelivered rows, and the cost grows with
+ // the delivered backlog rather than with the work outstanding.
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_undelivered_idx"
+ ON "${TableName.EventOutbox}" ("consumer", "occurredAt")
+ WHERE status IN ('pending', 'retry', 'processing')
+ `);
+
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_terminal_idx"
+ ON "${TableName.EventOutbox}" ("updatedAt")
+ WHERE status IN ('delivered', 'failed')
+ `);
+
+ await knex.schema.raw(`
+ CREATE UNIQUE INDEX IF NOT EXISTS "${TableName.EventOutbox}_idempotency_idx"
+ ON "${TableName.EventOutbox}" ("consumer", "idempotencyKey")
+ WHERE "idempotencyKey" IS NOT NULL
+ `);
+ }
+
+ await createOnUpdateTrigger(knex, TableName.EventOutbox);
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await dropOnUpdateTrigger(knex, TableName.EventOutbox);
+ await knex.schema.dropTableIfExists(TableName.EventOutbox);
+}
diff --git a/backend/src/db/schemas/event-outbox.ts b/backend/src/db/schemas/event-outbox.ts
new file mode 100644
index 0000000000..3669811e8d
--- /dev/null
+++ b/backend/src/db/schemas/event-outbox.ts
@@ -0,0 +1,33 @@
+// 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 EventOutboxSchema = z.object({
+ id: z.coerce.number(),
+ consumer: z.string(),
+ eventType: z.string(),
+ resourceType: z.string(),
+ resourceId: z.string(),
+ orgId: z.string().uuid(),
+ projectId: z.string().nullable().optional(),
+ payload: z.unknown(),
+ idempotencyKey: z.string().nullable().optional(),
+ occurredAt: z.date(),
+ status: z.string().default("pending"),
+ attempts: z.number().default(0),
+ nextRetryAt: z.date(),
+ lockedAt: z.date().nullable().optional(),
+ progress: z.unknown().nullable().optional(),
+ lastError: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TEventOutbox = z.infer<typeof EventOutboxSchema>;
+export type TEventOutboxInsert = Omit<z.input<typeof EventOutboxSchema>, TImmutableDBKeys>;
+export type TEventOutboxUpdate = Partial<Omit<z.input<typeof EventOutboxSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 47c48df72b..e4ec4d3e8f 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -45,6 +45,7 @@ export * from "./certificates";
export * from "./dynamic-secret-leases";
export * from "./dynamic-secrets";
export * from "./email-domains";
+export * from "./event-outbox";
export * from "./external-certificate-authorities";
export * from "./external-group-org-role-mappings";
export * from "./external-kms";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 98ed4fde09..e871f0e0b5 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -51,6 +51,7 @@ export enum TableName {
AlertChannelMembership = "alert_channel_memberships",
AlertHistory = "alert_history",
AlertHistoryTarget = "alert_history_target",
+ EventOutbox = "event_outbox",
Groups = "groups",
GroupProjectMembership = "group_project_memberships",
GroupProjectMembershipRole = "group_project_membership_roles",
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index cb92be8ca6..2f7096946d 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -47,6 +47,8 @@ export const CronJobName = {
PamHeartbeatQueueChecks: "pam-heartbeat-queue-checks",
MonthlyNativeIntegrationDeprecationNotice: "monthly-native-integration-deprecation-notice",
DailyAlertProcessing: "daily-alert-processing",
+ EventOutboxStaleClaimSweeper: "event-outbox-stale-claim-sweeper",
+ EventOutboxCleanup: "event-outbox-cleanup",
SecretScanningStuckScanReaper: "secret-scanning-stuck-scan-reaper",
InstanceUpdateCheck: "instance-update-check"
} as const;
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index eeb2f339f3..4187f290de 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -724,7 +724,8 @@ export enum AlertDispatchOutcome {
AlertDisabled = "alert_disabled",
// No provider registered for the alert's resource type (misconfiguration).
NoProvider = "no_provider",
- // Nothing matched the alert condition in this run.
+ // Nothing to alert on: on the scheduled path nothing matched the condition, on the event path the
+ // targets the event named no longer exist (deleted between the event and its delivery).
NoDueTargets = "no_due_targets",
// The alert has no enabled channels, so the run is skipped before scanning for targets.
NoChannels = "no_channels",
@@ -733,7 +734,10 @@ export enum AlertDispatchOutcome {
// is kept out of delivery_failed and must not alarm.
NoRecipients = "no_recipients",
// Targets matched, but every one had already been alerted inside the dedup window.
- AllDeduped = "all_deduped"
+ AllDeduped = "all_deduped",
+ // Event path only: the event reached the worker and no alert was configured for it. Expected in
+ // steady state, but a rate of zero across the board means emits are wired up and alerts are not.
+ NoMatchingAlert = "no_matching_alert"
}
export const alertDispatchOutcomeCounter = infisicalCoreMeter.createCounter("infisical.alert.dispatch.outcome.count", {
@@ -750,6 +754,38 @@ export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string;
});
};
+// -- Event outbox (InfisicalCore meter) --------------------------------------------------------------
+// The outbox's own health, distinct from what any consumer does with an event. The canonical canary is
+// the oldest-pending-age gauge, registered in event-outbox-queue.ts because it is fed by the relay tick
+// rather than by a delivery.
+
+export const eventOutboxLagHistogram = infisicalCoreMeter.createHistogram("infisical.event_outbox.lag", {
+ description:
+ "Seconds from an event occurring to the outbox reaching a terminal result for it. Tracks the relay interval plus delivery time; a p99 far above the interval means delivery, not discovery, is the bottleneck.",
+ unit: "s"
+});
+
+export const recordEventOutboxLagMetric = (params: { consumer: string; status: string; seconds: number }) =>
+ safely(() => {
+ if (!isTelemetryEnabled()) return;
+ eventOutboxLagHistogram.record(params.seconds, {
+ "event_outbox.consumer": params.consumer,
+ "event_outbox.status": params.status
+ });
+ });
+
+export const eventOutboxExhaustedCounter = infisicalCoreMeter.createCounter("infisical.event_outbox.exhausted.count", {
+ description:
+ "Outbox events abandoned after exhausting their attempts. Every one of these is a notification the customer configured and did not receive, so alarm on any sustained rate.",
+ unit: "{event}"
+});
+
+export const recordEventOutboxExhaustedMetric = (params: { consumer: string; count: number }) =>
+ safely(() => {
+ if (!isTelemetryEnabled()) return;
+ eventOutboxExhaustedCounter.add(params.count, { "event_outbox.consumer": params.consumer });
+ });
+
export enum ProductAnalyticsDropReason {
Retention = "retention",
Unparseable = "unparseable"
diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.ts
index 34c3fccc41..676eb63496 100644
--- a/backend/src/lib/telemetry/telemetry-attributes.ts
+++ b/backend/src/lib/telemetry/telemetry-attributes.ts
@@ -23,6 +23,8 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = [
"product_analytics.drop_reason",
"audit_log_stream.provider",
"audit_log_stream.id",
+ "event_outbox.consumer",
+ "event_outbox.status",
"scim.operation",
"sso.provider",
"sso.action",
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 53c6101a40..74a373454e 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -108,6 +108,7 @@ export enum QueueName {
SecretScanningV2RealtimeScan = "secret-scanning-v2-realtime-scan",
UserNotification = "user-notification",
AlertDispatch = "alert-dispatch",
+ EventOutboxFlush = "event-outbox-flush",
AuditReportGeneration = "audit-report-generation",
PamSessionExpiration = "pam-session-expiration",
PamDiscoveryScan = "pam-discovery-scan",
@@ -183,6 +184,7 @@ export enum QueueJobs {
SecretReminderMigration = "secret-reminder-migration",
UserNotification = "user-notification-job",
AlertDispatch = "alert-dispatch-job",
+ EventOutboxFlush = "event-outbox-flush-job",
GenerateAuditReport = "generate-audit-report-job",
HealthAlert = "health-alert",
CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal",
@@ -518,6 +520,10 @@ export type TQueueJobTypes = {
name: QueueJobs.AlertDispatch;
payload: { alertId: string; scheduledAt: string };
};
+ [QueueName.EventOutboxFlush]: {
+ name: QueueJobs.EventOutboxFlush;
+ payload: { consumer: string; resourceType: string; resourceId: string };
+ };
[QueueName.AuditReportGeneration]: {
name: QueueJobs.GenerateAuditReport;
payload: { auditReportId: string };
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 39a2e89949..4348a21083 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -222,6 +222,7 @@ import { alertChannelServiceFactory } from "@app/services/alert/alert-channel-se
import { alertChannelTestServiceFactory } from "@app/services/alert/alert-channel-test-service";
import { alertDALFactory } from "@app/services/alert/alert-dal";
import { alertEngineFactory } from "@app/services/alert/alert-engine";
+import { alertEventConsumerFactory } from "@app/services/alert/alert-event-consumer";
import { alertHistoryDALFactory } from "@app/services/alert/alert-history-dal";
import { alertProviderRegistryFactory } from "@app/services/alert/alert-provider-registry";
import { alertQueueServiceFactory } from "@app/services/alert/alert-queue";
@@ -311,6 +312,10 @@ import { acmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/
import { apiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { estEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
import { scepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
+import { eventOutboxDALFactory } from "@app/services/event-outbox/event-outbox-dal";
+import { eventOutboxQueueFactory } from "@app/services/event-outbox/event-outbox-queue";
+import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";
+import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";
import { externalGroupOrgRoleMappingDALFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-dal";
import { externalGroupOrgRoleMappingServiceFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-service";
import { externalMigrationQueueFactory } from "@app/services/external-migration/external-migration-queue";
@@ -1061,6 +1066,23 @@ export const registerRoutes = async (
alertProviderRegistry,
alertEngine
});
+ const eventOutboxDAL = eventOutboxDALFactory(db);
+ const eventOutboxRegistry = eventOutboxRegistryFactory();
+ eventOutboxRegistry.register(
+ alertEventConsumerFactory({
+ alertDAL,
+ alertEngine,
+ alertProviderRegistry
+ })
+ );
+ const eventOutboxService = eventOutboxServiceFactory({ eventOutboxDAL, eventOutboxRegistry });
+ const eventOutboxQueue = eventOutboxQueueFactory({
+ queueService,
+ cronJob,
+ eventOutboxDAL,
+ eventOutboxService
+ });
+
const alertChannelService = alertChannelServiceFactory({
alertChannelDAL,
alertChannelRecipientDAL,
@@ -4041,6 +4063,7 @@ export const registerRoutes = async (
usageEventQueue.init();
healthAlert.init();
alertQueue.init();
+ eventOutboxQueue.init();
auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
pkiSyncHealthCheckQueue.init();
@@ -4431,6 +4454,7 @@ export const registerRoutes = async (
cronJobs.forEach((job) => job.stop());
await cronJob.stop();
await workerHeartbeat.stop();
+ await eventOutboxQueue.shutdown();
await telemetryService.flushAll();
await eventBusService.close();
await projectEventsSSEService.close();
diff --git a/backend/src/server/routes/v1/alert-router.ts b/backend/src/server/routes/v1/alert-router.ts
index 95f3caefc0..a4ca960e77 100644
--- a/backend/src/server/routes/v1/alert-router.ts
+++ b/backend/src/server/routes/v1/alert-router.ts
@@ -40,6 +40,7 @@ const AlertResponseSchema = z.object({
resourceType: z.string(),
resourceId: z.string().nullable(),
eventType: z.string(),
+ triggerType: z.string(),
condition: z.unknown().nullable(),
enabled: z.boolean(),
orgId: z.string(),
diff --git a/backend/src/services/alert/alert-channel-test-service.test.ts b/backend/src/services/alert/alert-channel-test-service.test.ts
index 019a783517..e565cec672 100644
--- a/backend/src/services/alert/alert-channel-test-service.test.ts
+++ b/backend/src/services/alert/alert-channel-test-service.test.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import { alertChannelTestServiceFactory, TAlertChannelTestServiceFactoryDep } from "./alert-channel-test-service";
import { TAlertChannelSendContext, TAlertPayload, TChannelResult } from "./alert-channel-types";
import { alertProviderRegistryFactory } from "./alert-provider-registry";
-import { IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";
+import { AlertTriggerType, IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so the
@@ -32,7 +32,7 @@ const actor = {
const buildProvider = (opts?: { assertPermission?: (input: TAlertPermissionInput) => Promise<void> }) => {
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
- eventTypes: ["test.resource.expiration"],
+ events: [{ key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled }],
conditionSchema: z.object({}).optional(),
findDueTargets: async () => [],
buildViewUrl: async () => "https://app.infisical.com/x",
diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.ts
index bf55f5e51b..3dfb790363 100644
--- a/backend/src/services/alert/alert-dal.test.ts
+++ b/backend/src/services/alert/alert-dal.test.ts
@@ -14,7 +14,8 @@ const buildDAL = () => {
existsFrom: [] as unknown[],
existsJoin: [] as unknown[][],
existsWhere: [] as unknown[][],
- existsWhereRaw: [] as unknown[]
+ existsWhereRaw: [] as unknown[],
+ orWhereNull: [] as unknown[]
};
const existsChain = {
@@ -43,6 +44,10 @@ const buildDAL = () => {
return chain;
},
where: (...args: unknown[]) => {
+ if (typeof args[0] === "function") {
+ (args[0] as (qb: typeof chain) => void)(chain);
+ return chain;
+ }
calls.where.push(args);
return chain;
},
@@ -54,6 +59,10 @@ const buildDAL = () => {
cb(existsChain);
return chain;
},
+ orWhereNull: (col: unknown) => {
+ calls.orWhereNull.push(col);
+ return chain;
+ },
select: () => chain,
orderBy: async () => [] as TAlerts[]
};
@@ -89,4 +98,69 @@ describe("alert dal", () => {
// A channel that exists but is switched off must not keep the alert in the sweep.
expect(calls.existsWhere).toContainEqual([`${TableName.AlertChannel}.enabled`, true]);
});
+
+ test("findEnabledForEvent narrows to one resource, event and the event trigger", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findEnabledForEvent({
+ orgId: "org-1",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ eventType: "approval.workflow.request_opened"
+ });
+
+ expect(calls.where).toContainEqual([`${TableName.Alert}.orgId`, "org-1"]);
+ expect(calls.where).toContainEqual([`${TableName.Alert}.resourceType`, "approval.workflow"]);
+ expect(calls.where).toContainEqual([`${TableName.Alert}.resourceId`, "policy-1"]);
+ expect(calls.where).toContainEqual([`${TableName.Alert}.eventType`, "approval.workflow.request_opened"]);
+ // The mirror of the cron's filter: the outbox must never pick up a scheduled alert.
+ expect(calls.where).toContainEqual([`${TableName.Alert}.triggerType`, "event"]);
+ expect(calls.where).toContainEqual([`${TableName.Alert}.enabled`, true]);
+ });
+
+ test("findEnabledForEvent applies the same soft-deleted-project and enabled-channel filters", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findEnabledForEvent({
+ orgId: "org-1",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ eventType: "approval.workflow.request_opened"
+ });
+
+ expect(calls.whereNull).toContainEqual(`${TableName.Project}.deleteAfter`);
+ expect(calls.existsFrom).toContainEqual(TableName.AlertChannelMembership);
+ expect(calls.existsWhere).toContainEqual([`${TableName.AlertChannel}.enabled`, true]);
+ });
+
+ // A resource inside a project can be watched by a project-scoped alert and by an org-wide one, so
+ // both have to be in scope; without a projectId only the org-scoped row can match.
+ test("findEnabledForEvent matches the project-scoped and org-scoped alert when given a project", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findEnabledForEvent({
+ orgId: "org-1",
+ projectId: "proj-1",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ eventType: "approval.workflow.request_opened"
+ });
+
+ expect(calls.where).toContainEqual([`${TableName.Alert}.projectId`, "proj-1"]);
+ expect(calls.orWhereNull).toContainEqual(`${TableName.Alert}.projectId`);
+ });
+
+ test("findEnabledForEvent matches only org-scoped alerts when given no project", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findEnabledForEvent({
+ orgId: "org-1",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ eventType: "approval.workflow.request_opened"
+ });
+
+ expect(calls.whereNull).toContainEqual(`${TableName.Alert}.projectId`);
+ expect(calls.orWhereNull).toHaveLength(0);
+ });
});
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index 3e5e52a650..e1b0a8e567 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -42,6 +42,66 @@ export const alertDALFactory = (db: TDbClient) => {
}
};
+ // The event path's counterpart to findEnabledByResourceType. Same enabled-channel and
+ // soft-deleted-project filters, narrowed to one resource and one event key. Runs in the outbox
+ // worker only; the emit path never touches the alerts table.
+ const findEnabledForEvent = async (
+ filter: {
+ orgId: string;
+ projectId?: string | null;
+ resourceType: string;
+ resourceId: string;
+ eventType: string;
+ },
+ tx?: Knex
+ ): Promise<TAlerts[]> => {
+ try {
+ const query = (tx || db.replicaNode())(TableName.Alert)
+ .leftJoin(TableName.Project, `${TableName.Alert}.projectId`, `${TableName.Project}.id`)
+ .where(`${TableName.Alert}.orgId`, filter.orgId)
+ .where(`${TableName.Alert}.resourceType`, filter.resourceType)
+ .where(`${TableName.Alert}.resourceId`, filter.resourceId)
+ .where(`${TableName.Alert}.eventType`, filter.eventType)
+ .where(`${TableName.Alert}.triggerType`, AlertTriggerType.Event)
+ .where(`${TableName.Alert}.enabled`, true)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .whereExists(
+ (qb) =>
+ void qb
+ .select(db.raw("1"))
+ .from(TableName.AlertChannelMembership)
+ .join(
+ TableName.AlertChannel,
+ `${TableName.AlertChannelMembership}.channelId`,
+ `${TableName.AlertChannel}.id`
+ )
+ .whereRaw(`"${TableName.AlertChannelMembership}"."alertId" = "${TableName.Alert}"."id"`)
+ .where(`${TableName.AlertChannel}.enabled`, true)
+ );
+
+ // A resource in a project can be watched by a project-scoped alert and by an org-wide one, so
+ // both are in scope; without a projectId only the org-scoped row can match.
+ if (filter.projectId) {
+ void query.where(
+ (builder) =>
+ void builder
+ .where(`${TableName.Alert}.projectId`, filter.projectId as string)
+ .orWhereNull(`${TableName.Alert}.projectId`)
+ );
+ } else {
+ void query.whereNull(`${TableName.Alert}.projectId`);
+ }
+
+ const alerts = await query
+ .select(selectAllTableCols(TableName.Alert))
+ .orderBy(`${TableName.Alert}.createdAt`, "asc");
+
+ return alerts as TAlerts[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindEnabledForEvent" });
+ }
+ };
+
const findActiveById = async (id: string, tx?: Knex): Promise<TAlerts | undefined> => {
try {
const alert = await (tx || db.replicaNode())(TableName.Alert)
@@ -135,6 +195,7 @@ export const alertDALFactory = (db: TDbClient) => {
return {
...alertOrm,
findEnabledByResourceType,
+ findEnabledForEvent,
findActiveById,
findActiveByScope,
findByChannelId,
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 7fb99166c0..68504f7bae 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -5,7 +5,13 @@ import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";
import { TAlertPayload } from "./alert-channel-types";
import { alertEngineFactory, TAlertEngineDep } from "./alert-engine";
import { alertProviderRegistryFactory } from "./alert-provider-registry";
-import { AlertPrincipalType, AlertRunStatus, IResourceAlertProvider, TAlertContext } from "./alert-types";
+import {
+ AlertPrincipalType,
+ AlertRunStatus,
+ AlertTriggerType,
+ IResourceAlertProvider,
+ TAlertContext
+} from "./alert-types";
// logger is `export let logger` assigned by initLogger(), which unit tests don't run, so any
// channel-failure path (which logs) would otherwise dereference undefined. Mock it per-file.
@@ -55,12 +61,18 @@ const makeAlert = () => ({
const makeProvider = (targets: TTarget[], onFindDueTargets?: () => void): IResourceAlertProvider<TTarget> => ({
resourceType: RESOURCE_TYPE,
- eventTypes: ["test.resource.expiration"],
+ events: [
+ { key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ ],
conditionSchema: z.any(),
findDueTargets: async () => {
onFindDueTargets?.();
return targets;
},
+ // Mirrors a real provider: only ids that still resolve to a row come back, so a target deleted
+ // between the event and its delivery simply drops out.
+ findTargetsByIds: async ({ targetIds }) => targets.filter((target) => targetIds.includes(target.id)),
assertPermission: async () => undefined,
assertResourceInScope: async () => undefined,
targetId: (target) => target.id,
@@ -103,6 +115,7 @@ const buildEngine = (opts: {
recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;
failEmail?: boolean;
failEmailFor?: string;
+ failHistoryWrite?: boolean;
}) => {
const registry = alertProviderRegistryFactory();
let findDueTargetsCalls = 0;
@@ -140,6 +153,7 @@ const buildEngine = (opts: {
alertHistoryDAL: {
findRecentlyAlertedTargets: async () => opts.recentlyAlerted ?? [],
createWithTargets: async (_alertId: string, options: { status: string }, deliveries: TDelivery[]) => {
+ if (opts.failHistoryWrite) throw new Error("history table unavailable");
historyWrites.push({ deliveries, status: options.status });
return {} as never;
}
@@ -478,3 +492,116 @@ describe("alert engine", () => {
expect(historyWrites).toHaveLength(0);
});
});
+
+describe("alert engine, event path", () => {
+ const eventAlert = () => ({ ...makeAlert(), triggerType: "event", eventType: "test.resource.opened" });
+ const EVENT = { eventType: "test.resource.opened", targetIds: ["t1"] };
+
+ test("delivers the targets the event named", async () => {
+ const { engine, sentMail, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }, { id: "t2" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(result.deliveredChannelIds).toEqual(["c-email"]);
+ expect(sentMail).toHaveLength(1);
+ // t2 exists but the event did not name it, so it is not delivered.
+ expect(historyWrites[0].deliveries).toEqual([
+ { targetId: "t1", channelId: "c-email", channelType: "email", status: AlertRunStatus.SUCCESS }
+ ]);
+ });
+
+ // The whole reason the event path exists: a daily scan rediscovers the same target every day and
+ // needs dedup, an event does not. If someone reintroduces the dedup lookup here, this fails.
+ test("delivers the same target again even though it was just alerted on", async () => {
+ const { engine, sentMail } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ recentlyAlerted: [{ channelId: "c-email", targetId: "t1" }]
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(sentMail).toHaveLength(1);
+ });
+
+ test("reports no due targets when the event's targets no longer exist", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.NoDueTargets);
+ expect(result.deliveredChannelIds).toEqual([]);
+ expect(historyWrites).toHaveLength(0);
+ });
+
+ // A retry must not re-notify a channel that already succeeded, which is what makes retrying an
+ // event with no dedup behind it safe.
+ test("skips channels a previous attempt already delivered to", async () => {
+ const { engine, sentMail, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [
+ { id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true },
+ {
+ id: "c-slack",
+ channelType: "slack",
+ encryptedConfig: encConfig({ webhookUrl: "https://hooks.slack.com/services/T/B/x" }),
+ enabled: true
+ }
+ ]
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), { ...EVENT, skipChannelIds: ["c-email"] });
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(result.deliveredChannelIds).toEqual(["c-slack"]);
+ expect(sentMail).toHaveLength(0);
+ expect(historyWrites[0].deliveries.map((d) => d.channelId)).toEqual(["c-slack"]);
+ });
+
+ test("returns NoChannels when every channel was already delivered to", async () => {
+ const { engine } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), { ...EVENT, skipChannelIds: ["c-email"] });
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.NoChannels);
+ });
+
+ // Everything that can throw happens before the first send. A history write that fails afterwards
+ // must not turn a delivered event into a retry, or the retry would re-notify.
+ test("still reports success when the history write fails after delivery", async () => {
+ const { engine, sentMail } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ failHistoryWrite: true
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(sentMail).toHaveLength(1);
+ });
+
+ test("reports failure and no delivered channels when every channel fails", async () => {
+ const { engine } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
+ failEmail: true
+ });
+
+ const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+
+ expect(result.outcome).toBe(AlertDispatchOutcome.DeliveryFailed);
+ expect(result.deliveredChannelIds).toEqual([]);
+ });
+});
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index ef3d9c288a..fcb8425d3c 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -1,6 +1,6 @@
import pLimit from "p-limit";
-import { TAlerts } from "@app/db/schemas";
+import { TAlertChannels, TAlerts } from "@app/db/schemas";
import { logger } from "@app/lib/logger";
import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -13,11 +13,21 @@ import { AlertChannelType, TAlertChannelDeps, TAlertRecipient, TChannelTargetRes
import { TAlertHistoryDALFactory } from "./alert-history-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
import { TAlertRecipientResolver } from "./alert-recipient-resolver";
-import { AlertRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, TAlertContext } from "./alert-types";
+import { AlertRunStatus, DEFAULT_DEDUP_WINDOW_HOURS, IResourceAlertProvider, TAlertContext } from "./alert-types";
import { ALERT_CHANNEL_REGISTRY } from "./channels/alert-channel-registry";
const ALERT_DELIVERY_CONCURRENCY = 10;
+type TChannelWork = {
+ channel: TAlertChannels;
+ due: { target: unknown; id: string }[];
+};
+
+export type TDispatchResult = {
+ outcome: AlertDispatchOutcome;
+ deliveredChannelIds: string[];
+};
+
type TChannelDispatchResult = {
channelId: string;
channelType: string;
@@ -49,52 +59,11 @@ export const alertEngineFactory = ({
kmsService,
smtpService
}: TAlertEngineDep) => {
- const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {
- const provider = alertProviderRegistry.get(alert.resourceType);
- if (!provider) {
- logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);
- return AlertDispatchOutcome.NoProvider;
- }
-
- const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
- if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
-
- const dueTargets = await provider.findDueTargets({
- orgId: alert.orgId,
- projectId: alert.projectId,
- resourceId: alert.resourceId,
- eventType: alert.eventType,
- condition: alert.condition,
- asOf: opts?.asOf ?? new Date()
- });
- if (dueTargets.length === 0) return AlertDispatchOutcome.NoDueTargets;
-
- const targets = dueTargets.map((target) => ({ target, id: provider.targetId(target) }));
-
- const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
- const recentlyAlerted = await alertHistoryDAL.findRecentlyAlertedTargets(
- alert.id,
- targets.map((target) => target.id),
- window
- );
- const alertedSet = new Set(recentlyAlerted.map((row) => `${row.channelId}:${row.targetId}`));
-
- const channelWork = channels
- .map((channel) => {
- const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
- const due = targets.filter((target) => !alertedSet.has(`${channel.id}:${target.id}`));
- const cap = definition?.maxTargetsPerRun;
- if (cap && due.length > cap) {
- logger.info(
- `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${due.length - cap} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
- );
- return { channel, due: due.slice(0, cap) };
- }
- return { channel, due };
- })
- .filter((work) => work.due.length > 0);
- if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;
-
+ const $dispatchChannelWork = async (
+ alert: TAlerts,
+ provider: IResourceAlertProvider,
+ channelWork: TChannelWork[]
+ ): Promise<TDispatchResult> => {
const alertContext: TAlertContext = {
id: alert.id,
name: alert.name,
@@ -194,7 +163,7 @@ export const alertEngineFactory = ({
);
const dispatched = channelResults.filter((result) => !result.skipped);
- if (dispatched.length === 0) return AlertDispatchOutcome.NoRecipients;
+ if (dispatched.length === 0) return { outcome: AlertDispatchOutcome.NoRecipients, deliveredChannelIds: [] };
const deliveries = dispatched.flatMap((result) => {
const perTarget = new Map<string, boolean>((result.targetResults ?? []).map((t) => [t.targetId, t.success]));
@@ -218,13 +187,138 @@ export const alertEngineFactory = ({
logger.error(`Alert delivery failed on one or more channels [alertId=${alert.id}]: ${errorText}`);
}
- await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);
+ // Deliberately not allowed to fail the run. On the event path the caller may retry, and a throw
+ // after channels have already sent would re-notify; every other failure mode is handled above,
+ // before the first send.
+ try {
+ await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);
+ } catch (err) {
+ logger.error(err, `Failed to record alert history after delivery [alertId=${alert.id}]`);
+ }
+
+ const deliveredChannelIds = dispatched.filter((result) => result.success).map((result) => result.channelId);
+
+ if (status === AlertRunStatus.SUCCESS) {
+ return { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds };
+ }
+ return {
+ outcome:
+ status === AlertRunStatus.PARTIAL ? AlertDispatchOutcome.DeliveryPartial : AlertDispatchOutcome.DeliveryFailed,
+ deliveredChannelIds
+ };
+ };
+
+ const runAlert = async (alert: TAlerts, opts?: { asOf?: Date }): Promise<AlertDispatchOutcome> => {
+ const provider = alertProviderRegistry.get(alert.resourceType);
+ if (!provider) {
+ logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);
+ return AlertDispatchOutcome.NoProvider;
+ }
+ if (!provider.findDueTargets) {
+ logger.warn(
+ `Alert provider '${alert.resourceType}' has no findDueTargets, so a scheduled alert cannot run [alertId=${alert.id}]`
+ );
+ return AlertDispatchOutcome.NoProvider;
+ }
+
+ const channels = await alertChannelDAL.findByAlertId(alert.id, { enabled: true });
+ if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
+
+ const dueTargets = await provider.findDueTargets({
+ orgId: alert.orgId,
+ projectId: alert.projectId,
+ resourceId: alert.resourceId,
+ eventType: alert.eventType,
+ condition: alert.condition,
+ asOf: opts?.asOf ?? new Date()
+ });
+ if (dueTargets.length === 0) return AlertDispatchOutcome.NoDueTargets;
+
+ const targets = dueTargets.map((target) => ({ target, id: provider.targetId(target) }));
+
+ const window = provider.dedupWindowHours?.(alert.condition) ?? DEFAULT_DEDUP_WINDOW_HOURS;
+ const recentlyAlerted = await alertHistoryDAL.findRecentlyAlertedTargets(
+ alert.id,
+ targets.map((target) => target.id),
+ window
+ );
+ const alertedSet = new Set(recentlyAlerted.map((row) => `${row.channelId}:${row.targetId}`));
+
+ const channelWork = channels
+ .map((channel) => {
+ const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
+ const due = targets.filter((target) => !alertedSet.has(`${channel.id}:${target.id}`));
+ const cap = definition?.maxTargetsPerRun;
+ if (cap && due.length > cap) {
+ logger.info(
+ `Alert ${channel.channelType} channel capped at ${cap} targets this run; ${due.length - cap} deferred to the next run [alertId=${alert.id}] [channelId=${channel.id}]`
+ );
+ return { channel, due: due.slice(0, cap) };
+ }
+ return { channel, due };
+ })
+ .filter((work) => work.due.length > 0);
+ if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;
+
+ const { outcome } = await $dispatchChannelWork(alert, provider, channelWork);
+ return outcome;
+ };
+
+ const runAlertForEvent = async (
+ alert: TAlerts,
+ input: { eventType: string; targetIds: string[]; skipChannelIds?: string[] }
+ ): Promise<TDispatchResult> => {
+ const provider = alertProviderRegistry.get(alert.resourceType);
+ if (!provider) {
+ logger.warn(`No alert provider registered for resource type '${alert.resourceType}' [alertId=${alert.id}]`);
+ return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
+ }
+ if (!provider.findTargetsByIds) {
+ logger.warn(
+ `Alert provider '${alert.resourceType}' has no findTargetsByIds, so an event alert cannot run [alertId=${alert.id}]`
+ );
+ return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
+ }
+
+ const skip = new Set(input.skipChannelIds ?? []);
+ const channels = (await alertChannelDAL.findByAlertId(alert.id, { enabled: true })).filter(
+ (channel) => !skip.has(channel.id)
+ );
+ if (channels.length === 0) return { outcome: AlertDispatchOutcome.NoChannels, deliveredChannelIds: [] };
+
+ const resolved = await provider.findTargetsByIds({
+ orgId: alert.orgId,
+ projectId: alert.projectId,
+ resourceId: alert.resourceId,
+ eventType: input.eventType,
+ condition: alert.condition,
+ targetIds: input.targetIds
+ });
+ // The rows were deleted between the event being recorded and it being delivered. Nothing to say.
+ if (resolved.length === 0) return { outcome: AlertDispatchOutcome.NoDueTargets, deliveredChannelIds: [] };
+
+ const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));
+
+ const channelWork = channels.map((channel) => {
+ const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];
+ const cap = definition?.maxTargetsPerRun;
+ if (cap && targets.length > cap) {
+ // On the scheduled path the tail defers to tomorrow's run. Here there is no next run, so this
+ // is a real drop — MAX_TARGET_IDS_PER_EVENT is set at or below every channel cap to keep it
+ // unreachable, and the log names what was lost if that ever stops holding.
+ logger.warn(
+ `Alert ${channel.channelType} channel caps at ${cap} targets; dropping ${targets.length - cap} from this event [alertId=${alert.id}] [channelId=${channel.id}] [dropped=${targets
+ .slice(cap)
+ .map((target) => target.id)
+ .join(",")}]`
+ );
+ return { channel, due: targets.slice(0, cap) };
+ }
+ return { channel, due: targets };
+ });
- if (status === AlertRunStatus.SUCCESS) return AlertDispatchOutcome.DeliverySuccess;
- return status === AlertRunStatus.PARTIAL
- ? AlertDispatchOutcome.DeliveryPartial
- : AlertDispatchOutcome.DeliveryFailed;
+ return $dispatchChannelWork(alert, provider, channelWork);
};
- return { runAlert };
+ return { runAlert, runAlertForEvent };
};
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
new file mode 100644
index 0000000000..cedb44ee72
--- /dev/null
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -0,0 +1,214 @@
+import { AlertDispatchOutcome } from "@app/lib/telemetry/metrics";
+import { EventOutboxStatus, TEventOutboxRow } from "@app/services/event-outbox/event-outbox-types";
+
+import { alertEventConsumerFactory } from "./alert-event-consumer";
+import { AlertTriggerType } from "./alert-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
+const ORG_ID = "11111111-1111-1111-1111-111111111111";
+const EVENT_TYPE = "approval.workflow.request_opened";
+
+const makeAlert = (id: string) => ({ id, resourceType: "approval.workflow", orgId: ORG_ID }) as never;
+
+const makeRow = (overrides?: Partial<TEventOutboxRow>): TEventOutboxRow =>
+ ({
+ id: 1,
+ consumer: "alert",
+ eventType: EVENT_TYPE,
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ orgId: ORG_ID,
+ projectId: null,
+ payload: { targetIds: ["req-1"] },
+ occurredAt: new Date(),
+ status: EventOutboxStatus.Processing,
+ attempts: 0,
+ progress: null,
+ ...overrides
+ }) as TEventOutboxRow;
+
+const buildConsumer = (opts?: {
+ alerts?: unknown[];
+ results?: { outcome: AlertDispatchOutcome; deliveredChannelIds: string[] }[];
+ eventKeys?: string[];
+ findAlerts?: () => Promise<unknown[]>;
+}) => {
+ const runs: { alertId: string; targetIds: string[]; skipChannelIds?: string[] }[] = [];
+ const results = opts?.results ?? [{ outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-1"] }];
+ let runIdx = 0;
+ let lookups = 0;
+ const eventKeys = opts?.eventKeys ?? [EVENT_TYPE];
+ const consumer = alertEventConsumerFactory({
+ alertDAL: {
+ findEnabledForEvent: async () => {
+ lookups += 1;
+ if (opts?.findAlerts) return (await opts.findAlerts()) as never;
+ return (opts?.alerts ?? [makeAlert("alert-1")]) as never;
+ }
+ },
+ alertEngine: {
+ runAlertForEvent: async (alert: { id: string }, input: { targetIds: string[]; skipChannelIds?: string[] }) => {
+ runs.push({ alertId: alert.id, targetIds: input.targetIds, skipChannelIds: input.skipChannelIds });
+ const result = results[Math.min(runIdx, results.length - 1)];
+ runIdx += 1;
+ return result;
+ }
+ } as never,
+ alertProviderRegistry: {
+ eventTriggeredKeys: () => new Set(eventKeys),
+ get: (resourceType: string) =>
+ resourceType === "approval.workflow"
+ ? ({ events: eventKeys.map((key) => ({ key, triggerType: AlertTriggerType.Event })) } as never)
+ : undefined
+ }
+ });
+
+ return { consumer, runs, getLookups: () => lookups };
+};
+
+describe("alert outbox consumer", () => {
+ test("subscribes only to event keys a registered provider declares as event-triggered", () => {
+ const { consumer } = buildConsumer();
+
+ expect(consumer.subscribesTo(EVENT_TYPE)).toBe(true);
+ expect(consumer.subscribesTo("identity.authentication.expiry")).toBe(false);
+ });
+
+ test("delivers the event's targets and marks the row delivered", async () => {
+ const { consumer, runs } = buildConsumer();
+
+ const [result] = await consumer.handle([makeRow()]);
+
+ expect(result.status).toBe(EventOutboxStatus.Delivered);
+ expect(runs[0].targetIds).toEqual(["req-1"]);
+ expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
+ });
+
+ // The alert was deleted or disabled between the gate and the worker. Nothing owes anyone a
+ // notification, so this is a completed event rather than something to retry forever.
+ test("marks the row delivered when no alert matches any more", async () => {
+ const { consumer, runs } = buildConsumer({ alerts: [] });
+
+ const [result] = await consumer.handle([makeRow()]);
+
+ expect(result.status).toBe(EventOutboxStatus.Delivered);
+ expect(runs).toHaveLength(0);
+ });
+
+ test("retries and records what already delivered when a channel fails", async () => {
+ const { consumer } = buildConsumer({
+ results: [{ outcome: AlertDispatchOutcome.DeliveryPartial, deliveredChannelIds: ["c-1"] }]
+ });
+
+ const [result] = await consumer.handle([makeRow()]);
+
+ expect(result.status).toBe(EventOutboxStatus.Retry);
+ expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
+ });
+
+ test("skips the channels a previous attempt already delivered to", async () => {
+ const { consumer, runs } = buildConsumer();
+
+ await consumer.handle([makeRow({ progress: { deliveredChannelIds: ["c-1"] } })]);
+
+ expect(runs[0].skipChannelIds).toEqual(["c-1"]);
+ });
+
+ // Retrying cannot fix a payload the consumer cannot read, so it fails terminally instead of burning
+ // every attempt first.
+ test("fails terminally on an unreadable payload", async () => {
+ const { consumer } = buildConsumer();
+
+ const [result] = await consumer.handle([makeRow({ payload: { targetIds: [] } })]);
+
+ expect(result.status).toBe(EventOutboxStatus.Failed);
+ expect(result.error).toMatch(/Unreadable alert event payload/);
+ });
+
+ test("runs every matching alert in a scope", async () => {
+ const { consumer, runs } = buildConsumer({
+ alerts: [makeAlert("alert-project"), makeAlert("alert-org")],
+ results: [
+ { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-1"] },
+ { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-2"] }
+ ]
+ });
+
+ const [result] = await consumer.handle([makeRow()]);
+
+ expect(runs.map((run) => run.alertId)).toEqual(["alert-project", "alert-org"]);
+ expect(result.progress).toEqual({ deliveredChannelIds: ["c-1", "c-2"] });
+ });
+
+ // subscribesTo only sees the event type, so an emitter that pairs a real event key with the wrong
+ // resourceType gets through the gate. Silently marking that delivered would hide the misconfigured
+ // emit site; failing terminally with both halves named is what surfaces it.
+ test("fails terminally when no provider declares the event for that resource type", async () => {
+ const { consumer, runs, getLookups } = buildConsumer();
+
+ const [result] = await consumer.handle([makeRow({ resourceType: "pki.certificate" })]);
+
+ expect(result.status).toBe(EventOutboxStatus.Failed);
+ expect(result.error).toMatch(/pki\.certificate.*approval\.workflow\.request_opened/);
+ expect(runs).toHaveLength(0);
+ expect(getLookups()).toBe(0);
+ });
+
+ // Throwing out of handle() sends the whole batch back for retry, re-notifying on rows that had already
+ // delivered. One row's failure has to stay that row's failure.
+ test("retries only the row whose lookup threw", async () => {
+ let calls = 0;
+ const { consumer, runs } = buildConsumer({
+ eventKeys: [EVENT_TYPE, "approval.workflow.request_closed", "approval.workflow.request_reopened"],
+ findAlerts: async () => {
+ calls += 1;
+ if (calls === 2) throw new Error("connection reset");
+ return [makeAlert(`alert-${calls}`)];
+ }
+ });
+
+ const results = await consumer.handle([
+ makeRow({ id: 1, eventType: EVENT_TYPE }),
+ makeRow({ id: 2, eventType: "approval.workflow.request_closed" }),
+ makeRow({ id: 3, eventType: "approval.workflow.request_reopened" })
+ ]);
+
+ expect(results.map((result) => result.status)).toEqual([
+ EventOutboxStatus.Delivered,
+ EventOutboxStatus.Retry,
+ EventOutboxStatus.Delivered
+ ]);
+ expect(results[1].error).toBe("connection reset");
+ expect(runs.map((run) => run.alertId)).toEqual(["alert-1", "alert-3"]);
+ });
+
+ test("resolves the matching alerts once per event type within a batch", async () => {
+ const { consumer, getLookups } = buildConsumer();
+
+ await consumer.handle([
+ makeRow({ id: 1, payload: { targetIds: ["req-1"] } }),
+ makeRow({ id: 2, payload: { targetIds: ["req-2"] } }),
+ makeRow({ id: 3, payload: { targetIds: ["req-3"] } })
+ ]);
+
+ expect(getLookups()).toBe(1);
+ });
+
+ // Rows arrive in id order and share one resource, so handling them concurrently would deliver a
+ // resource's events out of order.
+ test("handles rows serially, in the order given", async () => {
+ const { consumer, runs } = buildConsumer();
+
+ const results = await consumer.handle([
+ makeRow({ id: 1, payload: { targetIds: ["req-1"] } }),
+ makeRow({ id: 2, payload: { targetIds: ["req-2"] } })
+ ]);
+
+ expect(results.map((result) => result.id)).toEqual(["1", "2"]);
+ expect(runs.map((run) => run.targetIds)).toEqual([["req-1"], ["req-2"]]);
+ });
+});
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
new file mode 100644
index 0000000000..2af198b4ef
--- /dev/null
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -0,0 +1,161 @@
+import { z } from "zod";
+
+import { AlertDispatchOutcome, recordAlertDispatchOutcomeMetric } from "@app/lib/telemetry/metrics";
+import {
+ EventOutboxStatus,
+ IEventOutboxConsumer,
+ TEventOutboxRow,
+ TOutboxRowResult
+} from "@app/services/event-outbox/event-outbox-types";
+
+import { TAlertDALFactory } from "./alert-dal";
+import { TAlertEngine } from "./alert-engine";
+import { TAlertProviderRegistry } from "./alert-provider-registry";
+import { AlertTriggerType, MAX_TARGET_IDS_PER_EVENT } from "./alert-types";
+
+export const ALERT_OUTBOX_CONSUMER = "alert";
+
+// The contract every event-triggered alert shares: an emitter names the targets by id and the provider
+// rehydrates them at delivery time via findTargetsByIds. Keeping the payload to identifiers is what
+// lets one consumer serve every provider without knowing their shapes.
+export const AlertEventPayloadSchema = z.object({
+ targetIds: z.array(z.string().trim().min(1).max(255)).min(1).max(MAX_TARGET_IDS_PER_EVENT)
+});
+
+const AlertEventProgressSchema = z.object({
+ deliveredChannelIds: z.array(z.string()).default([])
+});
+
+export type TAlertEventConsumerDep = {
+ alertDAL: Pick<TAlertDALFactory, "findEnabledForEvent">;
+ alertEngine: Pick<TAlertEngine, "runAlertForEvent">;
+ alertProviderRegistry: Pick<TAlertProviderRegistry, "get" | "eventTriggeredKeys">;
+};
+
+type TAlertLookup = Pick<TAlertDALFactory, "findEnabledForEvent">["findEnabledForEvent"];
+
+export const alertEventConsumerFactory = ({
+ alertDAL,
+ alertEngine,
+ alertProviderRegistry
+}: TAlertEventConsumerDep): IEventOutboxConsumer<z.infer<typeof AlertEventPayloadSchema>> => {
+ const subscribesTo = (eventType: string): boolean => alertProviderRegistry.eventTriggeredKeys().has(eventType);
+
+ // subscribesTo only sees the event type, so an emitter that pairs a valid event key with the wrong
+ // resourceType gets past the gate. Catching it here, terminally and with a message naming both
+ // halves, is what stops such a row from being silently marked delivered as "no matching alert".
+ const $isDeclaredEvent = (row: TEventOutboxRow): boolean =>
+ Boolean(
+ alertProviderRegistry
+ .get(row.resourceType)
+ ?.events.some((event) => event.key === row.eventType && event.triggerType === AlertTriggerType.Event)
+ );
+
+ const $handleRow = async (row: TEventOutboxRow, findAlerts: TAlertLookup): Promise<TOutboxRowResult> => {
+ const id = String(row.id);
+
+ if (!$isDeclaredEvent(row)) {
+ return {
+ id,
+ status: EventOutboxStatus.Failed,
+ error: `No alert provider for resource type '${row.resourceType}' declares '${row.eventType}' as an event-triggered alert`
+ };
+ }
+
+ const payload = AlertEventPayloadSchema.safeParse(row.payload);
+ if (!payload.success) {
+ return {
+ id,
+ status: EventOutboxStatus.Failed,
+ error: `Unreadable alert event payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`
+ };
+ }
+
+ const progress = AlertEventProgressSchema.safeParse(row.progress ?? {});
+ const delivered = new Set(progress.success ? progress.data.deliveredChannelIds : []);
+
+ const alerts = await findAlerts({
+ orgId: row.orgId,
+ projectId: row.projectId,
+ resourceType: row.resourceType,
+ resourceId: row.resourceId,
+ eventType: row.eventType
+ });
+
+ if (alerts.length === 0) {
+ recordAlertDispatchOutcomeMetric({
+ resourceType: row.resourceType,
+ outcome: AlertDispatchOutcome.NoMatchingAlert
+ });
+ return { id, status: EventOutboxStatus.Delivered };
+ }
+
+ const errors: string[] = [];
+
+ for (const alert of alerts) {
+ // eslint-disable-next-line no-await-in-loop -- at most a project- and an org-scoped alert
+ const result = await alertEngine.runAlertForEvent(alert, {
+ eventType: row.eventType,
+ targetIds: payload.data.targetIds,
+ skipChannelIds: [...delivered]
+ });
+ result.deliveredChannelIds.forEach((channelId) => delivered.add(channelId));
+ recordAlertDispatchOutcomeMetric({ resourceType: alert.resourceType, outcome: result.outcome });
+
+ if (
+ result.outcome === AlertDispatchOutcome.DeliveryFailed ||
+ result.outcome === AlertDispatchOutcome.DeliveryPartial
+ ) {
+ errors.push(`alert ${alert.id}: ${result.outcome}`);
+ }
+ }
+
+ const outcome = { id, progress: { deliveredChannelIds: [...delivered] } };
+ if (errors.length > 0) {
+ return { ...outcome, status: EventOutboxStatus.Retry, error: errors.join("; ") };
+ }
+ return { ...outcome, status: EventOutboxStatus.Delivered };
+ };
+
+ const handle = async (rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]> => {
+ // A batch shares one resource, so rows differ at most by event type and scope. Resolving the
+ // matching alerts once per distinct combination keeps a burst of events from repeating the same
+ // lookup for every row.
+ const alertsByScope = new Map<string, ReturnType<TAlertLookup>>();
+ const findAlerts: TAlertLookup = (filter) => {
+ const key = `${filter.orgId}|${filter.projectId ?? ""}|${filter.eventType}`;
+ let lookup = alertsByScope.get(key);
+ if (!lookup) {
+ lookup = alertDAL.findEnabledForEvent(filter);
+ alertsByScope.set(key, lookup);
+ }
+ return lookup;
+ };
+
+ const results: TOutboxRowResult[] = [];
+
+ for (const row of rows) {
+ try {
+ // eslint-disable-next-line no-await-in-loop -- ordering is the point
+ results.push(await $handleRow(row, findAlerts));
+ } catch (error) {
+ // Contained to this row: throwing out of handle() would send the whole batch back for retry,
+ // re-notifying on every row that had already delivered ahead of this one.
+ results.push({
+ id: String(row.id),
+ status: EventOutboxStatus.Retry,
+ error: error instanceof Error ? error.message : "Unknown error"
+ });
+ }
+ }
+
+ return results;
+ };
+
+ return {
+ name: ALERT_OUTBOX_CONSUMER,
+ payloadSchema: AlertEventPayloadSchema,
+ subscribesTo,
+ handle
+ };
+};
diff --git a/backend/src/services/alert/alert-provider-registry.test.ts b/backend/src/services/alert/alert-provider-registry.test.ts
new file mode 100644
index 0000000000..80361317d4
--- /dev/null
+++ b/backend/src/services/alert/alert-provider-registry.test.ts
@@ -0,0 +1,81 @@
+import { z } from "zod";
+
+import { alertProviderRegistryFactory } from "./alert-provider-registry";
+import { AlertTriggerType, IResourceAlertProvider } from "./alert-types";
+
+const baseProvider = (overrides: Partial<IResourceAlertProvider>): IResourceAlertProvider =>
+ ({
+ resourceType: "test.resource",
+ events: [],
+ conditionSchema: z.any(),
+ targetId: (target: { id: string }) => target.id,
+ buildViewUrl: async () => "https://app.infisical.com/x",
+ buildPayload: () => ({}) as never,
+ assertPermission: async () => undefined,
+ assertResourceInScope: async () => undefined,
+ ...overrides
+ }) as IResourceAlertProvider;
+
+describe("alert provider registry", () => {
+ test("rejects a second provider for the same resource type", () => {
+ const registry = alertProviderRegistryFactory();
+ registry.register(baseProvider({}));
+
+ expect(() => registry.register(baseProvider({}))).toThrow(/already registered/);
+ });
+
+ // Both guards fail the boot in routes/index.ts rather than letting a dispatch silently no-op in
+ // production, which is the failure mode they exist to prevent.
+ test("rejects a scheduled event with no findDueTargets", () => {
+ const registry = alertProviderRegistryFactory();
+
+ expect(() =>
+ registry.register(
+ baseProvider({ events: [{ key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled }] })
+ )
+ ).toThrow(/does not implement findDueTargets/);
+ });
+
+ test("rejects an event-triggered event with no findTargetsByIds", () => {
+ const registry = alertProviderRegistryFactory();
+
+ expect(() =>
+ registry.register(
+ baseProvider({ events: [{ key: "test.resource.opened", triggerType: AlertTriggerType.Event }] })
+ )
+ ).toThrow(/does not implement findTargetsByIds/);
+ });
+
+ test("accepts a provider that implements the method each of its events needs", () => {
+ const registry = alertProviderRegistryFactory();
+
+ expect(() =>
+ registry.register(
+ baseProvider({
+ events: [
+ { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ ],
+ findDueTargets: async () => [],
+ findTargetsByIds: async () => []
+ })
+ )
+ ).not.toThrow();
+ });
+
+ test("reports only the event-triggered keys, so the outbox consumer ignores scheduled ones", () => {
+ const registry = alertProviderRegistryFactory();
+ registry.register(
+ baseProvider({
+ events: [
+ { key: "test.resource.expiry", triggerType: AlertTriggerType.Scheduled },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ ],
+ findDueTargets: async () => [],
+ findTargetsByIds: async () => []
+ })
+ );
+
+ expect([...registry.eventTriggeredKeys()]).toEqual(["test.resource.opened"]);
+ });
+});
diff --git a/backend/src/services/alert/alert-provider-registry.ts b/backend/src/services/alert/alert-provider-registry.ts
index 36488e3748..a907e024dc 100644
--- a/backend/src/services/alert/alert-provider-registry.ts
+++ b/backend/src/services/alert/alert-provider-registry.ts
@@ -1,4 +1,4 @@
-import { IResourceAlertProvider } from "./alert-types";
+import { AlertTriggerType, IResourceAlertProvider } from "./alert-types";
export type TAlertProviderRegistry = ReturnType<typeof alertProviderRegistryFactory>;
@@ -9,6 +9,20 @@ export const alertProviderRegistryFactory = () => {
if (providers.has(provider.resourceType)) {
throw new Error(`Alert provider already registered for resource type '${provider.resourceType}'`);
}
+
+ for (const event of provider.events) {
+ if (event.triggerType === AlertTriggerType.Scheduled && !provider.findDueTargets) {
+ throw new Error(
+ `Alert provider '${provider.resourceType}' declares scheduled event '${event.key}' but does not implement findDueTargets`
+ );
+ }
+ if (event.triggerType === AlertTriggerType.Event && !provider.findTargetsByIds) {
+ throw new Error(
+ `Alert provider '${provider.resourceType}' declares event-triggered event '${event.key}' but does not implement findTargetsByIds`
+ );
+ }
+ }
+
providers.set(provider.resourceType, provider);
};
@@ -16,5 +30,12 @@ export const alertProviderRegistryFactory = () => {
const resourceTypes = (): string[] => [...providers.keys()];
- return { register, get, resourceTypes };
+ const eventTriggeredKeys = (): Set<string> =>
+ new Set(
+ [...providers.values()].flatMap((provider) =>
+ provider.events.filter((event) => event.triggerType === AlertTriggerType.Event).map((event) => event.key)
+ )
+ );
+
+ return { register, get, resourceTypes, eventTriggeredKeys };
};
diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.ts
index 6d6b2cf977..154288c471 100644
--- a/backend/src/services/alert/alert-service-types.ts
+++ b/backend/src/services/alert/alert-service-types.ts
@@ -60,6 +60,7 @@ export type TAlertResponse = {
resourceType: string;
resourceId: string | null;
eventType: string;
+ triggerType: string;
condition: unknown;
enabled: boolean;
orgId: string;
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index 8c3c249215..c29b844c1a 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -4,7 +4,7 @@ import { TAlertChannelInput } from "./alert-channel-service-types";
import { AlertChannelType, TAlertPayload } from "./alert-channel-types";
import { alertProviderRegistryFactory } from "./alert-provider-registry";
import { alertServiceFactory, TAlertServiceFactoryDep } from "./alert-service";
-import { AlertPrincipalType, IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";
+import { AlertPrincipalType, AlertTriggerType, IResourceAlertProvider, TAlertPermissionInput } from "./alert-types";
const RESOURCE_TYPE = "test.resource";
@@ -31,9 +31,13 @@ const buildService = (opts?: {
const permissionCalls: TAlertPermissionInput[] = [];
const provider: IResourceAlertProvider = {
resourceType: RESOURCE_TYPE,
- eventTypes: ["test.resource.expiration"],
+ events: [
+ { key: "test.resource.expiration", triggerType: AlertTriggerType.Scheduled },
+ { key: "test.resource.opened", triggerType: AlertTriggerType.Event }
+ ],
conditionSchema: z.object({ alertBefore: z.string() }),
findDueTargets: async () => [],
+ findTargetsByIds: async () => [],
buildViewUrl: async () => "https://app.infisical.com/x",
buildPayload: () => ({}) as TAlertPayload,
targetId: () => "t",
@@ -263,6 +267,27 @@ describe("alert service", () => {
);
});
+ // triggerType is derived from the provider's event definition, never taken from the request, so an
+ // alert on an event-triggered key is invisible to the daily scan and reachable only from the outbox.
+ test("stores the trigger type its event declares", async () => {
+ const { service, alerts } = buildService();
+
+ await service.createAlert(validCreate);
+ expect([...alerts.values()][0].triggerType).toBe("scheduled");
+
+ const { service: eventService, alerts: eventAlerts } = buildService();
+ await eventService.createAlert({ ...validCreate, eventType: "test.resource.opened" });
+ expect([...eventAlerts.values()][0].triggerType).toBe("event");
+ });
+
+ test("returns the trigger type so a client can tell a scheduled alert from an event one", async () => {
+ const { service } = buildService();
+
+ const created = await service.createAlert(validCreate);
+
+ expect(created.triggerType).toBe("scheduled");
+ });
+
test("rejects a resource-less (scope-wide) alert as unsupported", async () => {
const { service } = buildService();
await expect(service.createAlert({ ...validCreate, resourceId: undefined })).rejects.toThrow(/not supported yet/);
diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.ts
index 6dc5e7ff5f..fb5bcd53c2 100644
--- a/backend/src/services/alert/alert-service.ts
+++ b/backend/src/services/alert/alert-service.ts
@@ -21,7 +21,7 @@ import {
TListAlertsDTO,
TUpdateAlertDTO
} from "./alert-service-types";
-import { AlertPermissionAction, AlertTriggerType, IResourceAlertProvider, toAlertActor } from "./alert-types";
+import { AlertPermissionAction, IResourceAlertProvider, TAlertEventDefinition, toAlertActor } from "./alert-types";
export type TAlertServiceFactoryDep = {
alertDAL: TAlertDALFactory;
@@ -71,11 +71,15 @@ export const alertServiceFactory = ({
provider: IResourceAlertProvider,
input: { eventType?: string; condition?: unknown },
opts: { alwaysValidateCondition?: boolean } = {}
- ) => {
- if (input.eventType && !provider.eventTypes.includes(input.eventType)) {
- throw new BadRequestError({
- message: `Event type '${input.eventType}' is not supported by resource type '${provider.resourceType}'`
- });
+ ): TAlertEventDefinition | undefined => {
+ let event: TAlertEventDefinition | undefined;
+ if (input.eventType) {
+ event = provider.events.find((candidate) => candidate.key === input.eventType);
+ if (!event) {
+ throw new BadRequestError({
+ message: `Event type '${input.eventType}' is not supported by resource type '${provider.resourceType}'`
+ });
+ }
}
if (opts.alwaysValidateCondition || input.condition !== undefined) {
@@ -86,6 +90,8 @@ export const alertServiceFactory = ({
throw new BadRequestError({ message: `Invalid alert condition: ${message}` });
}
}
+
+ return event;
};
const $assembleResponse = (alert: TAlerts, channels: TAlertChannelEmbedded[]): TAlertResponse => ({
@@ -95,6 +101,7 @@ export const alertServiceFactory = ({
resourceType: alert.resourceType,
resourceId: alert.resourceId ?? null,
eventType: alert.eventType,
+ triggerType: alert.triggerType,
condition: alert.condition ?? null,
enabled: alert.enabled,
orgId: alert.orgId,
@@ -113,7 +120,7 @@ export const alertServiceFactory = ({
}
const provider = $getProvider(dto.resourceType);
- $validate(provider, dto, { alwaysValidateCondition: true });
+ const event = $validate(provider, dto, { alwaysValidateCondition: true }) as TAlertEventDefinition;
await $assertAlertPermission(
provider,
@@ -158,7 +165,7 @@ export const alertServiceFactory = ({
resourceType: dto.resourceType,
resourceId: dto.resourceId,
eventType: dto.eventType,
- triggerType: AlertTriggerType.Scheduled,
+ triggerType: event.triggerType,
condition: dto.condition != null ? JSON.stringify(dto.condition) : null,
enabled: dto.enabled ?? true,
orgId: dto.actorOrgId,
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 6c5f29a594..7d9aa1516a 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -10,9 +10,15 @@ export enum AlertPrincipalType {
}
export enum AlertTriggerType {
- Scheduled = "scheduled"
+ Scheduled = "scheduled",
+ Event = "event"
}
+export type TAlertEventDefinition = {
+ key: string;
+ triggerType: AlertTriggerType;
+};
+
export enum AlertRunStatus {
SUCCESS = "success",
PARTIAL = "partial",
@@ -49,6 +55,7 @@ export const ALERT_SCAN_LEAD_DAYS = 1;
export const ALERT_SCAN_LEAD_INTERVAL = "1 day";
export const MAX_CHANNELS_PER_ALERT = 10;
+export const MAX_TARGET_IDS_PER_EVENT = 25;
export const MAX_RECIPIENTS_PER_CHANNEL = 20;
export const ALERT_HISTORY_RETENTION_DAYS = 90;
@@ -66,6 +73,15 @@ export type TAlertContext = {
condition: unknown;
};
+export type TFindTargetsByIdsInput = {
+ orgId: string;
+ projectId?: string | null;
+ resourceId?: string | null;
+ eventType: string;
+ condition: unknown;
+ targetIds: string[];
+};
+
export type TFindDueTargetsInput = {
orgId: string;
projectId?: string | null;
@@ -75,11 +91,19 @@ export type TFindDueTargetsInput = {
asOf: Date;
};
+// Narrowed views for providers that commit to one trigger, so a provider's own factory can declare
+// which discovery method it guarantees rather than leaving callers to assert it.
+export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &
+ Required<Pick<IResourceAlertProvider<TTarget>, "findDueTargets">>;
+
+export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &
+ Required<Pick<IResourceAlertProvider<TTarget>, "findTargetsByIds">>;
+
export interface IResourceAlertProvider<TTarget = unknown> {
// Dot-namespaced, e.g. "pki.certificate", "identity.ua-secret".
resourceType: string;
- // Event keys this provider understands, e.g. ["pki.certificate.expiration"].
- eventTypes: string[];
+ // Event keys this provider understands, each declaring how it fires.
+ events: TAlertEventDefinition[];
// Validates an alert's `condition` (the "when"), e.g. { alertBefore: "30d" }.
conditionSchema: z.ZodTypeAny;
@@ -88,7 +112,14 @@ export interface IResourceAlertProvider<TTarget = unknown> {
// Must be ordered most-urgent-first (soonest expiry): the engine's per-channel maxTargetsPerRun cap
// keeps the head of this list and defers the tail, so urgency ordering ensures the targets closest
// to expiry are never the ones dropped.
- findDueTargets(input: TFindDueTargetsInput): Promise<TTarget[]>;
+ // Required for any Scheduled event; the registry enforces that at boot.
+ findDueTargets?(input: TFindDueTargetsInput): Promise<TTarget[]>;
+
+ // Rehydrate the targets an event named, by id. The event path knows its targets already, so nothing
+ // is scanned for; this exists so the row is read at delivery time rather than copied into the event.
+ // A target whose row is gone is dropped, not an error — it was deleted between emit and dispatch.
+ // Required for any Event event; the registry enforces that at boot.
+ findTargetsByIds?(input: TFindTargetsByIdsInput): Promise<TTarget[]>;
// Deep link to the alert's resource, honouring its scope (org- vs project-scoped). Resolved once
// per run by the engine and passed into buildPayload, so it may perform async lookups.
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
index 401b7885a0..3a96685429 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -14,8 +14,9 @@ import {
ALERT_SCAN_LEAD_DAYS,
ALERT_SCAN_LEAD_INTERVAL,
AlertPermissionAction,
+ AlertTriggerType,
DEFAULT_DEDUP_WINDOW_HOURS,
- IResourceAlertProvider,
+ IScheduledAlertProvider,
MAX_DEDUP_WINDOW_HOURS,
TAlertContext,
TAlertPermissionInput,
@@ -93,7 +94,7 @@ const targetId = (target: TIdentityCredentialTarget): string => `${target.creden
export const identityCredentialAlertProviderFactory = ({
identityCredentialAlertDAL,
permissionService
-}: TIdentityCredentialAlertProviderDep): IResourceAlertProvider<TIdentityCredentialTarget> => {
+}: TIdentityCredentialAlertProviderDep): IScheduledAlertProvider<TIdentityCredentialTarget> => {
const projectBaseUrl = (
siteUrl: string | undefined,
orgId: string,
@@ -265,7 +266,7 @@ export const identityCredentialAlertProviderFactory = ({
return {
resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
- eventTypes: [IDENTITY_AUTHENTICATION_EXPIRY_EVENT],
+ events: [{ key: IDENTITY_AUTHENTICATION_EXPIRY_EVENT, triggerType: AlertTriggerType.Scheduled }],
conditionSchema: IdentityCredentialConditionSchema,
findDueTargets,
buildViewUrl,
diff --git a/backend/src/services/event-outbox/event-outbox-dal.test.ts b/backend/src/services/event-outbox/event-outbox-dal.test.ts
new file mode 100644
index 0000000000..58159fff5a
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-dal.test.ts
@@ -0,0 +1,271 @@
+import { TableName } from "@app/db/schemas";
+
+import { eventOutboxDALFactory } from "./event-outbox-dal";
+import { EventOutboxStatus } from "./event-outbox-types";
+
+// These assert query *shape*, in the style of alert-dal.test.ts. The runtime concurrency property
+// (two claimers never take the same row) is a Postgres guarantee that only a real database can
+// demonstrate; what a unit test can protect is that the clauses buying it are still there.
+const buildDAL = () => {
+ const calls = {
+ where: [] as unknown[][],
+ whereIn: [] as unknown[][],
+ andWhere: [] as unknown[][],
+ andWhereRaw: [] as unknown[][],
+ orderBy: [] as unknown[],
+ forUpdate: 0,
+ skipLocked: 0,
+ limit: [] as number[],
+ update: [] as Record<string, unknown>[],
+ insert: [] as unknown[],
+ onConflict: [] as unknown[],
+ ignored: 0,
+ groupBy: [] as unknown[][],
+ orderByRaw: [] as unknown[]
+ };
+
+ const chain: Record<string, unknown> = {};
+ Object.assign(chain, {
+ where: (...args: unknown[]) => {
+ calls.where.push(args);
+ return chain;
+ },
+ whereIn: (...args: unknown[]) => {
+ if (typeof args[1] === "function") {
+ (args[1] as (qb: typeof chain) => void)(chain);
+ return chain;
+ }
+ calls.whereIn.push(args);
+ return chain;
+ },
+ from: () => chain,
+ andWhere: (...args: unknown[]) => {
+ calls.andWhere.push(args);
+ return chain;
+ },
+ andWhereRaw: (...args: unknown[]) => {
+ calls.andWhereRaw.push(args);
+ return chain;
+ },
+ orderBy: (...args: unknown[]) => {
+ calls.orderBy.push(args.length === 1 ? args[0] : args);
+ return chain;
+ },
+ orderByRaw: (arg: unknown) => {
+ calls.orderByRaw.push(arg);
+ return chain;
+ },
+ groupBy: (...args: unknown[]) => {
+ calls.groupBy.push(args);
+ return chain;
+ },
+ limit: (n: number) => {
+ calls.limit.push(n);
+ return chain;
+ },
+ forUpdate: () => {
+ calls.forUpdate += 1;
+ return chain;
+ },
+ skipLocked: () => {
+ calls.skipLocked += 1;
+ return chain;
+ },
+ insert: (rows: unknown) => {
+ calls.insert.push(rows);
+ return chain;
+ },
+ onConflict: (cols: unknown) => {
+ calls.onConflict.push(cols);
+ return chain;
+ },
+ ignore: () => {
+ calls.ignored += 1;
+ return chain;
+ },
+ update: (patch: Record<string, unknown>) => {
+ calls.update.push(patch);
+ return chain;
+ },
+ returning: async () => [],
+ del: async () => 0,
+ // Returns the chain so a subquery can keep building; awaiting it resolves through `then` below.
+ select: () => chain,
+ then: (resolve: (v: unknown) => unknown) => resolve([])
+ });
+
+ const queryBuilder = () => chain;
+ const db = Object.assign(queryBuilder, {
+ replicaNode: () => queryBuilder,
+ raw: (sql: string) => sql,
+ fn: { now: () => "NOW()" },
+ transaction: async (cb: (tx: unknown) => unknown) => cb(Object.assign(queryBuilder, { fn: { now: () => "NOW()" } }))
+ }) as never;
+
+ return { dal: eventOutboxDALFactory(db), calls, tx: queryBuilder as never };
+};
+
+describe("event outbox dal", () => {
+ // The conflict target has to repeat the index predicate: Postgres cannot infer a *partial* unique
+ // index from a bare column list and answers a plain ON CONFLICT (consumer, idempotencyKey) with
+ // 42P10 at runtime. Only rows carrying a key are in the index, so an event without one never
+ // collides.
+ test("insertEvents ignores a conflict on the partial idempotency index", async () => {
+ const { dal, calls, tx } = buildDAL();
+
+ await dal.insertEvents(
+ [
+ {
+ consumer: "alert",
+ eventType: "approval.workflow.request_opened",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ orgId: "org-1",
+ payload: { targetIds: ["req-1"] },
+ occurredAt: new Date()
+ }
+ ],
+ tx
+ );
+
+ expect(calls.onConflict[0]).toBe('("consumer", "idempotencyKey") WHERE "idempotencyKey" IS NOT NULL');
+ expect(calls.ignored).toBe(1);
+ });
+
+ test("insertEvents issues no statement for an empty batch", async () => {
+ const { dal, calls, tx } = buildDAL();
+
+ await dal.insertEvents([], tx);
+
+ expect(calls.insert).toHaveLength(0);
+ });
+
+ // SKIP LOCKED is what makes concurrent relays and overlapping flushes correct by construction, which
+ // is the reason the relay does not need the cron manager's fleet-wide exactly-once scheduling.
+ test("claimBatch locks rows with FOR UPDATE SKIP LOCKED", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.claimBatch({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" }, 100);
+
+ expect(calls.forUpdate).toBe(1);
+ expect(calls.skipLocked).toBe(1);
+ });
+
+ // The autoincrement id is the only column that reflects the order events actually happened. Sorting
+ // by nextRetryAt instead lets a later event overtake an earlier one that took a backoff, because a
+ // fresh row's nextRetryAt is its insert time and so sorts ahead of a retried row's future one.
+ test("claimBatch orders by id, not by a timestamp", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.claimBatch({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" }, 100);
+
+ expect(calls.orderBy[0]).toEqual(["id", "asc"]);
+ });
+
+ // The single-statement shape is what keeps the row locks scoped to the UPDATE itself: a claim never
+ // holds a connection across two round trips.
+ test("claimBatch flips the locked rows to processing in the same statement", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.claimBatch({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" }, 100);
+
+ expect(calls.update).toHaveLength(1);
+ expect(calls.update[0].status).toBe(EventOutboxStatus.Processing);
+ expect(calls.update[0].lockedAt).toBe("NOW()");
+ });
+
+ // Only a row still held by this worker gets its lease renewed. One the sweeper already handed back
+ // must not be pulled into 'processing' again by a late heartbeat.
+ test("extendClaims refreshes lockedAt only on rows still processing", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.extendClaims(["1", "2"]);
+
+ expect(calls.whereIn[0]).toEqual(["id", ["1", "2"]]);
+ expect(calls.where).toContainEqual(["status", EventOutboxStatus.Processing]);
+ expect(calls.update[0]).toEqual({ lockedAt: "NOW()" });
+ });
+
+ test("extendClaims issues no statement for an empty claim", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.extendClaims([]);
+
+ expect(calls.update).toHaveLength(0);
+ });
+
+ test("claimBatch only takes rows whose retry time has arrived", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.claimBatch({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" }, 100);
+
+ expect(calls.whereIn[0]).toEqual(["status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry]]);
+ expect(calls.andWhere[0][0]).toBe("nextRetryAt");
+ expect(calls.andWhere[0][1]).toBe("<=");
+ });
+
+ test("findDueFlushKeys groups by the flush key and takes the most overdue first", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.findDueFlushKeys(200);
+
+ expect(calls.groupBy[0]).toEqual(["consumer", "resourceType", "resourceId"]);
+ expect(calls.orderByRaw[0]).toBe('MIN("nextRetryAt") ASC');
+ expect(calls.limit).toContain(200);
+ });
+
+ // Computed DB-side so the retry schedule uses the same clock the claim compares against, with no
+ // app/DB skew.
+ test("commitResults computes the next retry time in SQL, not in JS", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.commitResults({
+ delivered: [],
+ retriable: [{ ids: ["1"], nextRetryDelayMs: 30_000 }],
+ failed: []
+ });
+
+ expect(calls.update[0].nextRetryAt).toBe("NOW() + (? || ' milliseconds')::INTERVAL");
+ expect(calls.update[0].status).toBe(EventOutboxStatus.Retry);
+ });
+
+ test("commitResults issues no statement when there is nothing to commit", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.commitResults({ delivered: [], retriable: [], failed: [] });
+
+ expect(calls.update).toHaveLength(0);
+ });
+
+ test("commitResults releases the claim on every terminal outcome", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.commitResults({
+ delivered: [{ ids: ["1"] }],
+ retriable: [],
+ failed: [{ ids: ["2"], error: "gave up" }]
+ });
+
+ expect(calls.update.every((patch) => patch.lockedAt === null)).toBe(true);
+ expect(calls.update.map((patch) => patch.status)).toEqual([EventOutboxStatus.Delivered, EventOutboxStatus.Failed]);
+ });
+
+ test("recoverStaleClaims looks only at claims older than the threshold", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.recoverStaleClaims(600_000, 5);
+
+ expect(calls.where).toContainEqual(["status", EventOutboxStatus.Processing]);
+ expect(calls.andWhereRaw[0][0]).toBe(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`);
+ expect(calls.andWhereRaw[0][1]).toEqual([600_000]);
+ });
+
+ test("prune targets the outbox table", async () => {
+ const { dal } = buildDAL();
+
+ await expect(
+ dal.deleteTerminalOlderThan({ deliveredBefore: new Date(), failedBefore: new Date(), batchSize: 100 })
+ ).resolves.toBe(0);
+ expect(TableName.EventOutbox).toBe("event_outbox");
+ });
+});
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
new file mode 100644
index 0000000000..1c1b97c127
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -0,0 +1,278 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+
+import { EventOutboxStatus, TEventOutboxRow, TOutboxFlushKey } from "./event-outbox-types";
+
+export type TEventOutboxDALFactory = ReturnType<typeof eventOutboxDALFactory>;
+
+export type TOutboxInsertRow = {
+ consumer: string;
+ eventType: string;
+ resourceType: string;
+ resourceId: string;
+ orgId: string;
+ projectId?: string | null;
+ payload: unknown;
+ idempotencyKey?: string | null;
+ occurredAt: Date;
+};
+
+export const eventOutboxDALFactory = (db: TDbClient) => {
+ const insertEvents = async (rows: TOutboxInsertRow[], tx: Knex): Promise<void> => {
+ if (rows.length === 0) return;
+ try {
+ await tx(TableName.EventOutbox)
+ .insert(
+ rows.map((row) => ({
+ ...row,
+ payload: JSON.stringify(row.payload),
+ projectId: row.projectId ?? null,
+ idempotencyKey: row.idempotencyKey ?? null
+ }))
+ )
+ .onConflict(db.raw('("consumer", "idempotencyKey") WHERE "idempotencyKey" IS NOT NULL'))
+ .ignore();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: insertEvents" });
+ }
+ };
+
+ const findDueFlushKeys = async (limit: number): Promise<TOutboxFlushKey[]> => {
+ try {
+ const rows = await db
+ .replicaNode()(TableName.EventOutbox)
+ .whereIn("status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry])
+ .andWhere("nextRetryAt", "<=", db.fn.now())
+ .groupBy("consumer", "resourceType", "resourceId")
+ .orderByRaw('MIN("nextRetryAt") ASC')
+ .limit(limit)
+ .select<TOutboxFlushKey[]>("consumer", "resourceType", "resourceId");
+
+ return rows;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: findDueFlushKeys" });
+ }
+ };
+
+ // One statement, no explicit transaction: the row locks live only for the duration of the UPDATE,
+ // and a claim costs one round trip instead of four.
+ const claimBatch = async (key: TOutboxFlushKey, limit: number): Promise<TEventOutboxRow[]> => {
+ try {
+ const claimed = await db(TableName.EventOutbox)
+ .whereIn("id", (qb) => {
+ void qb
+ .select("id")
+ .from(TableName.EventOutbox)
+ .where(key)
+ .whereIn("status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry])
+ .andWhere("nextRetryAt", "<=", db.fn.now())
+ // Ordered by the autoincrement id, never by a timestamp: id is the only column that reflects
+ // the order the events actually happened. Sorting by nextRetryAt instead lets a later event
+ // overtake an earlier one that took a backoff, because a fresh row's nextRetryAt is its
+ // insert time and so sorts ahead of a retried row's future one.
+ .orderBy("id", "asc")
+ .limit(limit)
+ .forUpdate()
+ .skipLocked();
+ })
+ .update({ status: EventOutboxStatus.Processing, lockedAt: db.fn.now() })
+ .returning("*");
+
+ return claimed as unknown as TEventOutboxRow[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: claimBatch" });
+ }
+ };
+
+ // Keeps a long-running claim from looking abandoned. The stale-claim sweeper treats any claim older
+ // than its threshold as a dead worker and hands the rows back out, so a batch that legitimately
+ // outlives the threshold has to keep refreshing lockedAt or its rows get delivered twice.
+ const extendClaims = async (ids: string[]): Promise<void> => {
+ if (ids.length === 0) return;
+ try {
+ await db(TableName.EventOutbox)
+ .whereIn("id", ids)
+ .where("status", EventOutboxStatus.Processing)
+ .update({ lockedAt: db.fn.now() });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: extendClaims" });
+ }
+ };
+
+ const commitResults = async (input: {
+ delivered: { ids: string[]; progress?: Record<string, unknown> | null }[];
+ retriable: { ids: string[]; nextRetryDelayMs: number; progress?: Record<string, unknown> | null; error?: string }[];
+ failed: { ids: string[]; error?: string }[];
+ }): Promise<void> => {
+ const total =
+ input.delivered.reduce((n, g) => n + g.ids.length, 0) +
+ input.retriable.reduce((n, g) => n + g.ids.length, 0) +
+ input.failed.reduce((n, g) => n + g.ids.length, 0);
+ if (total === 0) return;
+
+ try {
+ await db.transaction(async (tx) => {
+ for (const group of input.delivered) {
+ if (group.ids.length > 0) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
+ await tx(TableName.EventOutbox)
+ .whereIn("id", group.ids)
+ .update({
+ status: EventOutboxStatus.Delivered,
+ lockedAt: null,
+ lastError: null,
+ ...(group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {})
+ });
+ }
+ }
+
+ for (const group of input.retriable) {
+ if (group.ids.length > 0) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
+ await tx(TableName.EventOutbox)
+ .whereIn("id", group.ids)
+ .update({
+ status: EventOutboxStatus.Retry,
+ attempts: db.raw('"attempts" + 1'),
+ nextRetryAt: db.raw(`NOW() + (? || ' milliseconds')::INTERVAL`, [group.nextRetryDelayMs]),
+ lockedAt: null,
+ lastError: group.error ?? null,
+ ...(group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {})
+ });
+ }
+ }
+
+ for (const group of input.failed) {
+ if (group.ids.length > 0) {
+ // eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
+ await tx(TableName.EventOutbox)
+ .whereIn("id", group.ids)
+ .update({
+ status: EventOutboxStatus.Failed,
+ attempts: db.raw('"attempts" + 1'),
+ lockedAt: null,
+ lastError: group.error ?? null
+ });
+ }
+ }
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: commitResults" });
+ }
+ };
+
+ const recoverStaleClaims = async (
+ thresholdMs: number,
+ maxAttempts: number
+ ): Promise<{ retried: number; failed: number }> => {
+ try {
+ return await db.transaction(async (tx) => {
+ const staleRows = await tx(TableName.EventOutbox)
+ .where("status", EventOutboxStatus.Processing)
+ .andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])
+ .forUpdate()
+ .skipLocked()
+ .select<{ id: string; attempts: number }[]>("id", "attempts");
+
+ if (staleRows.length === 0) return { retried: 0, failed: 0 };
+
+ const exhausted = staleRows.filter((row) => row.attempts + 1 >= maxAttempts).map((row) => row.id);
+ const retriable = staleRows.filter((row) => row.attempts + 1 < maxAttempts).map((row) => row.id);
+
+ if (retriable.length > 0) {
+ await tx(TableName.EventOutbox)
+ .whereIn("id", retriable)
+ .update({
+ status: EventOutboxStatus.Retry,
+ attempts: db.raw('"attempts" + 1'),
+ nextRetryAt: tx.fn.now(),
+ lockedAt: null,
+ lastError: "Worker did not report a result before the claim went stale"
+ });
+ }
+
+ if (exhausted.length > 0) {
+ await tx(TableName.EventOutbox)
+ .whereIn("id", exhausted)
+ .update({
+ status: EventOutboxStatus.Failed,
+ attempts: db.raw('"attempts" + 1'),
+ lockedAt: null,
+ lastError: "Worker did not report a result before the claim went stale"
+ });
+ }
+
+ return { retried: retriable.length, failed: exhausted.length };
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: recoverStaleClaims" });
+ }
+ };
+
+ const findOldestPendingAgeSeconds = async (): Promise<{ consumer: string; ageSeconds: number }[]> => {
+ try {
+ const rows = await db
+ .replicaNode()(TableName.EventOutbox)
+ .whereIn("status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry, EventOutboxStatus.Processing])
+ .groupBy("consumer")
+ .select<
+ { consumer: string; ageSeconds: string }[]
+ >("consumer", db.raw('EXTRACT(EPOCH FROM (NOW() - MIN("occurredAt")))::float8 as "ageSeconds"'));
+
+ return rows.map((row) => ({ consumer: row.consumer, ageSeconds: Number(row.ageSeconds) }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: findOldestPendingAgeSeconds" });
+ }
+ };
+
+ const deleteTerminalOlderThan = async (input: {
+ deliveredBefore: Date;
+ failedBefore: Date;
+ batchSize: number;
+ }): Promise<number> => {
+ try {
+ return await db(TableName.EventOutbox)
+ .whereIn(
+ "id",
+ (qb) =>
+ void qb
+ .select("id")
+ .from(TableName.EventOutbox)
+ .where(
+ (builder) =>
+ void builder
+ .where(
+ (delivered) =>
+ void delivered
+ .where("status", EventOutboxStatus.Delivered)
+ .andWhere("updatedAt", "<", input.deliveredBefore)
+ )
+ .orWhere(
+ (failed) =>
+ void failed
+ .where("status", EventOutboxStatus.Failed)
+ .andWhere("updatedAt", "<", input.failedBefore)
+ )
+ )
+ .limit(input.batchSize)
+ )
+ .del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "EventOutbox: deleteTerminalOlderThan" });
+ }
+ };
+
+ return {
+ insertEvents,
+ findDueFlushKeys,
+ claimBatch,
+ extendClaims,
+ commitResults,
+ recoverStaleClaims,
+ findOldestPendingAgeSeconds,
+ deleteTerminalOlderThan
+ };
+};
diff --git a/backend/src/services/event-outbox/event-outbox-queue.test.ts b/backend/src/services/event-outbox/event-outbox-queue.test.ts
new file mode 100644
index 0000000000..2c01ab6f75
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-queue.test.ts
@@ -0,0 +1,102 @@
+import { QueueName } from "@app/queue";
+
+import { eventOutboxQueueFactory } from "./event-outbox-queue";
+import { TOutboxFlushKey } from "./event-outbox-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ isGeneralWorkerRunModeEnabled: true, OTEL_TELEMETRY_COLLECTION_ENABLED: false })
+}));
+
+const KEY: TOutboxFlushKey = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
+
+const buildQueue = (opts?: { keys?: TOutboxFlushKey[]; onDiscover?: () => Promise<void> }) => {
+ const queued: { name: string; data: unknown; jobId?: string; attempts?: number }[] = [];
+ let discoverCalls = 0;
+
+ const factory = eventOutboxQueueFactory({
+ queueService: {
+ queue: async (name: string, _job: string, data: unknown, options: { jobId?: string; attempts?: number }) => {
+ queued.push({ name, data, jobId: options.jobId, attempts: options.attempts });
+ },
+ start: () => {}
+ } as never,
+ cronJob: { register: () => {} } as never,
+ eventOutboxDAL: {
+ findDueFlushKeys: async () => {
+ discoverCalls += 1;
+ if (opts?.onDiscover) await opts.onDiscover();
+ return opts?.keys ?? [];
+ },
+ findOldestPendingAgeSeconds: async () => []
+ } as never,
+ eventOutboxService: {
+ drain: async () => ({ handled: 0, exhaustedConsumer: false }),
+ sweepStaleClaims: async () => {},
+ pruneTerminalRows: async () => {}
+ } as never
+ });
+
+ return { factory, queued, getDiscoverCalls: () => discoverCalls };
+};
+
+describe("event outbox relay", () => {
+ test("enqueues one flush job per discovered key", async () => {
+ const { factory, queued } = buildQueue({ keys: [KEY, { ...KEY, resourceId: "policy-2" }] });
+
+ await factory.runRelayTick();
+
+ expect(queued).toHaveLength(2);
+ expect(queued[0].name).toBe(QueueName.EventOutboxFlush);
+ expect(queued[0].data).toEqual(KEY);
+ });
+
+ // One flush per aggregate at a time is what keeps a resource's events in order, and it dedupes the
+ // relay rediscovering a key whose flush is still queued.
+ test("keys the job per aggregate so flushes for one resource cannot overlap", async () => {
+ const { factory, queued } = buildQueue({ keys: [KEY] });
+
+ await factory.runRelayTick();
+
+ expect(queued[0].jobId).toBe("outbox-flush-alert-approval.workflow-policy-1");
+ });
+
+ // BullMQ throws on a custom id containing ':'; with Promise.all that would fail the whole tick, every
+ // tick, for as long as the row sat pending. Encoding keeps the id both legal and collision-free.
+ test("encodes a resource id BullMQ would otherwise reject", async () => {
+ const { factory, queued } = buildQueue({ keys: [{ ...KEY, resourceId: "arn:aws:iam::123:role/x" }] });
+
+ await factory.runRelayTick();
+
+ expect(queued[0].jobId).toBe("outbox-flush-alert-approval.workflow-arn%3Aaws%3Aiam%3A%3A123%3Arole%2Fx");
+ expect(queued[0].jobId).not.toContain(":");
+ });
+
+ // Retry lives on the outbox row, where it is inspectable and survives a Redis flush. BullMQ retrying
+ // the job would re-run drain against rows already flipped to 'processing'.
+ test("does not ask BullMQ to retry a flush", async () => {
+ const { factory, queued } = buildQueue({ keys: [KEY] });
+
+ await factory.runRelayTick();
+
+ expect(queued[0].attempts).toBe(1);
+ });
+
+ test("enqueues nothing when there is no due work", async () => {
+ const { factory, queued } = buildQueue({ keys: [] });
+
+ await factory.runRelayTick();
+
+ expect(queued).toHaveLength(0);
+ });
+
+ test("stops cleanly when nothing was ever started", async () => {
+ const { factory } = buildQueue();
+
+ await expect(factory.shutdown()).resolves.toBeUndefined();
+ });
+});
diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.ts
new file mode 100644
index 0000000000..8aeb68b89b
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-queue.ts
@@ -0,0 +1,157 @@
+import { getConfig } from "@app/lib/config/env";
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
+import { logger } from "@app/lib/logger";
+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+
+import { TEventOutboxDALFactory } from "./event-outbox-dal";
+import { TEventOutboxServiceFactory } from "./event-outbox-service";
+import { OUTBOX_RELAY_INTERVAL_MS, RELAY_DISCOVERY_LIMIT, TOutboxFlushKey } from "./event-outbox-types";
+
+const FLUSH_WORKER_CONCURRENCY = 10;
+
+const STALE_CLAIM_SWEEPER_CRON = "*/5 * * * *";
+const CLEANUP_CRON = "*/15 * * * *";
+const CRON_RUN_HASH_TTL_S = 60 * 60;
+
+const RELAY_START_JITTER_MS = 5_000;
+
+export type TEventOutboxQueueFactoryDep = {
+ queueService: TQueueServiceFactory;
+ cronJob: TCronJobFactory;
+ eventOutboxDAL: Pick<TEventOutboxDALFactory, "findDueFlushKeys" | "findOldestPendingAgeSeconds">;
+ eventOutboxService: Pick<TEventOutboxServiceFactory, "drain" | "sweepStaleClaims" | "pruneTerminalRows">;
+};
+
+export const eventOutboxQueueFactory = ({
+ queueService,
+ cronJob,
+ eventOutboxDAL,
+ eventOutboxService
+}: TEventOutboxQueueFactoryDep) => {
+ const appCfg = getConfig();
+
+ let lastDiscoveryCount = 0;
+ let oldestPendingByConsumer: { consumer: string; ageSeconds: number }[] = [];
+
+ const $registerGauges = () => {
+ const meter = resolveCoreMeter();
+
+ const oldestPendingGauge = meter.createObservableGauge("infisical.event_outbox.oldest_pending_age", {
+ description:
+ "Age in seconds of the oldest undelivered outbox event, by consumer. Alarm when this exceeds a small multiple of the relay interval: it means events are being recorded but not delivered.",
+ unit: "s"
+ });
+ oldestPendingGauge.addCallback((result) => {
+ if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ oldestPendingByConsumer.forEach(({ consumer, ageSeconds }) => {
+ result.observe(ageSeconds, { "event_outbox.consumer": consumer });
+ });
+ });
+
+ const discoveryGauge = meter.createObservableGauge("infisical.event_outbox.discovered", {
+ description:
+ "Flush keys found on the last relay tick (capped at the discovery limit). Sustained value at the cap means the drain rate cannot keep up.",
+ unit: "{key}"
+ });
+ discoveryGauge.addCallback((result) => {
+ if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ result.observe(lastDiscoveryCount);
+ });
+ };
+
+ // BullMQ rejects a custom id containing ':' and resourceId is any string, so it is percent-encoded.
+ // The encoding is injective, so two distinct keys can never share a job id. consumer and
+ // resourceType are already restricted to [a-z0-9._-] by the emit schema.
+ const $enqueueFlush = async (key: TOutboxFlushKey) =>
+ queueService.queue(QueueName.EventOutboxFlush, QueueJobs.EventOutboxFlush, key, {
+ jobId: `outbox-flush-${key.consumer}-${key.resourceType}-${encodeURIComponent(key.resourceId)}`,
+ removeOnComplete: true,
+ removeOnFail: true,
+ attempts: 1
+ });
+
+ const runRelayTick = async () => {
+ const keys = await eventOutboxDAL.findDueFlushKeys(RELAY_DISCOVERY_LIMIT);
+ lastDiscoveryCount = keys.length;
+
+ if (keys.length === RELAY_DISCOVERY_LIMIT) {
+ logger.warn(`event-outbox: relay discovery hit its cap of ${RELAY_DISCOVERY_LIMIT} keys; a backlog is building`);
+ }
+
+ if (keys.length > 0) {
+ await Promise.all(keys.map((key) => $enqueueFlush(key)));
+ }
+
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ oldestPendingByConsumer = await eventOutboxDAL.findOldestPendingAgeSeconds();
+ }
+ };
+
+ let relayTimer: NodeJS.Timeout | undefined;
+ let startTimer: NodeJS.Timeout | undefined;
+ let inFlight: Promise<void> | undefined;
+
+ const $tick = () => {
+ if (inFlight) return;
+ inFlight = runRelayTick()
+ .catch((error) => {
+ logger.error(error, "event-outbox: relay tick failed");
+ })
+ .finally(() => {
+ inFlight = undefined;
+ });
+ };
+
+ const init = () => {
+ queueService.start(
+ QueueName.EventOutboxFlush,
+ async (job) => {
+ const { consumer, resourceType, resourceId } = job.data;
+ await eventOutboxService.drain({ consumer, resourceType, resourceId });
+ },
+ { concurrency: FLUSH_WORKER_CONCURRENCY }
+ );
+
+ cronJob.register({
+ name: CronJobName.EventOutboxStaleClaimSweeper,
+ pattern: STALE_CLAIM_SWEEPER_CRON,
+ runHashTtlS: CRON_RUN_HASH_TTL_S,
+ handler: async () => {
+ await eventOutboxService.sweepStaleClaims();
+ }
+ });
+
+ cronJob.register({
+ name: CronJobName.EventOutboxCleanup,
+ pattern: CLEANUP_CRON,
+ runHashTtlS: CRON_RUN_HASH_TTL_S,
+ handler: async () => {
+ await eventOutboxService.pruneTerminalRows();
+ }
+ });
+
+ if (!appCfg.isGeneralWorkerRunModeEnabled) return;
+
+ $registerGauges();
+ startTimer = setTimeout(
+ () => {
+ $tick();
+ relayTimer = setInterval($tick, OUTBOX_RELAY_INTERVAL_MS);
+ },
+ Math.floor(Math.random() * RELAY_START_JITTER_MS)
+ );
+ };
+
+ const shutdown = async () => {
+ if (startTimer) clearTimeout(startTimer);
+ if (relayTimer) clearInterval(relayTimer);
+ startTimer = undefined;
+ relayTimer = undefined;
+ await inFlight;
+ };
+
+ return { init, shutdown, runRelayTick };
+};
+
+export type TEventOutboxQueueFactory = ReturnType<typeof eventOutboxQueueFactory>;
diff --git a/backend/src/services/event-outbox/event-outbox-registry.ts b/backend/src/services/event-outbox/event-outbox-registry.ts
new file mode 100644
index 0000000000..c6cda210a5
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-registry.ts
@@ -0,0 +1,23 @@
+import { IEventOutboxConsumer } from "./event-outbox-types";
+
+export type TEventOutboxRegistry = ReturnType<typeof eventOutboxRegistryFactory>;
+
+export const eventOutboxRegistryFactory = () => {
+ const consumers = new Map<string, IEventOutboxConsumer>();
+
+ const register = (consumer: IEventOutboxConsumer) => {
+ if (consumers.has(consumer.name)) {
+ throw new Error(`Event outbox consumer already registered under the name '${consumer.name}'`);
+ }
+ consumers.set(consumer.name, consumer);
+ };
+
+ const get = (name: string): IEventOutboxConsumer | undefined => consumers.get(name);
+
+ const names = (): string[] => [...consumers.keys()];
+
+ const subscribersOf = (eventType: string): IEventOutboxConsumer[] =>
+ [...consumers.values()].filter((consumer) => consumer.subscribesTo(eventType));
+
+ return { register, get, names, subscribersOf };
+};
diff --git a/backend/src/services/event-outbox/event-outbox-service.test.ts b/backend/src/services/event-outbox/event-outbox-service.test.ts
new file mode 100644
index 0000000000..8beddf9038
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts
@@ -0,0 +1,328 @@
+import { z } from "zod";
+
+import { eventOutboxRegistryFactory } from "./event-outbox-registry";
+import { eventOutboxServiceFactory } from "./event-outbox-service";
+import { EventOutboxStatus, IEventOutboxConsumer, TEventOutboxRow, TOutboxEvent } from "./event-outbox-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
+const ORG_ID = "11111111-1111-1111-1111-111111111111";
+
+const makeEvent = (overrides?: Partial<TOutboxEvent>): TOutboxEvent => ({
+ eventType: "approval.workflow.request_opened",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ orgId: ORG_ID,
+ payload: { targetIds: ["req-1"] },
+ ...overrides
+});
+
+const makeConsumer = (overrides?: Partial<IEventOutboxConsumer>): IEventOutboxConsumer =>
+ ({
+ name: "alert",
+ payloadSchema: z.object({ targetIds: z.array(z.string()).min(1) }),
+ subscribesTo: (eventType: string) => eventType === "approval.workflow.request_opened",
+ handle: async () => [],
+ ...overrides
+ }) as IEventOutboxConsumer;
+
+// `tx` is a sentinel: emit must thread the caller's transaction through untouched, since a call that
+// silently opened its own connection is how the pool deadlocks.
+const TX = { sentinel: true } as never;
+
+const buildService = (consumers: IEventOutboxConsumer[]) => {
+ const registry = eventOutboxRegistryFactory();
+ consumers.forEach((consumer) => registry.register(consumer));
+
+ const inserted: { rows: unknown[]; tx: unknown }[] = [];
+ const service = eventOutboxServiceFactory({
+ eventOutboxDAL: {
+ insertEvents: async (rows: unknown[], tx: unknown) => {
+ inserted.push({ rows, tx });
+ }
+ } as never,
+ eventOutboxRegistry: registry
+ });
+
+ return { service, inserted, insertedRows: () => inserted.flatMap((call) => call.rows) };
+};
+
+describe("event outbox emit", () => {
+ test("writes one row per subscribing consumer and none for a non-subscriber", async () => {
+ const { service, insertedRows } = buildService([
+ makeConsumer({ name: "alert" }),
+ makeConsumer({ name: "other", subscribesTo: () => false })
+ ]);
+
+ await service.emit(makeEvent(), TX);
+
+ expect(insertedRows()).toHaveLength(1);
+ expect((insertedRows()[0] as { consumer: string }).consumer).toBe("alert");
+ });
+
+ test("does not touch the database when no consumer handles the event type", async () => {
+ const { service, inserted } = buildService([makeConsumer({ subscribesTo: () => false })]);
+
+ await service.emit(makeEvent(), TX);
+
+ expect(inserted).toHaveLength(0);
+ });
+
+ // The insert is the only statement emit adds to the caller's transaction. If a consumer callback
+ // ever reappears here, this is what fails.
+ test("writes a row without consulting the database about the resource", async () => {
+ const { service, inserted } = buildService([makeConsumer()]);
+
+ await service.emit(makeEvent(), TX);
+
+ expect(inserted).toHaveLength(1);
+ expect(inserted[0].tx).toBe(TX);
+ });
+
+ // A payload the consumer cannot read is a statically wrong emit site. Failing loudly beats dropping
+ // a notification because a field was misspelled, and this runs before any DB access so it cannot
+ // poison the caller's transaction.
+ test("throws when the payload does not match the consumer's schema", async () => {
+ const { service, inserted } = buildService([makeConsumer()]);
+
+ await expect(service.emit(makeEvent({ payload: { targetIds: [] } }), TX)).rejects.toThrow(
+ /the 'alert' consumer cannot accept/
+ );
+ expect(inserted).toHaveLength(0);
+ });
+
+ test("throws on an oversized payload rather than storing a document", async () => {
+ const { service, inserted } = buildService([
+ makeConsumer({ payloadSchema: z.object({ blob: z.string() }) as never })
+ ]);
+
+ await expect(service.emit(makeEvent({ payload: { blob: "x".repeat(20_000) } }), TX)).rejects.toThrow(
+ /over the .* byte limit/
+ );
+ expect(inserted).toHaveLength(0);
+ });
+
+ test("throws on a malformed event envelope", async () => {
+ const { service } = buildService([makeConsumer()]);
+
+ await expect(service.emit(makeEvent({ orgId: "not-a-uuid" }), TX)).rejects.toThrow(/Invalid outbox event/);
+ });
+
+ // Postgres aborts the whole transaction on a failed statement, so swallowing this would hand the
+ // caller a poisoned transaction instead of the real error.
+ test("propagates a failing insert rather than swallowing it", async () => {
+ const registry = eventOutboxRegistryFactory();
+ registry.register(makeConsumer());
+ const service = eventOutboxServiceFactory({
+ eventOutboxDAL: {
+ insertEvents: async () => {
+ throw new Error("connection terminated");
+ }
+ } as never,
+ eventOutboxRegistry: registry
+ });
+
+ await expect(service.emit(makeEvent(), TX)).rejects.toThrow("connection terminated");
+ });
+});
+
+describe("event outbox drain", () => {
+ const makeRow = (overrides?: Partial<TEventOutboxRow>): TEventOutboxRow =>
+ ({
+ id: 1,
+ consumer: "alert",
+ eventType: "approval.workflow.request_opened",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ orgId: ORG_ID,
+ projectId: null,
+ payload: { targetIds: ["req-1"] },
+ idempotencyKey: null,
+ occurredAt: new Date(),
+ status: EventOutboxStatus.Processing,
+ attempts: 0,
+ nextRetryAt: new Date(),
+ lockedAt: new Date(),
+ progress: null,
+ lastError: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides
+ }) as TEventOutboxRow;
+
+ const buildDrain = (opts: {
+ batches: TEventOutboxRow[][];
+ handle: IEventOutboxConsumer["handle"];
+ consumerName?: string;
+ }) => {
+ const registry = eventOutboxRegistryFactory();
+ registry.register(makeConsumer({ name: opts.consumerName ?? "alert", handle: opts.handle }));
+
+ const commits: {
+ delivered: { ids: string[]; progress?: unknown }[];
+ retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];
+ failed: { ids: string[]; error?: string }[];
+ }[] = [];
+ const extended: string[][] = [];
+ let batchIdx = 0;
+
+ const service = eventOutboxServiceFactory({
+ eventOutboxDAL: {
+ claimBatch: async () => {
+ const batch = opts.batches[batchIdx] ?? [];
+ batchIdx += 1;
+ return batch;
+ },
+ extendClaims: async (ids: string[]) => {
+ extended.push(ids);
+ },
+ commitResults: async (input: never) => {
+ commits.push(input);
+ }
+ } as never,
+ eventOutboxRegistry: registry
+ });
+
+ return { service, commits, extended };
+ };
+
+ const KEY = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
+
+ test("commits a delivered result and stops when a claim comes back empty", async () => {
+ const { service, commits } = buildDrain({
+ batches: [[makeRow()]],
+ handle: async (rows) => rows.map((row) => ({ id: String(row.id), status: EventOutboxStatus.Delivered }))
+ });
+
+ const result = await service.drain({
+ consumer: "alert",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1"
+ });
+
+ expect(result.handled).toBe(1);
+ expect(commits[0].delivered).toEqual([{ ids: ["1"], progress: undefined }]);
+ });
+
+ // A consumer that throws must not lose the batch: every row goes back for another attempt.
+ test("retries the whole batch when the consumer throws", async () => {
+ const { service, commits } = buildDrain({
+ batches: [[makeRow()]],
+ handle: async () => {
+ throw new Error("provider exploded");
+ }
+ });
+
+ await service.drain({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" });
+
+ expect(commits[0].retriable[0].ids).toEqual(["1"]);
+ expect(commits[0].delivered).toEqual([]);
+ });
+
+ // Otherwise a consumer that quietly returns nothing would leave rows stuck in 'processing' until
+ // the stale-claim sweeper noticed, which looks identical to a crashed worker.
+ test("retries a row the consumer returned no result for", async () => {
+ const { service, commits } = buildDrain({ batches: [[makeRow()]], handle: async () => [] });
+
+ await service.drain({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" });
+
+ expect(commits[0].retriable[0].ids).toEqual(["1"]);
+ });
+
+ test("fails a row terminally once it has used up its attempts", async () => {
+ const { service, commits } = buildDrain({
+ batches: [[makeRow({ attempts: 4 })]],
+ handle: async (rows) => rows.map((row) => ({ id: String(row.id), status: EventOutboxStatus.Retry })),
+ consumerName: "alert"
+ });
+
+ await service.drain({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" });
+
+ expect(commits[0].failed[0].ids).toEqual(["1"]);
+ expect(commits[0].retriable).toEqual([]);
+ });
+
+ // One UPDATE per distinct outcome, not one per row: a batch of a hundred deliveries is a single
+ // statement, and the retry delay is shared by rows on the same attempt so they group too.
+ test("groups rows that share an outcome into one commit entry", async () => {
+ const { service, commits } = buildDrain({
+ batches: [[makeRow({ id: 1 }), makeRow({ id: 2 }), makeRow({ id: 3 }), makeRow({ id: 4 })]],
+ handle: async (rows) =>
+ rows.map((row) =>
+ Number(row.id) <= 2
+ ? { id: String(row.id), status: EventOutboxStatus.Delivered }
+ : { id: String(row.id), status: EventOutboxStatus.Retry, error: "slack 502" }
+ )
+ });
+
+ await service.drain(KEY);
+
+ expect(commits[0].delivered).toEqual([{ ids: ["1", "2"], progress: undefined }]);
+ expect(commits[0].retriable).toHaveLength(1);
+ expect(commits[0].retriable[0].ids).toEqual(["3", "4"]);
+ expect(commits[0].retriable[0].error).toBe("slack 502");
+ });
+
+ test("keeps rows with different progress in separate commit entries", async () => {
+ const { service, commits } = buildDrain({
+ batches: [[makeRow({ id: 1 }), makeRow({ id: 2 })]],
+ handle: async (rows) =>
+ rows.map((row) => ({
+ id: String(row.id),
+ status: EventOutboxStatus.Delivered,
+ progress: { deliveredChannelIds: [`c-${row.id}`] }
+ }))
+ });
+
+ await service.drain(KEY);
+
+ expect(commits[0].delivered.map((group) => group.ids)).toEqual([["1"], ["2"]]);
+ });
+
+ // A batch that legitimately outlives the sweeper's threshold (a slow webhook, many rows) must keep
+ // its claim fresh, or the sweeper hands the same rows to a second worker mid-delivery.
+ test("extends the claim while the consumer is still handling a batch", async () => {
+ vi.useFakeTimers();
+ try {
+ let release: () => void = () => {};
+ const { service, extended } = buildDrain({
+ batches: [[makeRow({ id: 1 }), makeRow({ id: 2 })]],
+ handle: (rows) =>
+ new Promise((resolve) => {
+ release = () =>
+ resolve(rows.map((row) => ({ id: String(row.id), status: EventOutboxStatus.Delivered as const })));
+ })
+ });
+
+ const draining = service.drain(KEY);
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(extended.length).toBeGreaterThanOrEqual(3);
+ expect(extended[0]).toEqual(["1", "2"]);
+
+ release();
+ await draining;
+
+ const afterRelease = extended.length;
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(extended.length).toBe(afterRelease);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("leaves rows untouched when no consumer is registered under the key", async () => {
+ const { service, commits } = buildDrain({ batches: [[makeRow()]], handle: async () => [] });
+
+ const result = await service.drain({
+ consumer: "gone",
+ resourceType: "approval.workflow",
+ resourceId: "policy-1"
+ });
+
+ expect(result.unknownConsumer).toBe(true);
+ expect(commits).toHaveLength(0);
+ });
+});
diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.ts
new file mode 100644
index 0000000000..32ee696178
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-service.ts
@@ -0,0 +1,297 @@
+import { Knex } from "knex";
+
+import { InternalServerError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { recordEventOutboxExhaustedMetric, recordEventOutboxLagMetric } from "@app/lib/telemetry/metrics";
+
+import { TEventOutboxDALFactory, TOutboxInsertRow } from "./event-outbox-dal";
+import { TEventOutboxRegistry } from "./event-outbox-registry";
+import {
+ DELIVERED_RETENTION_MS,
+ EventOutboxStatus,
+ FAILED_RETENTION_MS,
+ IEventOutboxConsumer,
+ MAX_BATCHES_PER_FLUSH,
+ MAX_OUTBOX_ATTEMPTS,
+ MAX_OUTBOX_PAYLOAD_BYTES,
+ OUTBOX_BACKOFF_BASE_MS,
+ OUTBOX_CLAIM_BATCH_SIZE,
+ OutboxEventSchema,
+ STALE_CLAIM_THRESHOLD_MS,
+ TEventOutboxRow,
+ TOutboxEvent,
+ TOutboxFlushKey,
+ TOutboxRowResult
+} from "./event-outbox-types";
+
+const PRUNE_BATCH_SIZE = 5_000;
+const PRUNE_MAX_BATCHES = 20;
+
+// Well inside the sweeper's threshold, so a heartbeat can be missed once (a slow query, a paused event
+// loop) without the claim going stale.
+const CLAIM_HEARTBEAT_INTERVAL_MS = STALE_CLAIM_THRESHOLD_MS / 4;
+
+const computeBackoffMs = (attemptsAfterIncrement: number): number => {
+ const exponent = Math.min(attemptsAfterIncrement - 1, 10);
+ const base = OUTBOX_BACKOFF_BASE_MS * 2 ** exponent;
+ const jitter = Math.floor(Math.random() * Math.min(base / 2, 30_000));
+ return base + jitter;
+};
+
+const formatIssues = (issues: { path: (string | number)[]; message: string }[]) =>
+ issues.map((issue) => `${issue.path.join(".")} ${issue.message}`).join(", ");
+
+// Groups rows that share an outcome so commitResults issues one UPDATE per distinct outcome rather than
+// one per row.
+const groupByOutcome = <TItem extends { id: string }>(
+ items: TItem[],
+ keyOf: (item: TItem) => string
+): (Omit<TItem, "id"> & { ids: string[] })[] => {
+ const groups = new Map<string, Omit<TItem, "id"> & { ids: string[] }>();
+ for (const item of items) {
+ const key = keyOf(item);
+ const group = groups.get(key);
+ if (group) {
+ group.ids.push(item.id);
+ } else {
+ const { id, ...rest } = item;
+ groups.set(key, { ...rest, ids: [id] });
+ }
+ }
+ return [...groups.values()];
+};
+
+export type TEventOutboxServiceFactoryDep = {
+ eventOutboxDAL: TEventOutboxDALFactory;
+ eventOutboxRegistry: TEventOutboxRegistry;
+};
+
+export type TEventOutboxServiceFactory = ReturnType<typeof eventOutboxServiceFactory>;
+
+export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry }: TEventOutboxServiceFactoryDep) => {
+ // Records an event as part of the caller's unit of work. `tx` is required rather than optional:
+ // the whole point is that the row commits with the business write, so there is deliberately no
+ // weaker path to reach for.
+ //
+ // Nothing here reads the database. Validation and consumer matching are in-memory, so the only
+ // statement this adds to the caller's transaction is one insert. Whether any customer actually
+ // wants a given event is decided later, in the worker: guessing wrong costs a row that is marked
+ // delivered and pruned, which is a far better trade than letting a consumer run a query inside a
+ // transaction it knows nothing about.
+ //
+ // The insert is not caught. Postgres aborts a whole transaction on a failed statement, so
+ // swallowing it would hand the caller a poisoned transaction (25P02 on its next statement)
+ // instead of the real error, and a row that cannot be written means the operation did not happen.
+ //
+ // Validation failures are 500s, not 400s: the event is built by our code from data that already
+ // passed the route's own validation, so a rejected event is a bug at the emit site and nothing the
+ // API caller can act on.
+ const emit = async (event: TOutboxEvent, tx: Knex): Promise<void> => {
+ const parsed = OutboxEventSchema.safeParse(event);
+ if (!parsed.success) {
+ throw new InternalServerError({
+ name: "EventOutboxInvalidEvent",
+ message: `Invalid outbox event: ${formatIssues(parsed.error.issues)}`
+ });
+ }
+ const validated = parsed.data;
+
+ const payloadBytes = Buffer.byteLength(JSON.stringify(validated.payload), "utf8");
+ if (payloadBytes > MAX_OUTBOX_PAYLOAD_BYTES) {
+ throw new InternalServerError({
+ name: "EventOutboxPayloadTooLarge",
+ message: `Outbox event payload for '${validated.eventType}' is ${payloadBytes} bytes, over the ${MAX_OUTBOX_PAYLOAD_BYTES} byte limit. The outbox carries identifiers, not documents.`
+ });
+ }
+
+ const subscribers = eventOutboxRegistry.subscribersOf(validated.eventType);
+ if (subscribers.length === 0) return;
+
+ const occurredAt = validated.occurredAt ?? new Date();
+
+ const rows: TOutboxInsertRow[] = subscribers.map((consumer) => {
+ const payload = consumer.payloadSchema.safeParse(validated.payload);
+ if (!payload.success) {
+ throw new InternalServerError({
+ name: "EventOutboxPayloadRejected",
+ message: `Outbox event '${validated.eventType}' has a payload the '${consumer.name}' consumer cannot accept: ${formatIssues(payload.error.issues)}`
+ });
+ }
+
+ return {
+ consumer: consumer.name,
+ eventType: validated.eventType,
+ resourceType: validated.resourceType,
+ resourceId: validated.resourceId,
+ orgId: validated.orgId,
+ projectId: validated.projectId ?? null,
+ payload: validated.payload,
+ idempotencyKey: validated.idempotencyKey ?? null,
+ occurredAt
+ };
+ });
+
+ await eventOutboxDAL.insertEvents(rows, tx);
+ };
+
+ const $applyResults = async (rows: TEventOutboxRow[], results: TOutboxRowResult[]): Promise<void> => {
+ const byId = new Map(results.map((result) => [result.id, result]));
+ const now = Date.now();
+
+ const delivered: { id: string; progress?: Record<string, unknown> | null }[] = [];
+ const retriable: {
+ id: string;
+ nextRetryDelayMs: number;
+ progress?: Record<string, unknown> | null;
+ error?: string;
+ }[] = [];
+ const failed: { id: string; error?: string }[] = [];
+ const backoffByAttempt = new Map<number, number>();
+
+ for (const row of rows) {
+ const id = String(row.id);
+ // A consumer that returned nothing for a row left it unaccounted for; retry rather than
+ // silently marking it delivered.
+ const result = byId.get(id) ?? {
+ id,
+ status: EventOutboxStatus.Retry as const,
+ error: "Consumer returned no result for this event"
+ };
+
+ const attempts = row.attempts + 1;
+ let finalStatus: TOutboxRowResult["status"];
+ if (result.status === EventOutboxStatus.Delivered) {
+ finalStatus = EventOutboxStatus.Delivered;
+ delivered.push({ id, progress: result.progress });
+ } else if (result.status === EventOutboxStatus.Failed || attempts >= MAX_OUTBOX_ATTEMPTS) {
+ finalStatus = EventOutboxStatus.Failed;
+ failed.push({ id, error: result.error });
+ } else {
+ finalStatus = EventOutboxStatus.Retry;
+ let nextRetryDelayMs = backoffByAttempt.get(attempts);
+ if (nextRetryDelayMs === undefined) {
+ nextRetryDelayMs = computeBackoffMs(attempts);
+ backoffByAttempt.set(attempts, nextRetryDelayMs);
+ }
+ retriable.push({ id, nextRetryDelayMs, progress: result.progress, error: result.error });
+ }
+
+ recordEventOutboxLagMetric({
+ consumer: row.consumer,
+ status: finalStatus,
+ seconds: (now - new Date(row.occurredAt).getTime()) / 1000
+ });
+ }
+
+ await eventOutboxDAL.commitResults({
+ delivered: groupByOutcome(delivered, (item) => JSON.stringify(item.progress ?? null)),
+ retriable: groupByOutcome(retriable, (item) =>
+ JSON.stringify([item.nextRetryDelayMs, item.error ?? null, item.progress ?? null])
+ ),
+ failed: groupByOutcome(failed, (item) => item.error ?? "")
+ });
+
+ if (failed.length > 0) {
+ const { consumer, resourceType, resourceId } = rows[0];
+ recordEventOutboxExhaustedMetric({ consumer, count: failed.length });
+ const reasons = [...new Set(failed.map((item) => item.error ?? "unknown"))].join(" | ");
+ logger.error(
+ `event-outbox: gave up on ${failed.length} event(s) [consumer=${consumer}] [resourceType=${resourceType}] [resourceId=${resourceId}]: ${reasons}`
+ );
+ }
+ };
+
+ // Runs the consumer against one claimed batch while keeping the claim fresh. The heartbeat is what
+ // lets a batch legitimately outlive STALE_CLAIM_THRESHOLD_MS (a slow webhook endpoint, many rows)
+ // without the sweeper handing its rows to a second worker mid-delivery.
+ const $handleClaimed = async (
+ consumer: IEventOutboxConsumer,
+ key: TOutboxFlushKey,
+ claimed: TEventOutboxRow[]
+ ): Promise<TOutboxRowResult[]> => {
+ const ids = claimed.map((row) => String(row.id));
+ const heartbeat = setInterval(() => {
+ eventOutboxDAL.extendClaims(ids).catch((error) => {
+ logger.warn(
+ error,
+ `event-outbox: failed to extend a claim [consumer=${key.consumer}] [resourceType=${key.resourceType}] [resourceId=${key.resourceId}]`
+ );
+ });
+ }, CLAIM_HEARTBEAT_INTERVAL_MS);
+
+ try {
+ return await consumer.handle(claimed);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Unknown error";
+ logger.error(
+ error,
+ `event-outbox: consumer '${key.consumer}' threw while handling a batch [resourceType=${key.resourceType}] [resourceId=${key.resourceId}]`
+ );
+ return claimed.map((row) => ({ id: String(row.id), status: EventOutboxStatus.Retry as const, error: message }));
+ } finally {
+ clearInterval(heartbeat);
+ }
+ };
+
+ // Worker entrypoint for one flush key. Loops claim -> handle -> commit while rows remain, bounded
+ // so one wedged resource cannot hold a worker indefinitely; whatever is left is picked up by the
+ // relay's next tick.
+ const drain = async (key: TOutboxFlushKey): Promise<{ handled: number; unknownConsumer: boolean }> => {
+ const consumer = eventOutboxRegistry.get(key.consumer);
+ if (!consumer) {
+ logger.error(
+ `event-outbox: no consumer registered under '${key.consumer}'; leaving its events untouched [resourceType=${key.resourceType}] [resourceId=${key.resourceId}]`
+ );
+ return { handled: 0, unknownConsumer: true };
+ }
+
+ let handled = 0;
+
+ for (let batch = 0; batch < MAX_BATCHES_PER_FLUSH; batch += 1) {
+ // eslint-disable-next-line no-await-in-loop -- batches are serial on purpose, to stay paced
+ const claimed = await eventOutboxDAL.claimBatch(key, OUTBOX_CLAIM_BATCH_SIZE);
+ if (claimed.length === 0) break;
+
+ // eslint-disable-next-line no-await-in-loop -- see above
+ const results = await $handleClaimed(consumer, key, claimed);
+ // eslint-disable-next-line no-await-in-loop -- see above
+ await $applyResults(claimed, results);
+ handled += claimed.length;
+ }
+
+ return { handled, unknownConsumer: false };
+ };
+
+ const sweepStaleClaims = async (): Promise<void> => {
+ const { retried, failed } = await eventOutboxDAL.recoverStaleClaims(STALE_CLAIM_THRESHOLD_MS, MAX_OUTBOX_ATTEMPTS);
+ if (retried > 0 || failed > 0) {
+ logger.warn(
+ `event-outbox: recovered stale claims [retried=${retried}] [failed=${failed}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`
+ );
+ }
+ };
+
+ const pruneTerminalRows = async (): Promise<void> => {
+ const now = Date.now();
+ let deleted = 0;
+
+ for (let batch = 0; batch < PRUNE_MAX_BATCHES; batch += 1) {
+ // eslint-disable-next-line no-await-in-loop -- batches must run serially to stay paced
+ const removed = await eventOutboxDAL.deleteTerminalOlderThan({
+ deliveredBefore: new Date(now - DELIVERED_RETENTION_MS),
+ failedBefore: new Date(now - FAILED_RETENTION_MS),
+ batchSize: PRUNE_BATCH_SIZE
+ });
+ deleted += removed;
+ if (removed < PRUNE_BATCH_SIZE) break;
+ }
+
+ if (deleted > 0) {
+ logger.info(`event-outbox: pruned terminal rows [deleted=${deleted}]`);
+ }
+ };
+
+ return { emit, drain, sweepStaleClaims, pruneTerminalRows };
+};
+
+export type TEventOutboxEmitter = Pick<TEventOutboxServiceFactory, "emit">;
diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.ts
new file mode 100644
index 0000000000..b219b8db7c
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-types.ts
@@ -0,0 +1,88 @@
+import { z } from "zod";
+
+import { TEventOutbox } from "@app/db/schemas";
+
+export enum EventOutboxStatus {
+ Pending = "pending",
+ Processing = "processing",
+ Retry = "retry",
+ Delivered = "delivered",
+ Failed = "failed"
+}
+
+export const MAX_OUTBOX_PAYLOAD_BYTES = 16 * 1024;
+
+export const MAX_OUTBOX_KEY_LENGTH = 255;
+
+export const RELAY_DISCOVERY_LIMIT = 200;
+
+export const OUTBOX_RELAY_INTERVAL_MS = 10_000;
+
+export const MAX_BATCHES_PER_FLUSH = 10;
+
+export const OUTBOX_CLAIM_BATCH_SIZE = 100;
+
+export const MAX_OUTBOX_ATTEMPTS = 5;
+
+export const OUTBOX_BACKOFF_BASE_MS = 30_000;
+
+export const STALE_CLAIM_THRESHOLD_MS = 10 * 60_000;
+
+export const DELIVERED_RETENTION_MS = 24 * 60 * 60_000;
+export const FAILED_RETENTION_MS = 30 * 24 * 60 * 60_000;
+
+const keySchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(MAX_OUTBOX_KEY_LENGTH)
+ .regex(/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/, "Must be lowercase and dot-namespaced, e.g. 'pki.certificate.issued'");
+
+export const OutboxEventSchema = z.object({
+ eventType: keySchema,
+ resourceType: keySchema,
+ resourceId: z.string().trim().min(1).max(MAX_OUTBOX_KEY_LENGTH),
+ orgId: z.string().uuid(),
+ projectId: z.string().trim().min(1).max(MAX_OUTBOX_KEY_LENGTH).nullish(),
+ payload: z.record(z.unknown()),
+ idempotencyKey: z.string().trim().min(1).max(MAX_OUTBOX_KEY_LENGTH).optional(),
+ occurredAt: z.date().optional()
+});
+
+export type TOutboxEvent = z.input<typeof OutboxEventSchema>;
+
+export type TEventOutboxRow = TEventOutbox;
+
+export type TOutboxRowResult = {
+ id: string;
+ status: EventOutboxStatus.Delivered | EventOutboxStatus.Retry | EventOutboxStatus.Failed;
+ error?: string;
+ // Persisted on the row and handed back on the next attempt, so a retry can resume rather than
+ // repeat. Opaque to the outbox.
+ progress?: Record<string, unknown> | null;
+};
+
+export type TOutboxFlushKey = {
+ consumer: string;
+ resourceType: string;
+ resourceId: string;
+};
+
+export interface IEventOutboxConsumer<TPayload = unknown> {
+ // Stored in every row and part of the flush job id. Renaming it orphans in-flight rows.
+ name: string;
+
+ // The body this consumer expects. Parsed at emit so a malformed event fails at its source rather
+ // than in a worker later. Must not be `.strict()`: one event can feed several consumers, so a
+ // schema has to tolerate fields it does not care about.
+ payloadSchema: z.ZodType<TPayload>;
+
+ // Called on the request path for every emit, so it must stay pure and in-memory. This is the only
+ // thing consulted before a row is written: whether *this* event is one anyone actually wants is
+ // decided in handle(), off the caller's transaction, where getting it wrong costs a throwaway row
+ // rather than the business write.
+ subscribesTo(eventType: string): boolean;
+
+ // Rows for a single (resourceType, resourceId), in id order. Returns one result per row.
+ handle(rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]>;
+}