@nodii/outbox-dispatcher 0.0.1 → 0.2.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.
Files changed (55) hide show
  1. package/README.md +82 -2
  2. package/dist/cli/migrate-gen.d.ts +3 -0
  3. package/dist/cli/migrate-gen.d.ts.map +1 -0
  4. package/dist/cli/migrate-gen.js +97 -0
  5. package/dist/cli/migrate-gen.js.map +1 -0
  6. package/dist/define-dispatcher.d.ts +21 -0
  7. package/dist/define-dispatcher.d.ts.map +1 -0
  8. package/dist/define-dispatcher.js +65 -0
  9. package/dist/define-dispatcher.js.map +1 -0
  10. package/dist/drainer.d.ts +26 -0
  11. package/dist/drainer.d.ts.map +1 -0
  12. package/dist/drainer.js +339 -0
  13. package/dist/drainer.js.map +1 -0
  14. package/dist/envelope.d.ts +27 -0
  15. package/dist/envelope.d.ts.map +1 -0
  16. package/dist/envelope.js +77 -0
  17. package/dist/envelope.js.map +1 -0
  18. package/dist/hwm.d.ts +15 -0
  19. package/dist/hwm.d.ts.map +1 -0
  20. package/dist/hwm.js +51 -0
  21. package/dist/hwm.js.map +1 -0
  22. package/dist/index.d.ts +14 -2
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +30 -1
  25. package/dist/index.js.map +1 -0
  26. package/dist/lease.d.ts +27 -0
  27. package/dist/lease.d.ts.map +1 -0
  28. package/dist/lease.js +97 -0
  29. package/dist/lease.js.map +1 -0
  30. package/dist/migrations/index.d.ts +12 -0
  31. package/dist/migrations/index.d.ts.map +1 -0
  32. package/dist/migrations/index.js +88 -0
  33. package/dist/migrations/index.js.map +1 -0
  34. package/dist/sql-builders.d.ts +20 -0
  35. package/dist/sql-builders.d.ts.map +1 -0
  36. package/dist/sql-builders.js +70 -0
  37. package/dist/sql-builders.js.map +1 -0
  38. package/dist/start.d.ts +25 -0
  39. package/dist/start.d.ts.map +1 -0
  40. package/dist/start.js +74 -0
  41. package/dist/start.js.map +1 -0
  42. package/dist/test-doubles/index.d.ts +56 -0
  43. package/dist/test-doubles/index.d.ts.map +1 -0
  44. package/dist/test-doubles/index.js +145 -0
  45. package/dist/test-doubles/index.js.map +1 -0
  46. package/dist/types.d.ts +195 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +33 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/uuid.d.ts +2 -0
  51. package/dist/uuid.d.ts.map +1 -0
  52. package/dist/uuid.js +28 -0
  53. package/dist/uuid.js.map +1 -0
  54. package/package.json +40 -3
  55. package/src/migrations/001-outbox-dispatcher.sql +60 -0
package/README.md CHANGED
@@ -1,5 +1,85 @@
1
1
  # @nodii/outbox-dispatcher
2
2
 
3
- Placeholder package at v0.0.1. Real implementation ships at v0.1.0 per the locked feature_doc.
3
+ Producer-side Pattern-3 **outbox drainer** for the Nodii microservice stack —
4
+ the symmetric peer of [`@nodii/replica-consumer`](../replica-consumer) (the
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
7
+ exposure for snapshot live-stitch, lag/depth metrics, and graceful drain.
4
8
 
5
- **Spec**: `https://planning.dev.nucleus-cloud.in/api/v1/feature-docs?serviceId=nodii-libs&docKey=outbox-dispatcher`
9
+ Spec: planning hub `feature_doc` `serviceId=nodii-libs docKey=outbox-dispatcher`.
10
+ Implements `01-communication-doctrine § 9.2` (drainer, softened by **D209**:
11
+ `SET-NX-EX` lease is canonical, BullMQ optional) + `09-replication-doctrine
12
+ § 2.4` (XADD envelope) + `§ 7` (snapshot HWM cursor).
13
+
14
+ ## Quick start
15
+
16
+ ```ts
17
+ import { defineDispatcher, startDispatcher } from "@nodii/outbox-dispatcher";
18
+
19
+ const dispatcher = defineDispatcher({
20
+ serviceName: "nodii-tenant-service",
21
+ outboxTable: "outbox", // 09-replication § 2.2
22
+ streamFor: (row) => `tenant.${row.topic.split(".")[1]}`,
23
+ leaseKey: "lock:outbox:tenant-service", // D209 SET-NX-EX
24
+ leaseTtlMs: 30_000, // renew at ttl/2
25
+ pollMs: 500, // § 9.2
26
+ batchSize: 50, // § 9.2
27
+ publishMaxAttempts: 8, // DLQ threshold
28
+ drainDeadlineSeconds: 30, // graceful drain
29
+ });
30
+
31
+ const handle = await startDispatcher([dispatcher], { pgPool, redis, telemetry });
32
+
33
+ // snapshot RPC handler at freeze:
34
+ const hwm = handle.currentHwm("tenant.user_membership"); // → "1748100000000-0"
35
+ ```
36
+
37
+ ## Drain sequence (§ 5.2)
38
+
39
+ `acquire-lease (D209)` → `SELECT … FOR UPDATE SKIP LOCKED` → `XADD` canonical
40
+ envelope → `UPDATE … SET dispatched_at = now(), stream_id = …` → release.
41
+ At-least-once: the consumer dedupes on `event_id` via `consumed_events`.
42
+ Rows with `dispatched_at IS NOT NULL` are never re-claimed (idempotent
43
+ re-XADD on restart).
44
+
45
+ ## XADD envelope — consumer contract
46
+
47
+ The XADD output is **byte-identical** to what `@nodii/replica-consumer` reads:
48
+ a single Redis-Streams field named `event` carrying
49
+ `JSON.stringify({ event_id, topic, aggregate_kind, aggregate_id,
50
+ entity_version, payload, stream_id, committed_at })`. The outbox column
51
+ `source_entity_version` maps to the envelope key `entity_version`; the producer
52
+ `telemetry_envelope` is folded into `payload._telemetry`. The contract test
53
+ (`tests/contract.test.ts`) drives this output back through the consumer's read
54
+ path to prove round-trip. (The feature_doc § 5.2 lists individual XADD fields +
55
+ `source_entity_version`; the shipped consumer reads a single JSON `event`
56
+ field keyed `entity_version` — the consumer's read path is the binding
57
+ contract per the feature_doc's own statement; drift filed.)
58
+
59
+ ## DLQ (§ 5.4)
60
+
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.
65
+
66
+ ## Metrics (§ 5.6)
67
+
68
+ `outbox.depth{topic}` · `outbox.lag_seconds{topic}` · `outbox.dispatch_rate{topic}`
69
+ · `outbox.publish_failures{topic,reason}` · `outbox.hwm{stream}` ·
70
+ `outbox.lease_renewals{result}`.
71
+
72
+ ## migrate-gen (§ 5.8)
73
+
74
+ ```
75
+ bunx @nodii/outbox-dispatcher migrate-gen --service nodii-tenant-service [--out-dir .]
76
+ ```
77
+
78
+ Emits the `<service>_outbox` + `<service>_outbox_dlq` DDL + a `src/outbox/boot.ts`
79
+ skeleton.
80
+
81
+ ## Optional `@nodii/db-rls` (08-rls § 4)
82
+
83
+ Pass `tenantId` on the dispatcher + a `dbRls` handle at `startDispatcher` and
84
+ the drain `SELECT` runs inside `withSystemContext({ tenantId })`. Without it,
85
+ the raw pool is used (platform-tenant outbox only).
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=migrate-gen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate-gen.d.ts","sourceRoot":"","sources":["../../src/cli/migrate-gen.ts"],"names":[],"mappings":""}
@@ -0,0 +1,97 @@
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.
4
+ //
5
+ // bunx @nodii/outbox-dispatcher migrate-gen --service nodii-tenant-service
6
+ //
7
+ // Mirrors @nodii/replica-consumer's migrate-gen. Writes to stdout by
8
+ // default; pass --out-dir to write the SQL + boot files to disk.
9
+ import { mkdirSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { snakeServiceName } from "../define-dispatcher.js";
12
+ import { getOutboxDispatcherMigrationSQL } from "../migrations/index.js";
13
+ function parseArgs(argv) {
14
+ const out = { outboxTable: "outbox" };
15
+ for (let i = 0; i < argv.length; i++) {
16
+ const a = argv[i];
17
+ if (a === "--service")
18
+ out.service = argv[++i];
19
+ else if (a === "--outbox-table")
20
+ out.outboxTable = argv[++i] ?? "outbox";
21
+ else if (a === "--dlq-table")
22
+ out.dlqTable = argv[++i];
23
+ else if (a === "--out-dir")
24
+ out.outDir = argv[++i];
25
+ }
26
+ return out;
27
+ }
28
+ function bootSkeleton(service, outboxTable) {
29
+ return `// src/outbox/boot.ts — generated by @nodii/outbox-dispatcher migrate-gen.
30
+ //
31
+ // Wire this into your service boot. The dispatcher drains the outbox table
32
+ // to Redis Streams; the consumer side (@nodii/replica-consumer) reads them.
33
+
34
+ import { defineDispatcher, startDispatcher } from "@nodii/outbox-dispatcher";
35
+ import Redis from "ioredis";
36
+ import postgres from "postgres";
37
+
38
+ const sql = postgres(process.env.DATABASE_URL!);
39
+ const redis = new Redis(process.env.REDIS_URL!);
40
+
41
+ const pgPool = {
42
+ unsafe: (s: string, args?: readonly unknown[]) =>
43
+ sql.unsafe(s, (args ?? []) as Parameters<typeof sql.unsafe>[1]),
44
+ begin: <T>(fn: (tx: { unsafe: typeof pgPool.unsafe }) => Promise<T>) =>
45
+ sql.begin((tx) =>
46
+ fn({
47
+ unsafe: (s, args) =>
48
+ tx.unsafe(s, (args ?? []) as Parameters<typeof tx.unsafe>[1]),
49
+ }),
50
+ ) as Promise<T>,
51
+ };
52
+
53
+ const dispatcher = defineDispatcher({
54
+ serviceName: "${service}",
55
+ outboxTable: "${outboxTable}",
56
+ // One stream per event-type namespace ('<service>.<domain>') per
57
+ // 01-comms § 9.2. Adjust the split to your topic shape.
58
+ streamFor: (row) => "${snakeServiceName(service).split("_")[0] ?? service}." + String(row.topic).split(".")[1],
59
+ });
60
+
61
+ export const outboxHandle = await startDispatcher([dispatcher], {
62
+ pgPool,
63
+ redis: redis as unknown as Parameters<typeof startDispatcher>[1]["redis"],
64
+ });
65
+ `;
66
+ }
67
+ function main() {
68
+ const args = parseArgs(process.argv.slice(2));
69
+ if (!args.service) {
70
+ process.stderr.write("usage: outbox-dispatcher migrate-gen --service <name> " +
71
+ "[--outbox-table outbox] [--dlq-table <name>] [--out-dir <dir>]\n");
72
+ process.exit(2);
73
+ }
74
+ const dlqTable = args.dlqTable ?? `${snakeServiceName(args.service)}_outbox_dlq`;
75
+ const migrationSql = getOutboxDispatcherMigrationSQL({
76
+ outboxTable: args.outboxTable,
77
+ dlqTable,
78
+ });
79
+ const boot = bootSkeleton(args.service, args.outboxTable);
80
+ if (args.outDir) {
81
+ const sqlDir = join(args.outDir, "infra", "postgres", "00X-outbox");
82
+ const bootDir = join(args.outDir, "src", "outbox");
83
+ mkdirSync(sqlDir, { recursive: true });
84
+ mkdirSync(bootDir, { recursive: true });
85
+ writeFileSync(join(sqlDir, "outbox.sql"), migrationSql);
86
+ writeFileSync(join(bootDir, "boot.ts"), boot);
87
+ process.stdout.write(`wrote:\n ${join(sqlDir, "outbox.sql")}\n ${join(bootDir, "boot.ts")}\n`);
88
+ }
89
+ else {
90
+ process.stdout.write(`-- ====== ${args.outboxTable} + ${dlqTable} (migration SQL) ======\n`);
91
+ process.stdout.write(migrationSql);
92
+ process.stdout.write("\n-- ====== src/outbox/boot.ts ======\n");
93
+ process.stdout.write(boot);
94
+ }
95
+ }
96
+ main();
97
+ //# sourceMappingURL=migrate-gen.js.map
@@ -0,0 +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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cherConfig, type ResolvedDispatcher } from "./types.js";
2
+ /** Default poll interval (ms) per `01-comms § 9.2`. */
3
+ export declare const DEFAULT_POLL_MS = 500;
4
+ /** Default batch size per `01-comms § 9.2`. */
5
+ export declare const DEFAULT_BATCH_SIZE = 50;
6
+ /** Default publish attempts before DLQ. */
7
+ export declare const DEFAULT_PUBLISH_MAX_ATTEMPTS = 8;
8
+ /** Default lease TTL (ms) (D209). */
9
+ export declare const DEFAULT_LEASE_TTL_MS = 30000;
10
+ /** Default graceful-drain deadline (s) per § 5.7. */
11
+ export declare const DEFAULT_DRAIN_DEADLINE_SECONDS = 30;
12
+ /** Default per-stream MAXLEN ~ approximation (doctrine § 3). */
13
+ export declare const DEFAULT_STREAM_MAXLEN = 1000000;
14
+ /** Snake-case a service name for the default DLQ table + lease key. */
15
+ export declare function snakeServiceName(serviceName: string): string;
16
+ /**
17
+ * Define an outbox dispatcher. Resolves defaults + validates. Pass the
18
+ * result(s) to `startDispatcher([...])`.
19
+ */
20
+ export declare function defineDispatcher(config: DispatcherConfig): ResolvedDispatcher;
21
+ //# sourceMappingURL=define-dispatcher.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,65 @@
1
+ // defineDispatcher — declarative entry point. Per § 5.1.
2
+ //
3
+ // Resolves a DispatcherConfig into a ResolvedDispatcher with all defaults
4
+ // inlined + validates the shape (fails loud on a mis-wired config rather
5
+ // than at first drain).
6
+ import { InvalidDispatcherConfig, } from "./types.js";
7
+ /** Default poll interval (ms) per `01-comms § 9.2`. */
8
+ export const DEFAULT_POLL_MS = 500;
9
+ /** Default batch size per `01-comms § 9.2`. */
10
+ export const DEFAULT_BATCH_SIZE = 50;
11
+ /** Default publish attempts before DLQ. */
12
+ export const DEFAULT_PUBLISH_MAX_ATTEMPTS = 8;
13
+ /** Default lease TTL (ms) (D209). */
14
+ export const DEFAULT_LEASE_TTL_MS = 30_000;
15
+ /** Default graceful-drain deadline (s) per § 5.7. */
16
+ export const DEFAULT_DRAIN_DEADLINE_SECONDS = 30;
17
+ /** Default per-stream MAXLEN ~ approximation (doctrine § 3). */
18
+ export const DEFAULT_STREAM_MAXLEN = 1_000_000;
19
+ /** Snake-case a service name for the default DLQ table + lease key. */
20
+ export function snakeServiceName(serviceName) {
21
+ return serviceName
22
+ .replace(/[^A-Za-z0-9]+/g, "_")
23
+ .replace(/^_+|_+$/g, "")
24
+ .toLowerCase();
25
+ }
26
+ /**
27
+ * Define an outbox dispatcher. Resolves defaults + validates. Pass the
28
+ * result(s) to `startDispatcher([...])`.
29
+ */
30
+ export function defineDispatcher(config) {
31
+ if (!config.serviceName || typeof config.serviceName !== "string") {
32
+ throw new InvalidDispatcherConfig("serviceName is required");
33
+ }
34
+ if (typeof config.streamFor !== "function") {
35
+ throw new InvalidDispatcherConfig("streamFor must be a function");
36
+ }
37
+ const snake = snakeServiceName(config.serviceName);
38
+ const leaseTtlMs = config.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
39
+ if (leaseTtlMs < 2_000) {
40
+ throw new InvalidDispatcherConfig(`leaseTtlMs must be >= 2000 (got ${leaseTtlMs}); renewal cadence is ttl/2`);
41
+ }
42
+ const batchSize = config.batchSize ?? DEFAULT_BATCH_SIZE;
43
+ if (batchSize < 1) {
44
+ throw new InvalidDispatcherConfig("batchSize must be >= 1");
45
+ }
46
+ const publishMaxAttempts = config.publishMaxAttempts ?? DEFAULT_PUBLISH_MAX_ATTEMPTS;
47
+ if (publishMaxAttempts < 1) {
48
+ throw new InvalidDispatcherConfig("publishMaxAttempts must be >= 1");
49
+ }
50
+ return {
51
+ serviceName: config.serviceName,
52
+ outboxTable: config.outboxTable ?? "outbox",
53
+ dlqTable: config.dlqTable ?? `${snake}_outbox_dlq`,
54
+ streamFor: config.streamFor,
55
+ leaseKey: config.leaseKey ?? `lock:outbox:${config.serviceName}`,
56
+ leaseTtlMs,
57
+ pollMs: config.pollMs ?? DEFAULT_POLL_MS,
58
+ batchSize,
59
+ publishMaxAttempts,
60
+ drainDeadlineSeconds: config.drainDeadlineSeconds ?? DEFAULT_DRAIN_DEADLINE_SECONDS,
61
+ streamMaxLenApprox: config.streamMaxLenApprox ?? DEFAULT_STREAM_MAXLEN,
62
+ tenantId: config.tenantId,
63
+ };
64
+ }
65
+ //# sourceMappingURL=define-dispatcher.js.map
@@ -0,0 +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,C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AAI,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,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,GAAG,KAAK,aAAa;QAClD,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"}
@@ -0,0 +1,26 @@
1
+ import type { ResolvedDispatcher, ResolvedStartConfig } from "./types.js";
2
+ export interface DispatcherRunnerHandle {
3
+ /** Latest XADD id emitted for `stream` this process, or null (§ 5.3). */
4
+ currentHwm(stream: string): string | null;
5
+ /** Current p95 lag-seconds estimate (rolling). For ops queries. */
6
+ lag(): number;
7
+ /** True if this runner currently holds the single-active lease. */
8
+ readonly leaseAcquired: boolean;
9
+ /** Graceful shutdown: stop polling, finish in-flight XADDs, release. */
10
+ stop(): Promise<void>;
11
+ /** Run exactly one drain pass (test seam — bypasses the poll loop). */
12
+ drainOnce(): Promise<number>;
13
+ }
14
+ export declare function startDispatcherRunner(args: {
15
+ dispatcher: ResolvedDispatcher;
16
+ start: ResolvedStartConfig;
17
+ /** Override the per-process owner id (test seam). */
18
+ ownerId?: string;
19
+ /**
20
+ * Start the background poll loop. Default true (production). Tests pass
21
+ * false to drive `drainOnce()` deterministically without the loop racing
22
+ * the explicit pass. The depth-gauge sampler is also gated on this.
23
+ */
24
+ autoStart?: boolean;
25
+ }): Promise<DispatcherRunnerHandle>;
26
+ //# sourceMappingURL=drainer.d.ts.map
@@ -0,0 +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"}
@@ -0,0 +1,339 @@
1
+ // The drain loop — the producer-side Pattern-3 pump. Per § 5.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).
6
+ //
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().
10
+ import { buildEnvelope, xaddEnvelope } from "./envelope.js";
11
+ 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";
15
+ /** How often (ms) the `outbox.depth` gauge is sampled. Per § 5.6 (30s). */
16
+ const DEPTH_SAMPLE_MS = 30_000;
17
+ export async function startDispatcherRunner(args) {
18
+ const { dispatcher, start } = args;
19
+ const { redis, telemetry } = start;
20
+ const hwm = new HwmTracker();
21
+ const lagSamples = [];
22
+ let stopped = false;
23
+ let draining = false;
24
+ let inFlight = 0;
25
+ const claimSql = buildClaimBatchSql(dispatcher.outboxTable);
26
+ const markSql = buildMarkDispatchedSql(dispatcher.outboxTable);
27
+ const failSql = buildRecordFailureSql(dispatcher.outboxTable);
28
+ const dlqInsertSql = buildDlqInsertSql(dispatcher.dlqTable);
29
+ const deleteSql = buildDeleteOutboxRowSql(dispatcher.outboxTable);
30
+ const depthSql = buildDepthByTopicSql(dispatcher.outboxTable);
31
+ // ── Pool resolution (optional db-rls per 08-rls § 4) ───────────────
32
+ function resolvePool() {
33
+ if (dispatcher.tenantId && start.dbRls) {
34
+ const dbRls = start.dbRls;
35
+ const tenantId = dispatcher.tenantId;
36
+ return {
37
+ unsafe(sql, params) {
38
+ return dbRls.withSystemContext({ tenantId }, (db) => db.unsafe(sql, params));
39
+ },
40
+ begin(fn) {
41
+ return dbRls.withSystemContext({ tenantId }, (db) => db.begin(fn));
42
+ },
43
+ };
44
+ }
45
+ if (!start.pgPool) {
46
+ throw new Error("outbox-dispatcher: no pgPool wired (and no dbRls+tenantId for tenant-scoped outbox)");
47
+ }
48
+ return start.pgPool;
49
+ }
50
+ 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
+ });
60
+ function recordLag(occurredAtMs) {
61
+ const lagSec = (Date.now() - occurredAtMs) / 1000;
62
+ telemetry.recordMetric({
63
+ kind: "histogram",
64
+ name: "outbox.lag_seconds",
65
+ value: lagSec,
66
+ attributes: { service: dispatcher.serviceName },
67
+ });
68
+ lagSamples.push(lagSec);
69
+ if (lagSamples.length > 1024)
70
+ lagSamples.shift();
71
+ }
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
+ // ── XADD one row (outside the claim tx) + return the assigned id ────
116
+ async function publishRow(row) {
117
+ const stream = dispatcher.streamFor(row);
118
+ const env = buildEnvelope(row);
119
+ const streamId = await xaddEnvelope({
120
+ redis,
121
+ stream,
122
+ env,
123
+ streamMaxLenApprox: dispatcher.streamMaxLenApprox,
124
+ });
125
+ hwm.record(stream, streamId);
126
+ telemetry.recordMetric({
127
+ kind: "counter",
128
+ name: "outbox.dispatch_rate",
129
+ value: 1,
130
+ attributes: { topic: row.topic },
131
+ });
132
+ if (streamId) {
133
+ telemetry.recordMetric({
134
+ kind: "gauge",
135
+ name: "outbox.hwm",
136
+ // Surface the ms component as a numeric gauge (ids are
137
+ // monotonic-ish); the label carries the full id for ops.
138
+ value: hwmGaugeValue(streamId),
139
+ attributes: { stream, hwm: streamId },
140
+ });
141
+ }
142
+ return streamId;
143
+ }
144
+ // ── One drain pass: claim a batch in a tx, XADD each, mark dispatched.
145
+ //
146
+ // 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).
153
+ async function drainOnce() {
154
+ if (stopped && !draining)
155
+ return 0;
156
+ let dispatched = 0;
157
+ await pool.begin(async (tx) => {
158
+ const claimed = (await tx.unsafe(claimSql, [
159
+ dispatcher.publishMaxAttempts,
160
+ dispatcher.batchSize,
161
+ ]));
162
+ const rows = Array.isArray(claimed) ? claimed : [];
163
+ if (rows.length === 0)
164
+ return;
165
+ for (const row of normalizeRows(rows)) {
166
+ if (lease.lost)
167
+ break;
168
+ inFlight += 1;
169
+ try {
170
+ const streamId = await publishRow(row);
171
+ await tx.unsafe(markSql, [streamId, row.id]);
172
+ recordLag(toEpochMs(row.occurred_at));
173
+ dispatched += 1;
174
+ }
175
+ 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);
185
+ }
186
+ else {
187
+ await tx.unsafe(failSql, [msg, row.id]);
188
+ }
189
+ }
190
+ finally {
191
+ inFlight -= 1;
192
+ }
193
+ }
194
+ });
195
+ return dispatched;
196
+ }
197
+ // ── Depth gauge sampler (§ 5.6) ────────────────────────────────────
198
+ async function sampleDepth() {
199
+ try {
200
+ const rows = (await pool.unsafe(depthSql));
201
+ for (const r of rows ?? []) {
202
+ telemetry.recordMetric({
203
+ kind: "gauge",
204
+ name: "outbox.depth",
205
+ value: Number(r.depth),
206
+ attributes: { topic: r.topic },
207
+ });
208
+ }
209
+ }
210
+ catch (err) {
211
+ telemetry.logger?.warn("outbox-dispatcher: depth sample failed", {
212
+ error: err instanceof Error ? err.message : String(err),
213
+ service: dispatcher.serviceName,
214
+ });
215
+ }
216
+ }
217
+ const autoStart = args.autoStart !== false;
218
+ const depthTimer = autoStart
219
+ ? setInterval(() => {
220
+ if (lease.acquired && !lease.lost)
221
+ void sampleDepth();
222
+ }, DEPTH_SAMPLE_MS)
223
+ : undefined;
224
+ depthTimer?.unref?.();
225
+ // ── Main poll loop ─────────────────────────────────────────────────
226
+ const loop = !autoStart
227
+ ? Promise.resolve()
228
+ : (async () => {
229
+ while (!stopped) {
230
+ try {
231
+ // Re-acquire the lease if we don't hold it (or lost it).
232
+ if (!lease.acquired || lease.lost) {
233
+ 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) {
243
+ await sleep(dispatcher.pollMs);
244
+ continue;
245
+ }
246
+ }
247
+ const n = await drainOnce();
248
+ // If the batch was empty, back off a poll interval; if it was full,
249
+ // immediately drain again to clear a backlog quickly.
250
+ if (n === 0)
251
+ await sleep(dispatcher.pollMs);
252
+ else if (n < dispatcher.batchSize)
253
+ await sleep(dispatcher.pollMs);
254
+ }
255
+ catch (err) {
256
+ telemetry.logger?.warn("outbox-dispatcher: drain loop error", {
257
+ error: err instanceof Error ? err.message : String(err),
258
+ service: dispatcher.serviceName,
259
+ });
260
+ await sleep(Math.min(dispatcher.pollMs, 200));
261
+ }
262
+ }
263
+ })();
264
+ return {
265
+ currentHwm(stream) {
266
+ return hwm.current(stream);
267
+ },
268
+ lag() {
269
+ return percentile(lagSamples, 95);
270
+ },
271
+ get leaseAcquired() {
272
+ return lease.acquired && !lease.lost;
273
+ },
274
+ drainOnce,
275
+ async stop() {
276
+ // § 5.7 graceful drain: stop polling, wait for in-flight XADDs up to
277
+ // drainDeadlineSeconds, release the lease.
278
+ draining = true;
279
+ stopped = true;
280
+ if (depthTimer !== undefined)
281
+ clearInterval(depthTimer);
282
+ const deadlineMs = dispatcher.drainDeadlineSeconds * 1000;
283
+ const started = Date.now();
284
+ await Promise.race([loop, sleep(deadlineMs)]);
285
+ while (inFlight > 0 && Date.now() - started < deadlineMs) {
286
+ await sleep(25);
287
+ }
288
+ await lease.release();
289
+ },
290
+ };
291
+ }
292
+ // ── helpers ──────────────────────────────────────────────────────────
293
+ function normalizeRows(rows) {
294
+ return rows.map((r) => ({
295
+ ...r,
296
+ payload: parseMaybeJson(r.payload) ?? {},
297
+ telemetry_envelope: parseMaybeJson(r.telemetry_envelope),
298
+ publish_attempts: Number(r.publish_attempts ?? 0),
299
+ source_entity_version: Number(r.source_entity_version),
300
+ }));
301
+ }
302
+ function parseMaybeJson(v) {
303
+ if (v == null)
304
+ return null;
305
+ if (typeof v === "object")
306
+ return v;
307
+ if (typeof v === "string") {
308
+ try {
309
+ return JSON.parse(v);
310
+ }
311
+ catch {
312
+ return { _raw: v };
313
+ }
314
+ }
315
+ return null;
316
+ }
317
+ function toEpochMs(v) {
318
+ if (v instanceof Date)
319
+ return v.getTime();
320
+ const n = Date.parse(v);
321
+ return Number.isNaN(n) ? Date.now() : n;
322
+ }
323
+ function hwmGaugeValue(streamId) {
324
+ const dash = streamId.indexOf("-");
325
+ const ms = dash < 0 ? streamId : streamId.slice(0, dash);
326
+ const n = Number(ms);
327
+ return Number.isFinite(n) ? n : 0;
328
+ }
329
+ function percentile(samples, p) {
330
+ if (samples.length === 0)
331
+ return 0;
332
+ const sorted = [...samples].sort((a, b) => a - b);
333
+ const idx = Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length));
334
+ return sorted[idx] ?? 0;
335
+ }
336
+ function sleep(ms) {
337
+ return new Promise((r) => setTimeout(r, ms));
338
+ }
339
+ //# sourceMappingURL=drainer.js.map