Skip to content

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

move resource type and resource id into payload

Thiago Araujo da Silvaeba8444acb84
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 865f4bd97f..3942de91f7 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -710,11 +710,9 @@ await someDAL.transaction(async (tx) => {
await eventEmitter.emit(
{
eventType: "approval.workflow.request_opened",
- resourceType: "approval.workflow",
- resourceId: policyId,
orgId,
projectId,
- payload: { targetIds: [request.id] }
+ payload: { resourceType: "approval.workflow", resourceId: policyId, targetIds: [request.id] }
},
tx
);
@@ -746,9 +744,12 @@ await someDAL.transaction(async (tx) => {
result can't clear the new owner's lock or drop its outcome. `commitResults` returns how many rows it
settled and `drain` logs a short settle: that count is the only signal that a batch went out twice, since
the fence protects the bookkeeping but delivery stays at-least-once.
-- **Discovery only looks at consumers registered in this process.** Rows for any other name would sort
- first forever and, past the limit, hide every real key. They wait and show up on the oldest-pending
- gauge instead.
+- **The envelope carries only what the outbox queries on.** `consumer`, `eventType`, the retry and lock
+ columns, and the tenant pair (`orgId`, `projectId`) handed to every consumer. Which resource an event
+ is about lives in `payload` under a shape the consumer's `payloadSchema` declares; the outbox never
+ groups, filters or indexes on it.
+- **Discovery only looks at consumers registered in this process.** A row for any other name has nowhere
+ to go here. It waits and shows up on the oldest-pending gauge instead.
- **Don't let one event's failure escape `handle`.** The outbox retries the whole batch when `handle`
throws. Catch per event and report `Retry` for that event alone (see `alert-event-consumer.ts`).
- **BullMQ owns latency, not correctness.** `attempts: 1` on the flush job is intentional; retry lives
@@ -756,11 +757,14 @@ await someDAL.transaction(async (tx) => {
- **The relay is a `setInterval`, not a cron job.** It doesn't need exactly-once (`FOR UPDATE SKIP
LOCKED` plus the flush `jobId` make concurrent pollers safe) and it needs a sub-minute cadence the
cron manager can't give.
-- **Ordering is per resource and best-effort.** The flush `jobId` is keyed on
- `(consumer, resourceType, resourceId)` so one flush per aggregate runs at a time, and `claimBatch`
- sorts by `id` (re-sorting what `RETURNING` gives back, which is arbitrary). A row inside its backoff
- window is skipped, so a later row can overtake it. That's deliberate: blocking an aggregate behind its
- oldest failing row is the wrong trade for notifications. Don't promise strict ordering.
+- **Delivery is serial per consumer, and ordering is best-effort.** The flush `jobId` is the consumer
+ name, so one flush per consumer runs at a time and `drain` works through its backlog in bounded batches
+ (`MAX_BATCHES_PER_FLUSH` x `OUTBOX_CLAIM_BATCH_SIZE` per flush; the next relay tick picks up the rest).
+ `claimBatch` sorts by `id` (re-sorting what `RETURNING` gives back, which is arbitrary). A row inside
+ its backoff window is skipped, so a later row can overtake it. That's deliberate: blocking a consumer
+ behind its oldest failing row is the wrong trade for notifications. Don't promise strict ordering, and
+ don't add a partition key back until a consumer needs one: no consumer today depends on the order two
+ events for one resource arrive in, and each event is idempotent on its own through `progress`.
- **Delivery is at-least-once.** `commitResults` is retried in-process, since by then the consumer has
already sent; what's left is narrowed by `progress` and by the emitter's `idempotencyKey`.
@@ -769,9 +773,10 @@ stuck claim alike. `lag` and `exhausted.count` are recorded by the outbox, label
new consumer gets them for free.
**Adding an event-triggered alert** needs no outbox code: declare the event with
-`triggerType: AlertTriggerType.Event`, implement `findTargetsByIds`, and emit with the provider's
-`resourceType` and `payload: { targetIds, ...facts }`. A `resourceType` that doesn't declare the `eventType` fails
-the row terminally with both named, so a bad emit site shows up in the logs on its first event.
+`triggerType: AlertTriggerType.Event`, implement `findTargetsByIds`, and emit with
+`payload: { resourceType, resourceId, targetIds, ...facts }` where `resourceType` is the provider's. A
+`resourceType` that doesn't declare the `eventType` fails the row terminally with both named, so a bad
+emit site shows up in the logs on its first event.
**The event contract belongs to the domain that emits it, not to a consumer.** The identity auth method
event (key, resource type, change enum, payload schema, and the `emitIdentityAuthMethodChanged` helper)
diff --git a/backend/e2e-test/event-outbox.spec.ts b/backend/e2e-test/event-outbox.spec.ts
index 04283a1acc..884fb8701d 100644
--- a/backend/e2e-test/event-outbox.spec.ts
+++ b/backend/e2e-test/event-outbox.spec.ts
@@ -17,15 +17,13 @@ const dal = eventOutboxDALFactory(testDb as never);
const CONSUMER = `e2e-${randomUUID().slice(0, 8)}`;
const ORG_ID = randomUUID();
-const KEY = { consumer: CONSUMER, resourceType: "e2e.resource", resourceId: "res-1" };
+const KEY = { consumer: CONSUMER };
const makeRow = (overrides?: Partial<TOutboxInsertRow>): TOutboxInsertRow => ({
consumer: CONSUMER,
eventType: "e2e.resource.happened",
- resourceType: KEY.resourceType,
- resourceId: KEY.resourceId,
orgId: ORG_ID,
- payload: { targetIds: ["t-1"] },
+ payload: { resourceType: "e2e.resource", resourceId: "res-1", targetIds: ["t-1"] },
occurredAt: new Date(),
...overrides
});
@@ -121,22 +119,15 @@ describe("event outbox (postgres)", () => {
expect(failed.attempts).toBe(1);
expect(failed.lastError).toBe("bad payload");
- expect(await dal.findDueFlushKeys(10, [CONSUMER])).toEqual([]);
+ expect(await dal.findDueFlushKeys([CONSUMER])).toEqual([]);
});
- test("findDueFlushKeys groups due rows per resource and ignores consumers not asked for", async () => {
- await insert([
- makeRow(),
- makeRow(),
- makeRow({ resourceId: "res-2" }),
- makeRow({ consumer: `${CONSUMER}-other`, resourceId: "res-3" })
- ]);
+ test("findDueFlushKeys names each consumer with due rows once and ignores consumers not asked for", async () => {
+ await insert([makeRow(), makeRow(), makeRow(), makeRow({ consumer: `${CONSUMER}-other` })]);
- const keys = await dal.findDueFlushKeys(10, [CONSUMER]);
+ const keys = await dal.findDueFlushKeys([CONSUMER]);
- expect(keys).toHaveLength(2);
- expect(keys.map((key) => key.resourceId).sort()).toEqual(["res-1", "res-2"]);
- expect(keys.every((key) => key.consumer === CONSUMER)).toBe(true);
+ expect(keys).toEqual([{ consumer: CONSUMER }]);
});
test("recoverStaleClaims backs a live-looking claim off and fails an exhausted one", async () => {
diff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.ts
index eb468255ed..5783f1d9a6 100644
--- a/backend/src/db/migrations/20260908000000_event-outbox.ts
+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts
@@ -9,8 +9,6 @@ export async function up(knex: Knex): Promise<void> {
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");
t.jsonb("payload").notNullable();
@@ -27,11 +25,11 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true);
});
- // Backs discovery and the per-resource claim. `id` before `nextRetryAt` so the claim's ORDER BY
- // needs no sort node.
+ // Backs discovery and the claim. `id` before `nextRetryAt` so the claim's ORDER BY needs no sort
+ // node; `nextRetryAt` is there so rows still in backoff are skipped without touching the heap.
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"
- ON "${TableName.EventOutbox}" ("consumer", "resourceType", "resourceId", "id", "nextRetryAt")
+ ON "${TableName.EventOutbox}" ("consumer", "id", "nextRetryAt")
WHERE status IN ('pending', 'retry')
`);
diff --git a/backend/src/db/schemas/event-outbox.ts b/backend/src/db/schemas/event-outbox.ts
index 1df494dd0e..3aa420d4cd 100644
--- a/backend/src/db/schemas/event-outbox.ts
+++ b/backend/src/db/schemas/event-outbox.ts
@@ -11,8 +11,6 @@ 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(),
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 7c6a7f031e..45c4dd8c60 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -531,7 +531,7 @@ export type TQueueJobTypes = {
};
[QueueName.EventOutboxFlush]: {
name: QueueJobs.EventOutboxFlush;
- payload: { consumer: string; resourceType: string; resourceId: string };
+ payload: { consumer: string };
};
[QueueName.AuditReportGeneration]: {
name: QueueJobs.GenerateAuditReport;
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index a469ebb66b..bc86ee3fbb 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -14,15 +14,20 @@ const EVENT_TYPE = "approval.workflow.request_opened";
const makeAlert = (id: string) => ({ id, resourceType: "approval.workflow", orgId: ORG_ID }) as never;
+const makePayload = (overrides?: Record<string, unknown>) => ({
+ resourceType: "approval.workflow",
+ resourceId: "policy-1",
+ targetIds: ["req-1"],
+ ...overrides
+});
+
const makeEvent = (overrides?: Partial<TEvent>): TEvent =>
({
id: 1,
eventType: EVENT_TYPE,
- resourceType: "approval.workflow",
- resourceId: "policy-1",
orgId: ORG_ID,
projectId: null,
- payload: { targetIds: ["req-1"] },
+ payload: makePayload(),
occurredAt: new Date(),
progress: null,
...overrides
@@ -96,7 +101,7 @@ describe("alert event consumer", () => {
expect(result.status).toBe(EventResultStatus.Delivered);
expect(runs[0].targetIds).toEqual(["req-1"]);
// The provider sees everything the emitter wrote, not only the ids the consumer validated.
- expect(runs[0].payload).toEqual({ targetIds: ["req-1"] });
+ expect(runs[0].payload).toEqual(makePayload());
expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
});
@@ -134,7 +139,7 @@ describe("alert event consumer", () => {
test("fails terminally on an unreadable payload", async () => {
const { consumer } = buildConsumer();
- const [result] = await consumer.handle([makeEvent({ payload: { targetIds: [] } })]);
+ const [result] = await consumer.handle([makeEvent({ payload: makePayload({ targetIds: [] }) })]);
expect(result.status).toBe(EventResultStatus.Failed);
expect(result.error).toContain("Unreadable alert event payload");
@@ -160,7 +165,7 @@ describe("alert event consumer", () => {
test("fails terminally when no provider declares the event for that resource type", async () => {
const { consumer, runs, getLookups } = buildConsumer();
- const [result] = await consumer.handle([makeEvent({ resourceType: "pki.certificate" })]);
+ const [result] = await consumer.handle([makeEvent({ payload: makePayload({ resourceType: "pki.certificate" }) })]);
expect(result.status).toBe(EventResultStatus.Failed);
expect(result.error).toContain("pki.certificate");
@@ -201,22 +206,22 @@ describe("alert event consumer", () => {
const { consumer, getLookups } = buildConsumer();
await consumer.handle([
- makeEvent({ id: 1, payload: { targetIds: ["req-1"] } }),
- makeEvent({ id: 2, payload: { targetIds: ["req-2"] } }),
- makeEvent({ id: 3, payload: { targetIds: ["req-3"] } })
+ makeEvent({ id: 1, payload: makePayload({ targetIds: ["req-1"] }) }),
+ makeEvent({ id: 2, payload: makePayload({ targetIds: ["req-2"] }) }),
+ makeEvent({ id: 3, payload: makePayload({ targetIds: ["req-3"] }) })
]);
expect(getLookups()).toBe(1);
});
- // Events arrive in id order and share one resource, so handling them concurrently would deliver that
- // resource's events out of order.
+ // Events arrive in id order. Handling them concurrently would fan a whole batch of notifications out
+ // at once and deliver events for one resource out of order.
test("handles events serially, in the order given", async () => {
const { consumer, runs } = buildConsumer();
const results = await consumer.handle([
- makeEvent({ id: 1, payload: { targetIds: ["req-1"] } }),
- makeEvent({ id: 2, payload: { targetIds: ["req-2"] } })
+ makeEvent({ id: 1, payload: makePayload({ targetIds: ["req-1"] }) }),
+ makeEvent({ id: 2, payload: makePayload({ targetIds: ["req-2"] }) })
]);
expect(results.map((result) => result.id)).toEqual(["1", "2"]);
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index a37a6c3eae..74ced93733 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -15,12 +15,16 @@ import { AlertTriggerType, MAX_TARGET_IDS_PER_EVENT } from "./alert-types";
export const ALERT_EVENT_CONSUMER = "alert";
-// Emitters name targets by id and the provider rehydrates them at delivery. Keeping the payload to
-// ids is what lets one consumer serve every provider.
+// Emitters name the resource and its targets by id and the provider rehydrates them at delivery.
+// Keeping the payload to ids is what lets one consumer serve every provider.
export const AlertEventPayloadSchema = z.object({
+ resourceType: z.string().trim().min(1).max(255),
+ resourceId: z.string().trim().min(1).max(255),
targetIds: z.array(z.string().trim().min(1).max(255)).min(1).max(MAX_TARGET_IDS_PER_EVENT)
});
+type TAlertEventPayload = z.infer<typeof AlertEventPayloadSchema>;
+
const AlertEventProgressSchema = z.object({
deliveredChannelIds: z.array(z.string()).default([])
});
@@ -37,35 +41,36 @@ export const alertEventConsumerFactory = ({
alertDAL,
alertEngine,
alertProviderRegistry
-}: TAlertEventConsumerDep): IEventConsumer<z.infer<typeof AlertEventPayloadSchema>> => {
+}: TAlertEventConsumerDep): IEventConsumer<TAlertEventPayload> => {
const subscribesTo = (eventType: string): boolean => alertProviderRegistry.eventTriggeredKeys().has(eventType);
// subscribesTo only sees the event type, so a valid event key on the wrong resourceType gets past it.
// Fail here, terminally and naming both, instead of marking the event delivered as "no matching alert".
- const $isDeclaredEvent = (event: TEvent): boolean =>
+ const $isDeclaredEvent = (eventType: string, resourceType: string): boolean =>
Boolean(
alertProviderRegistry
- .get(event.resourceType)
- ?.events.some((declared) => declared.key === event.eventType && declared.triggerType === AlertTriggerType.Event)
+ .get(resourceType)
+ ?.events.some((declared) => declared.key === eventType && declared.triggerType === AlertTriggerType.Event)
);
const $handleEvent = async (event: TEvent, findAlerts: TAlertLookup): Promise<TEventConsumerResult> => {
const id = String(event.id);
- if (!$isDeclaredEvent(event)) {
+ const payload = AlertEventPayloadSchema.safeParse(event.payload);
+ if (!payload.success) {
return {
id,
status: EventResultStatus.Failed,
- error: `No alert provider for resource type '${event.resourceType}' declares '${event.eventType}' as an event-triggered alert`
+ error: `Unreadable alert event payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`
};
}
+ const { resourceType, resourceId, targetIds } = payload.data;
- const payload = AlertEventPayloadSchema.safeParse(event.payload);
- if (!payload.success) {
+ if (!$isDeclaredEvent(event.eventType, resourceType)) {
return {
id,
status: EventResultStatus.Failed,
- error: `Unreadable alert event payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`
+ error: `No alert provider for resource type '${resourceType}' declares '${event.eventType}' as an event-triggered alert`
};
}
@@ -75,16 +80,13 @@ export const alertEventConsumerFactory = ({
const alerts = await findAlerts({
orgId: event.orgId,
projectId: event.projectId,
- resourceType: event.resourceType,
- resourceId: event.resourceId,
+ resourceType,
+ resourceId,
eventType: event.eventType
});
if (alerts.length === 0) {
- recordAlertDispatchOutcomeMetric({
- resourceType: event.resourceType,
- outcome: AlertDispatchOutcome.NoMatchingAlert
- });
+ recordAlertDispatchOutcomeMetric({ resourceType, outcome: AlertDispatchOutcome.NoMatchingAlert });
return { id, status: EventResultStatus.Delivered };
}
@@ -94,7 +96,7 @@ export const alertEventConsumerFactory = ({
// eslint-disable-next-line no-await-in-loop -- at most a project- and an org-scoped alert
const result = await alertEngine.runAlertForEvent(alert, {
eventType: event.eventType,
- targetIds: payload.data.targetIds,
+ targetIds,
payload: (event.payload ?? {}) as Record<string, unknown>,
skipChannelIds: [...delivered]
});
diff --git a/backend/src/services/event-outbox/event-outbox-dal.test.ts b/backend/src/services/event-outbox/event-outbox-dal.test.ts
index a02a625e5c..ae7c460e12 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.test.ts
@@ -20,8 +20,7 @@ const buildDAL = (opts?: { returning?: unknown[]; updated?: number; selected?: u
insert: [] as unknown[],
onConflict: [] as unknown[],
ignored: 0,
- groupBy: [] as unknown[][],
- orderByRaw: [] as unknown[]
+ groupBy: [] as unknown[][]
};
// knex resolves an UPDATE to the affected row count and a SELECT to rows, and commitResults reads
@@ -55,10 +54,6 @@ const buildDAL = (opts?: { returning?: unknown[]; updated?: number; selected?: u
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;
@@ -126,10 +121,8 @@ describe("event outbox dal", () => {
{
consumer: "alert",
eventType: "approval.workflow.request_opened",
- resourceType: "approval.workflow",
- resourceId: "policy-1",
orgId: "org-1",
- payload: { targetIds: ["req-1"] },
+ payload: { resourceType: "approval.workflow", resourceId: "policy-1", targetIds: ["req-1"] },
occurredAt: new Date()
}
],
@@ -153,7 +146,7 @@ describe("event outbox dal", () => {
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);
+ await dal.claimBatch({ consumer: "alert" }, 100);
expect(calls.forUpdate).toBe(1);
expect(calls.skipLocked).toBe(1);
@@ -162,7 +155,7 @@ describe("event outbox dal", () => {
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);
+ await dal.claimBatch({ consumer: "alert" }, 100);
expect(calls.orderBy[0]).toEqual(["id", "asc"]);
});
@@ -172,10 +165,7 @@ describe("event outbox dal", () => {
test("claimBatch returns the claimed rows in id order regardless of how RETURNING ordered them", async () => {
const { dal } = buildDAL({ returning: [{ id: "8" }, { id: "6" }, { id: "10" }, { id: "7" }] });
- const { rows } = await dal.claimBatch(
- { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" },
- 10
- );
+ const { rows } = await dal.claimBatch({ consumer: "alert" }, 10);
expect(rows.map((row) => String(row.id))).toEqual(["6", "7", "8", "10"]);
});
@@ -183,7 +173,7 @@ describe("event outbox dal", () => {
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);
+ await dal.claimBatch({ consumer: "alert" }, 100);
expect(calls.update).toHaveLength(1);
expect(calls.update[0].status).toBe(EventOutboxStatus.Processing);
@@ -194,7 +184,7 @@ describe("event outbox dal", () => {
// rows and it has to differ per claim.
test("claimBatch stamps a fresh lockToken and hands it back", async () => {
const { dal, calls } = buildDAL();
- const key = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
+ const key = { consumer: "alert" };
const first = await dal.claimBatch(key, 100);
const second = await dal.claimBatch(key, 100);
@@ -228,29 +218,28 @@ describe("event outbox dal", () => {
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);
+ await dal.claimBatch({ consumer: "alert" }, 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 () => {
+ test("findDueFlushKeys reports each consumer with due work once", async () => {
const { dal, calls } = buildDAL();
- await dal.findDueFlushKeys(200, ["alert"]);
+ await dal.findDueFlushKeys(["alert"]);
- expect(calls.groupBy[0]).toEqual(["consumer", "resourceType", "resourceId"]);
- expect(calls.orderByRaw[0]).toBe('MIN("nextRetryAt") ASC');
- expect(calls.limit).toContain(200);
+ expect(calls.groupBy[0]).toEqual(["consumer"]);
+ expect(calls.whereIn).toContainEqual(["status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry]]);
+ expect(calls.andWhere[0][0]).toBe("nextRetryAt");
});
- // Rows for a consumer this process can't drain would otherwise sort first on every tick and, once
- // there are more of them than the limit, hide every real key behind them.
+ // A flush for a consumer this process hasn't registered has nothing to hand the rows to.
test("findDueFlushKeys only looks at consumers this process has registered", async () => {
const { dal, calls } = buildDAL();
- await dal.findDueFlushKeys(200, ["alert", "audit"]);
+ await dal.findDueFlushKeys(["alert", "audit"]);
expect(calls.whereIn).toContainEqual(["consumer", ["alert", "audit"]]);
});
@@ -258,7 +247,7 @@ describe("event outbox dal", () => {
test("findDueFlushKeys issues no statement when nothing is registered", async () => {
const { dal, calls } = buildDAL();
- await expect(dal.findDueFlushKeys(200, [])).resolves.toEqual([]);
+ await expect(dal.findDueFlushKeys([])).resolves.toEqual([]);
expect(calls.groupBy).toHaveLength(0);
});
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
index 3b0cab94fa..62106bcd5a 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -18,8 +18,6 @@ export type TOutboxClaim = {
export type TOutboxInsertRow = {
consumer: string;
eventType: string;
- resourceType: string;
- resourceId: string;
orgId: string;
projectId?: string | null;
payload: unknown;
@@ -47,7 +45,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
}
};
- const findDueFlushKeys = async (limit: number, consumers: string[]): Promise<TOutboxFlushKey[]> => {
+ const findDueFlushKeys = async (consumers: string[]): Promise<TOutboxFlushKey[]> => {
if (consumers.length === 0) return [];
try {
const rows = await db
@@ -55,10 +53,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
.whereIn("consumer", consumers)
.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");
+ .groupBy("consumer")
+ .select<TOutboxFlushKey[]>("consumer");
return rows;
} catch (error) {
@@ -77,7 +73,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
void qb
.select("id")
.from(TableName.EventOutbox)
- .where(key)
+ .where("consumer", key.consumer)
.whereIn("status", [EventOutboxStatus.Pending, EventOutboxStatus.Retry])
.andWhere("nextRetryAt", "<=", db.fn.now())
.orderBy("id", "asc")
diff --git a/backend/src/services/event-outbox/event-outbox-queue.test.ts b/backend/src/services/event-outbox/event-outbox-queue.test.ts
index 8a4fc85a24..36fadfb1cf 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.test.ts
@@ -33,7 +33,7 @@ beforeEach(() => {
loggedErrors.length = 0;
});
-const KEY: TOutboxFlushKey = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
+const KEY: TOutboxFlushKey = { consumer: "alert" };
type TFlushHandler = (job: { data: TOutboxFlushKey }) => Promise<void>;
@@ -64,7 +64,7 @@ const buildQueue = (opts?: {
} as never,
eventOutboxRegistry: { names: () => ["alert", "audit"] },
eventOutboxDAL: {
- findDueFlushKeys: async (_limit: number, consumers: string[]) => {
+ findDueFlushKeys: async (consumers: string[]) => {
discoverCalls += 1;
discoveredFor.push(consumers);
if (opts?.onDiscover) await opts.onDiscover();
@@ -98,8 +98,8 @@ describe("event outbox relay", () => {
expect(discoveredFor).toEqual([["alert", "audit"]]);
});
- test("enqueues one flush job per discovered key", async () => {
- const { factory, queued } = buildQueue({ keys: [KEY, { ...KEY, resourceId: "policy-2" }] });
+ test("enqueues one flush job per consumer with due work", async () => {
+ const { factory, queued } = buildQueue({ keys: [KEY, { consumer: "audit" }] });
await factory.runRelayTick();
@@ -108,25 +108,14 @@ describe("event outbox relay", () => {
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 a
- // key the relay rediscovers while its flush is still queued.
- test("keys the job per aggregate so flushes for one resource cannot overlap", async () => {
+ // One flush per consumer at a time is what keeps drain's batches serial, and it dedupes a consumer
+ // the relay rediscovers while its flush is still queued.
+ test("keys the job per consumer so two flushes for one consumer 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 ':', and under Promise.all that fails the whole tick, on
- // every tick, for as long as the row sits pending.
- 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(":");
+ expect(queued[0].jobId).toBe("outbox-flush-alert");
});
// Retry lives on the outbox row, where it's inspectable and survives a Redis flush. BullMQ retrying
@@ -191,7 +180,7 @@ describe("event outbox relay", () => {
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0][0]).toBe(boom);
- expect(loggedErrors[0][1]).toContain("policy-1");
+ expect(loggedErrors[0][1]).toContain("consumer=alert");
});
test("stops cleanly when nothing was ever started", async () => {
diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.ts
index a426a33137..28326792f8 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.ts
@@ -7,7 +7,7 @@ import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TEventOutboxDALFactory } from "./event-outbox-dal";
import { TEventOutboxRegistry } from "./event-outbox-registry";
import { TEventOutboxServiceFactory } from "./event-outbox-service";
-import { OUTBOX_RELAY_INTERVAL_MS, RELAY_DISCOVERY_LIMIT, TOutboxFlushKey } from "./event-outbox-types";
+import { OUTBOX_RELAY_INTERVAL_MS, TOutboxFlushKey } from "./event-outbox-types";
const FLUSH_WORKER_CONCURRENCY = 10;
@@ -34,7 +34,6 @@ export const eventOutboxQueueFactory = ({
}: TEventOutboxQueueFactoryDep) => {
const appCfg = getConfig();
- let lastDiscoveryCount = 0;
let oldestPendingByConsumer: { consumer: string; ageSeconds: number }[] = [];
const $registerGauges = () => {
@@ -51,33 +50,18 @@ export const eventOutboxQueueFactory = ({
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 (!appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) return;
- result.observe(lastDiscoveryCount);
- });
};
const $enqueueFlush = async (key: TOutboxFlushKey) =>
queueService.queue(QueueName.EventOutboxFlush, QueueJobs.EventOutboxFlush, key, {
- jobId: `outbox-flush-${key.consumer}-${key.resourceType}-${encodeURIComponent(key.resourceId)}`,
+ jobId: `outbox-flush-${key.consumer}`,
removeOnComplete: true,
removeOnFail: true,
attempts: 1
});
const runRelayTick = async () => {
- const keys = await eventOutboxDAL.findDueFlushKeys(RELAY_DISCOVERY_LIMIT, eventOutboxRegistry.names());
- 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`);
- }
+ const keys = await eventOutboxDAL.findDueFlushKeys(eventOutboxRegistry.names());
if (keys.length > 0) {
await Promise.all(keys.map((key) => $enqueueFlush(key)));
@@ -107,15 +91,12 @@ export const eventOutboxQueueFactory = ({
queueService.start(
QueueName.EventOutboxFlush,
async (job) => {
- const { consumer, resourceType, resourceId } = job.data;
+ const { consumer } = job.data;
try {
- await eventOutboxService.drain({ consumer, resourceType, resourceId });
+ await eventOutboxService.drain({ consumer });
} catch (error) {
// The job is removeOnFail with a single attempt, so this line is the only trace it leaves.
- logger.error(
- error,
- `event-outbox: flush worker crashed [consumer=${consumer}] [resourceType=${resourceType}] [resourceId=${resourceId}]`
- );
+ logger.error(error, `event-outbox: flush worker crashed [consumer=${consumer}]`);
throw error;
}
},
diff --git a/backend/src/services/event-outbox/event-outbox-service.test.ts b/backend/src/services/event-outbox/event-outbox-service.test.ts
index dd75fa7960..cf11e32204 100644
--- a/backend/src/services/event-outbox/event-outbox-service.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts
@@ -31,10 +31,8 @@ const ORG_ID = "11111111-1111-1111-1111-111111111111";
const makeEvent = (overrides?: Partial<TEventInput>): TEventInput => ({
eventType: "approval.workflow.request_opened",
- resourceType: "approval.workflow",
- resourceId: "policy-1",
orgId: ORG_ID,
- payload: { targetIds: ["req-1"] },
+ payload: { resourceType: "approval.workflow", resourceId: "policy-1", targetIds: ["req-1"] },
...overrides
});
@@ -151,11 +149,9 @@ describe("event outbox drain", () => {
id: 1,
consumer: "alert",
eventType: "approval.workflow.request_opened",
- resourceType: "approval.workflow",
- resourceId: "policy-1",
orgId: ORG_ID,
projectId: null,
- payload: { targetIds: ["req-1"] },
+ payload: { resourceType: "approval.workflow", resourceId: "policy-1", targetIds: ["req-1"] },
idempotencyKey: null,
occurredAt: new Date(),
status: EventOutboxStatus.Processing,
@@ -219,7 +215,7 @@ describe("event outbox drain", () => {
return { service, commits, extended, claimTokens };
};
- const KEY = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
+ const KEY = { consumer: "alert" };
test("commits a delivered result and stops when a claim comes back empty", async () => {
const { service, commits } = buildDrain({
@@ -227,11 +223,7 @@ describe("event outbox drain", () => {
handle: async (rows) => rows.map((row) => ({ id: String(row.id), status: EventResultStatus.Delivered }))
});
- const result = await service.drain({
- consumer: "alert",
- resourceType: "approval.workflow",
- resourceId: "policy-1"
- });
+ const result = await service.drain(KEY);
expect(result.handled).toBe(1);
expect(commits[0].delivered).toEqual([{ ids: ["1"], progress: undefined }]);
@@ -246,7 +238,7 @@ describe("event outbox drain", () => {
}
});
- await service.drain({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" });
+ await service.drain(KEY);
expect(commits[0].retriable[0].ids).toEqual(["1"]);
expect(commits[0].delivered).toEqual([]);
@@ -257,7 +249,7 @@ describe("event outbox drain", () => {
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" });
+ await service.drain(KEY);
expect(commits[0].retriable[0].ids).toEqual(["1"]);
});
@@ -269,7 +261,7 @@ describe("event outbox drain", () => {
consumerName: "alert"
});
- await service.drain({ consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" });
+ await service.drain(KEY);
expect(commits[0].failed[0].ids).toEqual(["1"]);
expect(commits[0].retriable).toEqual([]);
@@ -386,11 +378,7 @@ describe("event outbox drain", () => {
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"
- });
+ const result = await service.drain({ consumer: "gone" });
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
index d6a67d6599..05bb5080fd 100644
--- a/backend/src/services/event-outbox/event-outbox-service.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.ts
@@ -110,8 +110,6 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
return {
consumer: consumer.name,
eventType: validated.eventType,
- resourceType: validated.resourceType,
- resourceId: validated.resourceId,
orgId: validated.orgId,
projectId: validated.projectId ?? null,
payload: validated.payload,
@@ -124,7 +122,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
};
const $commitWithRetry = async (
- { consumer, resourceType, resourceId }: TOutboxFlushKey,
+ { consumer }: TOutboxFlushKey,
input: Parameters<TEventOutboxDALFactory["commitResults"]>[0]
): Promise<number> => {
for (let attempt = 1; ; attempt += 1) {
@@ -135,7 +133,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
if (attempt >= COMMIT_ATTEMPTS) throw error;
logger.warn(
error,
- `event-outbox: failed to commit results, retrying [attempt=${attempt}] [consumer=${consumer}] [resourceType=${resourceType}] [resourceId=${resourceId}]`
+ `event-outbox: failed to commit results, retrying [attempt=${attempt}] [consumer=${consumer}]`
);
// eslint-disable-next-line no-await-in-loop -- see above
await sleep(COMMIT_RETRY_DELAY_MS * attempt);
@@ -204,20 +202,17 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
failed: groupByOutcome(failed, (item) => item.error ?? "")
});
+ const { consumer } = rows[0];
if (settled < rows.length) {
- const { consumer, resourceType, resourceId } = rows[0];
logger.warn(
- `event-outbox: settled ${settled} of ${rows.length} row(s); the rest were no longer held by this claim [consumer=${consumer}] [resourceType=${resourceType}] [resourceId=${resourceId}]`
+ `event-outbox: settled ${settled} of ${rows.length} row(s); the rest were no longer held by this claim [consumer=${consumer}]`
);
}
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}`
- );
+ logger.error(`event-outbox: gave up on ${failed.length} event(s) [consumer=${consumer}]: ${reasons}`);
}
};
@@ -231,10 +226,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
const ids = claimed.map((row) => String(row.id));
const heartbeat = setInterval(() => {
eventOutboxDAL.extendClaims(ids, lockToken).catch((error) => {
- logger.warn(
- error,
- `event-outbox: failed to extend a claim [consumer=${key.consumer}] [resourceType=${key.resourceType}] [resourceId=${key.resourceId}]`
- );
+ logger.warn(error, `event-outbox: failed to extend a claim [consumer=${key.consumer}]`);
});
}, CLAIM_HEARTBEAT_INTERVAL_MS);
@@ -242,23 +234,18 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
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}]`
- );
+ logger.error(error, `event-outbox: consumer '${key.consumer}' threw while handling a batch`);
return claimed.map((row) => ({ id: String(row.id), status: EventResultStatus.Retry, error: message }));
} finally {
clearInterval(heartbeat);
}
};
- // Bounded so one busy resource can't hold a worker forever; the relay's next tick picks up the rest.
+ // Bounded so a deep backlog can't hold a worker forever; the relay's next tick picks up the rest.
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}]`
- );
+ logger.error(`event-outbox: no consumer registered under '${key.consumer}'; leaving its events untouched`);
return { handled: 0, unknownConsumer: true };
}
diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.ts
index 939f86f02b..76d8271740 100644
--- a/backend/src/services/event-outbox/event-outbox-types.ts
+++ b/backend/src/services/event-outbox/event-outbox-types.ts
@@ -16,8 +16,6 @@ export const MAX_OUTBOX_PAYLOAD_BYTES = 16 * 1024;
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;
@@ -52,8 +50,6 @@ const keySchema = z
export const EventInputSchema = 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()),
@@ -70,7 +66,7 @@ export type TEventEmitter = {
// What a consumer sees. Lock, attempt, and status columns are the outbox's business, not the consumer's.
export type TEvent = Pick<
TEventOutbox,
- "id" | "eventType" | "resourceType" | "resourceId" | "orgId" | "projectId" | "payload" | "progress" | "occurredAt"
+ "id" | "eventType" | "orgId" | "projectId" | "payload" | "progress" | "occurredAt"
>;
export enum EventResultStatus {
@@ -89,8 +85,6 @@ export type TEventConsumerResult = {
export type TOutboxFlushKey = {
consumer: string;
- resourceType: string;
- resourceId: string;
};
export interface IEventConsumer<TPayload = unknown> {
@@ -105,6 +99,7 @@ export interface IEventConsumer<TPayload = unknown> {
// wants the event is decided later, in handle().
subscribesTo(eventType: string): boolean;
- // Events for a single (resourceType, resourceId), in id order. Must return one result per event.
+ // Due events for this consumer, oldest first by id. One flush runs per consumer at a time, so
+ // within a flush a batch is ordered; across flushes nothing is promised. Must return one result per event.
handle(events: TEvent[]): Promise<TEventConsumerResult[]>;
}
diff --git a/backend/src/services/identity/identity-auth-method-events.ts b/backend/src/services/identity/identity-auth-method-events.ts
index 04200c0024..f303ba1794 100644
--- a/backend/src/services/identity/identity-auth-method-events.ts
+++ b/backend/src/services/identity/identity-auth-method-events.ts
@@ -44,11 +44,11 @@ export const emitIdentityAuthMethodChanged = (
eventEmitter.emit(
{
eventType: IDENTITY_AUTH_METHOD_CHANGED_EVENT,
- resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
- resourceId: membership.identity.id,
orgId: membership.scopeOrgId,
projectId: membership.identity.projectId,
payload: {
+ resourceType: IDENTITY_AUTHENTICATION_RESOURCE_TYPE,
+ resourceId: membership.identity.id,
targetIds: [membership.identity.id],
authMethod,
change,