Skip to content

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

fix comments

Thiago Araujo da Silva5e0e657c1ea0
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 5ab73c3b74..feabd0a9fe 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -610,7 +610,7 @@ 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`), 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`).
+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 need nothing 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.
@@ -618,7 +618,7 @@ That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS
**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.
+- `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.
@@ -634,19 +634,18 @@ 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)
+### Event Outbox (transactional and 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.
+participate in a Postgres commit, so enqueueing after commit instead 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.
+on the shared registry; anything else needing 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
+**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
@@ -666,87 +665,76 @@ await someDAL.transaction(async (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 |
+**Only `subscribesTo(eventType)` is consulted before a row is written**, a pure in-memory check for
+"is this event type handled at all". Whether a customer configured anything for *this* resource is
+settled later, in the worker, so `emit` adds exactly one statement to the caller's transaction and
+never calls back into a consumer. 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.
+
+**Nothing in `emit` is caught.** A swallowed insert failure 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:
+that emit site is statically wrong and fails on the first request in dev, which beats dropping a
+notification over a misspelled field. Both checks run before any database access, so neither can poison
+the transaction.
+
+**The row owns the retry state machine** (`attempts`, `nextRetryAt`, backoff, terminal `failed`) and the
+outbox owns the lag and exhausted metrics. `consumer.handle` owns delivery and what "delivered" means,
+reporting per row: `Delivered` / `Retry` / `Failed` plus `progress`.
**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`
+legitimately outlive that (one slow webhook endpoint timing 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.
+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.
+`handle` throws, because it cannot 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.
+lives on the outbox row, where an operator can query it and where it survives a Redis flush. A failed
+enqueue leaves the row `pending` for the next relay tick, so a lost job costs one interval.
**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.
+work goes through the cron manager. That rule exists to prevent duplicate execution, which the cron
+manager buys with slot election plus redlocks. This relay does not need exactly-once, because
+`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
+`(consumer, resourceType, resourceId)`, so at most one flush per aggregate runs at a time: never
+parallelize publishing within one aggregate, even though `SKIP LOCKED` makes it safe across different
+ones. Within a claim, `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 the id 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.
+One gap remains by choice: a row inside its backoff window is not eligible, so a later row for the same
+resource can be delivered first. Closing it would mean blocking the whole aggregate behind its oldest
+undelivered row, trading 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
+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.
+**Watch `infisical.event_outbox.oldest_pending_age`.** It is the canonical 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
+`eventOutbox.emit` with `resourceType` equal to the provider's and `payload: { targetIds }`. When the
+emitted `resourceType` does not declare that `eventType`, the alert consumer fails the row terminally
+with both halves named, 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
diff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.ts
index 7854be6790..f1e1a433cc 100644
--- a/backend/src/db/migrations/20260908000000_event-outbox.ts
+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts
@@ -14,7 +14,7 @@ export async function up(knex: Knex): Promise<void> {
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.
+ // Opaque here: 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());
@@ -29,9 +29,9 @@ export async function up(knex: Knex): Promise<void> {
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.
+ // Backs both the relay's discovery query and the per-resource claim. `id` comes before
+ // `nextRetryAt` so the claim's ORDER BY needs no sort node, and discovery's MIN() still gets
+ // answered from the index.
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"
ON "${TableName.EventOutbox}" ("consumer", "resourceType", "resourceId", "id", "nextRetryAt")
@@ -44,9 +44,9 @@ export async function up(knex: Knex): Promise<void> {
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.
+ // Backs the oldest-pending health gauge, which runs on every relay tick forever. Without it the
+ // gauge seq-scans the whole table for a handful of rows, at a cost that tracks the delivered
+ // backlog rather than the work outstanding.
await knex.schema.raw(`
CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_undelivered_idx"
ON "${TableName.EventOutbox}" ("consumer", "occurredAt")
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 4187f290de..45d537d437 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -724,8 +724,7 @@ export enum AlertDispatchOutcome {
AlertDisabled = "alert_disabled",
// No provider registered for the alert's resource type (misconfiguration).
NoProvider = "no_provider",
- // 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).
+ // Nothing to alert on: nothing matched the condition, or the targets an event named are gone.
NoDueTargets = "no_due_targets",
// The alert has no enabled channels, so the run is skipped before scanning for targets.
NoChannels = "no_channels",
@@ -735,8 +734,8 @@ export enum AlertDispatchOutcome {
NoRecipients = "no_recipients",
// Targets matched, but every one had already been alerted inside the dedup window.
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.
+ // Event path only: the event reached the worker with no alert configured for it. Expected in steady
+ // state, but a rate of zero everywhere means emits are wired up and alerts are not.
NoMatchingAlert = "no_matching_alert"
}
@@ -755,9 +754,8 @@ 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.
+// The outbox's own health, as opposed to what a consumer does with an event. The canonical canary is
+// the oldest-pending-age gauge, which lives in event-outbox-queue.ts because the relay tick feeds it.
export const eventOutboxLagHistogram = infisicalCoreMeter.createHistogram("infisical.event_outbox.lag", {
description:
diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.ts
index 3dfb790363..314eab2fdd 100644
--- a/backend/src/services/alert/alert-dal.test.ts
+++ b/backend/src/services/alert/alert-dal.test.ts
@@ -113,7 +113,7 @@ describe("alert dal", () => {
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.
+ // Mirrors 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]);
});
@@ -133,8 +133,6 @@ describe("alert dal", () => {
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();
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.ts
index e1b0a8e567..ce29e706fa 100644
--- a/backend/src/services/alert/alert-dal.ts
+++ b/backend/src/services/alert/alert-dal.ts
@@ -42,9 +42,8 @@ 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.
+ // The event path's counterpart to findEnabledByResourceType, 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;
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 68504f7bae..c1bcf608e3 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -70,8 +70,8 @@ const makeProvider = (targets: TTarget[], onFindDueTargets?: () => void): IResou
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.
+ // Mirrors a real provider: a target deleted between the event and its delivery drops out rather
+ // than coming back.
findTargetsByIds: async ({ targetIds }) => targets.filter((target) => targetIds.includes(target.id)),
assertPermission: async () => undefined,
assertResourceInScope: async () => undefined,
@@ -508,14 +508,14 @@ describe("alert engine, event path", () => {
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.
+ // t2 exists but the event didn't name it.
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.
+ // The whole reason the event path exists: a daily scan rediscovers the same target tomorrow and
+ // needs dedup, an event doesn't. Reintroduce the dedup lookup here and this fails.
test("delivers the same target again even though it was just alerted on", async () => {
const { engine, sentMail } = buildEngine({
targets: [{ id: "t1" }],
@@ -542,8 +542,8 @@ describe("alert engine, event path", () => {
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.
+ // A retry must not re-notify a channel that already succeeded. That's what makes retrying an event
+ // safe with no dedup behind it.
test("skips channels a previous attempt already delivered to", async () => {
const { engine, sentMail, historyWrites } = buildEngine({
targets: [{ id: "t1" }],
@@ -577,8 +577,8 @@ describe("alert engine, event path", () => {
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.
+ // A history write that fails after the sends must not turn a delivered event into a retry, or the
+ // retry re-notifies.
test("still reports success when the history write fails after delivery", async () => {
const { engine, sentMail } = buildEngine({
targets: [{ id: "t1" }],
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index fcb8425d3c..611b3c6380 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -187,9 +187,8 @@ export const alertEngineFactory = ({
logger.error(`Alert delivery failed on one or more channels [alertId=${alert.id}]: ${errorText}`);
}
- // 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.
+ // Deliberately not allowed to fail the run: the event path may retry, and a throw after channels
+ // have already sent would re-notify.
try {
await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);
} catch (err) {
@@ -294,7 +293,7 @@ export const alertEngineFactory = ({
condition: alert.condition,
targetIds: input.targetIds
});
- // The rows were deleted between the event being recorded and it being delivered. Nothing to say.
+ // The rows were deleted between the event being recorded and delivered, so there is nothing to say.
if (resolved.length === 0) return { outcome: AlertDispatchOutcome.NoDueTargets, deliveredChannelIds: [] };
const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));
@@ -303,8 +302,8 @@ export const alertEngineFactory = ({
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
+ // The scheduled path defers the tail to tomorrow's run, but an event has no next run, so this
+ // is a real drop. MAX_TARGET_IDS_PER_EVENT sits 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
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index cedb44ee72..38b098f589 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -88,8 +88,8 @@ describe("alert outbox consumer", () => {
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.
+ // The alert was deleted or disabled between the gate and the worker, so nobody is owed a
+ // notification. That's a completed event, not something to retry forever.
test("marks the row delivered when no alert matches any more", async () => {
const { consumer, runs } = buildConsumer({ alerts: [] });
@@ -118,8 +118,7 @@ describe("alert outbox consumer", () => {
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.
+ // Retrying can't fix a payload the consumer can't read, so don't burn every attempt on it first.
test("fails terminally on an unreadable payload", async () => {
const { consumer } = buildConsumer();
@@ -144,9 +143,8 @@ describe("alert outbox consumer", () => {
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.
+ // Marking a mismatched pair 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();
@@ -158,8 +156,8 @@ describe("alert outbox consumer", () => {
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.
+ // Throwing out of handle() sends the whole batch back for retry, re-notifying on rows that already
+ // delivered, so 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({
@@ -198,7 +196,7 @@ describe("alert outbox consumer", () => {
expect(getLookups()).toBe(1);
});
- // Rows arrive in id order and share one resource, so handling them concurrently would deliver a
+ // Rows arrive in id order and share one resource, so handling them concurrently would deliver that
// resource's events out of order.
test("handles rows serially, in the order given", async () => {
const { consumer, runs } = buildConsumer();
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index 2af198b4ef..84cedf5702 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -15,9 +15,9 @@ 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.
+// The contract every event-triggered alert shares: the emitter names targets by id and the provider
+// rehydrates them at delivery time. 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)
});
@@ -41,9 +41,9 @@ export const alertEventConsumerFactory = ({
}: 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".
+ // subscribesTo only sees the event type, so an emitter pairing a valid event key with the wrong
+ // resourceType gets past the gate. Failing it here, terminally and naming both halves, is what
+ // stops that row from being marked delivered as "no matching alert".
const $isDeclaredEvent = (row: TEventOutboxRow): boolean =>
Boolean(
alertProviderRegistry
@@ -118,9 +118,8 @@ export const alertEventConsumerFactory = ({
};
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.
+ // A batch shares one resource, so rows differ at most by event type and scope. Resolving once
+ // per 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}`;
@@ -139,8 +138,8 @@ export const alertEventConsumerFactory = ({
// 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.
+ // Contained to this row: throwing out of handle() sends the whole batch back for retry, which
+ // re-notifies on every row that already delivered ahead of this one.
results.push({
id: String(row.id),
status: EventOutboxStatus.Retry,
diff --git a/backend/src/services/alert/alert-provider-registry.test.ts b/backend/src/services/alert/alert-provider-registry.test.ts
index 80361317d4..cd7b6f95bc 100644
--- a/backend/src/services/alert/alert-provider-registry.test.ts
+++ b/backend/src/services/alert/alert-provider-registry.test.ts
@@ -24,8 +24,8 @@ describe("alert provider registry", () => {
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.
+ // Both guards fail the boot in routes/index.ts, rather than letting a dispatch silently no-op in
+ // production.
test("rejects a scheduled event with no findDueTargets", () => {
const registry = alertProviderRegistryFactory();
diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.ts
index c29b844c1a..d733795484 100644
--- a/backend/src/services/alert/alert-service.test.ts
+++ b/backend/src/services/alert/alert-service.test.ts
@@ -267,8 +267,8 @@ 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.
+ // triggerType comes from the provider's event definition, never 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();
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 7d9aa1516a..033d324b8b 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -91,8 +91,8 @@ 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.
+// Lets a provider's factory declare which discovery method it guarantees, instead of leaving callers
+// to assert it.
export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &
Required<Pick<IResourceAlertProvider<TTarget>, "findDueTargets">>;
@@ -115,9 +115,9 @@ export interface IResourceAlertProvider<TTarget = unknown> {
// 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.
+ // Rehydrate the targets an event named, by id. 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 was deleted
+ // between emit and dispatch, so it's dropped rather than an error.
// Required for any Event event; the registry enforces that at boot.
findTargetsByIds?(input: TFindTargetsByIdsInput): Promise<TTarget[]>;
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 58159fff5a..f528ae0796 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.test.ts
@@ -3,9 +3,9 @@ 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.
+// These assert query *shape*, in the style of alert-dal.test.ts. Only a real database can show that
+// two claimers never take the same row, so what a unit test protects is that the clauses buying that
+// guarantee are still there.
const buildDAL = () => {
const calls = {
where: [] as unknown[][],
@@ -89,7 +89,7 @@ const buildDAL = () => {
},
returning: async () => [],
del: async () => 0,
- // Returns the chain so a subquery can keep building; awaiting it resolves through `then` below.
+ // Returns the chain so a subquery keeps building; awaiting it resolves through `then` below.
select: () => chain,
then: (resolve: (v: unknown) => unknown) => resolve([])
});
@@ -106,10 +106,9 @@ const buildDAL = () => {
};
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.
+ // The conflict target repeats the index predicate because Postgres can't infer a *partial* unique
+ // index from a bare column list: a plain ON CONFLICT (consumer, idempotencyKey) is a 42P10 at
+ // runtime.
test("insertEvents ignores a conflict on the partial idempotency index", async () => {
const { dal, calls, tx } = buildDAL();
@@ -140,8 +139,8 @@ describe("event outbox dal", () => {
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.
+ // SKIP LOCKED is what makes concurrent relays correct by construction, and so the reason the relay
+ // doesn't need the cron manager's fleet-wide exactly-once scheduling.
test("claimBatch locks rows with FOR UPDATE SKIP LOCKED", async () => {
const { dal, calls } = buildDAL();
@@ -151,9 +150,6 @@ describe("event outbox dal", () => {
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();
@@ -162,8 +158,6 @@ describe("event outbox dal", () => {
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();
@@ -174,8 +168,8 @@ describe("event outbox dal", () => {
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.
+ // A row 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();
@@ -214,8 +208,7 @@ describe("event outbox dal", () => {
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.
+ // Same clock the claim compares against, so app/DB skew can't shift the retry schedule.
test("commitResults computes the next retry time in SQL, not in JS", async () => {
const { dal, calls } = buildDAL();
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
index 1c1b97c127..ab044e573c 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -57,8 +57,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
}
};
- // 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.
+ // One statement, no explicit transaction: the row locks live only as long as 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)
@@ -69,10 +69,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
.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.
+ // By id, never by a timestamp: a fresh row's nextRetryAt is its insert time, so sorting on
+ // that would let a later event overtake an earlier one that took a backoff.
.orderBy("id", "asc")
.limit(limit)
.forUpdate()
@@ -87,9 +85,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
}
};
- // 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.
+ // The sweeper reads a claim older than its threshold as a dead worker and hands the rows back out,
+ // so a batch that legitimately runs that long has to keep lockedAt fresh or it delivers twice.
const extendClaims = async (ids: string[]): Promise<void> => {
if (ids.length === 0) return;
try {
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 2c01ab6f75..abfee1a1ad 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.test.ts
@@ -55,8 +55,8 @@ 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 the
- // relay rediscovering a key whose flush is still queued.
+ // 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 () => {
const { factory, queued } = buildQueue({ keys: [KEY] });
@@ -65,8 +65,8 @@ describe("event outbox relay", () => {
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.
+ // 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" }] });
@@ -76,7 +76,7 @@ describe("event outbox relay", () => {
expect(queued[0].jobId).not.toContain(":");
});
- // Retry lives on the outbox row, where it is inspectable and survives a Redis flush. BullMQ retrying
+ // Retry lives on the outbox row, where it's 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] });
diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.ts
index 8aeb68b89b..1a6ece4b38 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.ts
@@ -60,9 +60,9 @@ export const eventOutboxQueueFactory = ({
});
};
- // 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.
+ // BullMQ rejects a custom id containing ':' and resourceId is any string, so it gets percent-encoded
+ // (injectively, so two keys can't collide on one 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)}`,
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 8beddf9038..68cdc881c6 100644
--- a/backend/src/services/event-outbox/event-outbox-service.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts
@@ -29,8 +29,8 @@ const makeConsumer = (overrides?: Partial<IEventOutboxConsumer>): IEventOutboxCo
...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.
+// `tx` is a sentinel: emit has to thread the caller's transaction through untouched, since a call
+// that silently opens its own connection is how the pool deadlocks.
const TX = { sentinel: true } as never;
const buildService = (consumers: IEventOutboxConsumer[]) => {
@@ -82,9 +82,8 @@ describe("event outbox emit", () => {
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.
+ // A payload the consumer can't read means a statically wrong emit site, and failing loudly beats
+ // dropping a notification over a misspelled field.
test("throws when the payload does not match the consumer's schema", async () => {
const { service, inserted } = buildService([makeConsumer()]);
@@ -111,8 +110,7 @@ describe("event outbox emit", () => {
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.
+ // Swallowing it 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());
@@ -245,8 +243,8 @@ describe("event outbox drain", () => {
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.
+ // One UPDATE per distinct outcome, not one per row, so a batch of a hundred deliveries is a single
+ // statement. Rows on the same attempt share a retry delay, 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 })]],
@@ -282,8 +280,8 @@ describe("event outbox drain", () => {
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.
+ // A batch that legitimately outlives the sweeper's threshold (a slow webhook, many rows) has to
+ // keep its claim fresh, or the sweeper hands its rows to a second worker mid-delivery.
test("extends the claim while the consumer is still handling a batch", async () => {
vi.useFakeTimers();
try {
diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.ts
index 32ee696178..0f3fc23929 100644
--- a/backend/src/services/event-outbox/event-outbox-service.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.ts
@@ -27,8 +27,8 @@ import {
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.
+// Frequent enough that one missed beat (a slow query, a paused event loop) doesn't let the sweeper
+// call a live claim stale.
const CLAIM_HEARTBEAT_INTERVAL_MS = STALE_CLAIM_THRESHOLD_MS / 4;
const computeBackoffMs = (attemptsAfterIncrement: number): number => {
@@ -41,8 +41,7 @@ const computeBackoffMs = (attemptsAfterIncrement: number): number => {
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.
+// Lets commitResults issue one UPDATE per distinct outcome instead of one per row.
const groupByOutcome = <TItem extends { id: string }>(
items: TItem[],
keyOf: (item: TItem) => string
@@ -69,23 +68,17 @@ export type TEventOutboxServiceFactoryDep = {
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.
+ // `tx` is required, not optional: the row has to commit 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.
+ // Nothing here reads the database. Validation and consumer matching are in-memory, so this adds a
+ // single insert to the caller's transaction and never calls back into a consumer. Whether anyone
+ // actually wants the event is settled later in the worker, where guessing wrong only costs a row
+ // that gets marked delivered and pruned.
//
- // 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.
+ // Nothing is caught either. A bad event is a bug at the emit site rather than something the API
+ // caller can act on (hence 500, not 400), and swallowing a failed insert would hand the caller a
+ // poisoned transaction instead of the real error.
const emit = async (event: TOutboxEvent, tx: Knex): Promise<void> => {
const parsed = OutboxEventSchema.safeParse(event);
if (!parsed.success) {
@@ -201,9 +194,8 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
}
};
- // 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.
+ // 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,
@@ -233,9 +225,8 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
}
};
- // 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.
+ // Bounded so one wedged resource can't hold a worker indefinitely; whatever is left over gets
+ // 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) {
diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.ts
index b219b8db7c..c22d3b467a 100644
--- a/backend/src/services/event-outbox/event-outbox-types.ts
+++ b/backend/src/services/event-outbox/event-outbox-types.ts
@@ -57,8 +57,7 @@ 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.
+ // Handed back on the next attempt so a retry can resume instead of repeating. Opaque to the outbox.
progress?: Record<string, unknown> | null;
};
@@ -69,20 +68,19 @@ export type TOutboxFlushKey = {
};
export interface IEventOutboxConsumer<TPayload = unknown> {
- // Stored in every row and part of the flush job id. Renaming it orphans in-flight rows.
+ // Stored on every row and part of the flush job id, so 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.
+ // Parsed at emit, so a malformed event fails at its source instead of in a worker later. Must not
+ // be `.strict()`: one event can feed several consumers, so a schema has to tolerate fields it
+ // doesn't 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.
+ // Runs on the request path for every emit, so keep it pure and in-memory. Whether anyone actually
+ // wants the event is decided later in handle(), off the caller's transaction, where guessing 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.
+ // Rows for a single (resourceType, resourceId), in id order. Must return one result per row.
handle(rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]>;
}