@nodii/outbox-dispatcher 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/prune.js ADDED
@@ -0,0 +1,753 @@
1
+ // Outbox retention (RETENTION-FIX-4, LIBS-72): prune published outbox rows and
2
+ // bound streams by age.
3
+ //
4
+ // WHAT IS DELETED, AND WHAT NEVER IS
5
+ //
6
+ // - A PUBLISHED outbox row (`dispatched_at IS NOT NULL`) is hard-deleted once
7
+ // its `dispatched_at` is older than the retention (operator ruling 3 of
8
+ // 20 Nov 2026: "published outbox rows: 30 days"). Payloads can hold
9
+ // personal data, so the row must not outlive its purpose.
10
+ // - An UNPUBLISHED row (`dispatched_at IS NULL`) is NEVER deleted, however
11
+ // old, and however many times its publish failed. D401 keeps a failed
12
+ // publish in the outbox as the source of truth (there is no publish-side
13
+ // DLQ table) and the 24h sweep alerts on it. A failed row that is later
14
+ // repaired gets `dispatched_at` when it finally publishes, so it is kept
15
+ // until then and deleted 30 days after that: "kept until resolved, then
16
+ // 30 days".
17
+ // - This library owns exactly one table, the service's outbox. `saga_outbox`
18
+ // belongs to `@nodii/saga` and the subscriber-side `replication_dlq` to
19
+ // `@nodii/replica-consumer`; neither is touched here.
20
+ //
21
+ // STREAMS (LIBS-72)
22
+ //
23
+ // `DEFAULT_STREAM_MAXLEN` (1,000,000 entries) never bites on a real stream, so
24
+ // Dev Redis held every event since July. The job trims each stream the service
25
+ // LISTS to `XTRIM <stream> MINID ~ <now - retention>` (default 14 days).
26
+ // Trimming is OPT-IN PER STREAM: a stream not listed is never trimmed. A
27
+ // consumer whose group starts from `0-0` with no snapshot path would silently
28
+ // lose history on a cold start if its stream were trimmed by default, and the
29
+ // library cannot see who consumes a stream. The service lists the streams
30
+ // whose every consumer can hydrate (see the README's checklist).
31
+ //
32
+ // The trim is approximate (`MINID ~`): Redis removes whole macro nodes only, so
33
+ // a few entries older than the bound can remain until a later trim.
34
+ //
35
+ // A listed stream is also never trimmed past an entry a consumer group still
36
+ // needs: the trim point is held at the oldest entry any group has not
37
+ // acknowledged (its lowest pending id, else its last-delivered id). A group
38
+ // that stopped reading therefore holds its stream; the job logs which group
39
+ // and reports `heldBack` so the group can be removed or repaired.
40
+ //
41
+ // SINGLE ACTIVE, FENCED (LIB-EVT-20, WORK-40)
42
+ //
43
+ // One replica prunes at a time, under the shared fenced lease
44
+ // `nodii:lease:<service>:outbox-prune`. The fence is checked before every
45
+ // DELETE batch and every XTRIM; a run that lost its lease stops at once and
46
+ // reports `leaseLost`. Deleting already-expired rows twice is harmless, so the
47
+ // lease bounds load rather than guarding correctness, but it is the rule.
48
+ //
49
+ // No audit event (AUDT-49): a scheduled system job reports through logs and
50
+ // low-cardinality metrics only (TELE-21: `service`, `table`, `stream`).
51
+ //
52
+ // Twins: python `nodii_outbox_dispatcher.prune`, go `prune.go`.
53
+ //
54
+ // AGGREGATE ORDER (COMM-47, DEC-0428)
55
+ //
56
+ // An `orderPerAggregate` dispatcher reads the aggregate's previous row (`prev`)
57
+ // to detect a version gap. Deleting an aggregate's whole published history
58
+ // would make a later out-of-order version look gap-free and publish at once.
59
+ // With `orderPerAggregate` (pass the dispatcher, or the same flag), the prune
60
+ // keeps each aggregate's highest-version published row and, once it is past
61
+ // the retention, scrubs its payload and trace columns (`payload = '{}'`), so the
62
+ // version the gap check needs survives and the personal data does not.
63
+ //
64
+ // DEDUPE HORIZON
65
+ //
66
+ // `writeOutboxEventOnce` skips a write whose `event_id` conflicts with a row
67
+ // still in the table. Once a published row is pruned, the same `event_id`
68
+ // inserts again: the event-id dedupe window becomes the outbox retention. A
69
+ // consumer that dedupes on outbox event ids therefore needs to keep its own
70
+ // dedupe records at least that long (30 days by default).
71
+ //
72
+ // ROW LEVEL SECURITY (LIBS-130)
73
+ //
74
+ // The prune must see every row. When row level security applies to its role
75
+ // on the outbox table (FORCE ROW LEVEL SECURITY, or a role that is not the
76
+ // owner) and no permissive `USING (true)` policy opens the table to that role,
77
+ // it would delete nothing and report the run complete. It checks first and
78
+ // fails the run with `OutboxPruneRowSecurityError` instead. The check is
79
+ // deliberately strict: it asks for `USING (true)` on SELECT, UPDATE and DELETE
80
+ // on every run, ordered or not, although only the ordered prune runs the scrub
81
+ // UPDATE. Separate FOR SELECT and FOR DELETE policies with no UPDATE policy
82
+ // are refused; give the role a FOR ALL policy, or add the FOR UPDATE one.
83
+ //
84
+ // INDEXES
85
+ //
86
+ // Without `idx_prune_<table>` (`buildPruneIndexSql`), the unordered DELETE can
87
+ // scan the table on every batch, and the ordered one without its
88
+ // aggregate-order index likewise. The job logs a warning naming the missing
89
+ // index.
90
+ import { FenceCheckUnavailableError, FenceLostError, withSingleActiveLease, } from "@nodii/telemetry/worker";
91
+ import { compareStreamIds } from "./hwm.js";
92
+ import { aggregateOrderIndexNames, buildOrderPerAggregateIndexSql, buildPruneIndexSql, buildPrunePublishedSql, buildScrubPublishedSql, buildTenantColumnCheckSql, quoteIdent, } from "./sql-builders.js";
93
+ import { InvalidDispatcherConfig, } from "./types.js";
94
+ const DAY_MS = 24 * 60 * 60 * 1000;
95
+ /** Published outbox rows are kept 30 days after publish (operator ruling 3). */
96
+ export const DEFAULT_OUTBOX_RETENTION_MS = 30 * DAY_MS;
97
+ /** A listed stream keeps 14 days of entries (LIBS-72, operator 10 Nov). */
98
+ export const DEFAULT_STREAM_RETENTION_MS = 14 * DAY_MS;
99
+ /** The job runs daily. */
100
+ export const DEFAULT_OUTBOX_PRUNE_INTERVAL_MS = DAY_MS;
101
+ /** Rows deleted per DELETE statement. */
102
+ export const DEFAULT_OUTBOX_PRUNE_BATCH_SIZE = 1_000;
103
+ /** Upper bound on DELETE statements per run (the orderPerAggregate scrub gets as many again). */
104
+ export const DEFAULT_OUTBOX_PRUNE_MAX_BATCHES = 1_000;
105
+ /** Largest accepted batch size. */
106
+ export const MAX_OUTBOX_PRUNE_BATCH_SIZE = 10_000;
107
+ /** XTRIM calls per stream per run, at most. */
108
+ export const DEFAULT_STREAM_TRIM_MAX_CALLS = 1_000;
109
+ /** Lease scope: `nodii:lease:<service>:outbox-prune`. */
110
+ export const OUTBOX_PRUNE_LEASE_SCOPE = "outbox-prune";
111
+ /** Lease TTL; it renews at half this for as long as the run lasts. */
112
+ export const DEFAULT_OUTBOX_PRUNE_LEASE_TTL_MS = 30_000;
113
+ /** The job's name for a service: `<service>.outbox-prune`. */
114
+ export function outboxPruneJobName(serviceName) {
115
+ return `${serviceName}.outbox-prune`;
116
+ }
117
+ function positiveInt(name, v, fallback) {
118
+ if (v === undefined)
119
+ return fallback;
120
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1) {
121
+ throw new InvalidDispatcherConfig(`${name} must be a whole number of at least 1, got ${String(v)}`);
122
+ }
123
+ return v;
124
+ }
125
+ function optionalBool(name, v, fallback) {
126
+ if (v === undefined)
127
+ return fallback;
128
+ if (typeof v !== "boolean") {
129
+ throw new InvalidDispatcherConfig(`${name} must be a boolean`);
130
+ }
131
+ return v;
132
+ }
133
+ /**
134
+ * Validate and default the prune-batch options. A retention or batch size of
135
+ * 0 or less is refused: a retention of 0 would delete rows published a moment
136
+ * ago, and a batch size of 0 would loop without deleting.
137
+ */
138
+ export function resolvePruneBatchOpts(opts) {
139
+ const outboxTable = opts.outboxTable ?? "outbox";
140
+ try {
141
+ quoteIdent(outboxTable);
142
+ }
143
+ catch (err) {
144
+ throw new InvalidDispatcherConfig(err instanceof Error ? err.message : String(err));
145
+ }
146
+ const batchSize = positiveInt("batchSize", opts.batchSize, DEFAULT_OUTBOX_PRUNE_BATCH_SIZE);
147
+ if (batchSize > MAX_OUTBOX_PRUNE_BATCH_SIZE) {
148
+ throw new InvalidDispatcherConfig(`batchSize must be at most ${MAX_OUTBOX_PRUNE_BATCH_SIZE}, got ${batchSize}`);
149
+ }
150
+ return {
151
+ outboxTable,
152
+ retentionMs: positiveInt("retentionMs", opts.retentionMs, DEFAULT_OUTBOX_RETENTION_MS),
153
+ batchSize,
154
+ maxBatches: positiveInt("maxBatches", opts.maxBatches, DEFAULT_OUTBOX_PRUNE_MAX_BATCHES),
155
+ orderPerAggregate: optionalBool("orderPerAggregate", opts.orderPerAggregate, false),
156
+ };
157
+ }
158
+ /** Validate and default the stream-trim options (retention and maxCalls of
159
+ * 0 or less are refused). */
160
+ export function resolveTrimOpts(opts) {
161
+ return {
162
+ retentionMs: positiveInt("retentionMs", opts.retentionMs, DEFAULT_STREAM_RETENTION_MS),
163
+ maxCalls: positiveInt("maxCalls", opts.maxCalls, DEFAULT_STREAM_TRIM_MAX_CALLS),
164
+ respectConsumerGroups: optionalBool("respectConsumerGroups", opts.respectConsumerGroups, true),
165
+ approximate: optionalBool("approximate", opts.approximate, true),
166
+ };
167
+ }
168
+ /** Validate and default the job options. Throws `InvalidDispatcherConfig`. */
169
+ export function resolveOutboxPruneOpts(opts) {
170
+ const serviceName = opts.serviceName ?? opts.dispatcher?.serviceName;
171
+ if (typeof serviceName !== "string" || serviceName.length === 0) {
172
+ throw new InvalidDispatcherConfig("serviceName is required");
173
+ }
174
+ const batch = resolvePruneBatchOpts({
175
+ outboxTable: opts.outboxTable ?? opts.dispatcher?.outboxTable,
176
+ retentionMs: opts.retentionMs,
177
+ batchSize: opts.batchSize,
178
+ maxBatches: opts.maxBatchesPerRun,
179
+ // The dispatcher's true wins over an explicit false (as in Go): dropping
180
+ // an ordered aggregate's latest row breaks its gap check.
181
+ orderPerAggregate: opts.dispatcher?.orderPerAggregate === true
182
+ ? true
183
+ : opts.orderPerAggregate,
184
+ });
185
+ const leaseTtlMs = positiveInt("leaseTtlMs", opts.leaseTtlMs, DEFAULT_OUTBOX_PRUNE_LEASE_TTL_MS);
186
+ if (leaseTtlMs < 2_000) {
187
+ throw new InvalidDispatcherConfig(`leaseTtlMs must be >= 2000 (got ${leaseTtlMs}); renewal cadence is ttl/2`);
188
+ }
189
+ const streams = [];
190
+ const seen = new Set();
191
+ for (const s of opts.streams ?? []) {
192
+ const entry = typeof s === "string" ? { stream: s } : s;
193
+ if (entry === null ||
194
+ typeof entry !== "object" ||
195
+ typeof entry.stream !== "string" ||
196
+ entry.stream.length === 0) {
197
+ throw new InvalidDispatcherConfig("streams must list non-empty stream names");
198
+ }
199
+ if (seen.has(entry.stream)) {
200
+ throw new InvalidDispatcherConfig(`stream ${JSON.stringify(entry.stream)} is listed twice`);
201
+ }
202
+ seen.add(entry.stream);
203
+ streams.push({
204
+ stream: entry.stream,
205
+ retentionMs: positiveInt(`streams[${JSON.stringify(entry.stream)}].retentionMs`, entry.retentionMs, DEFAULT_STREAM_RETENTION_MS),
206
+ });
207
+ }
208
+ return {
209
+ serviceName,
210
+ batch,
211
+ streams,
212
+ respectConsumerGroups: optionalBool("respectConsumerGroups", opts.respectConsumerGroups, true),
213
+ intervalMs: positiveInt("intervalMs", opts.intervalMs, DEFAULT_OUTBOX_PRUNE_INTERVAL_MS),
214
+ leaseTtlMs,
215
+ };
216
+ }
217
+ /**
218
+ * Thrown when row level security applies to the prune's role on the outbox
219
+ * table (FORCE ROW LEVEL SECURITY, or a role that is not the owner) and no
220
+ * permissive `USING (true)` policy lets the role see every row: the DELETE
221
+ * would see no rows, and the run would report complete having pruned nothing.
222
+ * Run the prune as the table owner on a table without FORCE ROW LEVEL
223
+ * SECURITY, as a role with BYPASSRLS, or give the role such a policy.
224
+ */
225
+ export class OutboxPruneRowSecurityError extends Error {
226
+ constructor(outboxTable, role) {
227
+ super(`outbox prune: row level security applies to role ${role} on ${outboxTable} (FORCE ROW LEVEL SECURITY, or not the owner) and no policy lets it see every row, so the prune would delete nothing; run it as the owner without FORCE, as a BYPASSRLS role, or add a policy FOR ALL TO ${role} USING (true)`);
228
+ this.name = "OutboxPruneRowSecurityError";
229
+ }
230
+ }
231
+ /**
232
+ * Does row level security apply to this role on the table (`active`), and if
233
+ * so, does a permissive policy with `USING (true)` let the role select,
234
+ * update and delete every row (`open`) with no restrictive policy narrowing
235
+ * it (`unrestricted`)? db-rls's owner policy (`FOR ALL TO nodii_owner USING
236
+ * (true)`) is such a policy. Byte-equal with Python and Go.
237
+ */
238
+ export const PRUNE_ROW_SECURITY_SQL = "SELECT row_security_active(to_regclass($1)) AS active, current_user::text AS role, " +
239
+ " (SELECT bool_and(EXISTS (SELECT 1 FROM pg_policy p " +
240
+ " WHERE p.polrelid = to_regclass($1) AND p.polpermissive AND p.polcmd IN ('*', c.cmd) " +
241
+ " AND (0 = ANY (p.polroles) OR EXISTS (SELECT 1 FROM unnest(p.polroles) AS r(oid) " +
242
+ " WHERE r.oid <> 0 AND pg_has_role(current_user, r.oid, 'USAGE'))) " +
243
+ " AND pg_get_expr(p.polqual, p.polrelid) = 'true')) " +
244
+ " FROM (VALUES ('r'::\"char\"), ('w'::\"char\"), ('d'::\"char\")) AS c(cmd)) AS open, " +
245
+ " NOT EXISTS (SELECT 1 FROM pg_policy p " +
246
+ " WHERE p.polrelid = to_regclass($1) AND NOT p.polpermissive AND p.polcmd IN ('*', 'r', 'w', 'd') " +
247
+ " AND (0 = ANY (p.polroles) OR EXISTS (SELECT 1 FROM unnest(p.polroles) AS r(oid) " +
248
+ " WHERE r.oid <> 0 AND pg_has_role(current_user, r.oid, 'USAGE'))) " +
249
+ " AND pg_get_expr(p.polqual, p.polrelid) IS DISTINCT FROM 'true') AS unrestricted";
250
+ /** Fails when row level security would hide rows from the prune. */
251
+ async function assertRowSecurityInactive(pool, outboxTable) {
252
+ const rows = (await pool.unsafe(PRUNE_ROW_SECURITY_SQL, [
253
+ quoteIdent(outboxTable),
254
+ ]));
255
+ const r = rows?.[0];
256
+ if (r?.active === true && !(r.open === true && r.unrestricted === true)) {
257
+ throw new OutboxPruneRowSecurityError(outboxTable, r.role);
258
+ }
259
+ }
260
+ /** A VALID index of this name sits on this table. */
261
+ const VALID_INDEX_ON_TABLE_SQL = "SELECT EXISTS (SELECT 1 FROM pg_index WHERE indexrelid = to_regclass($1) AND indrelid = to_regclass($2) AND indisvalid) AS found";
262
+ async function hasTenantColumn(pool, outboxTable) {
263
+ const rows = (await pool.unsafe(buildTenantColumnCheckSql(), [
264
+ quoteIdent(outboxTable),
265
+ ]));
266
+ return rows?.[0]?.has_tenant === true;
267
+ }
268
+ /** Either aggregate-order index sits on this table. */
269
+ const AGGREGATE_ORDER_INDEX_ON_TABLE_SQL = "SELECT EXISTS (SELECT 1 FROM pg_index WHERE indexrelid IN (to_regclass($1), to_regclass($2)) AND indrelid = to_regclass($3)) AS found";
270
+ /**
271
+ * True when either aggregate-order index (`buildOrderPerAggregateIndexSql`)
272
+ * sits on this table, which marks a table an `orderPerAggregate` dispatcher
273
+ * serves. An invalid index (a failed CREATE INDEX CONCURRENTLY) counts too:
274
+ * it still shows the table is ordered. A name too long for the index means no
275
+ * such index. This is a backstop only: the index is optional, so a job for an
276
+ * ordered dispatcher must be built from `dispatcher` or set `orderPerAggregate`.
277
+ */
278
+ async function hasAggregateOrderIndex(pool, outboxTable, fullOnly = false) {
279
+ let names;
280
+ try {
281
+ names = aggregateOrderIndexNames(outboxTable);
282
+ }
283
+ catch {
284
+ return false;
285
+ }
286
+ // The full index alone serves the ordered DELETE's EXISTS over published
287
+ // rows; the pending one is partial on unpublished rows.
288
+ if (fullOnly)
289
+ names = [names[0], names[0]];
290
+ const rows = (await pool.unsafe(AGGREGATE_ORDER_INDEX_ON_TABLE_SQL, [
291
+ ...names,
292
+ quoteIdent(outboxTable),
293
+ ]));
294
+ return rows?.[0]?.found === true;
295
+ }
296
+ /** The prune index's CREATE statement when the table lacks it, else null. A
297
+ * table name too long for the index name has no such index to create. */
298
+ async function missingPruneIndex(pool, outboxTable) {
299
+ let create;
300
+ try {
301
+ create = buildPruneIndexSql(outboxTable);
302
+ }
303
+ catch {
304
+ return null;
305
+ }
306
+ const idx = quoteIdent(`idx_prune_${outboxTable}`);
307
+ // An INVALID index (a failed CREATE INDEX CONCURRENTLY) serves no scan.
308
+ const rows = (await pool.unsafe(VALID_INDEX_ON_TABLE_SQL, [
309
+ idx,
310
+ quoteIdent(outboxTable),
311
+ ]));
312
+ return rows?.[0]?.found === true ? null : create;
313
+ }
314
+ async function runBatches(pool, sql, r, budget, kind, hooks, keyset) {
315
+ let rows = 0;
316
+ let batches = 0;
317
+ // With a keyset cursor, each batch starts after the highest id the last one
318
+ // touched, so rows the run keeps are not scanned again batch after batch.
319
+ // The cursor compares id::text: for a TEXT id (the library's migration) the
320
+ // primary key serves it. For a uuid or bigint id, add an index on
321
+ // ((id::text)), or each batch re-reads every expired row.
322
+ let cursor = "";
323
+ while (budget.left > 0) {
324
+ await hooks.beforeBatch?.();
325
+ const params = keyset
326
+ ? [r.retentionMs, r.batchSize, cursor]
327
+ : [r.retentionMs, r.batchSize];
328
+ const out = (await pool.unsafe(sql, params));
329
+ budget.left -= 1;
330
+ batches += 1;
331
+ const n = Number(out?.[0]?.n ?? 0);
332
+ const last = out?.[0]?.last_id;
333
+ if (typeof last === "string")
334
+ cursor = last;
335
+ rows += n;
336
+ hooks.onBatch?.(n, kind);
337
+ // A short batch is not the end: SKIP LOCKED may have passed over rows a
338
+ // drain holds. Only a batch that touches nothing is. With the cursor, a
339
+ // row passed over lies behind it, so an empty batch past the start goes
340
+ // round once more from the start: done only when that touches nothing.
341
+ if (n === 0) {
342
+ if (keyset && cursor !== "") {
343
+ cursor = "";
344
+ continue;
345
+ }
346
+ return { rows, batches, done: true };
347
+ }
348
+ }
349
+ return { rows, batches, done: false };
350
+ }
351
+ /** The batch loops on resolved options (no second validation). */
352
+ async function runPrune(pool, opts, hooks) {
353
+ await assertRowSecurityInactive(pool, opts.outboxTable);
354
+ // Fail safe: a table that carries the aggregate-order index serves an
355
+ // `orderPerAggregate` dispatcher, so keep each aggregate's latest row even
356
+ // when the job was not told (built from `serviceName`, not `dispatcher`).
357
+ const r = {
358
+ ...opts,
359
+ orderPerAggregate: opts.orderPerAggregate ||
360
+ (await hasAggregateOrderIndex(pool, opts.outboxTable)),
361
+ };
362
+ if (r.orderPerAggregate &&
363
+ hooks.onMissingOrderIndex &&
364
+ !(await hasAggregateOrderIndex(pool, r.outboxTable, true))) {
365
+ // Without it each candidate's EXISTS over newer rows can scan the table.
366
+ hooks.onMissingOrderIndex(buildOrderPerAggregateIndexSql(r.outboxTable)[0]);
367
+ }
368
+ if (!r.orderPerAggregate && hooks.onMissingPruneIndex) {
369
+ // Without it each batch's DELETE can scan the table for expired rows.
370
+ const create = await missingPruneIndex(pool, r.outboxTable);
371
+ if (create !== null)
372
+ hooks.onMissingPruneIndex(create);
373
+ }
374
+ const untenanted = r.orderPerAggregate
375
+ ? !(await hasTenantColumn(pool, r.outboxTable))
376
+ : true;
377
+ const budget = { left: r.maxBatches };
378
+ const del = await runBatches(pool, buildPrunePublishedSql(r.outboxTable, {
379
+ keepLatestPerAggregate: r.orderPerAggregate,
380
+ untenanted,
381
+ }), r, budget, "deleted", hooks, r.orderPerAggregate);
382
+ if (!r.orderPerAggregate) {
383
+ return {
384
+ deletedRows: del.rows,
385
+ scrubbedRows: 0,
386
+ batches: del.batches,
387
+ complete: del.done,
388
+ };
389
+ }
390
+ // The scrub has its own budget and runs even while deletes are backlogged:
391
+ // a kept row's payload must not outlive the retention because older rows
392
+ // of other aggregates are still waiting to be deleted.
393
+ const scrub = await runBatches(pool, buildScrubPublishedSql(r.outboxTable), r, { left: r.maxBatches }, "scrubbed", hooks, true);
394
+ return {
395
+ deletedRows: del.rows,
396
+ scrubbedRows: scrub.rows,
397
+ batches: del.batches + scrub.batches,
398
+ complete: del.done && scrub.done,
399
+ };
400
+ }
401
+ /**
402
+ * Delete published rows older than `retentionMs`, `batchSize` at a time, up to
403
+ * `maxBatches` statements, until a statement deletes nothing. Unpublished rows
404
+ * are never selected. With `orderPerAggregate`, each aggregate's
405
+ * highest-version published row is kept, and scrubbed once past the retention.
406
+ * Throws `OutboxPruneRowSecurityError` when row level security would hide rows
407
+ * from the pool's role.
408
+ */
409
+ export async function prunePublishedOutbox(args) {
410
+ return runPrune(args.pool, resolvePruneBatchOpts(args), args);
411
+ }
412
+ /** Lowest of two stream ids. */
413
+ function minStreamId(a, b) {
414
+ return compareStreamIds(a, b) <= 0 ? a : b;
415
+ }
416
+ function field(row, name) {
417
+ // ioredis returns XINFO GROUPS rows as flat [k, v, k, v, ...] arrays.
418
+ if (Array.isArray(row)) {
419
+ for (let i = 0; i + 1 < row.length; i += 2) {
420
+ if (String(row[i]) === name)
421
+ return row[i + 1];
422
+ }
423
+ return undefined;
424
+ }
425
+ if (row !== null && typeof row === "object") {
426
+ return row[name];
427
+ }
428
+ return undefined;
429
+ }
430
+ function isNoSuchKey(err) {
431
+ return err instanceof Error && /no such key/i.test(err.message);
432
+ }
433
+ /**
434
+ * The oldest entry any consumer group of `stream` still needs: per group its
435
+ * lowest pending id, else its last-delivered id; the minimum over groups. A
436
+ * group with nothing pending that has read up to the stream's newest id
437
+ * (`last-generated-id`) needs nothing and does not count. Returns undefined
438
+ * when the stream does not exist, null when no group needs anything.
439
+ * The groups' XPENDING summaries are read concurrently.
440
+ */
441
+ export async function consumerGroupFloor(redis, stream) {
442
+ let groups;
443
+ try {
444
+ groups = await redis.xinfo("GROUPS", stream);
445
+ }
446
+ catch (err) {
447
+ if (isNoSuchKey(err))
448
+ return undefined;
449
+ throw err;
450
+ }
451
+ // The stream's newest id, read once and only when a group has nothing
452
+ // pending: such a group that has read up to it needs no entry at all.
453
+ let lastGenerated;
454
+ const streamLastGenerated = () => {
455
+ lastGenerated ??= Promise.resolve(redis.xinfo("STREAM", stream)).then((info) => {
456
+ const id = field(info, "last-generated-id");
457
+ return typeof id === "string" && id.length > 0 ? id : null;
458
+ });
459
+ return lastGenerated;
460
+ };
461
+ const floors = await Promise.all((groups ?? []).map(async (g) => {
462
+ const name = String(field(g, "name"));
463
+ const pending = Number(field(g, "pending") ?? 0);
464
+ let floor = String(field(g, "last-delivered-id") ?? "0-0");
465
+ if (pending > 0) {
466
+ const summary = (await redis.xpending(stream, name));
467
+ const lowest = summary?.[1];
468
+ if (typeof lowest === "string" && lowest.length > 0) {
469
+ floor = minStreamId(floor, lowest);
470
+ }
471
+ }
472
+ else {
473
+ // Caught up: delivered everything and acknowledged it. It holds
474
+ // nothing back, so a stream that has gone quiet is still trimmed.
475
+ const newest = await streamLastGenerated();
476
+ if (newest !== null && compareStreamIds(floor, newest) >= 0) {
477
+ return null;
478
+ }
479
+ }
480
+ return { floor, group: name };
481
+ }));
482
+ let best = null;
483
+ for (const f of floors) {
484
+ if (f === null)
485
+ continue;
486
+ if (best === null || compareStreamIds(f.floor, best.floor) < 0)
487
+ best = f;
488
+ }
489
+ return best;
490
+ }
491
+ /** The XTRIM loop on resolved options (no second validation). */
492
+ async function runTrim(redis, stream, o, nowMs, beforeTrim) {
493
+ const cutoff = `${Math.max(0, nowMs - o.retentionMs)}-0`;
494
+ const result = {
495
+ stream,
496
+ retentionMs: o.retentionMs,
497
+ minId: null,
498
+ trimmed: 0,
499
+ heldBackBy: null,
500
+ complete: false,
501
+ };
502
+ // An approximate XTRIM removes at most 100 macro nodes (10,000 entries by
503
+ // default) per call, so a backlog takes several calls. The group floor is
504
+ // read again before every call, so a group created or reset mid-run is
505
+ // protected from the next call on.
506
+ for (let i = 0; i < o.maxCalls; i++) {
507
+ let minId = cutoff;
508
+ let heldBackBy = null;
509
+ if (o.respectConsumerGroups) {
510
+ const floor = await consumerGroupFloor(redis, stream);
511
+ if (floor === undefined) {
512
+ // The stream does not exist (or was deleted mid-run): nothing to trim.
513
+ result.complete = true;
514
+ return result;
515
+ }
516
+ if (floor !== null && compareStreamIds(floor.floor, cutoff) < 0) {
517
+ minId = floor.floor;
518
+ heldBackBy = floor.group;
519
+ }
520
+ }
521
+ result.minId = minId;
522
+ result.heldBackBy = heldBackBy;
523
+ await beforeTrim?.();
524
+ const args = o.approximate
525
+ ? ["MINID", "~", minId]
526
+ : ["MINID", minId];
527
+ const n = Number((await redis.xtrim(stream, ...args)) ?? 0);
528
+ result.trimmed += n;
529
+ if (n === 0) {
530
+ result.complete = true;
531
+ return result;
532
+ }
533
+ }
534
+ return result;
535
+ }
536
+ /**
537
+ * Trim `stream` to the entries newer than `retentionMs` with
538
+ * `XTRIM MINID ~`, never past an entry a consumer group still needs (unless
539
+ * `respectConsumerGroups` is false). `beforeTrim` runs right before each XTRIM.
540
+ * `complete` is false when `maxCalls` ran out with entries still to remove.
541
+ */
542
+ export async function trimStreamByAge(args) {
543
+ return runTrim(args.redis, args.stream, resolveTrimOpts(args), args.nowMs ?? Date.now(), args.beforeTrim);
544
+ }
545
+ function isFenceFailure(err) {
546
+ return (err instanceof FenceLostError || err instanceof FenceCheckUnavailableError);
547
+ }
548
+ function message(err) {
549
+ return err instanceof Error ? err.message : String(err);
550
+ }
551
+ /**
552
+ * Build the outbox retention job. A service wires it with one call in its
553
+ * worker process and runs `handler()` every `intervalMs` (daily):
554
+ *
555
+ * ```ts
556
+ * worker.schedule(makeOutboxPruneJob({ dispatcher, pool: ownerSql, redis }));
557
+ * ```
558
+ *
559
+ * Each run, under the lease `nodii:lease:<service>:outbox-prune`, deletes the
560
+ * published rows older than 30 days, then trims each listed stream to 14 days.
561
+ * A run that finds the lease held by another replica returns `ran: false`. A
562
+ * failed run (a lease-backend outage at acquire, a database error, row level
563
+ * security hiding rows from the prune) records `outcome=error` and throws:
564
+ * nothing is deleted blind.
565
+ */
566
+ export function makeOutboxPruneJob(opts) {
567
+ const o = resolveOutboxPruneOpts(opts);
568
+ if (!opts.pool || typeof opts.pool.unsafe !== "function") {
569
+ throw new InvalidDispatcherConfig("pool (an owner-pool executor) is required");
570
+ }
571
+ if (!opts.redis) {
572
+ throw new InvalidDispatcherConfig("redis is required");
573
+ }
574
+ const redis = opts.redis;
575
+ if (o.streams.length > 0 &&
576
+ (typeof redis.xtrim !== "function" ||
577
+ typeof redis.xinfo !== "function" ||
578
+ typeof redis.xpending !== "function")) {
579
+ throw new InvalidDispatcherConfig("streams needs a redis client with xtrim, xinfo and xpending");
580
+ }
581
+ const telemetry = opts.telemetry;
582
+ const service = o.serviceName;
583
+ const table = o.batch.outboxTable;
584
+ const handler = async () => {
585
+ const result = {
586
+ ran: false,
587
+ deletedRows: 0,
588
+ scrubbedRows: 0,
589
+ batches: 0,
590
+ complete: false,
591
+ leaseLost: false,
592
+ streams: [],
593
+ ranAt: new Date().toISOString(),
594
+ };
595
+ let run;
596
+ try {
597
+ run = await withSingleActiveLease({
598
+ redis,
599
+ service,
600
+ scope: OUTBOX_PRUNE_LEASE_SCOPE,
601
+ ttlMs: o.leaseTtlMs,
602
+ }, async (lease) => {
603
+ result.ran = true;
604
+ try {
605
+ const pruned = await runPrune(opts.pool, o.batch, {
606
+ beforeBatch: () => lease.validateFence(),
607
+ onBatch: (n, kind) => {
608
+ if (kind === "deleted")
609
+ result.deletedRows += n;
610
+ else
611
+ result.scrubbedRows += n;
612
+ result.batches += 1;
613
+ },
614
+ onMissingOrderIndex: (create) => telemetry?.logger?.warn("outbox-dispatcher: ordered outbox prune without its aggregate-order index; each batch can scan the table", { service, table, create }),
615
+ onMissingPruneIndex: (create) => telemetry?.logger?.warn("outbox-dispatcher: outbox prune without its prune index; each batch can scan the table", { service, table, create }),
616
+ });
617
+ result.complete = pruned.complete;
618
+ const now = Date.now();
619
+ for (const s of o.streams) {
620
+ try {
621
+ const t = await runTrim(redis, s.stream, {
622
+ retentionMs: s.retentionMs,
623
+ maxCalls: DEFAULT_STREAM_TRIM_MAX_CALLS,
624
+ respectConsumerGroups: o.respectConsumerGroups,
625
+ approximate: true,
626
+ }, now, () => lease.validateFence());
627
+ if (!t.complete)
628
+ result.complete = false;
629
+ result.streams.push(t);
630
+ }
631
+ catch (err) {
632
+ if (isFenceFailure(err))
633
+ throw err;
634
+ // One bad stream must not stop the others, nor the report.
635
+ result.complete = false;
636
+ result.streams.push({
637
+ stream: s.stream,
638
+ retentionMs: s.retentionMs,
639
+ minId: null,
640
+ trimmed: 0,
641
+ heldBackBy: null,
642
+ complete: false,
643
+ error: message(err),
644
+ });
645
+ }
646
+ }
647
+ }
648
+ catch (err) {
649
+ if (!isFenceFailure(err))
650
+ throw err;
651
+ result.leaseLost = true;
652
+ result.complete = false;
653
+ telemetry?.logger?.warn("outbox-dispatcher: outbox prune lost its lease mid-run; stopping", { service, error: message(err) });
654
+ }
655
+ });
656
+ }
657
+ catch (err) {
658
+ // A lease-backend outage at acquire, or a database error mid-run: count
659
+ // the failed run and the rows it already deleted, then fail.
660
+ report(telemetry, service, table, result, err);
661
+ throw err;
662
+ }
663
+ if (!run.ran) {
664
+ telemetry?.recordMetric({
665
+ kind: "counter",
666
+ name: "outbox.prune.runs",
667
+ value: 1,
668
+ attributes: { service, outcome: "skipped" },
669
+ });
670
+ return result;
671
+ }
672
+ report(telemetry, service, table, result);
673
+ return result;
674
+ };
675
+ return {
676
+ name: outboxPruneJobName(service),
677
+ intervalMs: o.intervalMs,
678
+ pool: "owner",
679
+ handler,
680
+ };
681
+ }
682
+ function report(telemetry, service, table, result, error) {
683
+ if (!telemetry)
684
+ return;
685
+ const outcome = error !== undefined
686
+ ? "error"
687
+ : result.leaseLost
688
+ ? "lease_lost"
689
+ : result.complete
690
+ ? "complete"
691
+ : "partial";
692
+ telemetry.recordMetric({
693
+ kind: "counter",
694
+ name: "outbox.prune.runs",
695
+ value: 1,
696
+ attributes: { service, outcome },
697
+ });
698
+ telemetry.recordMetric({
699
+ kind: "counter",
700
+ name: "outbox.prune.deleted_rows",
701
+ value: result.deletedRows,
702
+ attributes: { service, table },
703
+ });
704
+ telemetry.recordMetric({
705
+ kind: "counter",
706
+ name: "outbox.prune.scrubbed_rows",
707
+ value: result.scrubbedRows,
708
+ attributes: { service, table },
709
+ });
710
+ for (const s of result.streams) {
711
+ if (s.error !== undefined) {
712
+ telemetry.recordMetric({
713
+ kind: "counter",
714
+ name: "outbox.stream_trim.errors",
715
+ value: 1,
716
+ attributes: { service, stream: s.stream },
717
+ });
718
+ telemetry.logger?.warn("outbox-dispatcher: stream trim failed", {
719
+ service,
720
+ stream: s.stream,
721
+ error: s.error,
722
+ });
723
+ continue;
724
+ }
725
+ telemetry.recordMetric({
726
+ kind: "counter",
727
+ name: "outbox.stream_trim.entries",
728
+ value: s.trimmed,
729
+ attributes: { service, stream: s.stream },
730
+ });
731
+ telemetry.recordMetric({
732
+ kind: "gauge",
733
+ name: "outbox.stream_trim.held_back",
734
+ value: s.heldBackBy === null ? 0 : 1,
735
+ attributes: { service, stream: s.stream },
736
+ });
737
+ if (s.heldBackBy !== null) {
738
+ telemetry.logger?.warn("outbox-dispatcher: stream trim held back by a consumer group that has not read past the retention cutoff", { service, stream: s.stream, group: s.heldBackBy, min_id: s.minId });
739
+ }
740
+ }
741
+ const log = error !== undefined ? telemetry.logger?.error : telemetry.logger?.info;
742
+ log?.call(telemetry.logger, "outbox-dispatcher: outbox prune run finished", {
743
+ service,
744
+ table,
745
+ outcome,
746
+ ...(error !== undefined ? { error: message(error) } : {}),
747
+ deleted_rows: result.deletedRows,
748
+ scrubbed_rows: result.scrubbedRows,
749
+ batches: result.batches,
750
+ streams_trimmed: result.streams.map((s) => `${s.stream}:${s.error !== undefined ? "error" : s.trimmed}`),
751
+ });
752
+ }
753
+ //# sourceMappingURL=prune.js.map