@pattern-stack/codegen 0.14.0 → 0.14.2
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/CHANGELOG.md +45 -0
- package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.d.ts +1 -1
- package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js +2 -2
- package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js.map +1 -1
- package/dist/runtime/subsystems/bridge/bridge.module.d.ts +22 -0
- package/dist/runtime/subsystems/bridge/bridge.module.js +177 -160
- package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
- package/dist/runtime/subsystems/bridge/index.js +159 -142
- package/dist/runtime/subsystems/bridge/index.js.map +1 -1
- package/dist/runtime/subsystems/index.js +161 -148
- package/dist/runtime/subsystems/index.js.map +1 -1
- package/dist/runtime/subsystems/jobs/index.js +128 -115
- package/dist/runtime/subsystems/jobs/index.js.map +1 -1
- package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +128 -6
- package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
- package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +17 -0
- package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
- package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js +25 -2
- package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js.map +1 -1
- package/dist/runtime/subsystems/jobs/job-worker.module.d.ts +26 -1
- package/dist/runtime/subsystems/jobs/job-worker.module.js +150 -137
- package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
- package/dist/runtime/subsystems/jobs/jobs-domain.module.js +133 -124
- package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
- package/dist/src/cli/index.js +1040 -635
- package/dist/src/cli/index.js.map +1 -1
- package/package.json +1 -1
- package/runtime/subsystems/bridge/bridge-delivery.memory-backend.ts +8 -1
- package/runtime/subsystems/bridge/bridge.module.ts +26 -1
- package/runtime/subsystems/jobs/job-orchestrator.memory-backend.ts +8 -3
- package/runtime/subsystems/jobs/job-run-service.memory-backend.ts +4 -1
- package/runtime/subsystems/jobs/job-step-service.memory-backend.ts +7 -2
- package/runtime/subsystems/jobs/job-worker.module.ts +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,51 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.14.2] — 2026-06-02
|
|
8
|
+
|
|
9
|
+
Package-mode bridge fixes — the two gaps that left the event→job bridge wired but
|
|
10
|
+
inert when the runtime is consumed from the package (`runtime: package`, ADR-037)
|
|
11
|
+
rather than vendored. Both are follow-ons to 0.14.1's package-mode subsystem
|
|
12
|
+
support. Vendored mode is unchanged; these are additive.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **Embedded worker now drains the reserved `events_*` bridge pools.** The
|
|
17
|
+
subsystem barrel emitted `JobWorkerModule.forRoot({ mode: 'embedded' })` with no
|
|
18
|
+
pool list, so the in-process worker polled only `interactive` + `batch` and
|
|
19
|
+
bridge wrappers sat pending forever (the BRIDGE-8 footgun, just past the boot
|
|
20
|
+
guard). When `bridge` is in `subsystems.install`, the embedded worker now
|
|
21
|
+
defaults to `allPools: true` (every lane in-process — exactly the knob
|
|
22
|
+
`BridgeModule`'s reserved-pool guard short-circuits on).
|
|
23
|
+
- **A package-mode consumer's `@JobHandler.triggers` now bind.** Previously
|
|
24
|
+
`BridgeModule` hardwired the bundled `./generated/registry` placeholder (frozen
|
|
25
|
+
`{}` inside the package), and the registry generator skipped entirely in package
|
|
26
|
+
mode (it gated on a vendored `bridge.protocol.ts` that doesn't exist), so no
|
|
27
|
+
event ever routed to a job. The registry is now generated into the consumer's
|
|
28
|
+
`src/generated/bridge-registry.ts` (type imported from
|
|
29
|
+
`@pattern-stack/codegen/runtime/subsystems/bridge/index`, install gated on
|
|
30
|
+
`subsystems.install`) and threaded into `BridgeModule.forRoot({ registry })` by
|
|
31
|
+
the barrel. `subsystem install bridge` drops an empty-registry stub so the
|
|
32
|
+
import never dangles before the next `entity new`.
|
|
33
|
+
|
|
34
|
+
### Added
|
|
35
|
+
|
|
36
|
+
- **`BridgeModuleOptions.registry?: BridgeRegistry`** — lets the generated barrel
|
|
37
|
+
supply the consumer's scanned registry. Omitted ⇒ falls back to the bundled
|
|
38
|
+
`./generated/registry` (which IS the consumer's generated file in vendored
|
|
39
|
+
mode), so existing consumers and tests are unaffected.
|
|
40
|
+
- **`jobs.worker_pools: string[]` and `jobs.all_pools: true`** config knobs on the
|
|
41
|
+
embedded worker. Precedence: explicit `worker_pools` (→ `pools: [...]`) >
|
|
42
|
+
`all_pools` (→ `allPools: true`) > bridge-installed default (`allPools: true`) >
|
|
43
|
+
the non-reserved default (unchanged).
|
|
44
|
+
|
|
45
|
+
### Known gaps
|
|
46
|
+
|
|
47
|
+
- Package-mode trigger-event **validation** against the events registry is skipped
|
|
48
|
+
(the event codegen generator is not yet mode-aware, so its registry isn't found
|
|
49
|
+
under the package-mode generated path). Triggers still generate and bind; only
|
|
50
|
+
the build-time "unknown event" check is inert. Tracked for a follow-on.
|
|
51
|
+
|
|
7
52
|
## [0.13.0] — 2026-05-31
|
|
8
53
|
|
|
9
54
|
Track D round-2/3 — the integration codegen now emits the **full** integration
|
|
@@ -22,7 +22,7 @@ declare class MemoryBridgeDeliveryRepo implements IJobBridge {
|
|
|
22
22
|
* Unlike `insertDelivery`, this read does NOT call `assertTenantId`:
|
|
23
23
|
* `tenantId === undefined` is the supported cross-tenant admin view.
|
|
24
24
|
*/
|
|
25
|
-
getStatusHistogram(windowHours: number, tenantId?: string | null): Promise<StatusHistogram>;
|
|
25
|
+
getStatusHistogram(windowHours: number, tenantId?: string | null, nowMs?: number): Promise<StatusHistogram>;
|
|
26
26
|
/** All deliveries for a given event (any status, declaration order). */
|
|
27
27
|
getDeliveriesForEvent(eventId: string): BridgeDeliveryRecord[];
|
|
28
28
|
/** All deliveries currently in the given status. */
|
|
@@ -80,11 +80,11 @@ var MemoryBridgeDeliveryRepo = class {
|
|
|
80
80
|
* Unlike `insertDelivery`, this read does NOT call `assertTenantId`:
|
|
81
81
|
* `tenantId === undefined` is the supported cross-tenant admin view.
|
|
82
82
|
*/
|
|
83
|
-
async getStatusHistogram(windowHours, tenantId) {
|
|
83
|
+
async getStatusHistogram(windowHours, tenantId, nowMs = Date.now()) {
|
|
84
84
|
if (!Number.isFinite(windowHours) || windowHours <= 0) {
|
|
85
85
|
throw new RangeError("windowHours must be positive");
|
|
86
86
|
}
|
|
87
|
-
const cutoffMs =
|
|
87
|
+
const cutoffMs = nowMs - windowHours * 36e5;
|
|
88
88
|
const histogram = {
|
|
89
89
|
pending: 0,
|
|
90
90
|
delivered: 0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../runtime/subsystems/bridge/bridge-delivery.memory-backend.ts","../../../../runtime/subsystems/bridge/bridge-errors.ts"],"sourcesContent":["/**\n * MemoryBridgeDeliveryRepo — in-memory `IJobBridge` (BRIDGE-3, ADR-023 Phase 2).\n *\n * Behavioral twin of the Drizzle backend (BRIDGE-4) for use in\n * `just test-unit`. No Docker, no Postgres, fully synchronous. Backs a\n * `Map<\"${eventId}::${triggerId}\", BridgeDeliveryRecord>` so the UNIQUE\n * `(event_id, trigger_id)` constraint can be simulated cheaply.\n *\n * Precedent: `MemoryEventBus` (EVT-5), `MemoryJobOrchestrator`\n * (jobs subsystem). Same shape — a class implementing the protocol plus\n * test-only helpers (`getDeliveriesForEvent`, `getByStatus`, `clear`) that\n * BRIDGE-5's framework-handler tests and BRIDGE-7's facade tests will\n * exercise.\n *\n * The synthetic `UniqueConstraintError` carries a `constraint` field equal\n * to the Drizzle constraint name (`uq_bridge_delivery_event_trigger`, set\n * in BRIDGE-1's schema) so consumers — including BRIDGE-4's\n * `INSERT … ON CONFLICT (event_id, trigger_id) DO NOTHING` path and\n * BRIDGE-7's Case B dedup tests — can branch on the same discriminator\n * regardless of which backend is wired up. ADR-023 explicitly relies on\n * this constraint as the dedup mechanism in two places (replay; facade-\n * vs-drain Case B); a typed error makes both call sites checkable.\n */\nimport { randomUUID } from 'node:crypto';\n\nimport type {\n BridgeDeliveryInsert,\n IJobBridge,\n StatusHistogram,\n} from './bridge.protocol';\nimport type { BridgeDeliveryRecord } from './bridge-delivery.schema';\nimport { UniqueConstraintError } from './bridge-errors';\n\nconst BRIDGE_DELIVERY_UNIQUE_CONSTRAINT =\n 'uq_bridge_delivery_event_trigger' as const;\n\nfunction key(eventId: string, triggerId: string): string {\n return `${eventId}::${triggerId}`;\n}\n\nexport class MemoryBridgeDeliveryRepo implements IJobBridge {\n private readonly deliveries = new Map<string, BridgeDeliveryRecord>();\n\n async insertDelivery(row: BridgeDeliveryInsert): Promise<void> {\n const k = key(row.eventId, row.triggerId);\n if (this.deliveries.has(k)) {\n throw new UniqueConstraintError(\n BRIDGE_DELIVERY_UNIQUE_CONSTRAINT,\n row.eventId,\n row.triggerId,\n );\n }\n // Materialize a full BridgeDeliveryRecord — fill in DB defaults that\n // the insert payload allowed to be omitted.\n const record: BridgeDeliveryRecord = {\n id: row.id ?? randomUUID(),\n eventId: row.eventId,\n triggerId: row.triggerId,\n wrapperRunId: row.wrapperRunId ?? null,\n userRunId: row.userRunId ?? null,\n status: row.status ?? 'pending',\n skipReason: row.skipReason ?? null,\n error: (row.error as Record<string, unknown> | null | undefined) ?? null,\n tenantId: row.tenantId ?? null,\n attemptedAt:\n row.attemptedAt instanceof Date ? row.attemptedAt : new Date(),\n deliveredAt:\n row.deliveredAt instanceof Date ? row.deliveredAt : null,\n };\n this.deliveries.set(k, record);\n }\n\n async findDelivery(\n eventId: string,\n triggerId: string,\n ): Promise<BridgeDeliveryRecord | null> {\n return this.deliveries.get(key(eventId, triggerId)) ?? null;\n }\n\n async findDeliveryById(id: string): Promise<BridgeDeliveryRecord | null> {\n for (const record of this.deliveries.values()) {\n if (record.id === id) return record;\n }\n return null;\n }\n\n async markDelivered(id: string, userRunId: string): Promise<void> {\n const record = this.findById(id);\n record.status = 'delivered';\n record.userRunId = userRunId;\n record.deliveredAt = new Date();\n }\n\n async markSkipped(id: string, reason: string): Promise<void> {\n const record = this.findById(id);\n record.status = 'skipped';\n record.skipReason = reason;\n }\n\n async markFailed(\n id: string,\n error: Record<string, unknown>,\n ): Promise<void> {\n const record = this.findById(id);\n record.status = 'failed';\n record.error = error;\n }\n\n /**\n * Observability read — see `IJobBridge.getStatusHistogram` JSDoc for the\n * tenant-filter and windowHours contract.\n *\n * Unlike `insertDelivery`, this read does NOT call `assertTenantId`:\n * `tenantId === undefined` is the supported cross-tenant admin view.\n */\n async getStatusHistogram(\n windowHours: number,\n tenantId?: string | null,\n ): Promise<StatusHistogram> {\n if (!Number.isFinite(windowHours) || windowHours <= 0) {\n throw new RangeError('windowHours must be positive');\n }\n\n const cutoffMs = Date.now() - windowHours * 3_600_000;\n const histogram: StatusHistogram = {\n pending: 0,\n delivered: 0,\n skipped: 0,\n failed: 0,\n };\n\n for (const record of this.deliveries.values()) {\n if (record.attemptedAt.getTime() < cutoffMs) continue;\n if (tenantId === null && record.tenantId !== null) continue;\n if (typeof tenantId === 'string' && record.tenantId !== tenantId) {\n continue;\n }\n // tenantId === undefined → no tenant filter.\n histogram[record.status] += 1;\n }\n\n return histogram;\n }\n\n // ─── Test helpers ────────────────────────────────────────────────────────\n\n /** All deliveries for a given event (any status, declaration order). */\n getDeliveriesForEvent(eventId: string): BridgeDeliveryRecord[] {\n return [...this.deliveries.values()].filter((r) => r.eventId === eventId);\n }\n\n /** All deliveries currently in the given status. */\n getByStatus(\n status: BridgeDeliveryRecord['status'],\n ): BridgeDeliveryRecord[] {\n return [...this.deliveries.values()].filter((r) => r.status === status);\n }\n\n /** Reset the store. Tests use this in `beforeEach`. */\n clear(): void {\n this.deliveries.clear();\n }\n\n // ─── Internals ───────────────────────────────────────────────────────────\n\n private findById(id: string): BridgeDeliveryRecord {\n for (const record of this.deliveries.values()) {\n if (record.id === id) return record;\n }\n throw new Error(\n `MemoryBridgeDeliveryRepo: no delivery with id '${id}' (transition ` +\n `methods may not be called for unknown rows; the framework handler ` +\n `should always findDelivery first or operate on a row it just ` +\n `inserted).`,\n );\n }\n}\n","/**\n * Typed errors for the bridge subsystem (ADR-023 Phase 2, BRIDGE-2).\n *\n * All thrown by the three enforcement sites named in ADR-023 §Multi-tenancy:\n * - `EventFlowService.publishAndStart` entry (BRIDGE-7)\n * - `BridgeDeliveryHandler.handle` entry (BRIDGE-5)\n * - `DrizzleBridgeDeliveryRepo.insertDelivery` pre-write (BRIDGE-4)\n *\n * Same shape as `runtime/subsystems/jobs/jobs-errors.ts` and\n * `runtime/subsystems/events/events-errors.ts` so consumers can catch them\n * with the same exception-filter pattern across all three subsystems.\n */\n\n/**\n * Thrown when `BridgeModule` was configured with `multiTenant: true` but\n * the caller did not pass a `tenantId` at one of the three enforcement\n * sites listed above.\n *\n * **Strict enforcement rationale (mirrors JOB-8 / SYNC-6 stance, locked\n * 2026-04-18 for jobs; same rationale applies here).** Cross-tenant data\n * leakage is the worst class of bug a multi-tenant system can ship;\n * surfacing the misuse loudly at the call site (rather than silently\n * defaulting to `null` or to \"the last tenant seen\") prevents both\n * accidental global writes and sneaky reads that return a union of tenants.\n *\n * - `undefined` `tenantId` → throw this error.\n * - Explicit `null` `tenantId` → passes; opts the call into cross-tenant\n * work (e.g. a system housekeeping event with no owning tenant). The\n * `bridge_delivery` row is persisted with `tenant_id = NULL`.\n *\n * The `callSite` constructor argument names which of the three enforcement\n * sites threw — review reports and ops dashboards rely on a stable site\n * name, so use the canonical strings: `'EventFlowService.publishAndStart'`,\n * `'BridgeDeliveryHandler.handle'`,\n * `'DrizzleBridgeDeliveryRepo.insertDelivery'`.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly callSite: string) {\n super(\n `MissingTenantIdError: BridgeModule was configured with ` +\n `multiTenant=true but ${callSite} was called without tenantId ` +\n `(undefined). Pass an explicit tenantId, or pass null for ` +\n `cross-tenant work.`,\n );\n }\n}\n\n/**\n * Synthetic error thrown by `MemoryBridgeDeliveryRepo.insertDelivery` when\n * a duplicate `(event_id, trigger_id)` insert hits the simulated UNIQUE\n * constraint (BRIDGE-3).\n *\n * Carries a `constraint` field equal to the Drizzle constraint name\n * declared in BRIDGE-1's schema (`uq_bridge_delivery_event_trigger`) so\n * call sites can branch on the same discriminator regardless of which\n * backend is wired up. This matters because ADR-023 explicitly leans on\n * the constraint as the dedup mechanism in two places — outbox replay\n * and `publishAndStart` Case B — and BRIDGE-4 / BRIDGE-7 will share a\n * type-check path with BRIDGE-3-driven tests.\n *\n * The Drizzle backend (BRIDGE-4) does NOT throw this error: it uses\n * `INSERT … ON CONFLICT (event_id, trigger_id) DO NOTHING RETURNING id`\n * per the BRIDGE-4 spec recommendation, so collisions surface as an empty\n * result set rather than an exception. The error exists so the memory\n * backend can faithfully model the \"duplicate raises\" behaviour for tests\n * that want to assert the constraint actually fires.\n */\n/**\n * Thrown by `BridgeModule.onModuleInit` when `JobWorkerModule` is wired\n * alongside the bridge but its active `pools` list does not include one\n * or more of the three reserved bridge pools (`events_inbound`,\n * `events_change`, `events_outbound`).\n *\n * Without a worker polling those pools, the wrapper `job_run` rows the\n * outbox drain inserts (BRIDGE-4) sit `pending` forever — a silent\n * footgun where `eventFlow.publish(...)` returns success but no user\n * job ever spawns. The boot-time check converts that into a fail-fast.\n *\n * Operators can either (a) add `...BRIDGE_RESERVED_POOLS` to their\n * `JobWorkerModule.forRoot({ pools })` configuration so the same\n * process polls the reserved pools, or (b) run a separate worker\n * process per reserved pool for lane isolation (ADR-022 §Pool\n * isolation).\n */\nexport class BridgeReservedPoolsNotPolledError extends Error {\n override readonly name = 'BridgeReservedPoolsNotPolledError';\n constructor(public readonly missingPools: readonly string[]) {\n super(\n `BridgeModule loaded but JobWorkerModule is not polling reserved ` +\n `pool '${missingPools[0]}'. Add ...BRIDGE_RESERVED_POOLS to your ` +\n `JobWorkerModule.forRoot({ pools }) configuration. Missing pools: ` +\n `${missingPools.join(', ')}. (Bridge-fanout wrappers will sit ` +\n `pending forever without these pollers.)`,\n );\n }\n}\n\nexport class UniqueConstraintError extends Error {\n override readonly name = 'UniqueConstraintError';\n constructor(\n public readonly constraint: string,\n public readonly eventId: string,\n public readonly triggerId: string,\n ) {\n super(\n `UniqueConstraintError: duplicate insert into bridge_delivery for ` +\n `(event_id='${eventId}', trigger_id='${triggerId}') — violates ` +\n `constraint '${constraint}'.`,\n );\n }\n}\n"],"mappings":";AAuBA,SAAS,kBAAkB;;;AC2EpB,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAE/C,YACkB,YACA,SACA,WAChB;AACA;AAAA,MACE,+EACgB,OAAO,kBAAkB,SAAS,kCACjC,UAAU;AAAA,IAC7B;AARgB;AACA;AACA;AAAA,EAOlB;AAAA,EATkB;AAAA,EACA;AAAA,EACA;AAAA,EAJA,OAAO;AAY3B;;;AD9EA,IAAM,oCACJ;AAEF,SAAS,IAAI,SAAiB,WAA2B;AACvD,SAAO,GAAG,OAAO,KAAK,SAAS;AACjC;AAEO,IAAM,2BAAN,MAAqD;AAAA,EACzC,aAAa,oBAAI,IAAkC;AAAA,EAEpE,MAAM,eAAe,KAA0C;AAC7D,UAAM,IAAI,IAAI,IAAI,SAAS,IAAI,SAAS;AACxC,QAAI,KAAK,WAAW,IAAI,CAAC,GAAG;AAC1B,YAAM,IAAI;AAAA,QACR;AAAA,QACA,IAAI;AAAA,QACJ,IAAI;AAAA,MACN;AAAA,IACF;AAGA,UAAM,SAA+B;AAAA,MACnC,IAAI,IAAI,MAAM,WAAW;AAAA,MACzB,SAAS,IAAI;AAAA,MACb,WAAW,IAAI;AAAA,MACf,cAAc,IAAI,gBAAgB;AAAA,MAClC,WAAW,IAAI,aAAa;AAAA,MAC5B,QAAQ,IAAI,UAAU;AAAA,MACtB,YAAY,IAAI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AAU,KAAK,WAAW,OAAO,GAAG;AAC7C,UAAI,OAAO,YAAY,QAAQ,IAAI,SAAU;AAC7C,UAAI,aAAa,QAAQ,OAAO,aAAa,KAAM;AACnD,UAAI,OAAO,aAAa,YAAY,OAAO,aAAa,UAAU;AAChE;AAAA,MACF;AAEA,gBAAU,OAAO,MAAM,KAAK;AAAA,IAC9B;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA,EAKA,sBAAsB,SAAyC;AAC7D,WAAO,CAAC,GAAG,KAAK,WAAW,OAAO,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,YAAY,OAAO;AAAA,EAC1E;AAAA;AAAA,EAGA,YACE,QACwB;AACxB,WAAO,CAAC,GAAG,KAAK,WAAW,OAAO,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM;AAAA,EACxE;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,WAAW,MAAM;AAAA,EACxB;AAAA;AAAA,EAIQ,SAAS,IAAkC;AACjD,eAAW,UAAU,KAAK,WAAW,OAAO,GAAG;AAC7C,UAAI,OAAO,OAAO,GAAI,QAAO;AAAA,IAC/B;AACA,UAAM,IAAI;AAAA,MACR,kDAAkD,EAAE;AAAA,IAItD;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../runtime/subsystems/bridge/bridge-delivery.memory-backend.ts","../../../../runtime/subsystems/bridge/bridge-errors.ts"],"sourcesContent":["/**\n * MemoryBridgeDeliveryRepo — in-memory `IJobBridge` (BRIDGE-3, ADR-023 Phase 2).\n *\n * Behavioral twin of the Drizzle backend (BRIDGE-4) for use in\n * `just test-unit`. No Docker, no Postgres, fully synchronous. Backs a\n * `Map<\"${eventId}::${triggerId}\", BridgeDeliveryRecord>` so the UNIQUE\n * `(event_id, trigger_id)` constraint can be simulated cheaply.\n *\n * Precedent: `MemoryEventBus` (EVT-5), `MemoryJobOrchestrator`\n * (jobs subsystem). Same shape — a class implementing the protocol plus\n * test-only helpers (`getDeliveriesForEvent`, `getByStatus`, `clear`) that\n * BRIDGE-5's framework-handler tests and BRIDGE-7's facade tests will\n * exercise.\n *\n * The synthetic `UniqueConstraintError` carries a `constraint` field equal\n * to the Drizzle constraint name (`uq_bridge_delivery_event_trigger`, set\n * in BRIDGE-1's schema) so consumers — including BRIDGE-4's\n * `INSERT … ON CONFLICT (event_id, trigger_id) DO NOTHING` path and\n * BRIDGE-7's Case B dedup tests — can branch on the same discriminator\n * regardless of which backend is wired up. ADR-023 explicitly relies on\n * this constraint as the dedup mechanism in two places (replay; facade-\n * vs-drain Case B); a typed error makes both call sites checkable.\n */\nimport { randomUUID } from 'node:crypto';\n\nimport type {\n BridgeDeliveryInsert,\n IJobBridge,\n StatusHistogram,\n} from './bridge.protocol';\nimport type { BridgeDeliveryRecord } from './bridge-delivery.schema';\nimport { UniqueConstraintError } from './bridge-errors';\n\nconst BRIDGE_DELIVERY_UNIQUE_CONSTRAINT =\n 'uq_bridge_delivery_event_trigger' as const;\n\nfunction key(eventId: string, triggerId: string): string {\n return `${eventId}::${triggerId}`;\n}\n\nexport class MemoryBridgeDeliveryRepo implements IJobBridge {\n private readonly deliveries = new Map<string, BridgeDeliveryRecord>();\n\n async insertDelivery(row: BridgeDeliveryInsert): Promise<void> {\n const k = key(row.eventId, row.triggerId);\n if (this.deliveries.has(k)) {\n throw new UniqueConstraintError(\n BRIDGE_DELIVERY_UNIQUE_CONSTRAINT,\n row.eventId,\n row.triggerId,\n );\n }\n // Materialize a full BridgeDeliveryRecord — fill in DB defaults that\n // the insert payload allowed to be omitted.\n const record: BridgeDeliveryRecord = {\n id: row.id ?? randomUUID(),\n eventId: row.eventId,\n triggerId: row.triggerId,\n wrapperRunId: row.wrapperRunId ?? null,\n userRunId: row.userRunId ?? null,\n status: row.status ?? 'pending',\n skipReason: row.skipReason ?? null,\n error: (row.error as Record<string, unknown> | null | undefined) ?? null,\n tenantId: row.tenantId ?? null,\n attemptedAt:\n row.attemptedAt instanceof Date ? row.attemptedAt : new Date(),\n deliveredAt:\n row.deliveredAt instanceof Date ? row.deliveredAt : null,\n };\n this.deliveries.set(k, record);\n }\n\n async findDelivery(\n eventId: string,\n triggerId: string,\n ): Promise<BridgeDeliveryRecord | null> {\n return this.deliveries.get(key(eventId, triggerId)) ?? null;\n }\n\n async findDeliveryById(id: string): Promise<BridgeDeliveryRecord | null> {\n for (const record of this.deliveries.values()) {\n if (record.id === id) return record;\n }\n return null;\n }\n\n async markDelivered(id: string, userRunId: string): Promise<void> {\n const record = this.findById(id);\n record.status = 'delivered';\n record.userRunId = userRunId;\n record.deliveredAt = new Date();\n }\n\n async markSkipped(id: string, reason: string): Promise<void> {\n const record = this.findById(id);\n record.status = 'skipped';\n record.skipReason = reason;\n }\n\n async markFailed(\n id: string,\n error: Record<string, unknown>,\n ): Promise<void> {\n const record = this.findById(id);\n record.status = 'failed';\n record.error = error;\n }\n\n /**\n * Observability read — see `IJobBridge.getStatusHistogram` JSDoc for the\n * tenant-filter and windowHours contract.\n *\n * Unlike `insertDelivery`, this read does NOT call `assertTenantId`:\n * `tenantId === undefined` is the supported cross-tenant admin view.\n */\n async getStatusHistogram(\n windowHours: number,\n tenantId?: string | null,\n // Reference instant for the window cutoff. Defaults to the wall clock; exposed\n // as a test-injection seam so a caller can pin the cutoff to the same `now` it\n // positioned a boundary row from. Without it the cutoff is re-sampled here a few\n // ms later, pushing an \"exactly at the boundary\" row just below the window\n // (the OBS-3 boundary test flake). The drizzle backend has no analogue — it\n // evaluates the cutoff once in SQL via `now()`.\n nowMs: number = Date.now(),\n ): Promise<StatusHistogram> {\n if (!Number.isFinite(windowHours) || windowHours <= 0) {\n throw new RangeError('windowHours must be positive');\n }\n\n const cutoffMs = nowMs - windowHours * 3_600_000;\n const histogram: StatusHistogram = {\n pending: 0,\n delivered: 0,\n skipped: 0,\n failed: 0,\n };\n\n for (const record of this.deliveries.values()) {\n if (record.attemptedAt.getTime() < cutoffMs) continue;\n if (tenantId === null && record.tenantId !== null) continue;\n if (typeof tenantId === 'string' && record.tenantId !== tenantId) {\n continue;\n }\n // tenantId === undefined → no tenant filter.\n histogram[record.status] += 1;\n }\n\n return histogram;\n }\n\n // ─── Test helpers ────────────────────────────────────────────────────────\n\n /** All deliveries for a given event (any status, declaration order). */\n getDeliveriesForEvent(eventId: string): BridgeDeliveryRecord[] {\n return [...this.deliveries.values()].filter((r) => r.eventId === eventId);\n }\n\n /** All deliveries currently in the given status. */\n getByStatus(\n status: BridgeDeliveryRecord['status'],\n ): BridgeDeliveryRecord[] {\n return [...this.deliveries.values()].filter((r) => r.status === status);\n }\n\n /** Reset the store. Tests use this in `beforeEach`. */\n clear(): void {\n this.deliveries.clear();\n }\n\n // ─── Internals ───────────────────────────────────────────────────────────\n\n private findById(id: string): BridgeDeliveryRecord {\n for (const record of this.deliveries.values()) {\n if (record.id === id) return record;\n }\n throw new Error(\n `MemoryBridgeDeliveryRepo: no delivery with id '${id}' (transition ` +\n `methods may not be called for unknown rows; the framework handler ` +\n `should always findDelivery first or operate on a row it just ` +\n `inserted).`,\n );\n }\n}\n","/**\n * Typed errors for the bridge subsystem (ADR-023 Phase 2, BRIDGE-2).\n *\n * All thrown by the three enforcement sites named in ADR-023 §Multi-tenancy:\n * - `EventFlowService.publishAndStart` entry (BRIDGE-7)\n * - `BridgeDeliveryHandler.handle` entry (BRIDGE-5)\n * - `DrizzleBridgeDeliveryRepo.insertDelivery` pre-write (BRIDGE-4)\n *\n * Same shape as `runtime/subsystems/jobs/jobs-errors.ts` and\n * `runtime/subsystems/events/events-errors.ts` so consumers can catch them\n * with the same exception-filter pattern across all three subsystems.\n */\n\n/**\n * Thrown when `BridgeModule` was configured with `multiTenant: true` but\n * the caller did not pass a `tenantId` at one of the three enforcement\n * sites listed above.\n *\n * **Strict enforcement rationale (mirrors JOB-8 / SYNC-6 stance, locked\n * 2026-04-18 for jobs; same rationale applies here).** Cross-tenant data\n * leakage is the worst class of bug a multi-tenant system can ship;\n * surfacing the misuse loudly at the call site (rather than silently\n * defaulting to `null` or to \"the last tenant seen\") prevents both\n * accidental global writes and sneaky reads that return a union of tenants.\n *\n * - `undefined` `tenantId` → throw this error.\n * - Explicit `null` `tenantId` → passes; opts the call into cross-tenant\n * work (e.g. a system housekeeping event with no owning tenant). The\n * `bridge_delivery` row is persisted with `tenant_id = NULL`.\n *\n * The `callSite` constructor argument names which of the three enforcement\n * sites threw — review reports and ops dashboards rely on a stable site\n * name, so use the canonical strings: `'EventFlowService.publishAndStart'`,\n * `'BridgeDeliveryHandler.handle'`,\n * `'DrizzleBridgeDeliveryRepo.insertDelivery'`.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly callSite: string) {\n super(\n `MissingTenantIdError: BridgeModule was configured with ` +\n `multiTenant=true but ${callSite} was called without tenantId ` +\n `(undefined). Pass an explicit tenantId, or pass null for ` +\n `cross-tenant work.`,\n );\n }\n}\n\n/**\n * Synthetic error thrown by `MemoryBridgeDeliveryRepo.insertDelivery` when\n * a duplicate `(event_id, trigger_id)` insert hits the simulated UNIQUE\n * constraint (BRIDGE-3).\n *\n * Carries a `constraint` field equal to the Drizzle constraint name\n * declared in BRIDGE-1's schema (`uq_bridge_delivery_event_trigger`) so\n * call sites can branch on the same discriminator regardless of which\n * backend is wired up. This matters because ADR-023 explicitly leans on\n * the constraint as the dedup mechanism in two places — outbox replay\n * and `publishAndStart` Case B — and BRIDGE-4 / BRIDGE-7 will share a\n * type-check path with BRIDGE-3-driven tests.\n *\n * The Drizzle backend (BRIDGE-4) does NOT throw this error: it uses\n * `INSERT … ON CONFLICT (event_id, trigger_id) DO NOTHING RETURNING id`\n * per the BRIDGE-4 spec recommendation, so collisions surface as an empty\n * result set rather than an exception. The error exists so the memory\n * backend can faithfully model the \"duplicate raises\" behaviour for tests\n * that want to assert the constraint actually fires.\n */\n/**\n * Thrown by `BridgeModule.onModuleInit` when `JobWorkerModule` is wired\n * alongside the bridge but its active `pools` list does not include one\n * or more of the three reserved bridge pools (`events_inbound`,\n * `events_change`, `events_outbound`).\n *\n * Without a worker polling those pools, the wrapper `job_run` rows the\n * outbox drain inserts (BRIDGE-4) sit `pending` forever — a silent\n * footgun where `eventFlow.publish(...)` returns success but no user\n * job ever spawns. The boot-time check converts that into a fail-fast.\n *\n * Operators can either (a) add `...BRIDGE_RESERVED_POOLS` to their\n * `JobWorkerModule.forRoot({ pools })` configuration so the same\n * process polls the reserved pools, or (b) run a separate worker\n * process per reserved pool for lane isolation (ADR-022 §Pool\n * isolation).\n */\nexport class BridgeReservedPoolsNotPolledError extends Error {\n override readonly name = 'BridgeReservedPoolsNotPolledError';\n constructor(public readonly missingPools: readonly string[]) {\n super(\n `BridgeModule loaded but JobWorkerModule is not polling reserved ` +\n `pool '${missingPools[0]}'. Add ...BRIDGE_RESERVED_POOLS to your ` +\n `JobWorkerModule.forRoot({ pools }) configuration. Missing pools: ` +\n `${missingPools.join(', ')}. (Bridge-fanout wrappers will sit ` +\n `pending forever without these pollers.)`,\n );\n }\n}\n\nexport class UniqueConstraintError extends Error {\n override readonly name = 'UniqueConstraintError';\n constructor(\n public readonly constraint: string,\n public readonly eventId: string,\n public readonly triggerId: string,\n ) {\n super(\n `UniqueConstraintError: duplicate insert into bridge_delivery for ` +\n `(event_id='${eventId}', trigger_id='${triggerId}') — violates ` +\n `constraint '${constraint}'.`,\n );\n }\n}\n"],"mappings":";AAuBA,SAAS,kBAAkB;;;AC2EpB,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAE/C,YACkB,YACA,SACA,WAChB;AACA;AAAA,MACE,+EACgB,OAAO,kBAAkB,SAAS,kCACjC,UAAU;AAAA,IAC7B;AARgB;AACA;AACA;AAAA,EAOlB;AAAA,EATkB;AAAA,EACA;AAAA,EACA;AAAA,EAJA,OAAO;AAY3B;;;AD9EA,IAAM,oCACJ;AAEF,SAAS,IAAI,SAAiB,WAA2B;AACvD,SAAO,GAAG,OAAO,KAAK,SAAS;AACjC;AAEO,IAAM,2BAAN,MAAqD;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IAItD;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { OnModuleInit, DynamicModule } from '@nestjs/common';
|
|
2
2
|
import { JobWorkerModuleOptions } from '../jobs/job-worker.module.js';
|
|
3
|
+
import { BridgeRegistry } from './bridge.protocol.js';
|
|
3
4
|
import '@nestjs/core';
|
|
4
5
|
import '../../types/drizzle.js';
|
|
5
6
|
import 'drizzle-orm/node-postgres';
|
|
@@ -15,6 +16,7 @@ import '../events/generated/types.js';
|
|
|
15
16
|
import '../jobs/job-run-service.protocol.js';
|
|
16
17
|
import '../jobs/job-step-service.protocol.js';
|
|
17
18
|
import '../jobs/job-worker.js';
|
|
19
|
+
import './bridge-delivery.schema.js';
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
22
|
* BridgeModule — `DynamicModule.forRoot({ backend, multiTenant })`
|
|
@@ -75,6 +77,26 @@ interface BridgeModuleOptions {
|
|
|
75
77
|
* `null` always passes (cross-tenant work). Defaults to `false`.
|
|
76
78
|
*/
|
|
77
79
|
multiTenant?: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* The codegen-emitted `Record<EventTypeName, BridgeTriggerEntry[]>` that
|
|
82
|
+
* drives outbox-drain trigger lookup (BRIDGE-4) and the facade's Case B
|
|
83
|
+
* dedup (BRIDGE-7).
|
|
84
|
+
*
|
|
85
|
+
* **Package mode (ADR-037).** When the runtime is imported from
|
|
86
|
+
* `@pattern-stack/codegen` (not vendored), the bundled
|
|
87
|
+
* `./generated/registry` is a frozen empty placeholder (`{}`) — a
|
|
88
|
+
* consumer's `@JobHandler.triggers` are scanned into a registry that lives
|
|
89
|
+
* in THEIR `src/generated/bridge-registry.ts`, which the package can't
|
|
90
|
+
* import. The generated subsystem barrel therefore threads that registry in
|
|
91
|
+
* here: `BridgeModule.forRoot({ ..., registry: bridgeRegistry })`. Omitted
|
|
92
|
+
* (vendored mode / tests) ⇒ falls back to the bundled `./generated/registry`,
|
|
93
|
+
* which in vendored mode IS the consumer's freshly-generated file.
|
|
94
|
+
*
|
|
95
|
+
* Without this, package-mode consumers' triggers never bind and the bridge
|
|
96
|
+
* routes nothing (the "wrappers sit pending" footgun's silent twin —
|
|
97
|
+
* nothing is ever enqueued in the first place).
|
|
98
|
+
*/
|
|
99
|
+
registry?: BridgeRegistry;
|
|
78
100
|
}
|
|
79
101
|
declare class BridgeModule implements OnModuleInit {
|
|
80
102
|
private readonly workerOpts?;
|