notifkit 0.1.14 → 0.1.16
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/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
- package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/{bootstrap-m107TukN.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
- package/dist/{bulk-xAd_biYV.mjs → bulk-CJ5QXiPa.mjs} +1 -1
- package/dist/index.d.mts +71 -27
- package/dist/index.mjs +2 -2
- package/dist/{main-CWIBUEc7.mjs → main-6_bXQBDH.mjs} +21 -41
- package/dist/{main-WkxXwP5q.mjs → main-8nP3qmCT.mjs} +29 -49
- package/dist/{main-HT5c6jyf.mjs → main-B82bsFoy.mjs} +183 -334
- package/dist/{main-C87TSAqM.mjs → main-CpaHF1Zw.mjs} +13 -15
- package/dist/{main-DRHL2bst.mjs → main-DULD8-th.mjs} +8 -6
- package/dist/{main-D_62f9fH.mjs → main-ZW5RaiOK.mjs} +77 -64
- package/dist/{main-5kVwbbnW.mjs → main-g1KEcXXp.mjs} +676 -582
- package/dist/{main-C0MjK1Au.mjs → main-mGIT8jv4.mjs} +4 -4
- package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
- package/dist/{src-DYqdD694.mjs → src-BE_EUpZ6.mjs} +93 -93
- package/package.json +1 -1
- package/scripts/create-admin.mjs +0 -0
- package/scripts/create-project.mjs +6 -2
- package/scripts/migrate.mjs +0 -0
- package/scripts/notifkit.mjs +0 -0
- package/src/client.ts +3 -3
- package/src/config/index.ts +1 -0
- package/src/contracts/common.ts +2 -0
- package/src/contracts/envelope.ts +1 -1
- package/src/contracts/events/notification-created.ts +2 -0
- package/src/contracts/events/notification-delivered.ts +1 -1
- package/src/contracts/events/notification-failed.ts +1 -1
- package/src/contracts/events/notification-requested.ts +3 -2
- package/src/contracts/helpers.ts +1 -2
- package/src/contracts/index.ts +1 -0
- package/src/contracts/registry.ts +1 -0
- package/src/contracts/sdk.ts +8 -37
- package/src/db/schema.ts +8 -13
- package/src/idempotency/index.ts +6 -8
- package/src/metrics/index.ts +2 -0
- package/src/rate-limiter/api-rate-limiter.ts +208 -0
- package/src/rate-limiter/index.ts +3 -411
- package/src/rate-limiter/project-settings-cache.ts +99 -0
- package/src/rate-limiter/user-throttle.ts +100 -0
- package/src/redis/index.ts +10 -3
- package/src/repositories/admin-user.ts +83 -0
- package/src/repositories/contact.ts +359 -0
- package/src/repositories/index.ts +9 -1416
- package/src/repositories/preference.ts +35 -0
- package/src/repositories/project.ts +110 -0
- package/src/repositories/segment.ts +16 -0
- package/src/repositories/template.ts +72 -0
- package/src/repositories/types.ts +49 -0
- package/src/repositories/user.ts +644 -0
- package/src/repositories/workflow.ts +64 -0
- package/src/services/ai/main.ts +29 -71
- package/src/services/api/admin-static.ts +4 -1
- package/src/services/api/handlers/auth.ts +109 -0
- package/src/services/api/handlers/campaigns.ts +191 -0
- package/src/services/api/handlers/events.ts +99 -0
- package/src/services/api/handlers/notifications.ts +356 -0
- package/src/services/api/handlers/projects.ts +116 -0
- package/src/services/api/handlers/shared.ts +262 -0
- package/src/services/api/handlers/suppressions.ts +95 -0
- package/src/services/api/handlers/system.ts +314 -0
- package/src/services/api/handlers/templates.ts +97 -0
- package/src/services/api/handlers/unsubscribe.ts +215 -0
- package/src/services/api/handlers/users.ts +262 -0
- package/src/services/api/handlers/workflows.ts +150 -0
- package/src/services/api/handlers.ts +25 -2190
- package/src/services/api/health.ts +133 -0
- package/src/services/api/http.ts +12 -0
- package/src/services/api/main.ts +32 -322
- package/src/services/api/router.ts +1 -1
- package/src/services/api/webhooks.ts +172 -0
- package/src/services/delivery/main.ts +256 -498
- package/src/services/engine/main.ts +31 -235
- package/src/services/engine/quiet-hours.ts +151 -0
- package/src/services/engine/schedule-or-dispatch.ts +104 -0
- package/src/services/enricher/main.ts +9 -21
- package/src/services/events/main.ts +2 -2
- package/src/services/scheduler/main.ts +16 -25
- package/src/services/workflow/duration.ts +24 -0
- package/src/services/workflow/main.ts +6 -164
- package/src/services/workflow/timers.ts +157 -0
- package/src/shared/events.ts +3 -2
- package/src/templates/render.ts +1 -0
- package/src/workers/index.ts +7 -4
- package/src/workflows/sdk.ts +1 -0
- package/dashboard/README.md +0 -29
- package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
- package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
|
@@ -15,18 +15,17 @@ import {
|
|
|
15
15
|
CONSUMER_GROUPS,
|
|
16
16
|
PUBSUB_CHANNELS,
|
|
17
17
|
registry,
|
|
18
|
+
type EventRegistry,
|
|
18
19
|
buildStreamEvent,
|
|
19
|
-
type NotificationEnrichedPayload,
|
|
20
20
|
type DispatchedTaskPayload,
|
|
21
21
|
type StreamEvent,
|
|
22
22
|
} from "@/index.js";
|
|
23
23
|
import { IdempotencyGuard } from "@/index.js";
|
|
24
24
|
import { UserThrottle, ProjectSettingsCache } from "@/index.js";
|
|
25
25
|
import { TemplateRepository, ContactRepository, ProjectRepository } from "@/index.js";
|
|
26
|
-
import {
|
|
26
|
+
import { suppressions } from "@/db/schema.js";
|
|
27
27
|
import { and, eq } from "drizzle-orm";
|
|
28
28
|
import {
|
|
29
|
-
getPriorityBucket,
|
|
30
29
|
globalEmitter,
|
|
31
30
|
normaliseTarget,
|
|
32
31
|
type WorkerOptions,
|
|
@@ -35,6 +34,7 @@ import {
|
|
|
35
34
|
} from "@/shared/index.js";
|
|
36
35
|
import { TemplateCache } from "@/templates/index.js";
|
|
37
36
|
import { buildUnsubscribeHeaders } from "@/unsubscribe/index.js";
|
|
37
|
+
import { scheduleOrDispatch } from "./schedule-or-dispatch.js";
|
|
38
38
|
import { startHealthReporter } from "@/workers/index.js";
|
|
39
39
|
import {
|
|
40
40
|
createPriorityProducers,
|
|
@@ -43,146 +43,9 @@ import {
|
|
|
43
43
|
shutdownWorker,
|
|
44
44
|
uniqueConsumerId,
|
|
45
45
|
} from "@/workers/bootstrap.js";
|
|
46
|
+
import { isInQuietHours } from "./quiet-hours.js";
|
|
46
47
|
|
|
47
|
-
|
|
48
|
-
year: number,
|
|
49
|
-
month: number,
|
|
50
|
-
day: number,
|
|
51
|
-
hour: number,
|
|
52
|
-
minute: number,
|
|
53
|
-
second: number,
|
|
54
|
-
timezone: string,
|
|
55
|
-
): Date {
|
|
56
|
-
let utcMs = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
57
|
-
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
58
|
-
timeZone: timezone,
|
|
59
|
-
year: "numeric",
|
|
60
|
-
month: "2-digit",
|
|
61
|
-
day: "2-digit",
|
|
62
|
-
hour: "2-digit",
|
|
63
|
-
minute: "2-digit",
|
|
64
|
-
second: "2-digit",
|
|
65
|
-
hour12: false,
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
for (let iter = 0; iter < 3; iter++) {
|
|
69
|
-
const parts = formatter.formatToParts(new Date(utcMs));
|
|
70
|
-
const pYear = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
|
|
71
|
-
const pMonth = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
|
|
72
|
-
const pDay = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
|
|
73
|
-
const pHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
|
|
74
|
-
const pMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
|
|
75
|
-
const pSec = parseInt(parts.find((p) => p.type === "second")?.value ?? "0", 10);
|
|
76
|
-
|
|
77
|
-
const targetMs = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
78
|
-
const actualMs = Date.UTC(pYear, pMonth - 1, pDay, pHour, pMin, pSec);
|
|
79
|
-
const diff = targetMs - actualMs;
|
|
80
|
-
if (diff === 0) break;
|
|
81
|
-
utcMs += diff;
|
|
82
|
-
}
|
|
83
|
-
return new Date(utcMs);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function isInQuietHours(
|
|
87
|
-
timezone: string,
|
|
88
|
-
quietHours: { start: string; end: string }[],
|
|
89
|
-
fromDate: Date = new Date(),
|
|
90
|
-
): { inQuietHours: boolean; nextActiveTime?: Date } {
|
|
91
|
-
if (!quietHours || quietHours.length === 0) {
|
|
92
|
-
return { inQuietHours: false };
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const checkWindowAt = (date: Date) => {
|
|
96
|
-
let parts: Intl.DateTimeFormatPart[];
|
|
97
|
-
try {
|
|
98
|
-
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
99
|
-
timeZone: timezone,
|
|
100
|
-
year: "numeric",
|
|
101
|
-
month: "2-digit",
|
|
102
|
-
day: "2-digit",
|
|
103
|
-
hour: "2-digit",
|
|
104
|
-
minute: "2-digit",
|
|
105
|
-
second: "2-digit",
|
|
106
|
-
hour12: false,
|
|
107
|
-
});
|
|
108
|
-
parts = formatter.formatToParts(date);
|
|
109
|
-
} catch {
|
|
110
|
-
return null;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const year = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
|
|
114
|
-
const month = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
|
|
115
|
-
const day = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
|
|
116
|
-
const currentHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
|
|
117
|
-
const currentMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
|
|
118
|
-
|
|
119
|
-
const currentMinutes = currentHour * 60 + currentMin;
|
|
120
|
-
|
|
121
|
-
for (const window of quietHours) {
|
|
122
|
-
const [startH, startM] = window.start.split(":").map(Number);
|
|
123
|
-
const [endH, endM] = window.end.split(":").map(Number);
|
|
124
|
-
|
|
125
|
-
if (startH === undefined || startM === undefined || endH === undefined || endM === undefined)
|
|
126
|
-
continue;
|
|
127
|
-
|
|
128
|
-
const startMinutes = startH * 60 + startM;
|
|
129
|
-
const endMinutes = endH * 60 + endM;
|
|
130
|
-
|
|
131
|
-
let inWindow = false;
|
|
132
|
-
if (startMinutes <= endMinutes) {
|
|
133
|
-
inWindow = currentMinutes >= startMinutes && currentMinutes < endMinutes;
|
|
134
|
-
} else {
|
|
135
|
-
inWindow = currentMinutes >= startMinutes || currentMinutes < endMinutes;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
if (inWindow) {
|
|
139
|
-
let targetYear = year;
|
|
140
|
-
let targetMonth = month;
|
|
141
|
-
let targetDay = day;
|
|
142
|
-
|
|
143
|
-
if (currentMinutes >= endMinutes) {
|
|
144
|
-
const nextDay = new Date(Date.UTC(year, month - 1, day + 1));
|
|
145
|
-
targetYear = nextDay.getUTCFullYear();
|
|
146
|
-
targetMonth = nextDay.getUTCMonth() + 1;
|
|
147
|
-
targetDay = nextDay.getUTCDate();
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
const nextActive = localTimeToUtc(
|
|
151
|
-
targetYear,
|
|
152
|
-
targetMonth,
|
|
153
|
-
targetDay,
|
|
154
|
-
endH,
|
|
155
|
-
endM,
|
|
156
|
-
0,
|
|
157
|
-
timezone,
|
|
158
|
-
);
|
|
159
|
-
return { inQuietHours: true, nextActiveTime: nextActive };
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return { inQuietHours: false };
|
|
163
|
-
};
|
|
164
|
-
|
|
165
|
-
let initialCheck = checkWindowAt(fromDate);
|
|
166
|
-
if (!initialCheck || !initialCheck.inQuietHours) {
|
|
167
|
-
return { inQuietHours: false };
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
// Chained / overlapping quiet hours intervals
|
|
171
|
-
let candidateTime = initialCheck.nextActiveTime!;
|
|
172
|
-
for (let i = 0; i < 10; i++) {
|
|
173
|
-
const subsequentCheck = checkWindowAt(candidateTime);
|
|
174
|
-
if (subsequentCheck && subsequentCheck.inQuietHours && subsequentCheck.nextActiveTime) {
|
|
175
|
-
if (subsequentCheck.nextActiveTime.getTime() <= candidateTime.getTime()) {
|
|
176
|
-
break;
|
|
177
|
-
}
|
|
178
|
-
candidateTime = subsequentCheck.nextActiveTime;
|
|
179
|
-
} else {
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
return { inQuietHours: true, nextActiveTime: candidateTime };
|
|
185
|
-
}
|
|
48
|
+
export { isInQuietHours };
|
|
186
49
|
|
|
187
50
|
/** Idempotency stand-in for inline messages; see EngineWorker.process. */
|
|
188
51
|
const NO_IDEMPOTENCY = {
|
|
@@ -210,7 +73,7 @@ let worker: BaseWorker;
|
|
|
210
73
|
let healthInterval: NodeJS.Timeout | null = null;
|
|
211
74
|
|
|
212
75
|
export interface EngineWorkerOptions extends WorkerOptions {
|
|
213
|
-
registry:
|
|
76
|
+
registry: EventRegistry;
|
|
214
77
|
idempotency: any;
|
|
215
78
|
throttle: any;
|
|
216
79
|
projectSettings: ProjectSettingsCache;
|
|
@@ -225,11 +88,10 @@ export interface EngineWorkerOptions extends WorkerOptions {
|
|
|
225
88
|
}
|
|
226
89
|
|
|
227
90
|
export class EngineWorker extends BaseWorker {
|
|
228
|
-
private readonly registry:
|
|
91
|
+
private readonly registry: EventRegistry;
|
|
229
92
|
private readonly idempotency: any;
|
|
230
93
|
private readonly throttle: any;
|
|
231
94
|
private readonly projectSettings: ProjectSettingsCache;
|
|
232
|
-
private readonly redisCli: Redis;
|
|
233
95
|
private readonly templateCache: TemplateCache;
|
|
234
96
|
private readonly aiPendingProducer: any;
|
|
235
97
|
private readonly scheduledProducer: any;
|
|
@@ -246,7 +108,6 @@ export class EngineWorker extends BaseWorker {
|
|
|
246
108
|
this.idempotency = options.idempotency;
|
|
247
109
|
this.throttle = options.throttle;
|
|
248
110
|
this.projectSettings = options.projectSettings;
|
|
249
|
-
this.redisCli = options.redis;
|
|
250
111
|
this.templateCache = options.templateCache;
|
|
251
112
|
this.aiPendingProducer = options.aiPendingProducer;
|
|
252
113
|
this.scheduledProducer = options.scheduledProducer;
|
|
@@ -351,7 +212,7 @@ export class EngineWorker extends BaseWorker {
|
|
|
351
212
|
return;
|
|
352
213
|
}
|
|
353
214
|
|
|
354
|
-
const enriched = payloadResult.data
|
|
215
|
+
const enriched = payloadResult.data;
|
|
355
216
|
|
|
356
217
|
// Idempotency
|
|
357
218
|
// The enricher emits one event per resolved contact, so two addresses on one
|
|
@@ -594,17 +455,6 @@ export class EngineWorker extends BaseWorker {
|
|
|
594
455
|
// own convention — a password reset, a receipt — and putting an
|
|
595
456
|
// unsubscribe button on those invites people to switch off mail they
|
|
596
457
|
// actually need, with no topic to scope the opt-out to anyway.
|
|
597
|
-
if (
|
|
598
|
-
enriched.channel === "email" &&
|
|
599
|
-
templateTopics.length > 0 &&
|
|
600
|
-
!config.UNSUBSCRIBE_SECRET
|
|
601
|
-
) {
|
|
602
|
-
this.logger.warn(
|
|
603
|
-
{ projectId: enriched.projectId, recipientId: enriched.recipientId },
|
|
604
|
-
"UNSUBSCRIBE_SECRET is not configured — email sent without RFC 8058 one-click unsubscribe headers",
|
|
605
|
-
);
|
|
606
|
-
}
|
|
607
|
-
|
|
608
458
|
const unsubscribeHeaders =
|
|
609
459
|
enriched.channel === "email" &&
|
|
610
460
|
templateTopics.length > 0 &&
|
|
@@ -679,74 +529,25 @@ export class EngineWorker extends BaseWorker {
|
|
|
679
529
|
continue;
|
|
680
530
|
}
|
|
681
531
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
532
|
+
await scheduleOrDispatch(
|
|
533
|
+
{
|
|
534
|
+
db: this.db,
|
|
535
|
+
scheduledProducer: this.scheduledProducer,
|
|
536
|
+
outboundProducers: this.outboundProducers,
|
|
537
|
+
logger: this.logger,
|
|
538
|
+
inlineNext: this.inlineNext,
|
|
539
|
+
},
|
|
540
|
+
taskPayload,
|
|
541
|
+
{
|
|
542
|
+
source: "engine",
|
|
543
|
+
scheduledAt: enriched.scheduledAt,
|
|
544
|
+
messageId: message.id,
|
|
545
|
+
traceId: event.metadata.traceId,
|
|
546
|
+
logLevel: "debug",
|
|
547
|
+
scheduledMessage: "task scheduled and payload cached",
|
|
548
|
+
dispatchedMessage: "task dispatched",
|
|
549
|
+
},
|
|
687
550
|
);
|
|
688
|
-
|
|
689
|
-
// Route by scheduledAt
|
|
690
|
-
const now = Date.now();
|
|
691
|
-
const scheduledAt = enriched.scheduledAt ? new Date(enriched.scheduledAt).getTime() : now;
|
|
692
|
-
|
|
693
|
-
if (scheduledAt > now) {
|
|
694
|
-
await this.db
|
|
695
|
-
.insert(scheduledPayloads)
|
|
696
|
-
.values({
|
|
697
|
-
taskId,
|
|
698
|
-
payload: {
|
|
699
|
-
...taskPayload,
|
|
700
|
-
scheduledAt: enriched.scheduledAt,
|
|
701
|
-
},
|
|
702
|
-
})
|
|
703
|
-
.onConflictDoNothing();
|
|
704
|
-
|
|
705
|
-
const scheduledEnvelope = buildStreamEvent(
|
|
706
|
-
"notification.scheduled",
|
|
707
|
-
{
|
|
708
|
-
projectId: enriched.projectId,
|
|
709
|
-
enrichedEventId: event.id,
|
|
710
|
-
taskId,
|
|
711
|
-
scheduledAt: enriched.scheduledAt!,
|
|
712
|
-
},
|
|
713
|
-
"engine",
|
|
714
|
-
event.metadata.traceId,
|
|
715
|
-
);
|
|
716
|
-
|
|
717
|
-
await this.scheduledProducer.publish(scheduledEnvelope);
|
|
718
|
-
this.logger.debug(
|
|
719
|
-
{
|
|
720
|
-
messageId: message.id,
|
|
721
|
-
taskId,
|
|
722
|
-
scheduledAt: enriched.scheduledAt,
|
|
723
|
-
traceId: event.metadata.traceId,
|
|
724
|
-
},
|
|
725
|
-
"task scheduled and payload cached",
|
|
726
|
-
);
|
|
727
|
-
} else {
|
|
728
|
-
const p = getPriorityBucket(enriched.priority);
|
|
729
|
-
const outboundProducer = this.outboundProducers[p] ?? this.outboundProducers["normal"]!;
|
|
730
|
-
|
|
731
|
-
if (this.inlineNext) {
|
|
732
|
-
await this.inlineNext({
|
|
733
|
-
...envelope,
|
|
734
|
-
id: randomUUID(),
|
|
735
|
-
timestamp: new Date().toISOString(),
|
|
736
|
-
} as StreamEvent);
|
|
737
|
-
} else {
|
|
738
|
-
await outboundProducer.publish(envelope);
|
|
739
|
-
}
|
|
740
|
-
this.logger.debug(
|
|
741
|
-
{
|
|
742
|
-
messageId: message.id,
|
|
743
|
-
taskId,
|
|
744
|
-
recipientId: enriched.recipientId,
|
|
745
|
-
traceId: event.metadata.traceId,
|
|
746
|
-
},
|
|
747
|
-
"task dispatched",
|
|
748
|
-
);
|
|
749
|
-
}
|
|
750
551
|
}
|
|
751
552
|
await idempotency.markProcessed(idempotencyKey, customTtl);
|
|
752
553
|
} catch (err) {
|
|
@@ -763,6 +564,11 @@ export async function startEngineWorker() {
|
|
|
763
564
|
templateRepo = new TemplateRepository(db);
|
|
764
565
|
templateCache = new TemplateCache(templateRepo);
|
|
765
566
|
const contactRepo = new ContactRepository(db);
|
|
567
|
+
if (!config.UNSUBSCRIBE_SECRET) {
|
|
568
|
+
logger.warn(
|
|
569
|
+
"UNSUBSCRIBE_SECRET is not configured — emails with topics are sent without RFC 8058 one-click unsubscribe headers",
|
|
570
|
+
);
|
|
571
|
+
}
|
|
766
572
|
const consumerId = uniqueConsumerId("engine");
|
|
767
573
|
({ consumer, pendingScanner } = createStreamConsumer(
|
|
768
574
|
{ redis, logger },
|
|
@@ -809,16 +615,6 @@ export async function startEngineWorker() {
|
|
|
809
615
|
projectRepo.findThrottleSettings(projectId),
|
|
810
616
|
);
|
|
811
617
|
|
|
812
|
-
// ─── Stage 2: Decision Engine ───────────────────────────────────────────────
|
|
813
|
-
//
|
|
814
|
-
// Pipeline:
|
|
815
|
-
// 1. Parse payload as notification.enriched
|
|
816
|
-
// 2. Idempotency check
|
|
817
|
-
// 3. Check user opt-in (from enriched recipient.preferences)
|
|
818
|
-
// 4. Apply per-user hourly rate limit
|
|
819
|
-
// 5. Render template using user locale
|
|
820
|
-
// 6. Route: if scheduledAt is future → SCHEDULED; else → OUTBOUND
|
|
821
|
-
|
|
822
618
|
worker = new EngineWorker({
|
|
823
619
|
consumer,
|
|
824
620
|
pendingScanner,
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
function localTimeToUtc(
|
|
2
|
+
year: number,
|
|
3
|
+
month: number,
|
|
4
|
+
day: number,
|
|
5
|
+
hour: number,
|
|
6
|
+
minute: number,
|
|
7
|
+
second: number,
|
|
8
|
+
timezone: string,
|
|
9
|
+
): Date {
|
|
10
|
+
let utcMs = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
11
|
+
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
12
|
+
timeZone: timezone,
|
|
13
|
+
year: "numeric",
|
|
14
|
+
month: "2-digit",
|
|
15
|
+
day: "2-digit",
|
|
16
|
+
hour: "2-digit",
|
|
17
|
+
minute: "2-digit",
|
|
18
|
+
second: "2-digit",
|
|
19
|
+
hour12: false,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
for (let iter = 0; iter < 3; iter++) {
|
|
23
|
+
const parts = formatter.formatToParts(new Date(utcMs));
|
|
24
|
+
const pYear = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
|
|
25
|
+
const pMonth = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
|
|
26
|
+
const pDay = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
|
|
27
|
+
const pHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
|
|
28
|
+
const pMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
|
|
29
|
+
const pSec = parseInt(parts.find((p) => p.type === "second")?.value ?? "0", 10);
|
|
30
|
+
|
|
31
|
+
const targetMs = Date.UTC(year, month - 1, day, hour, minute, second);
|
|
32
|
+
const actualMs = Date.UTC(pYear, pMonth - 1, pDay, pHour, pMin, pSec);
|
|
33
|
+
const diff = targetMs - actualMs;
|
|
34
|
+
if (diff === 0) break;
|
|
35
|
+
utcMs += diff;
|
|
36
|
+
}
|
|
37
|
+
return new Date(utcMs);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isInQuietHours(
|
|
41
|
+
timezone: string,
|
|
42
|
+
quietHours: { start: string; end: string }[],
|
|
43
|
+
fromDate: Date = new Date(),
|
|
44
|
+
): { inQuietHours: boolean; nextActiveTime?: Date } {
|
|
45
|
+
if (!quietHours || quietHours.length === 0) {
|
|
46
|
+
return { inQuietHours: false };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const checkWindowAt = (date: Date) => {
|
|
50
|
+
let parts: Intl.DateTimeFormatPart[];
|
|
51
|
+
try {
|
|
52
|
+
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
53
|
+
timeZone: timezone,
|
|
54
|
+
year: "numeric",
|
|
55
|
+
month: "2-digit",
|
|
56
|
+
day: "2-digit",
|
|
57
|
+
hour: "2-digit",
|
|
58
|
+
minute: "2-digit",
|
|
59
|
+
second: "2-digit",
|
|
60
|
+
hour12: false,
|
|
61
|
+
});
|
|
62
|
+
parts = formatter.formatToParts(date);
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const year = parseInt(parts.find((p) => p.type === "year")?.value ?? "0", 10);
|
|
68
|
+
const month = parseInt(parts.find((p) => p.type === "month")?.value ?? "0", 10);
|
|
69
|
+
const day = parseInt(parts.find((p) => p.type === "day")?.value ?? "0", 10);
|
|
70
|
+
const currentHour = parseInt(parts.find((p) => p.type === "hour")?.value ?? "0", 10);
|
|
71
|
+
const currentMin = parseInt(parts.find((p) => p.type === "minute")?.value ?? "0", 10);
|
|
72
|
+
|
|
73
|
+
const currentMinutes = currentHour * 60 + currentMin;
|
|
74
|
+
|
|
75
|
+
for (const window of quietHours) {
|
|
76
|
+
const [startH, startM] = window.start.split(":").map(Number);
|
|
77
|
+
const [endH, endM] = window.end.split(":").map(Number);
|
|
78
|
+
|
|
79
|
+
if (startH === undefined || startM === undefined || endH === undefined || endM === undefined)
|
|
80
|
+
continue;
|
|
81
|
+
|
|
82
|
+
const startMinutes = startH * 60 + startM;
|
|
83
|
+
const endMinutes = endH * 60 + endM;
|
|
84
|
+
|
|
85
|
+
let inWindow = false;
|
|
86
|
+
if (startMinutes <= endMinutes) {
|
|
87
|
+
inWindow = currentMinutes >= startMinutes && currentMinutes < endMinutes;
|
|
88
|
+
} else {
|
|
89
|
+
inWindow = currentMinutes >= startMinutes || currentMinutes < endMinutes;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (inWindow) {
|
|
93
|
+
let targetYear = year;
|
|
94
|
+
let targetMonth = month;
|
|
95
|
+
let targetDay = day;
|
|
96
|
+
|
|
97
|
+
if (currentMinutes >= endMinutes) {
|
|
98
|
+
const nextDay = new Date(Date.UTC(year, month - 1, day + 1));
|
|
99
|
+
targetYear = nextDay.getUTCFullYear();
|
|
100
|
+
targetMonth = nextDay.getUTCMonth() + 1;
|
|
101
|
+
targetDay = nextDay.getUTCDate();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let nextActive = localTimeToUtc(
|
|
105
|
+
targetYear,
|
|
106
|
+
targetMonth,
|
|
107
|
+
targetDay,
|
|
108
|
+
endH,
|
|
109
|
+
endM,
|
|
110
|
+
0,
|
|
111
|
+
timezone,
|
|
112
|
+
);
|
|
113
|
+
// In a DST fall-back hour the end time occurs twice and localTimeToUtc
|
|
114
|
+
// picks the first, which can already be behind us; use the current
|
|
115
|
+
// UTC offset to land on the second occurrence instead.
|
|
116
|
+
if (nextActive.getTime() <= date.getTime()) {
|
|
117
|
+
const currentSec = parseInt(parts.find((p) => p.type === "second")?.value ?? "0", 10);
|
|
118
|
+
const offsetMs =
|
|
119
|
+
Date.UTC(year, month - 1, day, currentHour, currentMin, currentSec) -
|
|
120
|
+
Math.floor(date.getTime() / 1000) * 1000;
|
|
121
|
+
nextActive = new Date(
|
|
122
|
+
Date.UTC(targetYear, targetMonth - 1, targetDay, endH, endM, 0) - offsetMs,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return { inQuietHours: true, nextActiveTime: nextActive };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return { inQuietHours: false };
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
let initialCheck = checkWindowAt(fromDate);
|
|
132
|
+
if (!initialCheck || !initialCheck.inQuietHours) {
|
|
133
|
+
return { inQuietHours: false };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Chained / overlapping quiet hours intervals
|
|
137
|
+
let candidateTime = initialCheck.nextActiveTime!;
|
|
138
|
+
for (let i = 0; i < 10; i++) {
|
|
139
|
+
const subsequentCheck = checkWindowAt(candidateTime);
|
|
140
|
+
if (subsequentCheck && subsequentCheck.inQuietHours && subsequentCheck.nextActiveTime) {
|
|
141
|
+
if (subsequentCheck.nextActiveTime.getTime() <= candidateTime.getTime()) {
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
candidateTime = subsequentCheck.nextActiveTime;
|
|
145
|
+
} else {
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { inQuietHours: true, nextActiveTime: candidateTime };
|
|
151
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { Logger } from "@/index.js";
|
|
3
|
+
import { buildStreamEvent, type DispatchedTaskPayload, type StreamEvent } from "@/index.js";
|
|
4
|
+
import { scheduledPayloads } from "@/db/schema.js";
|
|
5
|
+
import { getPriorityBucket } from "@/shared/index.js";
|
|
6
|
+
|
|
7
|
+
export interface ScheduleOrDispatchDeps {
|
|
8
|
+
db: any;
|
|
9
|
+
scheduledProducer: any;
|
|
10
|
+
outboundProducers: any;
|
|
11
|
+
logger: Logger;
|
|
12
|
+
/** Delivery in this process, when the pipeline is fused. */
|
|
13
|
+
inlineNext?: ((event: StreamEvent) => Promise<void>) | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ScheduleOrDispatchOptions {
|
|
17
|
+
source: string;
|
|
18
|
+
scheduledAt?: string;
|
|
19
|
+
messageId: string;
|
|
20
|
+
traceId?: string;
|
|
21
|
+
logLevel: "debug" | "info";
|
|
22
|
+
scheduledMessage: string;
|
|
23
|
+
dispatchedMessage: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Caches the payload and publishes `notification.scheduled` when the task is due
|
|
28
|
+
* later, otherwise publishes `notification.dispatched` to the outbound stream
|
|
29
|
+
* for its priority (or hands it to the fused delivery worker).
|
|
30
|
+
*/
|
|
31
|
+
export async function scheduleOrDispatch(
|
|
32
|
+
deps: ScheduleOrDispatchDeps,
|
|
33
|
+
taskPayload: DispatchedTaskPayload,
|
|
34
|
+
opts: ScheduleOrDispatchOptions,
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
const { taskId } = taskPayload;
|
|
37
|
+
const envelope = buildStreamEvent(
|
|
38
|
+
"notification.dispatched",
|
|
39
|
+
taskPayload as Record<string, unknown>,
|
|
40
|
+
opts.source,
|
|
41
|
+
opts.traceId,
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
// Route by scheduledAt
|
|
45
|
+
const now = Date.now();
|
|
46
|
+
const scheduledAt = opts.scheduledAt ? new Date(opts.scheduledAt).getTime() : now;
|
|
47
|
+
|
|
48
|
+
if (scheduledAt > now) {
|
|
49
|
+
await deps.db
|
|
50
|
+
.insert(scheduledPayloads)
|
|
51
|
+
.values({
|
|
52
|
+
taskId,
|
|
53
|
+
// The send time rides in the payload so the scheduler can re-queue
|
|
54
|
+
// this from Postgres if Redis loses its data.
|
|
55
|
+
payload: { ...taskPayload, scheduledAt: opts.scheduledAt },
|
|
56
|
+
})
|
|
57
|
+
.onConflictDoNothing();
|
|
58
|
+
|
|
59
|
+
const scheduledEnvelope = buildStreamEvent(
|
|
60
|
+
"notification.scheduled",
|
|
61
|
+
{
|
|
62
|
+
projectId: taskPayload.projectId,
|
|
63
|
+
enrichedEventId: taskPayload.enrichedEventId,
|
|
64
|
+
taskId,
|
|
65
|
+
scheduledAt: opts.scheduledAt!,
|
|
66
|
+
},
|
|
67
|
+
opts.source,
|
|
68
|
+
opts.traceId,
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
await deps.scheduledProducer.publish(scheduledEnvelope);
|
|
72
|
+
deps.logger[opts.logLevel](
|
|
73
|
+
{
|
|
74
|
+
messageId: opts.messageId,
|
|
75
|
+
taskId,
|
|
76
|
+
scheduledAt: opts.scheduledAt,
|
|
77
|
+
traceId: opts.traceId,
|
|
78
|
+
},
|
|
79
|
+
opts.scheduledMessage,
|
|
80
|
+
);
|
|
81
|
+
} else {
|
|
82
|
+
const p = getPriorityBucket(taskPayload.priority);
|
|
83
|
+
const outboundProducer = deps.outboundProducers[p] ?? deps.outboundProducers["normal"]!;
|
|
84
|
+
|
|
85
|
+
if (deps.inlineNext) {
|
|
86
|
+
await deps.inlineNext({
|
|
87
|
+
...envelope,
|
|
88
|
+
id: randomUUID(),
|
|
89
|
+
timestamp: new Date().toISOString(),
|
|
90
|
+
} as StreamEvent);
|
|
91
|
+
} else {
|
|
92
|
+
await outboundProducer.publish(envelope);
|
|
93
|
+
}
|
|
94
|
+
deps.logger[opts.logLevel](
|
|
95
|
+
{
|
|
96
|
+
messageId: opts.messageId,
|
|
97
|
+
taskId,
|
|
98
|
+
recipientId: taskPayload.recipientId,
|
|
99
|
+
traceId: opts.traceId,
|
|
100
|
+
},
|
|
101
|
+
opts.dispatchedMessage,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -15,12 +15,7 @@ import {
|
|
|
15
15
|
type StreamEvent,
|
|
16
16
|
} from "@/index.js";
|
|
17
17
|
import { IdempotencyGuard } from "@/index.js";
|
|
18
|
-
import {
|
|
19
|
-
UserRepository,
|
|
20
|
-
PreferenceRepository,
|
|
21
|
-
TemplateRepository,
|
|
22
|
-
ContactRepository,
|
|
23
|
-
} from "@/index.js";
|
|
18
|
+
import { UserRepository, TemplateRepository, ContactRepository } from "@/index.js";
|
|
24
19
|
import { TemplateCache } from "@/templates/index.js";
|
|
25
20
|
import { getPriorityBucket, globalEmitter, type WorkerOptions } from "@/shared/index.js";
|
|
26
21
|
import { startHealthReporter } from "@/workers/index.js";
|
|
@@ -60,7 +55,7 @@ export interface EnricherWorkerOptions extends WorkerOptions {
|
|
|
60
55
|
producers: any;
|
|
61
56
|
idempotency: any;
|
|
62
57
|
userRepo: any;
|
|
63
|
-
prefRepo
|
|
58
|
+
prefRepo?: any;
|
|
64
59
|
contactRepo: any;
|
|
65
60
|
templateCache: TemplateCache;
|
|
66
61
|
}
|
|
@@ -69,7 +64,6 @@ export class EnricherWorker extends BaseWorker {
|
|
|
69
64
|
private readonly producers: any;
|
|
70
65
|
private readonly idempotency: any;
|
|
71
66
|
private readonly userRepo: any;
|
|
72
|
-
private readonly prefRepo: any;
|
|
73
67
|
private readonly contactRepo: any;
|
|
74
68
|
private readonly templateCache: TemplateCache;
|
|
75
69
|
/** Engine in this process, when the pipeline is fused. See `setInlineNext`. */
|
|
@@ -140,7 +134,6 @@ export class EnricherWorker extends BaseWorker {
|
|
|
140
134
|
this.producers = options.producers;
|
|
141
135
|
this.idempotency = options.idempotency;
|
|
142
136
|
this.userRepo = options.userRepo;
|
|
143
|
-
this.prefRepo = options.prefRepo;
|
|
144
137
|
this.contactRepo = options.contactRepo;
|
|
145
138
|
this.templateCache = options.templateCache;
|
|
146
139
|
|
|
@@ -248,6 +241,7 @@ export class EnricherWorker extends BaseWorker {
|
|
|
248
241
|
const requestedResult = registry.safeParsePayload("notification.requested", event.payload);
|
|
249
242
|
let createdResult: any = null;
|
|
250
243
|
if (!requestedResult.success) {
|
|
244
|
+
// @deprecated fallback to the legacy `notification.created` payload (see below).
|
|
251
245
|
createdResult = registry.safeParsePayload("notification.created", event.payload);
|
|
252
246
|
isRequested = false;
|
|
253
247
|
}
|
|
@@ -260,7 +254,12 @@ export class EnricherWorker extends BaseWorker {
|
|
|
260
254
|
return;
|
|
261
255
|
}
|
|
262
256
|
|
|
263
|
-
|
|
257
|
+
/**
|
|
258
|
+
* Legacy `notification.created` path.
|
|
259
|
+
* @deprecated Nothing in notifkit publishes `notification.created` any more;
|
|
260
|
+
* this branch only serves callers writing straight to the inbound stream.
|
|
261
|
+
* Removed in the next minor version.
|
|
262
|
+
*/
|
|
264
263
|
if (!isRequested) {
|
|
265
264
|
const raw = createdResult.data as NotificationCreatedPayload;
|
|
266
265
|
const dedupeId = `${raw.projectId}:${raw.idempotencyKey ?? event.id}`;
|
|
@@ -595,19 +594,9 @@ export async function startEnricherWorker() {
|
|
|
595
594
|
});
|
|
596
595
|
|
|
597
596
|
const userRepo = new UserRepository(db);
|
|
598
|
-
const prefRepo = new PreferenceRepository(db);
|
|
599
597
|
const contactRepo = new ContactRepository(db);
|
|
600
598
|
const templateCache = new TemplateCache(new TemplateRepository(db));
|
|
601
599
|
|
|
602
|
-
// ─── Stage 1: Context Enricher ──────────────────────────────────────────────
|
|
603
|
-
//
|
|
604
|
-
// Pipeline:
|
|
605
|
-
// 1. Parse payload as notification.created
|
|
606
|
-
// 2. Idempotency check — drop if already processed
|
|
607
|
-
// 3. Load user profile (language, timezone) from DB
|
|
608
|
-
// 4. Load all stored preferences for this user
|
|
609
|
-
// 5. Publish notification.enriched to ENRICHED stream
|
|
610
|
-
|
|
611
600
|
worker = new EnricherWorker({
|
|
612
601
|
consumer,
|
|
613
602
|
pendingScanner,
|
|
@@ -617,7 +606,6 @@ export async function startEnricherWorker() {
|
|
|
617
606
|
producers,
|
|
618
607
|
idempotency,
|
|
619
608
|
userRepo,
|
|
620
|
-
prefRepo,
|
|
621
609
|
contactRepo,
|
|
622
610
|
templateCache,
|
|
623
611
|
});
|