@pattern-stack/codegen 0.4.4 → 0.4.5

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 (34) hide show
  1. package/dist/runtime/subsystems/index.d.ts +7 -0
  2. package/dist/runtime/subsystems/index.js +905 -208
  3. package/dist/runtime/subsystems/index.js.map +1 -1
  4. package/dist/runtime/subsystems/observability/index.d.ts +10 -0
  5. package/dist/runtime/subsystems/observability/index.js +895 -0
  6. package/dist/runtime/subsystems/observability/index.js.map +1 -0
  7. package/dist/runtime/subsystems/observability/observability.drizzle-backend.d.ts +15 -0
  8. package/dist/runtime/subsystems/observability/observability.drizzle-backend.js +465 -0
  9. package/dist/runtime/subsystems/observability/observability.drizzle-backend.js.map +1 -0
  10. package/dist/runtime/subsystems/observability/observability.memory-backend.d.ts +28 -0
  11. package/dist/runtime/subsystems/observability/observability.memory-backend.js +75 -0
  12. package/dist/runtime/subsystems/observability/observability.memory-backend.js.map +1 -0
  13. package/dist/runtime/subsystems/observability/observability.module.d.ts +56 -0
  14. package/dist/runtime/subsystems/observability/observability.module.js +887 -0
  15. package/dist/runtime/subsystems/observability/observability.module.js.map +1 -0
  16. package/dist/runtime/subsystems/observability/observability.protocol.d.ts +155 -0
  17. package/dist/runtime/subsystems/observability/observability.protocol.js +1 -0
  18. package/dist/runtime/subsystems/observability/observability.protocol.js.map +1 -0
  19. package/dist/runtime/subsystems/observability/observability.tokens.d.ts +19 -0
  20. package/dist/runtime/subsystems/observability/observability.tokens.js +8 -0
  21. package/dist/runtime/subsystems/observability/observability.tokens.js.map +1 -0
  22. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.d.ts +79 -0
  23. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js +425 -0
  24. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js.map +1 -0
  25. package/dist/runtime/subsystems/sync/sync-audit.schema.d.ts +4 -4
  26. package/package.json +6 -1
  27. package/runtime/subsystems/index.ts +23 -0
  28. package/runtime/subsystems/observability/index.ts +35 -0
  29. package/runtime/subsystems/observability/observability.drizzle-backend.ts +223 -0
  30. package/runtime/subsystems/observability/observability.memory-backend.ts +111 -0
  31. package/runtime/subsystems/observability/observability.module.ts +115 -0
  32. package/runtime/subsystems/observability/observability.protocol.ts +167 -0
  33. package/runtime/subsystems/observability/observability.tokens.ts +18 -0
  34. package/runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts +222 -0
@@ -0,0 +1,895 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc2) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __decorateClass = (decorators, target, key, kind) => {
28
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
29
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
30
+ if (decorator = decorators[i])
31
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
32
+ if (kind && result) __defProp(target, key, result);
33
+ return result;
34
+ };
35
+ var __decorateParam = (index5, decorator) => (target, key) => decorator(target, key, index5);
36
+
37
+ // runtime/constants/tokens.ts
38
+ var DRIZZLE;
39
+ var init_tokens = __esm({
40
+ "runtime/constants/tokens.ts"() {
41
+ "use strict";
42
+ DRIZZLE = "DRIZZLE";
43
+ }
44
+ });
45
+
46
+ // runtime/subsystems/jobs/job-orchestration.schema.ts
47
+ import {
48
+ pgEnum,
49
+ pgTable,
50
+ uuid,
51
+ text,
52
+ jsonb,
53
+ integer,
54
+ timestamp,
55
+ index,
56
+ uniqueIndex
57
+ } from "drizzle-orm/pg-core";
58
+ import { sql } from "drizzle-orm";
59
+ var jobRunStatusEnum, jobStepKindEnum, jobStepStatusEnum, collisionModeEnum, replayFromEnum, parentClosePolicyEnum, waitKindEnum, triggerSourceEnum, jobs, jobRuns, jobSteps;
60
+ var init_job_orchestration_schema = __esm({
61
+ "runtime/subsystems/jobs/job-orchestration.schema.ts"() {
62
+ "use strict";
63
+ jobRunStatusEnum = pgEnum("job_run_status", [
64
+ "pending",
65
+ "running",
66
+ "waiting",
67
+ "completed",
68
+ "failed",
69
+ "timed_out",
70
+ "canceled"
71
+ ]);
72
+ jobStepKindEnum = pgEnum("job_step_kind", ["task"]);
73
+ jobStepStatusEnum = pgEnum("job_step_status", [
74
+ "pending",
75
+ "running",
76
+ "completed",
77
+ "failed",
78
+ "skipped"
79
+ ]);
80
+ collisionModeEnum = pgEnum("job_collision_mode", [
81
+ "queue",
82
+ "reject",
83
+ "replace"
84
+ ]);
85
+ replayFromEnum = pgEnum("job_replay_from", [
86
+ "scratch",
87
+ "last_step",
88
+ "last_checkpoint"
89
+ ]);
90
+ parentClosePolicyEnum = pgEnum("job_parent_close_policy", [
91
+ "terminate",
92
+ "cancel",
93
+ "abandon"
94
+ ]);
95
+ waitKindEnum = pgEnum("job_wait_kind", ["signal"]);
96
+ triggerSourceEnum = pgEnum("job_trigger_source", [
97
+ "manual",
98
+ "schedule",
99
+ "event",
100
+ "parent"
101
+ ]);
102
+ jobs = pgTable("job", {
103
+ type: text("type").primaryKey(),
104
+ version: integer("version").notNull().default(1),
105
+ pool: text("pool").notNull(),
106
+ scopeEntityType: text("scope_entity_type"),
107
+ retryPolicy: jsonb("retry_policy").notNull().$type(),
108
+ timeoutMs: integer("timeout_ms"),
109
+ concurrencyKeyTemplate: text("concurrency_key_template"),
110
+ collisionMode: collisionModeEnum("collision_mode").notNull().default("queue"),
111
+ dedupeKeyTemplate: text("dedupe_key_template"),
112
+ dedupeWindowMs: integer("dedupe_window_ms"),
113
+ priorityDefault: integer("priority_default").notNull().default(0),
114
+ replayFrom: replayFromEnum("replay_from").notNull().default("last_checkpoint"),
115
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
116
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
117
+ });
118
+ jobRuns = pgTable(
119
+ "job_run",
120
+ {
121
+ id: uuid("id").primaryKey().defaultRandom(),
122
+ jobType: text("job_type").notNull().references(() => jobs.type),
123
+ jobVersion: integer("job_version").notNull(),
124
+ parentRunId: uuid("parent_run_id").references(() => jobRuns.id),
125
+ /**
126
+ * Service generates `id` client-side via randomUUID() and sets
127
+ * root_run_id = id for root runs (single INSERT, no self-FK race).
128
+ */
129
+ rootRunId: uuid("root_run_id").notNull(),
130
+ parentClosePolicy: parentClosePolicyEnum("parent_close_policy").notNull().default("terminate"),
131
+ scopeEntityType: text("scope_entity_type"),
132
+ scopeEntityId: text("scope_entity_id"),
133
+ tenantId: text("tenant_id"),
134
+ tags: jsonb("tags").notNull().default({}).$type(),
135
+ pool: text("pool").notNull(),
136
+ priority: integer("priority").notNull().default(0),
137
+ concurrencyKey: text("concurrency_key"),
138
+ dedupeKey: text("dedupe_key"),
139
+ status: jobRunStatusEnum("status").notNull().default("pending"),
140
+ input: jsonb("input").notNull().$type(),
141
+ output: jsonb("output").$type(),
142
+ error: jsonb("error").$type(),
143
+ triggerSource: triggerSourceEnum("trigger_source").notNull(),
144
+ triggerRef: text("trigger_ref"),
145
+ runAt: timestamp("run_at", { withTimezone: true }).notNull().defaultNow(),
146
+ startedAt: timestamp("started_at", { withTimezone: true }),
147
+ finishedAt: timestamp("finished_at", { withTimezone: true }),
148
+ claimedAt: timestamp("claimed_at", { withTimezone: true }),
149
+ attempts: integer("attempts").notNull().default(0),
150
+ // Phase 3 placeholder — see ADR-025
151
+ waitKind: waitKindEnum("wait_kind"),
152
+ // Phase 3 placeholder — see ADR-025
153
+ resumeToken: text("resume_token"),
154
+ // Phase 3 placeholder — see ADR-025
155
+ waitDeadline: timestamp("wait_deadline", { withTimezone: true }),
156
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
157
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
158
+ },
159
+ (t) => ({
160
+ /** Claim query: ORDER BY priority DESC, run_at ASC. */
161
+ idxJobRunClaim: index("idx_job_run_claim").on(t.status, t.pool, t.runAt),
162
+ /** Tree traversal / cascade cancel. */
163
+ idxJobRunRoot: index("idx_job_run_root").on(t.rootRunId),
164
+ /** listForScope query. */
165
+ idxJobRunScope: index("idx_job_run_scope").on(t.scopeEntityType, t.scopeEntityId),
166
+ /** Idempotency collapse — partial index. */
167
+ idxJobRunDedupe: index("idx_job_run_dedupe").on(t.jobType, t.dedupeKey).where(sql`${t.dedupeKey} IS NOT NULL`),
168
+ /** Collision check — partial index. */
169
+ idxJobRunConcurrency: index("idx_job_run_concurrency").on(t.concurrencyKey).where(
170
+ sql`${t.concurrencyKey} IS NOT NULL AND ${t.status} IN ('pending','running')`
171
+ )
172
+ })
173
+ );
174
+ jobSteps = pgTable(
175
+ "job_step",
176
+ {
177
+ id: uuid("id").primaryKey().defaultRandom(),
178
+ jobRunId: uuid("job_run_id").notNull().references(() => jobRuns.id),
179
+ stepId: text("step_id").notNull(),
180
+ kind: jobStepKindEnum("kind").notNull().default("task"),
181
+ /**
182
+ * Monotonic within run. integer (max ~2B per run) is sufficient —
183
+ * downgraded from ADR-022's bigint; revisit only if a single run
184
+ * ever exceeds 2 billion steps.
185
+ */
186
+ seq: integer("seq").notNull(),
187
+ status: jobStepStatusEnum("status").notNull().default("pending"),
188
+ input: jsonb("input").$type(),
189
+ /** Memoised on success for replay. */
190
+ output: jsonb("output").$type(),
191
+ error: jsonb("error").$type(),
192
+ attempts: integer("attempts").notNull().default(0),
193
+ startedAt: timestamp("started_at", { withTimezone: true }),
194
+ finishedAt: timestamp("finished_at", { withTimezone: true })
195
+ },
196
+ (t) => ({
197
+ /** No duplicate step IDs per run. */
198
+ idxJobStepRunStep: uniqueIndex("idx_job_step_run_step").on(t.jobRunId, t.stepId),
199
+ /** Ordered timeline reads. */
200
+ idxJobStepTimeline: index("idx_job_step_timeline").on(t.jobRunId, t.seq)
201
+ })
202
+ );
203
+ }
204
+ });
205
+
206
+ // runtime/subsystems/events/domain-events.schema.ts
207
+ import {
208
+ index as index3,
209
+ jsonb as jsonb3,
210
+ pgTable as pgTable3,
211
+ text as text3,
212
+ timestamp as timestamp3,
213
+ uuid as uuid3
214
+ } from "drizzle-orm/pg-core";
215
+ var domainEvents;
216
+ var init_domain_events_schema = __esm({
217
+ "runtime/subsystems/events/domain-events.schema.ts"() {
218
+ "use strict";
219
+ domainEvents = pgTable3(
220
+ "domain_events",
221
+ {
222
+ id: uuid3("id").primaryKey(),
223
+ type: text3("type").notNull(),
224
+ aggregateId: text3("aggregate_id").notNull(),
225
+ aggregateType: text3("aggregate_type").notNull(),
226
+ payload: jsonb3("payload").notNull().$type(),
227
+ occurredAt: timestamp3("occurred_at", { withTimezone: true }).notNull(),
228
+ processedAt: timestamp3("processed_at", { withTimezone: true }),
229
+ /** Lifecycle status: pending | processed | failed */
230
+ status: text3("status").notNull().default("pending"),
231
+ /** Error message from the last failed dispatch attempt. */
232
+ error: text3("error"),
233
+ metadata: jsonb3("metadata").$type(),
234
+ /** Routing pool (e.g. `events_inbound`, `events_change`, `events_outbound`). Populated by DrizzleEventBus.publish() in EVT-4. */
235
+ pool: text3("pool"),
236
+ /** Routing direction: `inbound` | `change` | `outbound`. Populated by DrizzleEventBus.publish() in EVT-4. */
237
+ direction: text3("direction"),
238
+ // conditional: emitted only when events.multi_tenant: true
239
+ tenantId: text3("tenant_id")
240
+ },
241
+ (t) => ({
242
+ /** Polling drain filter (existing — promoted from comment to declaration in EVT-1). */
243
+ idxDomainEventsStatusOccurredAt: index3("idx_domain_events_status_occurred_at").on(
244
+ t.status,
245
+ t.occurredAt
246
+ ),
247
+ /** Event replay per aggregate (existing — promoted from comment to declaration in EVT-1). */
248
+ idxDomainEventsAggregate: index3("idx_domain_events_aggregate").on(
249
+ t.aggregateId,
250
+ t.aggregateType
251
+ ),
252
+ /** Per-pool drain filter (EVT-1). Enables DrizzleEventBus to drain a single pool without scanning all events. */
253
+ idxDomainEventsPoolStatusOccurredAt: index3(
254
+ "idx_domain_events_pool_status_occurred_at"
255
+ ).on(t.pool, t.status, t.occurredAt)
256
+ })
257
+ );
258
+ }
259
+ });
260
+
261
+ // runtime/subsystems/bridge/bridge-delivery.schema.ts
262
+ import {
263
+ index as index4,
264
+ jsonb as jsonb4,
265
+ pgEnum as pgEnum3,
266
+ pgTable as pgTable4,
267
+ text as text4,
268
+ timestamp as timestamp4,
269
+ unique,
270
+ uuid as uuid4
271
+ } from "drizzle-orm/pg-core";
272
+ import { sql as sql3 } from "drizzle-orm";
273
+ var bridgeDeliveryStatusEnum, bridgeDelivery;
274
+ var init_bridge_delivery_schema = __esm({
275
+ "runtime/subsystems/bridge/bridge-delivery.schema.ts"() {
276
+ "use strict";
277
+ init_domain_events_schema();
278
+ init_job_orchestration_schema();
279
+ bridgeDeliveryStatusEnum = pgEnum3("bridge_delivery_status", [
280
+ "pending",
281
+ "delivered",
282
+ "skipped",
283
+ "failed"
284
+ ]);
285
+ bridgeDelivery = pgTable4(
286
+ "bridge_delivery",
287
+ {
288
+ id: uuid4("id").primaryKey().defaultRandom(),
289
+ /** FK to the source event in the outbox. */
290
+ eventId: uuid4("event_id").notNull().references(() => domainEvents.id),
291
+ /**
292
+ * Stable codegen-emitted identifier for the (job, trigger) pair, of the
293
+ * form `<job_type>#<triggerIndex>` (BRIDGE-6). Forms the second half of
294
+ * the UNIQUE idempotency key.
295
+ */
296
+ triggerId: text4("trigger_id").notNull(),
297
+ /**
298
+ * Wrapper `job_run.id` (the framework `@framework/bridge_delivery` run
299
+ * that drove this delivery). Nullable: the facade-eager path
300
+ * (`publishAndStart` Case B) pre-writes a delivered row with no wrapper.
301
+ */
302
+ wrapperRunId: uuid4("wrapper_run_id").references(() => jobRuns.id),
303
+ /**
304
+ * Spawned user `job_run.id`. Null until status is `delivered`; remains
305
+ * null for `skipped` and `failed` deliveries.
306
+ */
307
+ userRunId: uuid4("user_run_id").references(() => jobRuns.id),
308
+ status: bridgeDeliveryStatusEnum("status").notNull().default("pending"),
309
+ /** Populated when status=`skipped` (e.g. `'when_returned_false'`, `'trigger_unregistered'`). */
310
+ skipReason: text4("skip_reason"),
311
+ /** Populated when status=`failed`. Mirrors `job_run.error` shape. */
312
+ error: jsonb4("error").$type(),
313
+ /**
314
+ * Emitted unconditionally and nullable (JOB-8 / SYNC-6 precedent).
315
+ * Enforcement gated on `BRIDGE_MULTI_TENANT` at the service layer
316
+ * (BRIDGE-8); no DB constraint.
317
+ */
318
+ tenantId: text4("tenant_id"),
319
+ attemptedAt: timestamp4("attempted_at", { withTimezone: true }).notNull().defaultNow(),
320
+ deliveredAt: timestamp4("delivered_at", { withTimezone: true })
321
+ },
322
+ (t) => ({
323
+ /**
324
+ * Idempotency ledger. Outbox replays and facade-vs-drain collisions both
325
+ * dedup through this constraint.
326
+ */
327
+ uqBridgeDeliveryEventTrigger: unique("uq_bridge_delivery_event_trigger").on(
328
+ t.eventId,
329
+ t.triggerId
330
+ ),
331
+ /** Lookup all deliveries for an event (fanout report, debugging). */
332
+ idxBridgeDeliveryEvent: index4("idx_bridge_delivery_event").on(t.eventId),
333
+ /**
334
+ * Ops dashboard filter — only the actionable states. Partial index keeps
335
+ * it small at scale (the bulk of rows will be `delivered`).
336
+ */
337
+ idxBridgeDeliveryStatus: index4("idx_bridge_delivery_status").on(t.status).where(sql3`${t.status} IN ('pending','failed')`),
338
+ /**
339
+ * Reverse lookup from a spawned user run back to its delivery row.
340
+ * Partial — most rows in the bridge ledger but only successful
341
+ * deliveries have a `user_run_id`.
342
+ */
343
+ idxBridgeDeliveryUserRun: index4("idx_bridge_delivery_user_run").on(t.userRunId).where(sql3`${t.userRunId} IS NOT NULL`)
344
+ })
345
+ );
346
+ }
347
+ });
348
+
349
+ // runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts
350
+ var bridge_metrics_reporter_exports = {};
351
+ __export(bridge_metrics_reporter_exports, {
352
+ BridgeMetricsReporter: () => BridgeMetricsReporter
353
+ });
354
+ import {
355
+ Inject as Inject2,
356
+ Injectable as Injectable3,
357
+ Logger
358
+ } from "@nestjs/common";
359
+ import { and, eq as eq2, gt, sql as sql4 } from "drizzle-orm";
360
+ var INTERVAL_NAME, DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, BridgeMetricsReporter;
361
+ var init_bridge_metrics_reporter = __esm({
362
+ "runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts"() {
363
+ "use strict";
364
+ init_tokens();
365
+ init_bridge_delivery_schema();
366
+ init_domain_events_schema();
367
+ INTERVAL_NAME = "bridge-metrics-tick";
368
+ DEFAULT_INTERVAL_MS = 6e4;
369
+ MIN_INTERVAL_MS = 1e3;
370
+ BridgeMetricsReporter = class {
371
+ constructor(db, scheduler) {
372
+ this.db = db;
373
+ this.scheduler = scheduler;
374
+ this.intervalMs = this.resolveIntervalMs();
375
+ this.lastTickAt = /* @__PURE__ */ new Date();
376
+ }
377
+ db;
378
+ scheduler;
379
+ logger = new Logger(BridgeMetricsReporter.name);
380
+ intervalMs;
381
+ lastTickAt;
382
+ onModuleInit() {
383
+ this.logger.log(
384
+ `BridgeMetricsReporter starting (intervalMs=${this.intervalMs}).`
385
+ );
386
+ const timer = setInterval(() => {
387
+ void this.tick();
388
+ }, this.intervalMs);
389
+ timer.unref?.();
390
+ this.scheduler.addInterval(INTERVAL_NAME, timer);
391
+ }
392
+ onModuleDestroy() {
393
+ if (this.scheduler.getIntervals().includes(INTERVAL_NAME)) {
394
+ this.scheduler.deleteInterval(INTERVAL_NAME);
395
+ }
396
+ }
397
+ /**
398
+ * Run one sampling tick. Public so tests can drive it deterministically
399
+ * without waiting on the timer.
400
+ */
401
+ async tick() {
402
+ const windowStart = this.lastTickAt;
403
+ const windowEnd = /* @__PURE__ */ new Date();
404
+ this.lastTickAt = windowEnd;
405
+ let rows = [];
406
+ try {
407
+ rows = await this.sample(windowStart, windowEnd);
408
+ } catch (err) {
409
+ this.logger.error(
410
+ `bridge metrics sample failed: ${err.message}`
411
+ );
412
+ return { windowStart, windowEnd, rows: [] };
413
+ }
414
+ this.emit({ windowStart, windowEnd, rows });
415
+ return { windowStart, windowEnd, rows };
416
+ }
417
+ async sample(windowStart, windowEnd) {
418
+ const lastTransition = sql4`COALESCE(${bridgeDelivery.deliveredAt}, ${bridgeDelivery.attemptedAt})`;
419
+ const result = await this.db.select({
420
+ status: bridgeDelivery.status,
421
+ eventType: domainEvents.type,
422
+ skipReason: bridgeDelivery.skipReason,
423
+ count: sql4`COUNT(*)::int`
424
+ }).from(bridgeDelivery).innerJoin(domainEvents, eq2(bridgeDelivery.eventId, domainEvents.id)).where(
425
+ and(
426
+ gt(lastTransition, windowStart),
427
+ sql4`${lastTransition} <= ${windowEnd}`
428
+ )
429
+ ).groupBy(
430
+ bridgeDelivery.status,
431
+ domainEvents.type,
432
+ bridgeDelivery.skipReason
433
+ );
434
+ return result.map((r) => ({
435
+ status: r.status,
436
+ eventType: r.eventType,
437
+ skipReason: r.skipReason,
438
+ count: r.count
439
+ }));
440
+ }
441
+ emit(tick) {
442
+ if (tick.rows.length === 0) {
443
+ this.logger.log(
444
+ `bridge_metrics tick=empty window=[${tick.windowStart.toISOString()}..${tick.windowEnd.toISOString()}]`
445
+ );
446
+ return;
447
+ }
448
+ const totals = tick.rows.reduce(
449
+ (acc, r) => {
450
+ acc[r.status] = (acc[r.status] ?? 0) + r.count;
451
+ return acc;
452
+ },
453
+ {}
454
+ );
455
+ const detail = tick.rows.map(
456
+ (r) => `${r.eventType}|${r.status}${r.skipReason ? `:${r.skipReason}` : ""}=${r.count}`
457
+ ).join(" ");
458
+ this.logger.log(
459
+ `bridge_metrics tick window=[${tick.windowStart.toISOString()}..${tick.windowEnd.toISOString()}] totals=${JSON.stringify(totals)} detail=[${detail}]`
460
+ );
461
+ }
462
+ resolveIntervalMs() {
463
+ const raw = process.env["BRIDGE_METRICS_INTERVAL_MS"];
464
+ if (!raw) return DEFAULT_INTERVAL_MS;
465
+ const parsed = Number.parseInt(raw, 10);
466
+ if (!Number.isFinite(parsed) || parsed < MIN_INTERVAL_MS) {
467
+ new Logger(BridgeMetricsReporter.name).warn(
468
+ `Ignoring BRIDGE_METRICS_INTERVAL_MS='${raw}' (invalid or < ${MIN_INTERVAL_MS}ms); using default ${DEFAULT_INTERVAL_MS}ms.`
469
+ );
470
+ return DEFAULT_INTERVAL_MS;
471
+ }
472
+ return parsed;
473
+ }
474
+ };
475
+ BridgeMetricsReporter = __decorateClass([
476
+ Injectable3(),
477
+ __decorateParam(0, Inject2(DRIZZLE))
478
+ ], BridgeMetricsReporter);
479
+ }
480
+ });
481
+
482
+ // runtime/subsystems/observability/observability.tokens.ts
483
+ var OBSERVABILITY = /* @__PURE__ */ Symbol("OBSERVABILITY");
484
+ var OBSERVABILITY_REPORTERS = /* @__PURE__ */ Symbol("OBSERVABILITY_REPORTERS");
485
+
486
+ // runtime/subsystems/observability/observability.module.ts
487
+ import { Module } from "@nestjs/common";
488
+
489
+ // runtime/subsystems/observability/observability.drizzle-backend.ts
490
+ init_tokens();
491
+ init_job_orchestration_schema();
492
+ import { Inject, Injectable } from "@nestjs/common";
493
+ import { desc, eq, sql as sql2 } from "drizzle-orm";
494
+
495
+ // runtime/subsystems/sync/sync-audit.schema.ts
496
+ import {
497
+ pgEnum as pgEnum2,
498
+ pgTable as pgTable2,
499
+ uuid as uuid2,
500
+ text as text2,
501
+ jsonb as jsonb2,
502
+ integer as integer2,
503
+ boolean,
504
+ timestamp as timestamp2,
505
+ index as index2,
506
+ uniqueIndex as uniqueIndex2
507
+ } from "drizzle-orm/pg-core";
508
+ var syncRunDirectionEnum = pgEnum2("sync_run_direction", [
509
+ "inbound",
510
+ "outbound"
511
+ ]);
512
+ var syncRunActionEnum = pgEnum2("sync_run_action", [
513
+ "poll",
514
+ "cdc",
515
+ "webhook",
516
+ "manual",
517
+ "writeback"
518
+ ]);
519
+ var syncRunStatusEnum = pgEnum2("sync_run_status", [
520
+ "running",
521
+ "success",
522
+ "no_changes",
523
+ "failed"
524
+ ]);
525
+ var syncRunItemOperationEnum = pgEnum2("sync_run_item_operation", [
526
+ "created",
527
+ "updated",
528
+ "deleted",
529
+ "noop"
530
+ ]);
531
+ var syncRunItemStatusEnum = pgEnum2("sync_run_item_status", [
532
+ "success",
533
+ "failed",
534
+ "skipped"
535
+ ]);
536
+ var syncSubscriptions = pgTable2(
537
+ "sync_subscriptions",
538
+ {
539
+ id: uuid2("id").primaryKey().defaultRandom(),
540
+ integrationId: text2("integration_id").notNull(),
541
+ adapter: text2("adapter").notNull(),
542
+ domain: text2("domain").notNull(),
543
+ externalRef: text2("external_ref"),
544
+ enabled: boolean("enabled").notNull().default(true),
545
+ /**
546
+ * Per-subscription configuration bag. Strategies type it internally;
547
+ * e.g. polling strategies stash `{ batchSize, highWatermark }` here.
548
+ */
549
+ config: jsonb2("config").notNull().default({}).$type(),
550
+ /**
551
+ * Opaque cursor persisted by `ICursorStore.put()`. NULL until the first
552
+ * successful run advances it.
553
+ */
554
+ cursor: jsonb2("cursor").$type(),
555
+ lastSyncAt: timestamp2("last_sync_at", { withTimezone: true }),
556
+ /** Runtime-enforced when `SYNC_MULTI_TENANT` is true; see SYNC-6. */
557
+ tenantId: text2("tenant_id"),
558
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow(),
559
+ updatedAt: timestamp2("updated_at", { withTimezone: true }).notNull().defaultNow()
560
+ },
561
+ (t) => ({
562
+ /**
563
+ * Composite uniqueness per the epic shape. `external_ref` is nullable;
564
+ * Postgres treats NULLs as distinct in a UNIQUE constraint, which means
565
+ * two rows with the same `(integration_id, adapter, domain)` and NULL
566
+ * external_ref are allowed. That's intentional — a subscription with
567
+ * NULL external_ref covers the full domain, and duplicates there would
568
+ * be a consumer-layer modeling issue, not a schema concern.
569
+ */
570
+ uqSyncSubscriptionTuple: uniqueIndex2("uq_sync_subscriptions_tuple").on(
571
+ t.integrationId,
572
+ t.adapter,
573
+ t.domain,
574
+ t.externalRef
575
+ ),
576
+ /** Scheduling query: list enabled subscriptions ordered by staleness. */
577
+ idxSyncSubscriptionsEnabledLastSync: index2(
578
+ "idx_sync_subscriptions_enabled_last_sync"
579
+ ).on(t.enabled, t.lastSyncAt)
580
+ })
581
+ );
582
+ var syncRuns = pgTable2(
583
+ "sync_runs",
584
+ {
585
+ id: uuid2("id").primaryKey().defaultRandom(),
586
+ subscriptionId: uuid2("subscription_id").notNull().references(() => syncSubscriptions.id, { onDelete: "cascade" }),
587
+ direction: syncRunDirectionEnum("direction").notNull(),
588
+ action: syncRunActionEnum("action").notNull(),
589
+ status: syncRunStatusEnum("status").notNull().default("running"),
590
+ recordsFound: integer2("records_found").notNull().default(0),
591
+ recordsProcessed: integer2("records_processed").notNull().default(0),
592
+ cursorBefore: jsonb2("cursor_before").$type(),
593
+ cursorAfter: jsonb2("cursor_after").$type(),
594
+ durationMs: integer2("duration_ms"),
595
+ error: text2("error"),
596
+ startedAt: timestamp2("started_at", { withTimezone: true }).notNull().defaultNow(),
597
+ completedAt: timestamp2("completed_at", { withTimezone: true }),
598
+ /** Runtime-enforced when `SYNC_MULTI_TENANT` is true; see SYNC-6. */
599
+ tenantId: text2("tenant_id")
600
+ },
601
+ (t) => ({
602
+ /** Timeline read: "most recent runs for this subscription". */
603
+ idxSyncRunsSubscriptionStartedAt: index2(
604
+ "idx_sync_runs_subscription_started_at"
605
+ ).on(t.subscriptionId, t.startedAt),
606
+ /** Stale-run sweeper: "runs that started > N minutes ago and are still running". */
607
+ idxSyncRunsStatusStartedAt: index2("idx_sync_runs_status_started_at").on(
608
+ t.status,
609
+ t.startedAt
610
+ )
611
+ })
612
+ );
613
+ var syncRunItems = pgTable2(
614
+ "sync_run_items",
615
+ {
616
+ id: uuid2("id").primaryKey().defaultRandom(),
617
+ syncRunId: uuid2("sync_run_id").notNull().references(() => syncRuns.id, { onDelete: "cascade" }),
618
+ entityType: text2("entity_type").notNull(),
619
+ externalId: text2("external_id").notNull(),
620
+ localId: text2("local_id"),
621
+ operation: syncRunItemOperationEnum("operation").notNull(),
622
+ status: syncRunItemStatusEnum("status").notNull(),
623
+ /**
624
+ * Structured per-field diff — ADR-0003 shape enforced by
625
+ * `FieldDiffSchema.parse` at the recorder service layer.
626
+ *
627
+ * Shape: `{ [fieldName]: { from: unknown, to: unknown } }`.
628
+ * Empty `{}` for `noop` items; `{ [field]: { from: null, to: <value> } }`
629
+ * for created items; `{ [field]: { from: <value>, to: null } }` for
630
+ * deleted items.
631
+ */
632
+ changedFields: jsonb2("changed_fields").notNull().default({}).$type(),
633
+ title: text2("title"),
634
+ error: text2("error"),
635
+ createdAt: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow(),
636
+ /** Runtime-enforced when `SYNC_MULTI_TENANT` is true; see SYNC-6. */
637
+ tenantId: text2("tenant_id")
638
+ },
639
+ (t) => ({
640
+ /** Ordered timeline within a run. */
641
+ idxSyncRunItemsRunCreatedAt: index2("idx_sync_run_items_run_created_at").on(
642
+ t.syncRunId,
643
+ t.createdAt
644
+ ),
645
+ /** Per-record history: "every sync that touched opportunity/$extId". */
646
+ idxSyncRunItemsEntityExternal: index2(
647
+ "idx_sync_run_items_entity_external"
648
+ ).on(t.entityType, t.externalId)
649
+ })
650
+ );
651
+
652
+ // runtime/subsystems/observability/observability.drizzle-backend.ts
653
+ var DrizzleObservabilityService = class {
654
+ constructor(db) {
655
+ this.db = db;
656
+ }
657
+ db;
658
+ async getPoolDepths() {
659
+ const result = await this.db.execute(sql2`
660
+ SELECT
661
+ pool AS name,
662
+ COUNT(*) FILTER (WHERE status = 'pending')::int AS pending,
663
+ COUNT(*) FILTER (WHERE status = 'running')::int AS running,
664
+ (percentile_cont(0.95) WITHIN GROUP (
665
+ ORDER BY EXTRACT(EPOCH FROM (now() - claimed_at)) * 1000
666
+ ) FILTER (WHERE status = 'running' AND claimed_at IS NOT NULL))::int
667
+ AS claimed_age_p95_ms
668
+ FROM job_run
669
+ WHERE status IN ('pending','running')
670
+ GROUP BY pool
671
+ ORDER BY pool
672
+ `);
673
+ const rows = extractRows(result);
674
+ return rows.map((r) => ({
675
+ name: r.name,
676
+ pending: r.pending,
677
+ running: r.running,
678
+ claimedAgeP95Ms: r.claimed_age_p95_ms
679
+ }));
680
+ }
681
+ async getRecentSyncRuns(limit, integrationId) {
682
+ const base = this.db.select({
683
+ id: syncRuns.id,
684
+ subscriptionId: syncRuns.subscriptionId,
685
+ integrationId: syncSubscriptions.integrationId,
686
+ adapter: syncSubscriptions.adapter,
687
+ domain: syncSubscriptions.domain,
688
+ direction: syncRuns.direction,
689
+ action: syncRuns.action,
690
+ status: syncRuns.status,
691
+ recordsFound: syncRuns.recordsFound,
692
+ recordsProcessed: syncRuns.recordsProcessed,
693
+ durationMs: syncRuns.durationMs,
694
+ error: syncRuns.error,
695
+ startedAt: syncRuns.startedAt,
696
+ completedAt: syncRuns.completedAt
697
+ }).from(syncRuns).innerJoin(
698
+ syncSubscriptions,
699
+ eq(syncRuns.subscriptionId, syncSubscriptions.id)
700
+ );
701
+ const filtered = integrationId !== void 0 ? base.where(eq(syncSubscriptions.integrationId, integrationId)) : base;
702
+ const rows = await filtered.orderBy(desc(syncRuns.startedAt)).limit(limit);
703
+ return rows.map((r) => ({
704
+ id: r.id,
705
+ subscriptionId: r.subscriptionId,
706
+ integrationId: r.integrationId,
707
+ adapter: r.adapter,
708
+ domain: r.domain,
709
+ direction: r.direction,
710
+ action: r.action,
711
+ status: r.status,
712
+ recordsFound: r.recordsFound,
713
+ recordsProcessed: r.recordsProcessed,
714
+ durationMs: r.durationMs,
715
+ error: r.error,
716
+ startedAt: r.startedAt,
717
+ completedAt: r.completedAt
718
+ }));
719
+ }
720
+ async getBridgeDeliveryHistogram(windowHours) {
721
+ const result = await this.db.execute(sql2`
722
+ SELECT status, COUNT(*)::int AS count
723
+ FROM bridge_delivery
724
+ WHERE COALESCE(delivered_at, attempted_at) > now() - make_interval(hours => ${windowHours})
725
+ GROUP BY status
726
+ `);
727
+ const rows = extractRows(result);
728
+ const hist = {};
729
+ for (const r of rows) hist[r.status] = r.count;
730
+ return hist;
731
+ }
732
+ async getRecentFailedJobs(limit) {
733
+ const rows = await this.db.select({
734
+ id: jobRuns.id,
735
+ jobType: jobRuns.jobType,
736
+ pool: jobRuns.pool,
737
+ status: jobRuns.status,
738
+ error: jobRuns.error,
739
+ startedAt: jobRuns.startedAt,
740
+ finishedAt: jobRuns.finishedAt,
741
+ attempts: jobRuns.attempts
742
+ }).from(jobRuns).where(eq(jobRuns.status, "failed")).orderBy(desc(jobRuns.finishedAt)).limit(limit);
743
+ return rows.map((r) => ({
744
+ id: r.id,
745
+ jobType: r.jobType,
746
+ pool: r.pool,
747
+ status: r.status,
748
+ error: r.error,
749
+ startedAt: r.startedAt,
750
+ finishedAt: r.finishedAt,
751
+ attempts: r.attempts
752
+ }));
753
+ }
754
+ async getCursors() {
755
+ const rows = await this.db.select({
756
+ id: syncSubscriptions.id,
757
+ integrationId: syncSubscriptions.integrationId,
758
+ adapter: syncSubscriptions.adapter,
759
+ domain: syncSubscriptions.domain,
760
+ cursor: syncSubscriptions.cursor,
761
+ lastSyncAt: syncSubscriptions.lastSyncAt
762
+ }).from(syncSubscriptions).where(eq(syncSubscriptions.enabled, true)).orderBy(syncSubscriptions.integrationId, syncSubscriptions.domain);
763
+ return rows.map((r) => ({
764
+ subscriptionId: r.id,
765
+ integrationId: r.integrationId,
766
+ adapter: r.adapter,
767
+ domain: r.domain,
768
+ lastCursor: r.cursor,
769
+ lastSyncAt: r.lastSyncAt
770
+ }));
771
+ }
772
+ };
773
+ DrizzleObservabilityService = __decorateClass([
774
+ Injectable(),
775
+ __decorateParam(0, Inject(DRIZZLE))
776
+ ], DrizzleObservabilityService);
777
+ function extractRows(result) {
778
+ const maybe = result;
779
+ if (Array.isArray(maybe.rows)) return maybe.rows;
780
+ if (Array.isArray(result)) return result;
781
+ return [];
782
+ }
783
+
784
+ // runtime/subsystems/observability/observability.memory-backend.ts
785
+ import { Injectable as Injectable2 } from "@nestjs/common";
786
+ var MemoryObservabilityService = class {
787
+ pools = [];
788
+ syncRuns = [];
789
+ bridgeHistogram = {};
790
+ failedJobs = [];
791
+ cursors = [];
792
+ // ─── Core contract ─────────────────────────────────────────────────────
793
+ async getPoolDepths() {
794
+ return [...this.pools];
795
+ }
796
+ async getRecentSyncRuns(limit, integrationId) {
797
+ const filtered = integrationId !== void 0 ? this.syncRuns.filter((r) => r.integrationId === integrationId) : this.syncRuns;
798
+ return filtered.slice().sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime()).slice(0, limit);
799
+ }
800
+ async getBridgeDeliveryHistogram(_windowHours) {
801
+ return { ...this.bridgeHistogram };
802
+ }
803
+ async getRecentFailedJobs(limit) {
804
+ return this.failedJobs.slice().sort(
805
+ (a, b) => (b.finishedAt?.getTime() ?? 0) - (a.finishedAt?.getTime() ?? 0)
806
+ ).slice(0, limit);
807
+ }
808
+ async getCursors() {
809
+ return [...this.cursors];
810
+ }
811
+ // ─── Test seams ────────────────────────────────────────────────────────
812
+ /** Replace the pool-depth slice. */
813
+ seedPools(pools) {
814
+ this.pools = [...pools];
815
+ }
816
+ /** Replace the sync-run slice. */
817
+ seedSyncRuns(runs) {
818
+ this.syncRuns = [...runs];
819
+ }
820
+ /** Replace the bridge-delivery histogram. */
821
+ seedBridgeHistogram(hist) {
822
+ this.bridgeHistogram = { ...hist };
823
+ }
824
+ /** Replace the failed-jobs slice. */
825
+ seedFailedJobs(jobs2) {
826
+ this.failedJobs = [...jobs2];
827
+ }
828
+ /** Replace the cursor slice. */
829
+ seedCursors(cursors) {
830
+ this.cursors = [...cursors];
831
+ }
832
+ /** Reset every slice — for afterEach hooks. */
833
+ reset() {
834
+ this.pools = [];
835
+ this.syncRuns = [];
836
+ this.bridgeHistogram = {};
837
+ this.failedJobs = [];
838
+ this.cursors = [];
839
+ }
840
+ };
841
+ MemoryObservabilityService = __decorateClass([
842
+ Injectable2()
843
+ ], MemoryObservabilityService);
844
+
845
+ // runtime/subsystems/observability/observability.module.ts
846
+ var ObservabilityModule = class {
847
+ static forRoot(options = { backend: "drizzle" }) {
848
+ const ConcreteClass = options.backend === "drizzle" ? DrizzleObservabilityService : MemoryObservabilityService;
849
+ const wantsBridgeMetrics = options.reporters?.bridgeMetrics === true;
850
+ const providers = [
851
+ // Register the concrete class as the canonical instance.
852
+ ConcreteClass,
853
+ // OBSERVABILITY token points at the same instance — no duplicate.
854
+ { provide: OBSERVABILITY, useExisting: ConcreteClass },
855
+ // Expose the resolved reporter config for introspection / tests.
856
+ {
857
+ provide: OBSERVABILITY_REPORTERS,
858
+ useValue: options.reporters ?? {}
859
+ }
860
+ ];
861
+ const exports = [OBSERVABILITY];
862
+ if (wantsBridgeMetrics) {
863
+ const { BridgeMetricsReporter: BridgeMetricsReporter2 } = (init_bridge_metrics_reporter(), __toCommonJS(bridge_metrics_reporter_exports));
864
+ providers.push(BridgeMetricsReporter2);
865
+ exports.push(BridgeMetricsReporter2);
866
+ }
867
+ const imports = [];
868
+ if (wantsBridgeMetrics) {
869
+ const { ScheduleModule } = __require("@nestjs/schedule");
870
+ imports.push(ScheduleModule.forRoot());
871
+ }
872
+ return {
873
+ module: ObservabilityModule,
874
+ global: true,
875
+ imports,
876
+ providers,
877
+ exports
878
+ };
879
+ }
880
+ };
881
+ ObservabilityModule = __decorateClass([
882
+ Module({})
883
+ ], ObservabilityModule);
884
+
885
+ // runtime/subsystems/observability/index.ts
886
+ init_bridge_metrics_reporter();
887
+ export {
888
+ BridgeMetricsReporter,
889
+ DrizzleObservabilityService,
890
+ MemoryObservabilityService,
891
+ OBSERVABILITY,
892
+ OBSERVABILITY_REPORTERS,
893
+ ObservabilityModule
894
+ };
895
+ //# sourceMappingURL=index.js.map