notifkit 0.1.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.
@@ -0,0 +1,571 @@
1
+ import { $t as PUBSUB_CHANNELS, A as ProjectSettingsCache, C as ProjectRepository, G as normaliseTarget, I as DataLoader, J as PendingMessageScanner, Jt as buildStreamEvent, T as TemplateRepository, W as getPriorityBucket, X as StreamProducer, Xt as ENRICHED_STREAMS, Y as StreamConsumer, Yt as CONSUMER_GROUPS, an as registry, b as renderWithTemplate, c as BaseWorker, d as buildUnsubscribeHeaders, dt as suppressions, en as STREAMS, et as createLogger, g as TemplateCache, hn as readBaseConfig, it as createDatabase, j as UserThrottle, k as RedisClient, pn as loadEnv, q as globalEmitter, rt as IdempotencyGuard, u as startHealthReporter, ut as scheduledPayloads, x as ContactRepository } from "./src-DrSN2wCg.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { and, eq } from "drizzle-orm";
4
+ //#region src/services/engine/main.ts
5
+ function localTimeToUtc(year, month, day, hour, minute, second, timezone) {
6
+ let utcMs = Date.UTC(year, month - 1, day, hour, minute, second);
7
+ const formatter = new Intl.DateTimeFormat("en-US", {
8
+ timeZone: timezone,
9
+ year: "numeric",
10
+ month: "2-digit",
11
+ day: "2-digit",
12
+ hour: "2-digit",
13
+ minute: "2-digit",
14
+ second: "2-digit",
15
+ hour12: false
16
+ });
17
+ for (let iter = 0; iter < 3; iter++) {
18
+ const parts = formatter.formatToParts(new Date(utcMs));
19
+ const pYear = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
20
+ const pMonth = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
21
+ const pDay = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
22
+ const pHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
23
+ const pMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
24
+ const pSec = parseInt(parts.find((p) => p.type === "second")?.value ?? "0", 10);
25
+ const diff = Date.UTC(year, month - 1, day, hour, minute, second) - Date.UTC(pYear, pMonth - 1, pDay, pHour, pMin, pSec);
26
+ if (diff === 0) break;
27
+ utcMs += diff;
28
+ }
29
+ return new Date(utcMs);
30
+ }
31
+ function isInQuietHours(timezone, quietHours, fromDate = /* @__PURE__ */ new Date()) {
32
+ if (!quietHours || quietHours.length === 0) return { inQuietHours: false };
33
+ const checkWindowAt = (date) => {
34
+ let parts;
35
+ try {
36
+ parts = new Intl.DateTimeFormat("en-US", {
37
+ timeZone: timezone,
38
+ year: "numeric",
39
+ month: "2-digit",
40
+ day: "2-digit",
41
+ hour: "2-digit",
42
+ minute: "2-digit",
43
+ second: "2-digit",
44
+ hour12: false
45
+ }).formatToParts(date);
46
+ } catch {
47
+ return null;
48
+ }
49
+ const year = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
50
+ const month = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
51
+ const day = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
52
+ const currentHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
53
+ const currentMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
54
+ const currentMinutes = currentHour * 60 + currentMin;
55
+ for (const window of quietHours) {
56
+ const [startH, startM] = window.start.split(":").map(Number);
57
+ const [endH, endM] = window.end.split(":").map(Number);
58
+ if (startH === void 0 || startM === void 0 || endH === void 0 || endM === void 0) continue;
59
+ const startMinutes = startH * 60 + startM;
60
+ const endMinutes = endH * 60 + endM;
61
+ let inWindow = false;
62
+ if (startMinutes <= endMinutes) inWindow = currentMinutes >= startMinutes && currentMinutes < endMinutes;
63
+ else inWindow = currentMinutes >= startMinutes || currentMinutes < endMinutes;
64
+ if (inWindow) {
65
+ let targetYear = year;
66
+ let targetMonth = month;
67
+ let targetDay = day;
68
+ if (currentMinutes >= endMinutes) {
69
+ const nextDay = new Date(Date.UTC(year, month - 1, day + 1));
70
+ targetYear = nextDay.getUTCFullYear();
71
+ targetMonth = nextDay.getUTCMonth() + 1;
72
+ targetDay = nextDay.getUTCDate();
73
+ }
74
+ return {
75
+ inQuietHours: true,
76
+ nextActiveTime: localTimeToUtc(targetYear, targetMonth, targetDay, endH, endM, 0, timezone)
77
+ };
78
+ }
79
+ }
80
+ return { inQuietHours: false };
81
+ };
82
+ let initialCheck = checkWindowAt(fromDate);
83
+ if (!initialCheck || !initialCheck.inQuietHours) return { inQuietHours: false };
84
+ let candidateTime = initialCheck.nextActiveTime;
85
+ for (let i = 0; i < 10; i++) {
86
+ const subsequentCheck = checkWindowAt(candidateTime);
87
+ if (subsequentCheck && subsequentCheck.inQuietHours && subsequentCheck.nextActiveTime) {
88
+ if (subsequentCheck.nextActiveTime.getTime() <= candidateTime.getTime()) break;
89
+ candidateTime = subsequentCheck.nextActiveTime;
90
+ } else break;
91
+ }
92
+ return {
93
+ inQuietHours: true,
94
+ nextActiveTime: candidateTime
95
+ };
96
+ }
97
+ loadEnv();
98
+ const config = readBaseConfig();
99
+ let logger;
100
+ let redis;
101
+ let sql$1;
102
+ let db;
103
+ let templateRepo;
104
+ let templateCache;
105
+ let consumer;
106
+ let pendingScanner;
107
+ let worker;
108
+ let healthInterval = null;
109
+ var EngineWorker = class extends BaseWorker {
110
+ registry;
111
+ idempotency;
112
+ throttle;
113
+ projectSettings;
114
+ redisCli;
115
+ templateCache;
116
+ aiPendingProducer;
117
+ scheduledProducer;
118
+ outboundProducers;
119
+ globalEmitter;
120
+ contactRepo;
121
+ db;
122
+ constructor(options) {
123
+ super(options);
124
+ this.registry = options.registry;
125
+ this.idempotency = options.idempotency;
126
+ this.throttle = options.throttle;
127
+ this.projectSettings = options.projectSettings;
128
+ this.redisCli = options.redis;
129
+ this.templateCache = options.templateCache;
130
+ this.aiPendingProducer = options.aiPendingProducer;
131
+ this.scheduledProducer = options.scheduledProducer;
132
+ this.outboundProducers = options.outboundProducers;
133
+ this.globalEmitter = options.globalEmitter;
134
+ this.contactRepo = options.contactRepo;
135
+ this.db = options.db;
136
+ }
137
+ contactsLoader = new DataLoader(async (keys) => {
138
+ const byProject = /* @__PURE__ */ new Map();
139
+ for (const key of keys) {
140
+ if (!byProject.has(key.projectId)) byProject.set(key.projectId, []);
141
+ byProject.get(key.projectId).push(key.recipientId);
142
+ }
143
+ const resultsByProjectAndUser = /* @__PURE__ */ new Map();
144
+ for (const [projectId, userIds] of byProject) {
145
+ const activeContactsMap = await this.contactRepo.findActiveByUserIds(projectId, userIds);
146
+ resultsByProjectAndUser.set(projectId, activeContactsMap);
147
+ }
148
+ return keys.map((key) => {
149
+ const projectMap = resultsByProjectAndUser.get(key.projectId);
150
+ if (!projectMap) return [];
151
+ return projectMap.get(key.recipientId) || [];
152
+ });
153
+ });
154
+ /**
155
+ * Suppressed destinations for one (project, channel), as a normalised set.
156
+ *
157
+ * Loaded per project+channel rather than per address: a campaign is thousands
158
+ * of messages against one channel, so this collapses to a single query for
159
+ * the whole batch. Cached for the loader's lifetime of a tick, which means a
160
+ * suppression written mid-batch takes effect on the next batch — acceptable,
161
+ * since the webhook that writes it is itself minutes behind the send.
162
+ */
163
+ suppressionsLoader = new DataLoader(async (keys) => {
164
+ const results = /* @__PURE__ */ new Map();
165
+ for (const key of keys) {
166
+ const cacheKey = `${key.projectId}:${key.channel}`;
167
+ if (results.has(cacheKey)) continue;
168
+ try {
169
+ const rows = await this.db.select({ target: suppressions.target }).from(suppressions).where(and(eq(suppressions.projectId, key.projectId), eq(suppressions.channel, key.channel)));
170
+ results.set(cacheKey, new Set(rows.map((r) => normaliseTarget(r.target))));
171
+ } catch (err) {
172
+ this.logger.error({
173
+ err,
174
+ projectId: key.projectId,
175
+ channel: key.channel
176
+ }, "suppression lookup failed — holding message");
177
+ throw err;
178
+ }
179
+ }
180
+ return keys.map((key) => results.get(`${key.projectId}:${key.channel}`) ?? /* @__PURE__ */ new Set());
181
+ });
182
+ async process(message) {
183
+ const { event } = message;
184
+ const payloadResult = this.registry.safeParsePayload("notification.enriched", event.payload);
185
+ if (!payloadResult.success) {
186
+ this.logger.warn({
187
+ messageId: message.id,
188
+ issues: payloadResult.error.issues
189
+ }, "invalid notification.enriched payload — skipping");
190
+ return;
191
+ }
192
+ const enriched = payloadResult.data;
193
+ const idempotencyKey = `${enriched.rawEventId}:${enriched.recipientId}:${enriched.channel}`;
194
+ let customTtl;
195
+ if (enriched.scheduledAt) {
196
+ const msUntil = new Date(enriched.scheduledAt).getTime() - Date.now();
197
+ if (msUntil > 0) customTtl = 86400 + Math.ceil(msUntil / 1e3);
198
+ }
199
+ if (!await this.idempotency.checkAndMark(idempotencyKey, 60)) {
200
+ this.logger.debug({
201
+ messageId: message.id,
202
+ eventId: event.id
203
+ }, "duplicate — skipping");
204
+ return;
205
+ }
206
+ try {
207
+ if (enriched.recipient.preferences.optedOut) {
208
+ this.logger.info({
209
+ messageId: message.id,
210
+ recipientId: enriched.recipientId,
211
+ eventType: event.type
212
+ }, "user opted out — dropping");
213
+ this.globalEmitter.emit("notification:skipped", {
214
+ projectId: enriched.projectId,
215
+ eventId: event.id,
216
+ recipientId: enriched.recipientId,
217
+ reason: "user_opted_out"
218
+ });
219
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
220
+ return;
221
+ }
222
+ if (enriched.recipient.preferences.channels?.includes(enriched.channel)) {
223
+ this.logger.info({
224
+ messageId: message.id,
225
+ recipientId: enriched.recipientId,
226
+ channel: enriched.channel
227
+ }, "user disabled notification channel — dropping");
228
+ this.globalEmitter.emit("notification:skipped", {
229
+ projectId: enriched.projectId,
230
+ eventId: event.id,
231
+ recipientId: enriched.recipientId,
232
+ reason: "channel_disabled"
233
+ });
234
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
235
+ return;
236
+ }
237
+ const qh = enriched.recipient.preferences.quietHours;
238
+ if (qh && qh.length > 0 && enriched.priority !== "critical") {
239
+ const qhResult = isInQuietHours(enriched.recipient.timezone, qh);
240
+ if (qhResult.inQuietHours && qhResult.nextActiveTime) {
241
+ this.logger.info({
242
+ messageId: message.id,
243
+ recipientId: enriched.recipientId,
244
+ nextActiveTime: qhResult.nextActiveTime.toISOString()
245
+ }, "user is in quiet hours — deferring notification");
246
+ enriched.scheduledAt = qhResult.nextActiveTime.toISOString();
247
+ }
248
+ }
249
+ let projectThrottle = {
250
+ throttleLimit: null,
251
+ throttleWindowHours: null
252
+ };
253
+ try {
254
+ projectThrottle = await this.projectSettings.get(enriched.projectId);
255
+ } catch (err) {
256
+ this.logger.warn({
257
+ err,
258
+ projectId: enriched.projectId
259
+ }, "could not read project throttle settings — falling back to the global default");
260
+ }
261
+ const throttleResult = await this.throttle.check(enriched.projectId, enriched.recipientId, enriched.priority, {
262
+ limit: projectThrottle.throttleLimit,
263
+ windowHours: projectThrottle.throttleWindowHours,
264
+ scheduledAt: enriched.scheduledAt
265
+ });
266
+ if (!throttleResult.allowed) {
267
+ this.logger.info({
268
+ messageId: message.id,
269
+ recipientId: enriched.recipientId,
270
+ count: throttleResult.count,
271
+ limit: throttleResult.limit,
272
+ priority: enriched.priority
273
+ }, "user throttled — dropping");
274
+ this.globalEmitter.emit("notification:throttled", enriched.recipientId, throttleResult.count);
275
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
276
+ return;
277
+ }
278
+ let dbTemplate = null;
279
+ if (enriched.templateId) {
280
+ dbTemplate = await this.templateCache.getCachedTemplate(enriched.projectId, enriched.templateId);
281
+ if (!dbTemplate) {
282
+ this.logger.warn({
283
+ messageId: message.id,
284
+ templateId: enriched.templateId
285
+ }, "template not found — dropping");
286
+ this.globalEmitter.emit("notification:skipped", {
287
+ projectId: enriched.projectId,
288
+ eventId: event.id,
289
+ recipientId: enriched.recipientId,
290
+ reason: "template_not_found"
291
+ });
292
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
293
+ return;
294
+ }
295
+ }
296
+ const aiPrompts = {
297
+ ...dbTemplate?.aiPrompts ?? {},
298
+ ...enriched.aiPrompts ?? {}
299
+ };
300
+ const templateTopics = dbTemplate?.topics ?? [];
301
+ if (Object.keys(aiPrompts).length > 0) {
302
+ const aiPendingPayload = {
303
+ projectId: enriched.projectId,
304
+ enrichedEventId: event.id,
305
+ recipientId: enriched.recipientId,
306
+ channel: enriched.channel,
307
+ priority: enriched.priority,
308
+ templateId: enriched.templateId,
309
+ templateVariables: enriched.templateVariables,
310
+ recipient: enriched.recipient,
311
+ aiPrompts,
312
+ scheduledAt: enriched.scheduledAt,
313
+ fallbackChain: enriched.fallbackChain
314
+ };
315
+ const aiPendingEnvelope = buildStreamEvent("notification.ai_pending", aiPendingPayload, "engine", event.metadata.traceId);
316
+ await this.aiPendingProducer.publish(aiPendingEnvelope);
317
+ this.logger.info({
318
+ messageId: message.id,
319
+ eventId: event.id,
320
+ recipientId: enriched.recipientId,
321
+ traceId: event.metadata.traceId
322
+ }, "task routed to AI worker");
323
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
324
+ return;
325
+ }
326
+ const rendered = renderWithTemplate(dbTemplate, enriched.templateVariables);
327
+ const activeContacts = (await this.contactsLoader.load({
328
+ projectId: enriched.projectId,
329
+ recipientId: enriched.recipientId
330
+ })).filter((c) => c.channel === enriched.channel && c.active);
331
+ if (activeContacts.length === 0) {
332
+ this.logger.info({
333
+ messageId: message.id,
334
+ recipientId: enriched.recipientId,
335
+ channel: enriched.channel
336
+ }, "no active contacts for channel — dropping");
337
+ this.globalEmitter.emit("notification:skipped", {
338
+ projectId: enriched.projectId,
339
+ eventId: event.id,
340
+ recipientId: enriched.recipientId,
341
+ reason: "no_active_contacts"
342
+ });
343
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
344
+ return;
345
+ }
346
+ const suppressedTargets = await this.suppressionsLoader.load({
347
+ projectId: enriched.projectId,
348
+ channel: enriched.channel
349
+ });
350
+ for (const contact of activeContacts) {
351
+ if (contact.preferences?.optedOut) continue;
352
+ if (contact.target && suppressedTargets.has(normaliseTarget(contact.target))) {
353
+ this.logger.info({
354
+ messageId: message.id,
355
+ recipientId: enriched.recipientId,
356
+ channel: enriched.channel
357
+ }, "destination suppressed — dropping");
358
+ this.globalEmitter.emit("notification:skipped", {
359
+ projectId: enriched.projectId,
360
+ eventId: event.id,
361
+ recipientId: enriched.recipientId,
362
+ reason: "suppressed"
363
+ });
364
+ continue;
365
+ }
366
+ const taskId = `${enriched.rawEventId}:${contact.id || randomUUID()}`;
367
+ const resolvedDestination = contact.target;
368
+ if (enriched.channel === "email" && templateTopics.length > 0 && !config.UNSUBSCRIBE_SECRET) this.logger.warn({
369
+ projectId: enriched.projectId,
370
+ recipientId: enriched.recipientId
371
+ }, "UNSUBSCRIBE_SECRET is not configured — email sent without RFC 8058 one-click unsubscribe headers");
372
+ const unsubscribeHeaders = enriched.channel === "email" && templateTopics.length > 0 && config.UNSUBSCRIBE_SECRET && config.PUBLIC_URL && resolvedDestination ? buildUnsubscribeHeaders({
373
+ claim: {
374
+ projectId: enriched.projectId,
375
+ userId: enriched.recipientId,
376
+ channel: enriched.channel,
377
+ target: resolvedDestination,
378
+ topics: templateTopics
379
+ },
380
+ secret: config.UNSUBSCRIBE_SECRET,
381
+ publicUrl: config.PUBLIC_URL
382
+ }) : void 0;
383
+ const taskPayload = {
384
+ projectId: enriched.projectId,
385
+ taskId,
386
+ enrichedEventId: event.id,
387
+ recipientId: enriched.recipientId,
388
+ channel: enriched.channel,
389
+ priority: enriched.priority,
390
+ templateId: enriched.templateId,
391
+ templateVariables: enriched.templateVariables,
392
+ aiPrompts: enriched.aiPrompts,
393
+ recipient: enriched.recipient,
394
+ renderedContent: rendered,
395
+ destination: resolvedDestination,
396
+ deliveryOptions: {
397
+ maxAttempts: 3,
398
+ timeoutMs: 1e4,
399
+ ...unsubscribeHeaders ? { headers: unsubscribeHeaders } : {}
400
+ },
401
+ fallbackChain: enriched.fallbackChain,
402
+ campaignId: enriched.campaignId
403
+ };
404
+ const envelope = buildStreamEvent("notification.dispatched", taskPayload, "engine", event.metadata.traceId);
405
+ const now = Date.now();
406
+ if ((enriched.scheduledAt ? new Date(enriched.scheduledAt).getTime() : now) > now) {
407
+ await this.db.insert(scheduledPayloads).values({
408
+ taskId,
409
+ payload: {
410
+ ...taskPayload,
411
+ scheduledAt: enriched.scheduledAt
412
+ }
413
+ }).onConflictDoNothing();
414
+ const scheduledEnvelope = buildStreamEvent("notification.scheduled", {
415
+ projectId: enriched.projectId,
416
+ enrichedEventId: event.id,
417
+ taskId,
418
+ scheduledAt: enriched.scheduledAt
419
+ }, "engine", event.metadata.traceId);
420
+ await this.scheduledProducer.publish(scheduledEnvelope);
421
+ this.logger.info({
422
+ messageId: message.id,
423
+ taskId,
424
+ scheduledAt: enriched.scheduledAt,
425
+ traceId: event.metadata.traceId
426
+ }, "task scheduled and payload cached");
427
+ } else {
428
+ const p = getPriorityBucket(enriched.priority);
429
+ await (this.outboundProducers[p] ?? this.outboundProducers["normal"]).publish(envelope);
430
+ this.logger.info({
431
+ messageId: message.id,
432
+ taskId,
433
+ recipientId: enriched.recipientId,
434
+ traceId: event.metadata.traceId
435
+ }, "task dispatched");
436
+ }
437
+ }
438
+ await this.idempotency.markProcessed(idempotencyKey, customTtl);
439
+ } catch (err) {
440
+ await this.idempotency.unmark(idempotencyKey).catch(() => {});
441
+ throw err;
442
+ }
443
+ }
444
+ };
445
+ let subscriber = null;
446
+ async function startEngineWorker() {
447
+ logger = createLogger({
448
+ name: "engine",
449
+ level: config.LOG_LEVEL
450
+ });
451
+ redis = new RedisClient({
452
+ url: config.REDIS_URL,
453
+ name: "engine",
454
+ logger
455
+ });
456
+ const dbData = createDatabase({
457
+ url: config.DATABASE_URL,
458
+ applicationName: "engine",
459
+ logger
460
+ });
461
+ sql$1 = dbData.sql;
462
+ db = dbData.db;
463
+ templateRepo = new TemplateRepository(db);
464
+ templateCache = new TemplateCache(templateRepo);
465
+ const contactRepo = new ContactRepository(db);
466
+ consumer = new StreamConsumer({
467
+ redis: redis.native,
468
+ stream: ENRICHED_STREAMS,
469
+ group: CONSUMER_GROUPS.ENGINE,
470
+ consumer: `engine-${process.pid}`,
471
+ dlqStream: STREAMS.DEAD_LETTER,
472
+ batchSize: config.WORKER_CONCURRENCY,
473
+ logger
474
+ });
475
+ pendingScanner = new PendingMessageScanner({
476
+ redis: redis.native,
477
+ stream: ENRICHED_STREAMS,
478
+ group: CONSUMER_GROUPS.ENGINE,
479
+ consumer: `engine-${process.pid}`,
480
+ logger
481
+ });
482
+ const outboundProducers = {
483
+ critical: new StreamProducer({
484
+ redis: redis.native,
485
+ stream: STREAMS.OUTBOUND_CRITICAL,
486
+ logger
487
+ }),
488
+ normal: new StreamProducer({
489
+ redis: redis.native,
490
+ stream: STREAMS.OUTBOUND_NORMAL,
491
+ logger
492
+ }),
493
+ low: new StreamProducer({
494
+ redis: redis.native,
495
+ stream: STREAMS.OUTBOUND_LOW,
496
+ logger
497
+ })
498
+ };
499
+ const scheduledProducer = new StreamProducer({
500
+ redis: redis.native,
501
+ stream: STREAMS.SCHEDULED,
502
+ logger
503
+ });
504
+ const aiPendingProducer = new StreamProducer({
505
+ redis: redis.native,
506
+ stream: STREAMS.AI_PENDING,
507
+ logger
508
+ });
509
+ const idempotency = new IdempotencyGuard({
510
+ redis: redis.native,
511
+ keyPrefix: "notif:processed:engine",
512
+ ttlSeconds: 86400
513
+ });
514
+ const throttle = new UserThrottle({
515
+ redis: redis.native,
516
+ maxPerHour: parseInt(process.env.RATE_LIMIT_PER_HOUR || "100", 10)
517
+ });
518
+ const projectRepo = new ProjectRepository(db);
519
+ const projectSettings = new ProjectSettingsCache((projectId) => projectRepo.findThrottleSettings(projectId));
520
+ worker = new EngineWorker({
521
+ consumer,
522
+ pendingScanner,
523
+ logger,
524
+ concurrency: config.WORKER_CONCURRENCY,
525
+ registry,
526
+ idempotency,
527
+ throttle,
528
+ projectSettings,
529
+ redis: redis.native,
530
+ templateCache,
531
+ aiPendingProducer,
532
+ scheduledProducer,
533
+ outboundProducers,
534
+ globalEmitter,
535
+ contactRepo,
536
+ db
537
+ });
538
+ subscriber = redis.native.duplicate();
539
+ await subscriber.subscribe(PUBSUB_CHANNELS.TEMPLATE_INVALIDATED, PUBSUB_CHANNELS.PROJECT_INVALIDATED);
540
+ subscriber.on("message", (channel, message) => {
541
+ if (channel === PUBSUB_CHANNELS.TEMPLATE_INVALIDATED) {
542
+ templateCache.invalidateKey(message);
543
+ logger.info({ cacheKey: message }, "invalidated template cache");
544
+ } else if (channel === PUBSUB_CHANNELS.PROJECT_INVALIDATED) {
545
+ projectSettings.invalidate(message);
546
+ logger.info({ projectId: message }, "invalidated project settings cache");
547
+ }
548
+ });
549
+ healthInterval = startHealthReporter("engine", worker, redis, logger);
550
+ logger.info({ env: config.NODE_ENV }, "engine starting");
551
+ await worker.start();
552
+ }
553
+ async function stopEngineWorker() {
554
+ logger?.info("shutdown initiated");
555
+ if (healthInterval) {
556
+ clearInterval(healthInterval);
557
+ healthInterval = null;
558
+ }
559
+ if (subscriber) {
560
+ subscriber.disconnect();
561
+ subscriber = null;
562
+ }
563
+ if (worker) await worker.stop();
564
+ if (sql$1) await sql$1.end();
565
+ if (redis) await redis.disconnect();
566
+ logger?.info("engine stopped");
567
+ }
568
+ //#endregion
569
+ export { startEngineWorker, stopEngineWorker };
570
+
571
+ //# sourceMappingURL=main-Dlfy9mWs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main-Dlfy9mWs.mjs","names":["sql"],"sources":["../src/services/engine/main.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { loadEnv, readBaseConfig } from \"@/index.js\";\nimport { createLogger } from \"@/index.js\";\nimport { RedisClient, type Redis } from \"@/index.js\";\nimport {\n StreamConsumer,\n PendingMessageScanner,\n StreamProducer,\n type StreamMessage,\n} from \"@/index.js\";\nimport { BaseWorker } from \"@/index.js\";\nimport {\n STREAMS,\n ENRICHED_STREAMS,\n CONSUMER_GROUPS,\n PUBSUB_CHANNELS,\n registry,\n buildStreamEvent,\n type NotificationEnrichedPayload,\n type NotificationDispatchedPayload,\n} from \"@/index.js\";\nimport { type StreamName } from \"@/contracts/streams.js\";\nimport { IdempotencyGuard } from \"@/index.js\";\nimport { UserThrottle, ProjectSettingsCache } from \"@/index.js\";\nimport { TemplateRepository, ContactRepository, ProjectRepository } from \"@/index.js\";\nimport { createDatabase } from \"@/db/index.js\";\nimport { scheduledPayloads, suppressions } from \"@/db/schema.js\";\nimport { and, eq } from \"drizzle-orm\";\nimport {\n getPriorityBucket,\n globalEmitter,\n normaliseTarget,\n type WorkerOptions,\n DataLoader,\n} from \"@/shared/index.js\";\nimport { renderWithTemplate, TemplateCache } from \"@/templates/index.js\";\nimport { buildUnsubscribeHeaders } from \"@/unsubscribe/index.js\";\nimport { startHealthReporter } from \"@/workers/index.js\";\n\nfunction localTimeToUtc(\n year: number,\n month: number,\n day: number,\n hour: number,\n minute: number,\n second: number,\n timezone: string,\n): Date {\n let utcMs = Date.UTC(year, month - 1, day, hour, minute, second);\n const formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n\n for (let iter = 0; iter < 3; iter++) {\n const parts = formatter.formatToParts(new Date(utcMs));\n const pYear = parseInt(parts.find((p) => p.type === \"year\")?.value ?? \"0\", 10);\n const pMonth = parseInt(parts.find((p) => p.type === \"month\")?.value ?? \"0\", 10);\n const pDay = parseInt(parts.find((p) => p.type === \"day\")?.value ?? \"0\", 10);\n const pHour = parseInt(parts.find((p) => p.type === \"hour\")?.value ?? \"0\", 10);\n const pMin = parseInt(parts.find((p) => p.type === \"minute\")?.value ?? \"0\", 10);\n const pSec = parseInt(parts.find((p) => p.type === \"second\")?.value ?? \"0\", 10);\n\n const targetMs = Date.UTC(year, month - 1, day, hour, minute, second);\n const actualMs = Date.UTC(pYear, pMonth - 1, pDay, pHour, pMin, pSec);\n const diff = targetMs - actualMs;\n if (diff === 0) break;\n utcMs += diff;\n }\n return new Date(utcMs);\n}\n\nexport function isInQuietHours(\n timezone: string,\n quietHours: { start: string; end: string }[],\n fromDate: Date = new Date(),\n): { inQuietHours: boolean; nextActiveTime?: Date } {\n if (!quietHours || quietHours.length === 0) {\n return { inQuietHours: false };\n }\n\n const checkWindowAt = (date: Date) => {\n let parts: Intl.DateTimeFormatPart[];\n try {\n const formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n parts = formatter.formatToParts(date);\n } catch {\n return null;\n }\n\n const year = parseInt(parts.find((p) => p.type === \"year\")?.value ?? \"0\", 10);\n const month = parseInt(parts.find((p) => p.type === \"month\")?.value ?? \"0\", 10);\n const day = parseInt(parts.find((p) => p.type === \"day\")?.value ?? \"0\", 10);\n const currentHour = parseInt(parts.find((p) => p.type === \"hour\")?.value ?? \"0\", 10);\n const currentMin = parseInt(parts.find((p) => p.type === \"minute\")?.value ?? \"0\", 10);\n\n const currentMinutes = currentHour * 60 + currentMin;\n\n for (const window of quietHours) {\n const [startH, startM] = window.start.split(\":\").map(Number);\n const [endH, endM] = window.end.split(\":\").map(Number);\n\n if (startH === undefined || startM === undefined || endH === undefined || endM === undefined)\n continue;\n\n const startMinutes = startH * 60 + startM;\n const endMinutes = endH * 60 + endM;\n\n let inWindow = false;\n if (startMinutes <= endMinutes) {\n inWindow = currentMinutes >= startMinutes && currentMinutes < endMinutes;\n } else {\n inWindow = currentMinutes >= startMinutes || currentMinutes < endMinutes;\n }\n\n if (inWindow) {\n let targetYear = year;\n let targetMonth = month;\n let targetDay = day;\n\n if (currentMinutes >= endMinutes) {\n const nextDay = new Date(Date.UTC(year, month - 1, day + 1));\n targetYear = nextDay.getUTCFullYear();\n targetMonth = nextDay.getUTCMonth() + 1;\n targetDay = nextDay.getUTCDate();\n }\n\n const nextActive = localTimeToUtc(\n targetYear,\n targetMonth,\n targetDay,\n endH,\n endM,\n 0,\n timezone,\n );\n return { inQuietHours: true, nextActiveTime: nextActive };\n }\n }\n return { inQuietHours: false };\n };\n\n let initialCheck = checkWindowAt(fromDate);\n if (!initialCheck || !initialCheck.inQuietHours) {\n return { inQuietHours: false };\n }\n\n // Chained / overlapping quiet hours intervals\n let candidateTime = initialCheck.nextActiveTime!;\n for (let i = 0; i < 10; i++) {\n const subsequentCheck = checkWindowAt(candidateTime);\n if (subsequentCheck && subsequentCheck.inQuietHours && subsequentCheck.nextActiveTime) {\n if (subsequentCheck.nextActiveTime.getTime() <= candidateTime.getTime()) {\n break;\n }\n candidateTime = subsequentCheck.nextActiveTime;\n } else {\n break;\n }\n }\n\n return { inQuietHours: true, nextActiveTime: candidateTime };\n}\n\n// ─── Bootstrap ─────────────────────────────────────────────────────────────\n\nloadEnv();\nconst config = readBaseConfig();\n\nlet logger: ReturnType<typeof createLogger>;\nlet redis: RedisClient;\nlet sql: any;\nlet db: any;\nlet templateRepo: TemplateRepository;\n\nlet templateCache: TemplateCache;\n\nlet consumer: StreamConsumer;\nlet pendingScanner: PendingMessageScanner;\nlet worker: BaseWorker;\nlet healthInterval: NodeJS.Timeout | null = null;\n\nexport interface EngineWorkerOptions extends WorkerOptions {\n registry: any;\n idempotency: any;\n throttle: any;\n projectSettings: ProjectSettingsCache;\n redis: Redis;\n templateCache: TemplateCache;\n aiPendingProducer: any;\n scheduledProducer: any;\n outboundProducers: any;\n globalEmitter: any;\n contactRepo: any;\n db: any;\n}\n\nexport class EngineWorker extends BaseWorker {\n private readonly registry: any;\n private readonly idempotency: any;\n private readonly throttle: any;\n private readonly projectSettings: ProjectSettingsCache;\n private readonly redisCli: Redis;\n private readonly templateCache: TemplateCache;\n private readonly aiPendingProducer: any;\n private readonly scheduledProducer: any;\n private readonly outboundProducers: any;\n private readonly globalEmitter: any;\n private readonly contactRepo: any;\n private readonly db: any;\n\n constructor(options: EngineWorkerOptions) {\n super(options);\n this.registry = options.registry;\n this.idempotency = options.idempotency;\n this.throttle = options.throttle;\n this.projectSettings = options.projectSettings;\n this.redisCli = options.redis;\n this.templateCache = options.templateCache;\n this.aiPendingProducer = options.aiPendingProducer;\n this.scheduledProducer = options.scheduledProducer;\n this.outboundProducers = options.outboundProducers;\n this.globalEmitter = options.globalEmitter;\n this.contactRepo = options.contactRepo;\n this.db = options.db;\n }\n\n private readonly contactsLoader = new DataLoader<\n { projectId: string; recipientId: string },\n any[]\n >(async (keys) => {\n const byProject = new Map<string, string[]>();\n for (const key of keys) {\n if (!byProject.has(key.projectId)) byProject.set(key.projectId, []);\n byProject.get(key.projectId)!.push(key.recipientId);\n }\n\n const resultsByProjectAndUser = new Map<string, Map<string, any[]>>();\n for (const [projectId, userIds] of byProject) {\n const activeContactsMap = await this.contactRepo.findActiveByUserIds(projectId, userIds);\n resultsByProjectAndUser.set(projectId, activeContactsMap);\n }\n\n return keys.map((key) => {\n const projectMap = resultsByProjectAndUser.get(key.projectId);\n if (!projectMap) return [];\n return projectMap.get(key.recipientId) || [];\n });\n });\n\n /**\n * Suppressed destinations for one (project, channel), as a normalised set.\n *\n * Loaded per project+channel rather than per address: a campaign is thousands\n * of messages against one channel, so this collapses to a single query for\n * the whole batch. Cached for the loader's lifetime of a tick, which means a\n * suppression written mid-batch takes effect on the next batch — acceptable,\n * since the webhook that writes it is itself minutes behind the send.\n */\n private readonly suppressionsLoader = new DataLoader<\n { projectId: string; channel: string },\n Set<string>\n >(async (keys) => {\n const results = new Map<string, Set<string>>();\n for (const key of keys) {\n const cacheKey = `${key.projectId}:${key.channel}`;\n if (results.has(cacheKey)) continue;\n try {\n const rows = await this.db\n .select({ target: suppressions.target })\n .from(suppressions)\n .where(\n and(\n eq(suppressions.projectId, key.projectId),\n eq(suppressions.channel, key.channel as any),\n ),\n );\n results.set(\n cacheKey,\n new Set(rows.map((r: { target: string }) => normaliseTarget(r.target))),\n );\n } catch (err) {\n // A suppression lookup that fails must not silently become \"nothing\n // is suppressed\" — that would resume mailing people who opted out.\n this.logger.error(\n { err, projectId: key.projectId, channel: key.channel },\n \"suppression lookup failed — holding message\",\n );\n throw err;\n }\n }\n return keys.map((key) => results.get(`${key.projectId}:${key.channel}`) ?? new Set<string>());\n });\n\n async process(message: StreamMessage): Promise<void> {\n const { event } = message;\n\n const payloadResult = this.registry.safeParsePayload(\"notification.enriched\", event.payload);\n if (!payloadResult.success) {\n this.logger.warn(\n { messageId: message.id, issues: payloadResult.error.issues },\n \"invalid notification.enriched payload — skipping\",\n );\n return;\n }\n\n const enriched = payloadResult.data as NotificationEnrichedPayload;\n\n // Idempotency\n const idempotencyKey = `${enriched.rawEventId}:${enriched.recipientId}:${enriched.channel}`;\n let customTtl: number | undefined;\n if (enriched.scheduledAt) {\n const msUntil = new Date(enriched.scheduledAt).getTime() - Date.now();\n if (msUntil > 0) {\n // base 24h (86400) + schedule time\n customTtl = 86400 + Math.ceil(msUntil / 1000);\n }\n }\n\n if (!(await this.idempotency.checkAndMark(idempotencyKey, 60))) {\n this.logger.debug({ messageId: message.id, eventId: event.id }, \"duplicate — skipping\");\n return;\n }\n\n try {\n // Opt-in check\n if (enriched.recipient.preferences.optedOut) {\n this.logger.info(\n { messageId: message.id, recipientId: enriched.recipientId, eventType: event.type },\n \"user opted out — dropping\",\n );\n this.globalEmitter.emit(\"notification:skipped\", {\n projectId: enriched.projectId,\n eventId: event.id,\n recipientId: enriched.recipientId,\n reason: \"user_opted_out\",\n });\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n\n if (enriched.recipient.preferences.channels?.includes(enriched.channel)) {\n this.logger.info(\n { messageId: message.id, recipientId: enriched.recipientId, channel: enriched.channel },\n \"user disabled notification channel — dropping\",\n );\n this.globalEmitter.emit(\"notification:skipped\", {\n projectId: enriched.projectId,\n eventId: event.id,\n recipientId: enriched.recipientId,\n reason: \"channel_disabled\",\n });\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n\n // Quiet hours check\n const qh = enriched.recipient.preferences.quietHours;\n if (qh && qh.length > 0 && enriched.priority !== \"critical\") {\n const qhResult = isInQuietHours(enriched.recipient.timezone, qh);\n if (qhResult.inQuietHours && qhResult.nextActiveTime) {\n this.logger.info(\n {\n messageId: message.id,\n recipientId: enriched.recipientId,\n nextActiveTime: qhResult.nextActiveTime.toISOString(),\n },\n \"user is in quiet hours — deferring notification\",\n );\n enriched.scheduledAt = qhResult.nextActiveTime.toISOString();\n }\n }\n\n // Rate limit. Per-project overrides win over the process-wide default;\n // a lookup failure must not drop the notification, so fall back rather\n // than propagate.\n let projectThrottle: { throttleLimit: number | null; throttleWindowHours: number | null } = {\n throttleLimit: null,\n throttleWindowHours: null,\n };\n try {\n projectThrottle = await this.projectSettings.get(enriched.projectId);\n } catch (err) {\n this.logger.warn(\n { err, projectId: enriched.projectId },\n \"could not read project throttle settings — falling back to the global default\",\n );\n }\n\n const throttleResult = await this.throttle.check(\n enriched.projectId,\n enriched.recipientId,\n enriched.priority,\n {\n limit: projectThrottle.throttleLimit,\n windowHours: projectThrottle.throttleWindowHours,\n scheduledAt: enriched.scheduledAt,\n },\n );\n if (!throttleResult.allowed) {\n this.logger.info(\n {\n messageId: message.id,\n recipientId: enriched.recipientId,\n count: throttleResult.count,\n limit: throttleResult.limit,\n priority: enriched.priority,\n },\n \"user throttled — dropping\",\n );\n this.globalEmitter.emit(\n \"notification:throttled\",\n enriched.recipientId,\n throttleResult.count,\n );\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n\n // Gather AI Prompts\n // Gather AI Prompts\n let dbTemplate = null;\n if (enriched.templateId) {\n dbTemplate = await this.templateCache.getCachedTemplate(\n enriched.projectId,\n enriched.templateId,\n );\n if (!dbTemplate) {\n this.logger.warn(\n { messageId: message.id, templateId: enriched.templateId },\n \"template not found — dropping\",\n );\n this.globalEmitter.emit(\"notification:skipped\", {\n projectId: enriched.projectId,\n eventId: event.id,\n recipientId: enriched.recipientId,\n reason: \"template_not_found\",\n });\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n }\n const aiPrompts = {\n ...(dbTemplate?.aiPrompts ?? {}),\n ...(enriched.aiPrompts ?? {}),\n };\n\n // Drives whether this message gets an unsubscribe header, and what the\n // resulting opt-out applies to.\n const templateTopics: string[] = dbTemplate?.topics ?? [];\n\n if (Object.keys(aiPrompts).length > 0) {\n const aiPendingPayload = {\n projectId: enriched.projectId,\n enrichedEventId: event.id,\n recipientId: enriched.recipientId,\n channel: enriched.channel,\n priority: enriched.priority,\n templateId: enriched.templateId,\n templateVariables: enriched.templateVariables,\n recipient: enriched.recipient,\n aiPrompts,\n scheduledAt: enriched.scheduledAt,\n fallbackChain: enriched.fallbackChain,\n };\n\n const aiPendingEnvelope = buildStreamEvent(\n \"notification.ai_pending\",\n aiPendingPayload as Record<string, unknown>,\n \"engine\",\n event.metadata.traceId,\n );\n\n await this.aiPendingProducer.publish(aiPendingEnvelope);\n this.logger.info(\n {\n messageId: message.id,\n eventId: event.id,\n recipientId: enriched.recipientId,\n traceId: event.metadata.traceId,\n },\n \"task routed to AI worker\",\n );\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n\n // Render template\n const rendered = renderWithTemplate(dbTemplate, enriched.templateVariables);\n\n const allContacts = await this.contactsLoader.load({\n projectId: enriched.projectId,\n recipientId: enriched.recipientId,\n });\n const activeContacts = allContacts.filter(\n (c: any) => c.channel === enriched.channel && c.active,\n );\n\n if (activeContacts.length === 0) {\n this.logger.info(\n { messageId: message.id, recipientId: enriched.recipientId, channel: enriched.channel },\n \"no active contacts for channel — dropping\",\n );\n this.globalEmitter.emit(\"notification:skipped\", {\n projectId: enriched.projectId,\n eventId: event.id,\n recipientId: enriched.recipientId,\n reason: \"no_active_contacts\",\n });\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n return;\n }\n\n const suppressedTargets = await this.suppressionsLoader.load({\n projectId: enriched.projectId,\n channel: enriched.channel,\n });\n\n for (const contact of activeContacts) {\n if (contact.preferences?.optedOut) {\n continue;\n }\n\n // A suppression outranks every other gate, `critical` included: it\n // records that the person asked us to stop, or that the address is\n // dead. Sending anyway is what gets a domain blocked.\n if (contact.target && suppressedTargets.has(normaliseTarget(contact.target))) {\n this.logger.info(\n {\n messageId: message.id,\n recipientId: enriched.recipientId,\n channel: enriched.channel,\n },\n \"destination suppressed — dropping\",\n );\n this.globalEmitter.emit(\"notification:skipped\", {\n projectId: enriched.projectId,\n eventId: event.id,\n recipientId: enriched.recipientId,\n reason: \"suppressed\",\n });\n continue;\n }\n\n const taskId = `${enriched.rawEventId}:${contact.id || randomUUID()}`;\n const resolvedDestination = contact.target;\n\n // One-click unsubscribe headers, but only on mail that should carry\n // them. A template with no topic is transactional by this codebase's\n // own convention — a password reset, a receipt — and putting an\n // unsubscribe button on those invites people to switch off mail they\n // actually need, with no topic to scope the opt-out to anyway.\n if (\n enriched.channel === \"email\" &&\n templateTopics.length > 0 &&\n !config.UNSUBSCRIBE_SECRET\n ) {\n this.logger.warn(\n { projectId: enriched.projectId, recipientId: enriched.recipientId },\n \"UNSUBSCRIBE_SECRET is not configured — email sent without RFC 8058 one-click unsubscribe headers\",\n );\n }\n\n const unsubscribeHeaders =\n enriched.channel === \"email\" &&\n templateTopics.length > 0 &&\n config.UNSUBSCRIBE_SECRET &&\n config.PUBLIC_URL &&\n resolvedDestination\n ? buildUnsubscribeHeaders({\n claim: {\n projectId: enriched.projectId,\n userId: enriched.recipientId,\n channel: enriched.channel,\n target: resolvedDestination,\n topics: templateTopics,\n },\n secret: config.UNSUBSCRIBE_SECRET,\n publicUrl: config.PUBLIC_URL,\n })\n : undefined;\n\n const taskPayload: NotificationDispatchedPayload = {\n projectId: enriched.projectId,\n taskId,\n enrichedEventId: event.id,\n recipientId: enriched.recipientId,\n channel: enriched.channel,\n priority: enriched.priority,\n templateId: enriched.templateId,\n templateVariables: enriched.templateVariables,\n aiPrompts: enriched.aiPrompts,\n recipient: enriched.recipient,\n renderedContent: rendered,\n destination: resolvedDestination,\n deliveryOptions: {\n maxAttempts: 3,\n timeoutMs: 10_000,\n ...(unsubscribeHeaders ? { headers: unsubscribeHeaders } : {}),\n },\n fallbackChain: enriched.fallbackChain,\n campaignId: enriched.campaignId,\n };\n\n const envelope = buildStreamEvent(\n \"notification.dispatched\",\n taskPayload as Record<string, unknown>,\n \"engine\",\n event.metadata.traceId,\n );\n\n // Route by scheduledAt\n const now = Date.now();\n const scheduledAt = enriched.scheduledAt ? new Date(enriched.scheduledAt).getTime() : now;\n\n if (scheduledAt > now) {\n await this.db\n .insert(scheduledPayloads)\n .values({\n taskId,\n payload: {\n ...taskPayload,\n scheduledAt: enriched.scheduledAt,\n },\n })\n .onConflictDoNothing();\n\n const scheduledEnvelope = buildStreamEvent(\n \"notification.scheduled\",\n {\n projectId: enriched.projectId,\n enrichedEventId: event.id,\n taskId,\n scheduledAt: enriched.scheduledAt!,\n },\n \"engine\",\n event.metadata.traceId,\n );\n\n await this.scheduledProducer.publish(scheduledEnvelope);\n this.logger.info(\n {\n messageId: message.id,\n taskId,\n scheduledAt: enriched.scheduledAt,\n traceId: event.metadata.traceId,\n },\n \"task scheduled and payload cached\",\n );\n } else {\n const p = getPriorityBucket(enriched.priority);\n const outboundProducer = this.outboundProducers[p] ?? this.outboundProducers[\"normal\"]!;\n\n await outboundProducer.publish(envelope);\n this.logger.info(\n {\n messageId: message.id,\n taskId,\n recipientId: enriched.recipientId,\n traceId: event.metadata.traceId,\n },\n \"task dispatched\",\n );\n }\n }\n await this.idempotency.markProcessed(idempotencyKey, customTtl);\n } catch (err) {\n await this.idempotency.unmark(idempotencyKey).catch(() => {});\n throw err;\n }\n }\n}\n\nlet subscriber: any = null;\n\nexport async function startEngineWorker() {\n logger = createLogger({ name: \"engine\", level: config.LOG_LEVEL });\n redis = new RedisClient({ url: config.REDIS_URL, name: \"engine\", logger });\n const dbData = createDatabase({ url: config.DATABASE_URL, applicationName: \"engine\", logger });\n sql = dbData.sql;\n db = dbData.db;\n templateRepo = new TemplateRepository(db);\n templateCache = new TemplateCache(templateRepo);\n const contactRepo = new ContactRepository(db);\n consumer = new StreamConsumer({\n redis: redis.native,\n stream: ENRICHED_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENGINE,\n consumer: `engine-${process.pid}`,\n dlqStream: STREAMS.DEAD_LETTER,\n batchSize: config.WORKER_CONCURRENCY,\n logger,\n });\n\n pendingScanner = new PendingMessageScanner({\n redis: redis.native,\n stream: ENRICHED_STREAMS as unknown as StreamName[],\n group: CONSUMER_GROUPS.ENGINE,\n consumer: `engine-${process.pid}`,\n logger,\n });\n\n const outboundProducers = {\n critical: new StreamProducer({\n redis: redis.native,\n stream: STREAMS.OUTBOUND_CRITICAL,\n logger,\n }),\n normal: new StreamProducer({ redis: redis.native, stream: STREAMS.OUTBOUND_NORMAL, logger }),\n low: new StreamProducer({ redis: redis.native, stream: STREAMS.OUTBOUND_LOW, logger }),\n };\n\n const scheduledProducer = new StreamProducer({\n redis: redis.native,\n stream: STREAMS.SCHEDULED,\n logger,\n });\n\n const aiPendingProducer = new StreamProducer({\n redis: redis.native,\n stream: STREAMS.AI_PENDING,\n logger,\n });\n\n const idempotency = new IdempotencyGuard({\n redis: redis.native,\n keyPrefix: \"notif:processed:engine\",\n ttlSeconds: 86_400,\n });\n\n const throttle = new UserThrottle({\n redis: redis.native,\n maxPerHour: parseInt(process.env.RATE_LIMIT_PER_HOUR || \"100\", 10),\n });\n\n // Per-project throttle overrides, cached because this is read once per\n // notification. Stale entries expire on their own; the pub/sub subscriber\n // below only makes an admin's change take effect sooner.\n const projectRepo = new ProjectRepository(db);\n const projectSettings = new ProjectSettingsCache((projectId) =>\n projectRepo.findThrottleSettings(projectId),\n );\n\n // ─── Stage 2: Decision Engine ───────────────────────────────────────────────\n //\n // Pipeline:\n // 1. Parse payload as notification.enriched\n // 2. Idempotency check\n // 3. Check user opt-in (from enriched recipient.preferences)\n // 4. Apply per-user hourly rate limit\n // 5. Render template using user locale\n // 6. Route: if scheduledAt is future → SCHEDULED; else → OUTBOUND\n\n worker = new EngineWorker({\n consumer,\n pendingScanner,\n logger,\n concurrency: config.WORKER_CONCURRENCY,\n registry,\n idempotency,\n throttle,\n projectSettings,\n redis: redis.native,\n templateCache,\n aiPendingProducer,\n scheduledProducer,\n outboundProducers,\n globalEmitter,\n contactRepo,\n db,\n });\n\n subscriber = redis.native.duplicate();\n await subscriber.subscribe(\n PUBSUB_CHANNELS.TEMPLATE_INVALIDATED,\n PUBSUB_CHANNELS.PROJECT_INVALIDATED,\n );\n subscriber.on(\"message\", (channel: string, message: string) => {\n if (channel === PUBSUB_CHANNELS.TEMPLATE_INVALIDATED) {\n templateCache.invalidateKey(message);\n logger.info({ cacheKey: message }, \"invalidated template cache\");\n } else if (channel === PUBSUB_CHANNELS.PROJECT_INVALIDATED) {\n projectSettings.invalidate(message);\n logger.info({ projectId: message }, \"invalidated project settings cache\");\n }\n });\n\n // ─── Health check interval ──────────────────────────────────────────────────\n\n healthInterval = startHealthReporter(\"engine\", worker, redis, logger);\n\n logger.info({ env: config.NODE_ENV }, \"engine starting\");\n await worker.start();\n}\n\n// ─── Shutdown ──────────────────────────────────────────────────────────────\n\nexport async function stopEngineWorker(): Promise<void> {\n logger?.info(\"shutdown initiated\");\n if (healthInterval) {\n clearInterval(healthInterval);\n healthInterval = null;\n }\n if (subscriber) {\n subscriber.disconnect();\n subscriber = null;\n }\n if (worker) await worker.stop();\n if (sql) await sql.end();\n if (redis) await redis.disconnect();\n logger?.info(\"engine stopped\");\n}\n"],"mappings":";;;;AAuCA,SAAS,eACP,MACA,OACA,KACA,MACA,QACA,QACA,UACM;CACN,IAAI,QAAQ,KAAK,IAAI,MAAM,QAAQ,GAAG,KAAK,MAAM,QAAQ,MAAM;CAC/D,MAAM,YAAY,IAAI,KAAK,eAAe,SAAS;EACjD,UAAU;EACV,MAAM;EACN,OAAO;EACP,KAAK;EACL,MAAM;EACN,QAAQ;EACR,QAAQ;EACR,QAAQ;CACV,CAAC;CAED,KAAK,IAAI,OAAO,GAAG,OAAO,G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