@nodii/outbox-dispatcher 0.3.0 → 0.5.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/README.md CHANGED
@@ -3,7 +3,8 @@
3
3
  Producer-side Pattern-3 **outbox drainer** for the Nodii microservice stack —
4
4
  the symmetric peer of [`@nodii/replica-consumer`](../replica-consumer) (the
5
5
  consumer side). Drains a service's `<service>_outbox` table to Redis Streams
6
- via `XADD`, with single-active-worker leasing, retry-budget + DLQ, HWM
6
+ via `XADD`, with single-active-worker leasing, a retry-backoff cap, a
7
+ 24h-unpublished ops-alert sweep (**D401** — no publish-side DLQ), HWM
7
8
  exposure for snapshot live-stitch, lag/depth metrics, and graceful drain.
8
9
 
9
10
  Spec: planning hub `feature_doc` `serviceId=nodii-libs docKey=outbox-dispatcher`.
@@ -24,7 +25,7 @@ const dispatcher = defineDispatcher({
24
25
  leaseTtlMs: 30_000, // renew at ttl/2
25
26
  pollMs: 500, // § 9.2
26
27
  batchSize: 50, // § 9.2
27
- publishMaxAttempts: 8, // DLQ threshold
28
+ publishMaxAttempts: 8, // retry-backoff cap (D401: never deletes/DLQs)
28
29
  drainDeadlineSeconds: 30, // graceful drain
29
30
  });
30
31
 
@@ -56,18 +57,40 @@ path to prove round-trip. (The feature_doc § 5.2 lists individual XADD fields +
56
57
  field keyed `entity_version` — the consumer's read path is the binding
57
58
  contract per the feature_doc's own statement; drift filed.)
58
59
 
59
- ## DLQ (§ 5.4)
60
+ ## Publish failures + the 24h-unpublished sweep (D401)
60
61
 
61
- Rows hitting `publish_attempts >= publishMaxAttempts` move to
62
- `<service>_outbox_dlq` (`original_outbox_id`, `final_error`, `payload`, …) in
63
- the same tx as the failure, and a page-tier `outbox.publish_failures` counter
64
- fires. DLQ rows are not auto-retried.
62
+ There is **no publish-side DLQ**. Per locked decision **D401**
63
+ (`01-comms § 9.2` / `09-replication § 2.5`), a failed `XADD` only increments
64
+ `publish_attempts` + records `last_error` on the outbox row — the row is
65
+ **never deleted and never moved to a `<service>_outbox_dlq` table**, so the
66
+ at-least-once / replay-from-outbox invariant holds for financial + business
67
+ events. `publishMaxAttempts` caps retry **backoff** only (the claim query stops
68
+ re-claiming a row once `publish_attempts` reaches it); it never affects row
69
+ lifecycle.
70
+
71
+ Liveness is surfaced by a per-service **24h-unpublished sweep**. Schedule
72
+ `sweepUnpublishedOutbox` (e.g. hourly) — it selects rows un-dispatched past a
73
+ threshold (default 24h) and raises an **M17 page-tier ops alert**
74
+ (`outbox.unpublished_alert`, `severity=page`) carrying `outbox_id`, `topic`,
75
+ `event_id`, `publish_attempts`, `last_error`, `age`:
76
+
77
+ ```ts
78
+ import { sweepUnpublishedOutbox } from "@nodii/outbox-dispatcher";
79
+
80
+ // in your scheduler (BullMQ per 01 § 9.3, or your existing cron):
81
+ await sweepUnpublishedOutbox({ pool: pgPool, dispatcher, telemetry });
82
+ ```
83
+
84
+ This is distinct from the subscriber-side `replication_dlq` (`09 § 8.1`), which
85
+ handles consume-side poison applies and is unaffected.
65
86
 
66
87
  ## Metrics (§ 5.6)
67
88
 
68
89
  `outbox.depth{topic}` · `outbox.lag_seconds{topic}` · `outbox.dispatch_rate{topic}`
69
90
  · `outbox.publish_failures{topic,reason}` · `outbox.hwm{stream}` ·
70
- `outbox.lease_renewals{result}`.
91
+ `outbox.lease_renewals{result}`. D401 sweep:
92
+ `outbox.unpublished_over_threshold{service}` (gauge) ·
93
+ `outbox.unpublished_alert{topic,service,severity=page}` (the M17 alert).
71
94
 
72
95
  ## migrate-gen (§ 5.8)
73
96
 
@@ -75,8 +98,8 @@ fires. DLQ rows are not auto-retried.
75
98
  bunx @nodii/outbox-dispatcher migrate-gen --service nodii-tenant-service [--out-dir .]
76
99
  ```
77
100
 
78
- Emits the `<service>_outbox` + `<service>_outbox_dlq` DDL + a `src/outbox/boot.ts`
79
- skeleton.
101
+ Emits the `<service>_outbox` table DDL (D401: no publish-side DLQ table) + a
102
+ `src/outbox/boot.ts` skeleton.
80
103
 
81
104
  ## Optional `@nodii/db-rls` (08-rls § 4)
82
105
 
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- // migrate-gen CLI — emits the `<service>_outbox` + `<service>_outbox_dlq`
3
- // tables + boot wiring for a producing service. Per § 5.8.
2
+ // migrate-gen CLI — emits the `<service>_outbox` table + boot wiring for a
3
+ // producing service. Per § 5.8. (D401: no publish-side DLQ table.)
4
4
  //
5
5
  // bunx @nodii/outbox-dispatcher migrate-gen --service nodii-tenant-service
6
6
  //
@@ -18,8 +18,6 @@ function parseArgs(argv) {
18
18
  out.service = argv[++i];
19
19
  else if (a === "--outbox-table")
20
20
  out.outboxTable = argv[++i] ?? "outbox";
21
- else if (a === "--dlq-table")
22
- out.dlqTable = argv[++i];
23
21
  else if (a === "--out-dir")
24
22
  out.outDir = argv[++i];
25
23
  }
@@ -68,13 +66,11 @@ function main() {
68
66
  const args = parseArgs(process.argv.slice(2));
69
67
  if (!args.service) {
70
68
  process.stderr.write("usage: outbox-dispatcher migrate-gen --service <name> " +
71
- "[--outbox-table outbox] [--dlq-table <name>] [--out-dir <dir>]\n");
69
+ "[--outbox-table outbox] [--out-dir <dir>]\n");
72
70
  process.exit(2);
73
71
  }
74
- const dlqTable = args.dlqTable ?? `${snakeServiceName(args.service)}_outbox_dlq`;
75
72
  const migrationSql = getOutboxDispatcherMigrationSQL({
76
73
  outboxTable: args.outboxTable,
77
- dlqTable,
78
74
  });
79
75
  const boot = bootSkeleton(args.service, args.outboxTable);
80
76
  if (args.outDir) {
@@ -87,7 +83,7 @@ function main() {
87
83
  process.stdout.write(`wrote:\n ${join(sqlDir, "outbox.sql")}\n ${join(bootDir, "boot.ts")}\n`);
88
84
  }
89
85
  else {
90
- process.stdout.write(`-- ====== ${args.outboxTable} + ${dlqTable} (migration SQL) ======\n`);
86
+ process.stdout.write(`-- ====== ${args.outboxTable} (migration SQL) ======\n`);
91
87
  process.stdout.write(migrationSql);
92
88
  process.stdout.write("\n-- ====== src/outbox/boot.ts ======\n");
93
89
  process.stdout.write(boot);
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-gen.js","sourceRoot":"","sources":["../../src/cli/migrate-gen.ts"],"names":[],"mappings":";AACA,0EAA0E;AAC1E,2DAA2D;AAC3D,EAAE;AACF,6EAA6E;AAC7E,EAAE;AACF,qEAAqE;AACrE,iEAAiE;AAEjE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AASzE,SAAS,SAAS,CAAC,IAAc;IAC/B,MAAM,GAAG,GAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC;IAC5C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,IAAI,CAAC,KAAK,WAAW;YAAE,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;aAC1C,IAAI,CAAC,KAAK,gBAAgB;YAAE,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,QAAQ,CAAC;aACpE,IAAI,CAAC,KAAK,aAAa;YAAE,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;aAClD,IAAI,CAAC,KAAK,WAAW;YAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,YAAY,CAAC,OAAe,EAAE,WAAmB;IACxD,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;kBAy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,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;QACnD,SAAS,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACvC,SAAS,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACxC,aAAa,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,EAAE,YAAY,CAAC,CAAC;QACxD,aAAa,CAAC,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC;QAC9C,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,aAAa,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,IAAI,CAC3E,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,aAAa,IAAI,CAAC,WAAW,2BAA2B,CACzD,CAAC;QACF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACnC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;QAChE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC"}
@@ -3,7 +3,7 @@ import { type DispatcherConfig, type ResolvedDispatcher } from "./types.js";
3
3
  export declare const DEFAULT_POLL_MS = 500;
4
4
  /** Default batch size per `01-comms § 9.2`. */
5
5
  export declare const DEFAULT_BATCH_SIZE = 50;
6
- /** Default publish attempts before DLQ. */
6
+ /** Default retry-backoff cap (D401: caps re-claim, never deletes the row). */
7
7
  export declare const DEFAULT_PUBLISH_MAX_ATTEMPTS = 8;
8
8
  /** Default lease TTL (ms) (D209). */
9
9
  export declare const DEFAULT_LEASE_TTL_MS = 30000;
@@ -11,7 +11,7 @@ export declare const DEFAULT_LEASE_TTL_MS = 30000;
11
11
  export declare const DEFAULT_DRAIN_DEADLINE_SECONDS = 30;
12
12
  /** Default per-stream MAXLEN ~ approximation (doctrine § 3). */
13
13
  export declare const DEFAULT_STREAM_MAXLEN = 1000000;
14
- /** Snake-case a service name for the default DLQ table + lease key. */
14
+ /** Snake-case a service name (used by migrate-gen for default table naming). */
15
15
  export declare function snakeServiceName(serviceName: string): string;
16
16
  /**
17
17
  * Define an outbox dispatcher. Resolves defaults + validates. Pass the
@@ -1 +1 @@
1
- {"version":3,"file":"define-dispatcher.d.ts","sourceRoot":"","sources":["../src/define-dispatcher.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EACxB,MAAM,YAAY,CAAC;AAEpB,uDAAuD;AACvD,eAAO,MAAM,eAAe,MAAM,CAAC;AACnC,+CAA+C;AAC/C,eAAO,MAAM,kBAAkB,KAAK,CAAC;AACrC,2CAA2C;AAC3C,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,qCAAqC;AACrC,eAAO,MAAM,oBAAoB,QAAS,CAAC;AAC3C,qDAAqD;AACrD,eAAO,MAAM,8BAA8B,KAAK,CAAC;AACjD,gEAAgE;AAChE,eAAO,MAAM,qBAAqB,UAAY,CAAC;AAE/C,uEAAuE;AACvE,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAK5D;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,kBAAkB,CAuC7E"}
1
+ {"version":3,"file":"define-dispatcher.d.ts","sourceRoot":"","sources":["../src/define-dispatcher.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EACxB,MAAM,YAAY,CAAC;AAEpB,uDAAuD;AACvD,eAAO,MAAM,eAAe,MAAM,CAAC;AACnC,+CAA+C;AAC/C,eAAO,MAAM,kBAAkB,KAAK,CAAC;AACrC,8EAA8E;AAC9E,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,qCAAqC;AACrC,eAAO,MAAM,oBAAoB,QAAS,CAAC;AAC3C,qDAAqD;AACrD,eAAO,MAAM,8BAA8B,KAAK,CAAC;AACjD,gEAAgE;AAChE,eAAO,MAAM,qBAAqB,UAAY,CAAC;AAE/C,gFAAgF;AAChF,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAK5D;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,kBAAkB,CAqC7E"}
@@ -8,7 +8,7 @@ import { InvalidDispatcherConfig, } from "./types.js";
8
8
  export const DEFAULT_POLL_MS = 500;
9
9
  /** Default batch size per `01-comms § 9.2`. */
10
10
  export const DEFAULT_BATCH_SIZE = 50;
11
- /** Default publish attempts before DLQ. */
11
+ /** Default retry-backoff cap (D401: caps re-claim, never deletes the row). */
12
12
  export const DEFAULT_PUBLISH_MAX_ATTEMPTS = 8;
13
13
  /** Default lease TTL (ms) (D209). */
14
14
  export const DEFAULT_LEASE_TTL_MS = 30_000;
@@ -16,7 +16,7 @@ export const DEFAULT_LEASE_TTL_MS = 30_000;
16
16
  export const DEFAULT_DRAIN_DEADLINE_SECONDS = 30;
17
17
  /** Default per-stream MAXLEN ~ approximation (doctrine § 3). */
18
18
  export const DEFAULT_STREAM_MAXLEN = 1_000_000;
19
- /** Snake-case a service name for the default DLQ table + lease key. */
19
+ /** Snake-case a service name (used by migrate-gen for default table naming). */
20
20
  export function snakeServiceName(serviceName) {
21
21
  return serviceName
22
22
  .replace(/[^A-Za-z0-9]+/g, "_")
@@ -34,7 +34,6 @@ export function defineDispatcher(config) {
34
34
  if (typeof config.streamFor !== "function") {
35
35
  throw new InvalidDispatcherConfig("streamFor must be a function");
36
36
  }
37
- const snake = snakeServiceName(config.serviceName);
38
37
  const leaseTtlMs = config.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
39
38
  if (leaseTtlMs < 2_000) {
40
39
  throw new InvalidDispatcherConfig(`leaseTtlMs must be >= 2000 (got ${leaseTtlMs}); renewal cadence is ttl/2`);
@@ -50,7 +49,6 @@ export function defineDispatcher(config) {
50
49
  return {
51
50
  serviceName: config.serviceName,
52
51
  outboxTable: config.outboxTable ?? "outbox",
53
- dlqTable: config.dlqTable ?? `${snake}_outbox_dlq`,
54
52
  streamFor: config.streamFor,
55
53
  leaseKey: config.leaseKey ?? `lock:outbox:${config.serviceName}`,
56
54
  leaseTtlMs,
@@ -1 +1 @@
1
- {"version":3,"file":"define-dispatcher.js","sourceRoot":"","sources":["../src/define-dispatcher.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,EAAE;AACF,0EAA0E;AAC1E,yEAAyE;AACzE,wBAAwB;AAExB,OAAO,EAEL,uBAAuB,GAExB,MAAM,YAAY,CAAC;AAEpB,uDAAuD;AACvD,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAC;AACnC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AACrC,2CAA2C;AAC3C,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAC9C,qCAAqC;AACrC,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAC3C,qDAAqD;AACrD,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AACjD,gEAAgE;AAChE,MAAM,CAAC,MAAM,qBAAqB,GAAG,SAAS,CAAC;AAE/C,uEAAuE;AACvE,MAAM,UAAU,gBAAgB,CAAC,WAAmB;IAClD,OAAO,WAAW;SACf,OAAO,CAAC,gBAAgB,EAAE,GAAG,CAAC;SAC9B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,WAAW,EAAE,CAAC;AACnB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAwB;IACvD,IAAI,CAAC,MAAM,CAAC,WAAW,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EA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AAM,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,oBAAoB,CAAC;IAC7D,IAAI,UAAU,GAAG,KAAK,EAAE,CAAC;QACvB,MAAM,IAAI,uBAAuB,CAC/B,mCAAmC,UAAU,6BAA6B,CAC3E,CAAC;IACJ,CAAC;IACD,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,kBAAkB,CAAC;IACzD,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;QAClB,MAAM,IAAI,uBAAuB,CAAC,wBAAwB,CAAC,CAAC;IAC9D,CAAC;IACD,MAAM,kBAAkB,GACtB,MAAM,CAAC,kBAAkB,IAAI,4BAA4B,CAAC;IAC5D,IAAI,kBAAkB,GAAG,CAAC,EAAE,CAAC;QAC3B,MAAM,IAAI,uBAAuB,CAAC,iCAAiC,CAAC,CAAC;IACvE,CAAC;IAED,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,QAAQ;QAC3C,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,eAAe,MAAM,CAAC,WAAW,EAAE;QAChE,UAAU;QACV,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,eAAe;QACxC,SAAS;QACT,kBAAkB;QAClB,oBAAoB,EAClB,MAAM,CAAC,oBAAoB,IAAI,8BAA8B;QAC/D,kBAAkB,EAAE,MAAM,CAAC,kBAAkB,IAAI,qBAAqB;QACtE,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAC;AACJ,CAAC"}
package/dist/drainer.d.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  import type { ResolvedDispatcher, ResolvedStartConfig } from "./types.js";
2
+ /**
3
+ * The substrate-lease scope for the outbox drainer. The canonical lease key is
4
+ * `nodii:lease:<service>:outbox`; the OLD `lock:outbox:<service>` key becomes the
5
+ * deploy-window `legacyKey`. Pinned by D402 PR5.
6
+ */
7
+ export declare const LEASE_SCOPE = "outbox";
2
8
  export interface DispatcherRunnerHandle {
3
9
  /** Latest XADD id emitted for `stream` this process, or null (§ 5.3). */
4
10
  currentHwm(stream: string): string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"drainer.d.ts","sourceRoot":"","sources":["../src/drainer.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAEV,kBAAkB,EAClB,mBAAmB,EAGpB,MAAM,YAAY,CAAC;AAMpB,MAAM,WAAW,sBAAsB;IACrC,yEAAyE;IACzE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAC1C,mEAAmE;IACnE,GAAG,IAAI,MAAM,CAAC;IACd,mEAAmE;IACnE,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,wEAAwE;IACxE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,uEAAuE;IACvE,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9B;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE;IAChD,UAAU,EAAE,kBAAkB,CAAC;IAC/B,KAAK,EAAE,mBAAmB,CAAC;IAC3B,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CA2RlC"}
1
+ {"version":3,"file":"drainer.d.ts","sourceRoot":"","sources":["../src/drainer.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EAGV,kBAAkB,EAClB,mBAAmB,EAGpB,MAAM,YAAY,CAAC;AAKpB;;;;GAIG;AACH,eAAO,MAAM,WAAW,WAAW,CAAC;AAUpC,MAAM,WAAW,sBAAsB;IACrC,yEAAyE;IACzE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IAC1C,mEAAmE;IACnE,GAAG,IAAI,MAAM,CAAC;IACd,mEAAmE;IACnE,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,wEAAwE;IACxE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB,uEAAuE;IACvE,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC9B;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE;IAChD,UAAU,EAAE,kBAAkB,CAAC;IAC/B,KAAK,EAAE,mBAAmB,CAAC;IAC3B,qDAAqD;IACrD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAkVlC"}
package/dist/drainer.js CHANGED
@@ -1,19 +1,69 @@
1
1
  // The drain loop — the producer-side Pattern-3 pump. Per § 5.2:
2
2
  //
3
- // acquire-lease (D209 SET-NX-EX) → SELECT FOR UPDATE SKIP LOCKED →
4
- // XADD canonical envelope → mark dispatched_at → release. At-least-once
5
- // (the consumer dedupes via consumed_events).
3
+ // acquire-lease (substrate SingleActiveLease) → SELECT FOR UPDATE SKIP LOCKED →
4
+ // XADD canonical envelope → validateFence(token) → mark dispatched_at → release.
5
+ // At-least-once (the consumer dedupes via consumed_events).
6
6
  //
7
7
  // One DispatcherRunner per ResolvedDispatcher. The runner holds the lease,
8
- // polls + drains, tracks the HWM, emits the six § 5.6 metrics, moves rows to
9
- // the DLQ on max-retry, and drains gracefully on stop().
8
+ // polls + drains, tracks the HWM, emits the six § 5.6 metrics, and drains
9
+ // gracefully on stop(). Per locked decision D401 a publish failure NEVER moves
10
+ // a row off the outbox: it only increments publish_attempts + last_error and
11
+ // leaves the row in place (the 24h-unpublished sweep surfaces the liveness
12
+ // problem — see sweep.ts).
13
+ //
14
+ // ── D402 PR5: lease UNIFIED onto the substrate `SingleActiveLease` ───────────
15
+ // The bespoke `tryAcquireLease` (bare-owner SET-NX-EX, NO fence) is replaced by
16
+ // the canonical `SingleActiveLease` from `@nodii/telemetry/worker`, which adds:
17
+ //
18
+ // 1. A FENCING TOKEN, captured at acquire + validated AT THE SIDE-EFFECTING
19
+ // MOMENT. The outbox drain is NON-IDEMPOTENT (markDispatched + at-least-once
20
+ // publish), so a drainer that lost the lease mid-batch (TTL lapse / takeover)
21
+ // MUST NOT mark rows dispatched — that would cede a row to a successor while
22
+ // ALSO marking it done here, dropping the event. We call
23
+ // `lease.validateFence(token)` AFTER publishRow and BEFORE markDispatched:
24
+ // - FenceLostError → the lease verifiably belongs to a successor now.
25
+ // Abort the batch (cede); the row is NOT marked,
26
+ // the successor re-drains it. Benign handoff.
27
+ // - FenceCheckUnavailableError → the lease backend is unreachable, so
28
+ // ownership cannot be DETERMINED. FAIL CLOSED:
29
+ // abort + retry next tick; never mark, never
30
+ // double-publish-mark.
31
+ // This mirrors the substrate `OutboxDispatcher` worker's already-correct
32
+ // semantics (go/telemetry/worker/outbox_dispatcher.go).
33
+ //
34
+ // 2. A deploy-window `legacyKey` shim. The substrate canonical key is
35
+ // `nodii:lease:<service>:outbox` (scope "outbox"); `legacyKey` is the OLD
36
+ // key the consumer used (`dispatcher.leaseKey`, default `lock:outbox:<svc>`).
37
+ // During a rolling deploy an OLD instance's `SET lock:outbox:<svc> NX` and a
38
+ // NEW substrate-leased instance mutually exclude (both-or-neither acquire).
39
+ //
40
+ // 3. FAIL-CLOSED on a lease-backend outage at ACQUIRE: if the lease cannot be
41
+ // acquired because the lease Redis is down, we DO NOT drain (skip the tick +
42
+ // fire an observability signal). We never drain without the lease.
43
+ //
44
+ // NOTE (future wave): this swaps only the LEASE primitive — the bespoke drainer
45
+ // ENGINE (buildEnvelope / stream routing / streamMaxLenApprox / tenant pool /
46
+ // 24h sweep / migrate-gen CLI) is UNCHANGED. Rebasing the whole drainer onto the
47
+ // substrate `OutboxDispatcher` worker type is a SEPARATE future item, not this PR.
48
+ import { FenceCheckUnavailableError, FenceLostError, SingleActiveLease, } from "@nodii/telemetry/worker";
10
49
  import { buildEnvelope, xaddEnvelope } from "./envelope.js";
11
50
  import { HwmTracker } from "./hwm.js";
12
- import { tryAcquireLease } from "./lease.js";
13
- import { buildClaimBatchSql, buildDeleteOutboxRowSql, buildDepthByTopicSql, buildDlqInsertSql, buildMarkDispatchedSql, buildRecordFailureSql, } from "./sql-builders.js";
14
- import { uuidv7 } from "./uuid.js";
51
+ import { buildClaimBatchSql, buildDepthByTopicSql, buildMarkDispatchedSql, buildRecordFailureSql, } from "./sql-builders.js";
15
52
  /** How often (ms) the `outbox.depth` gauge is sampled. Per § 5.6 (30s). */
16
53
  const DEPTH_SAMPLE_MS = 30_000;
54
+ /**
55
+ * The substrate-lease scope for the outbox drainer. The canonical lease key is
56
+ * `nodii:lease:<service>:outbox`; the OLD `lock:outbox:<service>` key becomes the
57
+ * deploy-window `legacyKey`. Pinned by D402 PR5.
58
+ */
59
+ export const LEASE_SCOPE = "outbox";
60
+ /**
61
+ * Counter fired when the drain tick is SKIPPED because the lease backend is
62
+ * unreachable (acquire/validate could not determine ownership). This is the
63
+ * fail-closed observability signal: a non-idempotent drainer never proceeds
64
+ * without a verified lease. `reason` distinguishes acquire-time vs fence-time.
65
+ */
66
+ const LEASE_UNAVAILABLE_METRIC = "outbox.lease_unavailable";
17
67
  export async function startDispatcherRunner(args) {
18
68
  const { dispatcher, start } = args;
19
69
  const { redis, telemetry } = start;
@@ -25,8 +75,6 @@ export async function startDispatcherRunner(args) {
25
75
  const claimSql = buildClaimBatchSql(dispatcher.outboxTable);
26
76
  const markSql = buildMarkDispatchedSql(dispatcher.outboxTable);
27
77
  const failSql = buildRecordFailureSql(dispatcher.outboxTable);
28
- const dlqInsertSql = buildDlqInsertSql(dispatcher.dlqTable);
29
- const deleteSql = buildDeleteOutboxRowSql(dispatcher.outboxTable);
30
78
  const depthSql = buildDepthByTopicSql(dispatcher.outboxTable);
31
79
  // ── Pool resolution (optional db-rls per 08-rls § 4) ───────────────
32
80
  function resolvePool() {
@@ -48,15 +96,58 @@ export async function startDispatcherRunner(args) {
48
96
  return start.pgPool;
49
97
  }
50
98
  const pool = resolvePool();
51
- // ── Lease (D209) ───────────────────────────────────────────────────
52
- let lease = await tryAcquireLease({
53
- redis,
54
- leaseKey: dispatcher.leaseKey,
55
- leaseTtlMs: dispatcher.leaseTtlMs,
56
- ownerId: args.ownerId,
57
- telemetry,
58
- serviceName: dispatcher.serviceName,
59
- });
99
+ /**
100
+ * Fail-closed observability signal: the drain tick was SKIPPED because the
101
+ * lease backend could not confirm ownership (acquire threw, or a fence check
102
+ * was unavailable). A non-idempotent drainer NEVER proceeds without a verified
103
+ * lease — we surface the skip loudly rather than draining blind.
104
+ */
105
+ function signalLeaseUnavailable(reason, err) {
106
+ telemetry.recordMetric({
107
+ kind: "counter",
108
+ name: LEASE_UNAVAILABLE_METRIC,
109
+ value: 1,
110
+ attributes: { service: dispatcher.serviceName, reason },
111
+ });
112
+ telemetry.logger?.warn("outbox-dispatcher: lease backend unavailable — drain tick withheld (fail-closed)", {
113
+ service: dispatcher.serviceName,
114
+ reason,
115
+ error: err instanceof Error ? err.message : String(err),
116
+ });
117
+ }
118
+ // ── Lease (D402: substrate SingleActiveLease) ──────────────────────
119
+ // Canonical key `nodii:lease:<service>:outbox`; `legacyKey` is the OLD
120
+ // key (`dispatcher.leaseKey`) so a rolling deploy mutually-excludes an old
121
+ // `lock:outbox:<svc>` SET-NX instance and this new substrate-leased one.
122
+ // `telemetry.recordMetric` matches the substrate's LeaseTelemetry shape — the
123
+ // lease emits the canonical `nodii.worker.lease.*` metrics through it.
124
+ const leaseTelemetry = {
125
+ recordMetric: (m) => telemetry.recordMetric(m),
126
+ };
127
+ function newLease() {
128
+ return new SingleActiveLease({
129
+ redis: redis,
130
+ service: dispatcher.serviceName,
131
+ scope: LEASE_SCOPE,
132
+ ttlMs: dispatcher.leaseTtlMs,
133
+ ownerId: args.ownerId,
134
+ legacyKey: dispatcher.leaseKey,
135
+ telemetry: leaseTelemetry,
136
+ });
137
+ }
138
+ // Acquire is fail-closed: a lease-backend outage at acquire surfaces as a
139
+ // thrown eval (the substrate does NOT swallow acquire errors). We treat both
140
+ // "not acquired" and "acquire threw" as DO-NOT-DRAIN (see the poll loop +
141
+ // drainOnce); we never drain without the lease.
142
+ let lease = newLease();
143
+ let acquireFailed = false;
144
+ try {
145
+ await lease.acquire();
146
+ }
147
+ catch (err) {
148
+ acquireFailed = true;
149
+ signalLeaseUnavailable("acquire", err);
150
+ }
60
151
  function recordLag(occurredAtMs) {
61
152
  const lagSec = (Date.now() - occurredAtMs) / 1000;
62
153
  telemetry.recordMetric({
@@ -69,49 +160,6 @@ export async function startDispatcherRunner(args) {
69
160
  if (lagSamples.length > 1024)
70
161
  lagSamples.shift();
71
162
  }
72
- // ── Move a row to the DLQ (§ 5.4) ──────────────────────────────────
73
- async function moveToDlq(tx, row, finalError) {
74
- await tx.unsafe(dlqInsertSql, [
75
- uuidv7(),
76
- row.id,
77
- row.topic,
78
- row.aggregate_kind,
79
- row.aggregate_id,
80
- row.event_id,
81
- JSON.stringify(row.payload ?? {}),
82
- finalError,
83
- row.publish_attempts + 1,
84
- ]);
85
- await tx.unsafe(deleteSql, [row.id]);
86
- telemetry.recordMetric({
87
- kind: "counter",
88
- name: "outbox.publish_failures",
89
- value: 1,
90
- attributes: { topic: row.topic, reason: "dlq" },
91
- });
92
- // Page-tier alert per 03-logging-doctrine (§ 5.4).
93
- telemetry.recordMetric({
94
- kind: "counter",
95
- name: "outbox.publish_failures",
96
- value: 1,
97
- attributes: { topic: row.topic, reason: "dlq", severity: "page" },
98
- });
99
- try {
100
- await telemetry.emitAudit?.({
101
- action: `${dispatcher.serviceName}.outbox.dlq`,
102
- metadata: {
103
- original_outbox_id: row.id,
104
- event_id: row.event_id,
105
- topic: row.topic,
106
- final_error: finalError,
107
- publish_attempts: row.publish_attempts + 1,
108
- },
109
- });
110
- }
111
- catch {
112
- /* best-effort */
113
- }
114
- }
115
163
  // ── XADD one row (outside the claim tx) + return the assigned id ────
116
164
  async function publishRow(row) {
117
165
  const stream = dispatcher.streamFor(row);
@@ -141,18 +189,38 @@ export async function startDispatcherRunner(args) {
141
189
  }
142
190
  return streamId;
143
191
  }
144
- // ── One drain pass: claim a batch in a tx, XADD each, mark dispatched.
192
+ // ── One drain pass: claim a batch in a tx, XADD each, fence-guard, mark.
145
193
  //
146
194
  // We open ONE tx, SELECT FOR UPDATE SKIP LOCKED to claim the batch, then
147
- // XADD + mark each row inside that same tx so the row-lock is held across
148
- // the XADD (a second drainer can't double-claim). The XADD is at-least-once
149
- // safe: if the process dies AFTER XADD but BEFORE the tx commits, the row
150
- // stays un-dispatched and is re-XADD'd on restart; the consumer dedupes on
151
- // event_id. Idempotent re-XADD: dispatched_at IS NOT NULL rows are never
152
- // re-claimed (the WHERE clause excludes them).
195
+ // XADD + validateFence + mark each row inside that same tx so the row-lock is
196
+ // held across the XADD (a second drainer can't double-claim). The XADD is
197
+ // at-least-once safe: if the process dies AFTER XADD but BEFORE the tx commits,
198
+ // the row stays un-dispatched and is re-XADD'd on restart; the consumer
199
+ // dedupes on event_id. Idempotent re-XADD: dispatched_at IS NOT NULL rows are
200
+ // never re-claimed (the WHERE clause excludes them).
201
+ //
202
+ // D402 PR5 — FAIL CLOSED + FENCE (the outbox drain is NON-idempotent):
203
+ // • If we don't hold the lease (never acquired / lost / acquire failed), do
204
+ // NOT drain. Return 0.
205
+ // • Before EACH markDispatched, `lease.validateFence(token)`:
206
+ // - FenceLostError → a successor owns the lease now. Abort the
207
+ // batch WITHOUT marking the row (cede; the successor re-drains it).
208
+ // - FenceCheckUnavailableError → the lease backend is unreachable;
209
+ // ownership is indeterminate. FAIL CLOSED: signal + abort the batch
210
+ // WITHOUT marking. Never mark, never double-publish-mark.
211
+ // Either way the in-flight row is left un-dispatched (its XADD may have
212
+ // landed — at-least-once; the consumer dedupes on event_id).
153
213
  async function drainOnce() {
154
214
  if (stopped && !draining)
155
215
  return 0;
216
+ // FAIL CLOSED at the tick boundary: a non-idempotent drainer never drains
217
+ // without a verified lease. `acquireFailed` (lease backend down at acquire)
218
+ // and "not currently holding the lease" both withhold the tick.
219
+ if (acquireFailed || !lease.leaseAcquired)
220
+ return 0;
221
+ const token = lease.fencingToken;
222
+ if (token === null)
223
+ return 0;
156
224
  let dispatched = 0;
157
225
  await pool.begin(async (tx) => {
158
226
  const claimed = (await tx.unsafe(claimSql, [
@@ -162,34 +230,64 @@ export async function startDispatcherRunner(args) {
162
230
  const rows = Array.isArray(claimed) ? claimed : [];
163
231
  if (rows.length === 0)
164
232
  return;
233
+ // Set true by a fence guard to abort the rest of the batch (cede to the
234
+ // successor / fail closed on an indeterminate lease) AFTER the finally runs.
235
+ let ceded = false;
165
236
  for (const row of normalizeRows(rows)) {
166
237
  if (lease.lost)
167
238
  break;
168
239
  inFlight += 1;
169
240
  try {
170
241
  const streamId = await publishRow(row);
242
+ // FENCE GUARD — prove the lease is STILL ours under `token` before the
243
+ // non-idempotent markDispatched. A lease lost/taken-over mid-batch
244
+ // throws here, so the row is NOT marked (it cedes to the successor).
245
+ await lease.validateFence(token);
171
246
  await tx.unsafe(markSql, [streamId, row.id]);
172
247
  recordLag(toEpochMs(row.occurred_at));
173
248
  dispatched += 1;
174
249
  }
175
250
  catch (err) {
176
- const msg = err instanceof Error ? err.message : String(err);
177
- telemetry.recordMetric({
178
- kind: "counter",
179
- name: "outbox.publish_failures",
180
- value: 1,
181
- attributes: { topic: row.topic, reason: "redis_xadd" },
182
- });
183
- if (row.publish_attempts + 1 >= dispatcher.publishMaxAttempts) {
184
- await moveToDlq(tx, row, msg);
251
+ if (err instanceof FenceLostError) {
252
+ // Verified handoff: the lease belongs to a successor. Abort the batch
253
+ // WITHOUT recording a publish failure (publishing succeeded; only the
254
+ // mark was withheld) — the successor re-drains this row. The tx
255
+ // commits whatever was marked before the loss.
256
+ telemetry.logger?.warn("outbox-dispatcher: fence lost mid-batch — ceding remaining rows to the lease successor", { service: dispatcher.serviceName, leaseKey: err.leaseKey });
257
+ ceded = true;
258
+ }
259
+ else if (err instanceof FenceCheckUnavailableError) {
260
+ // Lease backend unreachable — ownership indeterminate. FAIL CLOSED:
261
+ // withhold the mark + abort the batch + signal. The row stays
262
+ // un-dispatched and is re-drained on the next tick after recovery
263
+ // (at-least-once; never double-publish-mark).
264
+ signalLeaseUnavailable("fence", err);
265
+ ceded = true;
185
266
  }
186
267
  else {
268
+ const msg = err instanceof Error ? err.message : String(err);
269
+ telemetry.recordMetric({
270
+ kind: "counter",
271
+ name: "outbox.publish_failures",
272
+ value: 1,
273
+ attributes: { topic: row.topic, reason: "redis_xadd" },
274
+ });
275
+ // D401: ALWAYS record the failure on the outbox row (increment
276
+ // publish_attempts + last_error + last_attempt_at) and leave the row
277
+ // in place. NEVER DELETE, NEVER move to a DLQ table, regardless of
278
+ // attempt count. `publishMaxAttempts` caps retry *backoff* only (the
279
+ // claim query stops re-claiming a row once publish_attempts reaches
280
+ // it — buildClaimBatchSql `publish_attempts < $1`); the row stays as
281
+ // the source of truth and the 24h-unpublished sweep (sweep.ts) raises
282
+ // the M17 page-tier ops alert. (01-comms § 9.2 / 09-replication § 2.5)
187
283
  await tx.unsafe(failSql, [msg, row.id]);
188
284
  }
189
285
  }
190
286
  finally {
191
287
  inFlight -= 1;
192
288
  }
289
+ if (ceded)
290
+ break;
193
291
  }
194
292
  });
195
293
  return dispatched;
@@ -217,7 +315,7 @@ export async function startDispatcherRunner(args) {
217
315
  const autoStart = args.autoStart !== false;
218
316
  const depthTimer = autoStart
219
317
  ? setInterval(() => {
220
- if (lease.acquired && !lease.lost)
318
+ if (lease.leaseAcquired)
221
319
  void sampleDepth();
222
320
  }, DEPTH_SAMPLE_MS)
223
321
  : undefined;
@@ -228,18 +326,24 @@ export async function startDispatcherRunner(args) {
228
326
  : (async () => {
229
327
  while (!stopped) {
230
328
  try {
231
- // Re-acquire the lease if we don't hold it (or lost it).
232
- if (!lease.acquired || lease.lost) {
329
+ // Re-acquire the lease if we don't hold it (or lost it). A fresh
330
+ // SingleActiveLease per attempt captures a NEW (strictly greater)
331
+ // fence token, so a previously-lost holder cannot resurface.
332
+ if (!lease.leaseAcquired) {
233
333
  await lease.release();
234
- lease = await tryAcquireLease({
235
- redis,
236
- leaseKey: dispatcher.leaseKey,
237
- leaseTtlMs: dispatcher.leaseTtlMs,
238
- ownerId: args.ownerId,
239
- telemetry,
240
- serviceName: dispatcher.serviceName,
241
- });
242
- if (!lease.acquired) {
334
+ lease = newLease();
335
+ // FAIL CLOSED: a lease-backend outage at re-acquire throws (the
336
+ // substrate does not swallow acquire errors). Signal + back off;
337
+ // never drain without the lease.
338
+ try {
339
+ acquireFailed = false;
340
+ await lease.acquire();
341
+ }
342
+ catch (err) {
343
+ acquireFailed = true;
344
+ signalLeaseUnavailable("acquire", err);
345
+ }
346
+ if (acquireFailed || !lease.leaseAcquired) {
243
347
  await sleep(dispatcher.pollMs);
244
348
  continue;
245
349
  }
@@ -269,7 +373,7 @@ export async function startDispatcherRunner(args) {
269
373
  return percentile(lagSamples, 95);
270
374
  },
271
375
  get leaseAcquired() {
272
- return lease.acquired && !lease.lost;
376
+ return lease.leaseAcquired;
273
377
  },
274
378
  drainOnce,
275
379
  async stop() {