notifkit 0.1.15 → 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.
Files changed (85) hide show
  1. package/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
  2. package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
  3. package/dashboard/dist/index.html +2 -2
  4. package/dist/{bootstrap-BOmT69OH.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
  5. package/dist/{bulk-ZPiOJRx-.mjs → bulk-CJ5QXiPa.mjs} +1 -1
  6. package/dist/index.d.mts +71 -27
  7. package/dist/index.mjs +2 -2
  8. package/dist/{main-CCqcFDDe.mjs → main-6_bXQBDH.mjs} +21 -41
  9. package/dist/{main-BdZvBgV7.mjs → main-8nP3qmCT.mjs} +22 -48
  10. package/dist/{main-C0m9-Eos.mjs → main-B82bsFoy.mjs} +183 -334
  11. package/dist/{main-CTjaZ7ZD.mjs → main-CpaHF1Zw.mjs} +13 -15
  12. package/dist/{main-JEXBLP2A.mjs → main-DULD8-th.mjs} +8 -6
  13. package/dist/{main-C6S3EsJ3.mjs → main-ZW5RaiOK.mjs} +77 -64
  14. package/dist/{main-g33jpia4.mjs → main-g1KEcXXp.mjs} +676 -582
  15. package/dist/{main-24J4U8yP.mjs → main-mGIT8jv4.mjs} +4 -4
  16. package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
  17. package/dist/{src-9LXITcNi.mjs → src-BE_EUpZ6.mjs} +93 -93
  18. package/package.json +1 -1
  19. package/scripts/create-project.mjs +6 -2
  20. package/src/client.ts +3 -3
  21. package/src/config/index.ts +1 -0
  22. package/src/contracts/common.ts +2 -0
  23. package/src/contracts/envelope.ts +1 -1
  24. package/src/contracts/events/notification-created.ts +2 -0
  25. package/src/contracts/events/notification-delivered.ts +1 -1
  26. package/src/contracts/events/notification-failed.ts +1 -1
  27. package/src/contracts/events/notification-requested.ts +3 -2
  28. package/src/contracts/helpers.ts +1 -2
  29. package/src/contracts/index.ts +1 -0
  30. package/src/contracts/registry.ts +1 -0
  31. package/src/contracts/sdk.ts +8 -37
  32. package/src/db/schema.ts +8 -13
  33. package/src/idempotency/index.ts +6 -8
  34. package/src/metrics/index.ts +2 -0
  35. package/src/rate-limiter/api-rate-limiter.ts +208 -0
  36. package/src/rate-limiter/index.ts +3 -411
  37. package/src/rate-limiter/project-settings-cache.ts +99 -0
  38. package/src/rate-limiter/user-throttle.ts +100 -0
  39. package/src/redis/index.ts +10 -3
  40. package/src/repositories/admin-user.ts +83 -0
  41. package/src/repositories/contact.ts +359 -0
  42. package/src/repositories/index.ts +9 -1416
  43. package/src/repositories/preference.ts +35 -0
  44. package/src/repositories/project.ts +110 -0
  45. package/src/repositories/segment.ts +16 -0
  46. package/src/repositories/template.ts +72 -0
  47. package/src/repositories/types.ts +49 -0
  48. package/src/repositories/user.ts +644 -0
  49. package/src/repositories/workflow.ts +64 -0
  50. package/src/services/ai/main.ts +29 -71
  51. package/src/services/api/admin-static.ts +4 -1
  52. package/src/services/api/handlers/auth.ts +109 -0
  53. package/src/services/api/handlers/campaigns.ts +191 -0
  54. package/src/services/api/handlers/events.ts +99 -0
  55. package/src/services/api/handlers/notifications.ts +356 -0
  56. package/src/services/api/handlers/projects.ts +116 -0
  57. package/src/services/api/handlers/shared.ts +262 -0
  58. package/src/services/api/handlers/suppressions.ts +95 -0
  59. package/src/services/api/handlers/system.ts +314 -0
  60. package/src/services/api/handlers/templates.ts +97 -0
  61. package/src/services/api/handlers/unsubscribe.ts +215 -0
  62. package/src/services/api/handlers/users.ts +262 -0
  63. package/src/services/api/handlers/workflows.ts +150 -0
  64. package/src/services/api/handlers.ts +25 -2190
  65. package/src/services/api/health.ts +133 -0
  66. package/src/services/api/http.ts +12 -0
  67. package/src/services/api/main.ts +32 -322
  68. package/src/services/api/router.ts +1 -1
  69. package/src/services/api/webhooks.ts +172 -0
  70. package/src/services/delivery/main.ts +256 -498
  71. package/src/services/engine/main.ts +31 -247
  72. package/src/services/engine/quiet-hours.ts +151 -0
  73. package/src/services/engine/schedule-or-dispatch.ts +104 -0
  74. package/src/services/enricher/main.ts +9 -21
  75. package/src/services/events/main.ts +2 -2
  76. package/src/services/scheduler/main.ts +16 -25
  77. package/src/services/workflow/duration.ts +24 -0
  78. package/src/services/workflow/main.ts +6 -164
  79. package/src/services/workflow/timers.ts +157 -0
  80. package/src/shared/events.ts +3 -2
  81. package/src/templates/render.ts +1 -0
  82. package/src/workers/index.ts +7 -4
  83. package/src/workflows/sdk.ts +1 -0
  84. package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
  85. package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
@@ -1,6 +1,7 @@
1
1
  import { loadEnv, readBaseConfig } from "@/index.js";
2
2
  import type { Logger } from "@/index.js";
3
3
  import type { RedisClient, Redis } from "@/index.js";
4
+ import { redactUrl } from "@/index.js";
4
5
  import {
5
6
  type StreamConsumer,
6
7
  type PendingMessageScanner,
@@ -11,9 +12,9 @@ import { BaseWorker, type ProcessResult } from "@/index.js";
11
12
  import {
12
13
  STREAMS,
13
14
  CONSUMER_GROUPS,
15
+ PUBSUB_CHANNELS,
14
16
  registry,
15
- buildStreamEvent,
16
- type NotificationAiPendingPayload,
17
+ type EventRegistry,
17
18
  type NotificationDispatchedPayload,
18
19
  getAiConfig,
19
20
  AI_DEFAULTS,
@@ -21,8 +22,8 @@ import {
21
22
  import { generateText } from "ai";
22
23
  import { IdempotencyGuard } from "@/index.js";
23
24
  import { TemplateRepository } from "@/index.js";
24
- import { scheduledPayloads } from "@/db/schema.js";
25
- import { getPriorityBucket, globalEmitter, type WorkerOptions } from "@/shared/index.js";
25
+ import { scheduleOrDispatch } from "@/services/engine/schedule-or-dispatch.js";
26
+ import { globalEmitter, type WorkerOptions } from "@/shared/index.js";
26
27
  import { renderWithTemplate, TemplateCache } from "@/templates/index.js";
27
28
  import { startHealthReporter } from "@/workers/index.js";
28
29
  import {
@@ -83,7 +84,7 @@ export function isRetryableAiError(err: unknown): boolean {
83
84
  }
84
85
 
85
86
  export interface AiWorkerOptions extends WorkerOptions {
86
- registry: any;
87
+ registry: EventRegistry;
87
88
  idempotency: any;
88
89
  redis: Redis;
89
90
  generateAiContent: any;
@@ -94,9 +95,8 @@ export interface AiWorkerOptions extends WorkerOptions {
94
95
  }
95
96
 
96
97
  export class AiWorker extends BaseWorker {
97
- private readonly registry: any;
98
+ private readonly registry: EventRegistry;
98
99
  private readonly idempotency: any;
99
- private readonly redisCli: Redis;
100
100
  private readonly generateAiContent: any;
101
101
  private readonly templateCache: TemplateCache;
102
102
  private readonly scheduledProducer: any;
@@ -107,7 +107,6 @@ export class AiWorker extends BaseWorker {
107
107
  super(options);
108
108
  this.registry = options.registry;
109
109
  this.idempotency = options.idempotency;
110
- this.redisCli = options.redis;
111
110
  this.generateAiContent = options.generateAiContent;
112
111
  this.templateCache = options.templateCache;
113
112
  this.scheduledProducer = options.scheduledProducer;
@@ -126,7 +125,7 @@ export class AiWorker extends BaseWorker {
126
125
  return;
127
126
  }
128
127
 
129
- const pending = payloadResult.data as NotificationAiPendingPayload;
128
+ const pending = payloadResult.data;
130
129
 
131
130
  // Stable across replays: the engine's task id when it sent one. A fresh id
132
131
  // per attempt made a replay after a crash a second, unrelated task that
@@ -230,65 +229,24 @@ export class AiWorker extends BaseWorker {
230
229
  workflowInstanceId: pending.workflowInstanceId,
231
230
  };
232
231
 
233
- const envelope = buildStreamEvent(
234
- "notification.dispatched",
235
- taskPayload as Record<string, unknown>,
236
- "ai-worker",
237
- event.metadata.traceId,
232
+ await scheduleOrDispatch(
233
+ {
234
+ db: this.db,
235
+ scheduledProducer: this.scheduledProducer,
236
+ outboundProducers: this.outboundProducers,
237
+ logger: this.logger,
238
+ },
239
+ taskPayload,
240
+ {
241
+ source: "ai-worker",
242
+ scheduledAt: pending.scheduledAt,
243
+ messageId: message.id,
244
+ traceId: event.metadata.traceId,
245
+ logLevel: "info",
246
+ scheduledMessage: "task scheduled and payload cached after AI generation",
247
+ dispatchedMessage: "task dispatched after AI generation",
248
+ },
238
249
  );
239
-
240
- // Route by scheduledAt
241
- const now = Date.now();
242
- const scheduledAt = pending.scheduledAt ? new Date(pending.scheduledAt).getTime() : now;
243
-
244
- if (scheduledAt > now) {
245
- await this.db
246
- .insert(scheduledPayloads)
247
- .values({
248
- taskId,
249
- // The send time rides in the payload so the scheduler can re-queue
250
- // this from Postgres if Redis loses its data.
251
- payload: { ...taskPayload, scheduledAt: pending.scheduledAt },
252
- })
253
- .onConflictDoNothing();
254
-
255
- const scheduledEnvelope = buildStreamEvent(
256
- "notification.scheduled",
257
- {
258
- projectId: pending.projectId,
259
- enrichedEventId: pending.enrichedEventId,
260
- taskId,
261
- scheduledAt: pending.scheduledAt!,
262
- },
263
- "ai-worker",
264
- event.metadata.traceId,
265
- );
266
-
267
- await this.scheduledProducer.publish(scheduledEnvelope);
268
- this.logger.info(
269
- {
270
- messageId: message.id,
271
- taskId,
272
- scheduledAt: pending.scheduledAt,
273
- traceId: event.metadata.traceId,
274
- },
275
- "task scheduled and payload cached after AI generation",
276
- );
277
- } else {
278
- const p = getPriorityBucket(pending.priority);
279
- const outboundProducer = this.outboundProducers[p] ?? this.outboundProducers["normal"]!;
280
-
281
- await outboundProducer.publish(envelope);
282
- this.logger.info(
283
- {
284
- messageId: message.id,
285
- taskId,
286
- recipientId: pending.recipientId,
287
- traceId: event.metadata.traceId,
288
- },
289
- "task dispatched after AI generation",
290
- );
291
- }
292
250
  await this.idempotency.markProcessed?.(idempotencyKey);
293
251
  } catch (err) {
294
252
  await this.idempotency.unmark(idempotencyKey);
@@ -344,7 +302,7 @@ export async function startAiWorker() {
344
302
  const aiConfig = getAiConfig();
345
303
  const interpolated = prompt.replace(/\{\{(\w+)\}\}/g, (_, k: string) => String(vars[k] ?? ""));
346
304
 
347
- if (!aiConfig || !aiConfig.aiModel) {
305
+ if (!aiConfig.aiModel) {
348
306
  logger.warn("AI worker called but no AI model was provided to NotifkitServer");
349
307
  return `[AI Disabled] ${interpolated}`;
350
308
  }
@@ -389,9 +347,9 @@ export async function startAiWorker() {
389
347
  });
390
348
 
391
349
  subscriber = redis.native.duplicate({ enableAutoPipelining: false });
392
- await subscriber.subscribe("template.invalidated");
350
+ await subscriber.subscribe(PUBSUB_CHANNELS.TEMPLATE_INVALIDATED);
393
351
  subscriber.on("message", (channel: string, message: string) => {
394
- if (channel === "template.invalidated") {
352
+ if (channel === PUBSUB_CHANNELS.TEMPLATE_INVALIDATED) {
395
353
  templateCache.invalidateKey(message);
396
354
  logger.info({ cacheKey: message }, "invalidated template cache");
397
355
  }
@@ -399,7 +357,7 @@ export async function startAiWorker() {
399
357
 
400
358
  healthInterval = startHealthReporter("ai", worker, redis, logger);
401
359
 
402
- logger.info({ env: config.NODE_ENV, redis: config.REDIS_URL }, "ai starting");
360
+ logger.info({ env: config.NODE_ENV, redis: redactUrl(config.REDIS_URL) }, "ai starting");
403
361
  await worker.start();
404
362
  }
405
363
 
@@ -28,6 +28,7 @@ const MIME_TYPES: Record<string, string> = {
28
28
  // Where a built dashboard may sit, relative to a base directory.
29
29
  const DASHBOARD_SUBDIRS = [
30
30
  ["dashboard", "dist"],
31
+ /** @deprecated Next.js export dir; the dashboard is Vite. Remove at the next minor. */
31
32
  ["dashboard", "out"],
32
33
  ["dist", "admin"],
33
34
  ["dist", "dashboard"],
@@ -132,6 +133,7 @@ export async function handleAdminRequest(
132
133
  // 127.0.0.1:5173 outside production meant a deployment that never set
133
134
  // NODE_ENV sent every /admin request, credentials included, to whatever
134
135
  // listened there, and served its reply as the dashboard.
136
+ // @deprecated NEXT_DEV_URL: Next.js leftover; the dashboard is Vite. Remove at the next minor.
135
137
  const devProxyUrl =
136
138
  process.env.VITE_DEV_URL || process.env.ADMIN_DEV_URL || process.env.NEXT_DEV_URL;
137
139
  if (devProxyUrl && process.env.NODE_ENV !== "production") {
@@ -243,7 +245,8 @@ export async function handleAdminRequest(
243
245
  const ext = extname(filePath).toLowerCase();
244
246
  const contentType = MIME_TYPES[ext] || "application/octet-stream";
245
247
 
246
- // Cache static assets (_next/static) aggressively (immutable, 1 year), HTML files no-cache
248
+ // Cache static assets aggressively (immutable, 1 year), HTML files no-cache.
249
+ // @deprecated the `_next` match: Next.js leftover; the dashboard is Vite. Remove at the next minor.
247
250
  const isImmutable = filePath.includes("_next") || ext === ".js" || ext === ".css";
248
251
  const cacheControl = isImmutable
249
252
  ? "public, max-age=31536000, immutable"
@@ -0,0 +1,109 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import {
3
+ verifyPassword,
4
+ createAdminSession,
5
+ revokeAdminSession,
6
+ getAdminSession,
7
+ DUMMY_PASSWORD_HASH,
8
+ } from "@/services/auth/index.js";
9
+ import { readJsonBody, sendJson, sendValidationError } from "../http.js";
10
+ import { z } from "zod";
11
+ import { type Deps } from "./shared.js";
12
+
13
+ export function createAuthHandlers(deps: Deps) {
14
+ async function login(req: IncomingMessage, res: ServerResponse): Promise<void> {
15
+ if (!deps.adminUserRepo) {
16
+ sendJson(res, 500, {
17
+ error: "internal_error",
18
+ message: "Admin user repository not initialized",
19
+ });
20
+ return;
21
+ }
22
+
23
+ const body = await readJsonBody(req);
24
+ const parsed = z
25
+ .object({
26
+ identifier: z.string().min(1, "Identifier (email or username) is required"),
27
+ password: z.string().min(1, "Password is required"),
28
+ })
29
+ .safeParse(body);
30
+
31
+ if (!parsed.success) {
32
+ sendValidationError(res, parsed.error);
33
+ return;
34
+ }
35
+
36
+ const { identifier, password } = parsed.data;
37
+ const user = await deps.adminUserRepo.findByEmailOrUsername(identifier);
38
+ const targetHash = user ? user.passwordHash : DUMMY_PASSWORD_HASH;
39
+ let isValid = await verifyPassword(password, targetHash);
40
+ // The startup admin's ADMIN_PASSWORD is stored trimmed (a Windows `set`
41
+ // leaves a trailing space in it), so one configured with spaces at either
42
+ // end would otherwise never match what is typed. Only a failed attempt
43
+ // with such spaces pays the second check.
44
+ if (!isValid && password.trim() !== password && password.trim()) {
45
+ isValid = await verifyPassword(password.trim(), targetHash);
46
+ }
47
+ if (!user || !isValid) {
48
+ sendJson(res, 401, { error: "unauthorized", message: "Invalid credentials" });
49
+ return;
50
+ }
51
+
52
+ const session = await createAdminSession(deps.redis.native, user);
53
+ sendJson(res, 200, {
54
+ token: session.token,
55
+ user: {
56
+ id: user.id,
57
+ email: user.email,
58
+ username: user.username,
59
+ role: user.role,
60
+ },
61
+ expiresAt: session.expiresAt,
62
+ });
63
+ }
64
+
65
+ async function logout(req: IncomingMessage, res: ServerResponse): Promise<void> {
66
+ const authHeader = req.headers["authorization"];
67
+ let token: string | undefined;
68
+ if (typeof authHeader === "string" && authHeader.toLowerCase().startsWith("bearer ")) {
69
+ token = authHeader.slice(7).trim();
70
+ }
71
+ if (token) {
72
+ await revokeAdminSession(deps.redis.native, token);
73
+ }
74
+ sendJson(res, 200, { message: "Logged out successfully" });
75
+ }
76
+
77
+ async function getMe(req: IncomingMessage, res: ServerResponse): Promise<void> {
78
+ const authHeader = req.headers["authorization"];
79
+ let token: string | undefined;
80
+ if (typeof authHeader === "string" && authHeader.toLowerCase().startsWith("bearer ")) {
81
+ token = authHeader.slice(7).trim();
82
+ }
83
+ if (!token) {
84
+ sendJson(res, 401, { error: "unauthorized", message: "Missing token" });
85
+ return;
86
+ }
87
+
88
+ const session = await getAdminSession(deps.redis.native, token);
89
+ if (!session) {
90
+ sendJson(res, 401, { error: "unauthorized", message: "Invalid or expired session" });
91
+ return;
92
+ }
93
+
94
+ sendJson(res, 200, {
95
+ user: {
96
+ id: session.adminId,
97
+ email: session.email,
98
+ username: session.username,
99
+ role: session.role,
100
+ },
101
+ });
102
+ }
103
+
104
+ return {
105
+ login,
106
+ logout,
107
+ getMe,
108
+ };
109
+ }
@@ -0,0 +1,191 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { sendJson } from "../http.js";
3
+ import type { RouteContext } from "../router.js";
4
+ import { eq, desc, and, lte, gte, sql, like, isNotNull } from "drizzle-orm";
5
+ import { messageLogs } from "@/db/schema.js";
6
+ import { type Deps, contains, getQueryParam, parseLimit } from "./shared.js";
7
+
8
+ export function createCampaignsHandlers(deps: Deps) {
9
+ // One row per campaign label, newest activity first, with support for filtering
10
+ // by search keyword, channel, date range, and minimum message counts.
11
+ async function listCampaigns(
12
+ _req: IncomingMessage,
13
+ res: ServerResponse,
14
+ ctx: RouteContext,
15
+ ): Promise<void> {
16
+ const limit = parseLimit(ctx, 20);
17
+ const search = getQueryParam(ctx, "search")?.trim();
18
+ const channel = getQueryParam(ctx, "channel")?.trim();
19
+ const since = getQueryParam(ctx, "since")?.trim();
20
+ const until = getQueryParam(ctx, "until")?.trim();
21
+ const minMessagesParam = parseInt(getQueryParam(ctx, "minMessages") || "", 10);
22
+ const minMessages = isNaN(minMessagesParam) ? undefined : Math.max(minMessagesParam, 1);
23
+
24
+ const conditions = [
25
+ eq(messageLogs.projectId, ctx.projectId!),
26
+ isNotNull(messageLogs.campaignId),
27
+ ];
28
+
29
+ if (search) {
30
+ conditions.push(like(messageLogs.campaignId, contains(search)));
31
+ }
32
+ if (channel) {
33
+ conditions.push(eq(messageLogs.channel, channel as any));
34
+ }
35
+ if (since) {
36
+ const sinceDate = new Date(since);
37
+ if (!isNaN(sinceDate.getTime())) {
38
+ conditions.push(gte(messageLogs.timestamp, sinceDate));
39
+ }
40
+ }
41
+ if (until) {
42
+ const untilDate = new Date(until);
43
+ if (!isNaN(untilDate.getTime())) {
44
+ conditions.push(lte(messageLogs.timestamp, untilDate));
45
+ }
46
+ }
47
+
48
+ let query = deps.db
49
+ .select({
50
+ campaign: messageLogs.campaignId,
51
+ messages: sql<number>`count(distinct ${messageLogs.taskId})`,
52
+ firstSentAt: sql<string>`min(${messageLogs.timestamp})`,
53
+ lastActivityAt: sql<string>`max(${messageLogs.timestamp})`,
54
+ })
55
+ .from(messageLogs)
56
+ .where(and(...conditions))
57
+ .groupBy(messageLogs.campaignId)
58
+ .orderBy(desc(sql`max(${messageLogs.timestamp})`))
59
+ .limit(limit);
60
+
61
+ if (minMessages !== undefined) {
62
+ query = query.having(gte(sql`count(distinct ${messageLogs.taskId})`, minMessages)) as any;
63
+ }
64
+
65
+ const rows = await query;
66
+
67
+ sendJson(res, 200, {
68
+ campaigns: rows.map((r: any) => ({
69
+ campaign: r.campaign,
70
+ messages: Number(r.messages ?? 0),
71
+ firstSentAt: r.firstSentAt,
72
+ lastActivityAt: r.lastActivityAt,
73
+ })),
74
+ });
75
+ }
76
+
77
+ // The delivery funnel for one campaign, in a single grouped scan.
78
+ //
79
+ // Every figure counts *distinct tasks*, not rows: a task accumulates a
80
+ // dispatch row, an attempt row, and any number of engagement rows, so
81
+ // counting rows would inflate every number by a different factor. Opening the
82
+ // same email twice is one person who opened it.
83
+ async function getCampaignStats(
84
+ _req: IncomingMessage,
85
+ res: ServerResponse,
86
+ ctx: RouteContext,
87
+ ): Promise<void> {
88
+ const campaign = ctx.params.campaign;
89
+ if (!campaign) return sendJson(res, 400, { error: "missing_campaign" });
90
+
91
+ const rows = await deps.db
92
+ .select({
93
+ channel: messageLogs.channel,
94
+ kind: messageLogs.kind,
95
+ status: messageLogs.status,
96
+ tasks: sql<number>`count(distinct ${messageLogs.taskId})`,
97
+ })
98
+ .from(messageLogs)
99
+ .where(and(eq(messageLogs.projectId, ctx.projectId!), eq(messageLogs.campaignId, campaign)))
100
+ .groupBy(messageLogs.channel, messageLogs.kind, messageLogs.status);
101
+
102
+ if (rows.length === 0) {
103
+ return sendJson(res, 404, {
104
+ error: "not_found",
105
+ message: `No messages recorded for campaign '${campaign}'`,
106
+ });
107
+ }
108
+
109
+ const ENGAGEMENT = ["opened", "clicked", "bounced", "complained", "unsubscribed"] as const;
110
+ type Engagement = (typeof ENGAGEMENT)[number];
111
+
112
+ const blank = () => ({
113
+ sent: 0,
114
+ delivered: 0,
115
+ failed: 0,
116
+ opened: 0,
117
+ clicked: 0,
118
+ bounced: 0,
119
+ complained: 0,
120
+ unsubscribed: 0,
121
+ });
122
+
123
+ const byChannel = new Map<string, ReturnType<typeof blank>>();
124
+ for (const row of rows as any[]) {
125
+ const bucket = byChannel.get(row.channel) ?? blank();
126
+ const n = Number(row.tasks ?? 0);
127
+
128
+ if (ENGAGEMENT.includes(row.kind as Engagement)) {
129
+ bucket[row.kind as Engagement] += n;
130
+ } else if (row.kind === "dispatched") {
131
+ // `sent` is every task that reached a provider at all, which is the
132
+ // denominator a bounce rate is measured against. Each attempt logs a
133
+ // dispatched row besides its outcome row, and the two are grouped
134
+ // separately, so counting both counted every message twice.
135
+ bucket.sent += n;
136
+ } else {
137
+ if (row.status === "delivered") bucket.delivered += n;
138
+ if (row.status === "failed") bucket.failed += n;
139
+ }
140
+ byChannel.set(row.channel, bucket);
141
+ }
142
+
143
+ const total = blank();
144
+ for (const bucket of byChannel.values()) {
145
+ for (const key of Object.keys(total) as (keyof ReturnType<typeof blank>)[]) {
146
+ total[key] += bucket[key];
147
+ }
148
+ }
149
+
150
+ const pct = (n: number, d: number) => (d > 0 ? Number(((n / d) * 100).toFixed(2)) : null);
151
+
152
+ // Engagement only exists where a provider reports it back. Saying "0% open
153
+ // rate" for an SMS blast, or for email with no webhook wired, reads as a
154
+ // failed campaign rather than an untracked one.
155
+ const channels = [...byChannel.keys()];
156
+ const engagementCapable = channels.some((c) => c === "email");
157
+ const sawEngagement = ENGAGEMENT.some((k) => total[k] > 0);
158
+
159
+ const warnings: string[] = [];
160
+ if (!engagementCapable) {
161
+ warnings.push(
162
+ `Opens and clicks are not reported on ${channels.join(", ")} — those figures are not tracked, not zero.`,
163
+ );
164
+ } else if (!sawEngagement && total.delivered > 0) {
165
+ warnings.push(
166
+ "No engagement events recorded. If the provider webhook is not configured, opens and clicks cannot be tracked and will stay at zero.",
167
+ );
168
+ }
169
+
170
+ sendJson(res, 200, {
171
+ campaign,
172
+ totals: {
173
+ ...total,
174
+ deliveryRate: pct(total.delivered, total.sent),
175
+ openRate: pct(total.opened, total.delivered),
176
+ clickRate: pct(total.clicked, total.delivered),
177
+ bounceRate: pct(total.bounced, total.sent),
178
+ complaintRate: pct(total.complained, total.delivered),
179
+ unsubscribeRate: pct(total.unsubscribed, total.delivered),
180
+ },
181
+ byChannel: Object.fromEntries(byChannel),
182
+ engagementTracked: engagementCapable && sawEngagement,
183
+ warnings,
184
+ });
185
+ }
186
+
187
+ return {
188
+ listCampaigns,
189
+ getCampaignStats,
190
+ };
191
+ }
@@ -0,0 +1,99 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { IncomingMessage, ServerResponse } from "node:http";
3
+ import { buildStreamEvent, IngestEventSchema } from "@/contracts/index.js";
4
+ import { readJsonBody, sendJson, sendValidationError } from "../http.js";
5
+ import type { RouteContext } from "../router.js";
6
+ import { type Deps } from "./shared.js";
7
+
8
+ export function createEventsHandlers(deps: Deps) {
9
+ const { logger } = deps;
10
+
11
+ async function ingestEvent(
12
+ req: IncomingMessage,
13
+ res: ServerResponse,
14
+ ctx: RouteContext,
15
+ ): Promise<void> {
16
+ const tsStr = req.headers["x-timestamp"];
17
+ const expiryStr = req.headers["x-expiry"];
18
+
19
+ if (tsStr && expiryStr) {
20
+ const now = Date.now();
21
+ const eventTime = new Date(tsStr as string).getTime();
22
+ const expMs = parseInt(expiryStr as string, 10) * 1000;
23
+
24
+ // An unreadable timestamp or expiry made every comparison false, which
25
+ // let the event through unchecked.
26
+ if (Number.isNaN(eventTime) || Number.isNaN(expMs)) {
27
+ sendJson(res, 400, {
28
+ error: "invalid_timestamp",
29
+ message: "x-timestamp and x-expiry must be a date and a number of seconds",
30
+ });
31
+ return;
32
+ }
33
+ if (now > eventTime + expMs) {
34
+ sendJson(res, 400, { error: "event_expired", message: "Webhook event is expired" });
35
+ return;
36
+ }
37
+ }
38
+
39
+ const parsed = IngestEventSchema.safeParse(await readJsonBody(req));
40
+ if (!parsed.success) return sendValidationError(res, parsed.error);
41
+
42
+ const eventId = randomUUID();
43
+ const messageId = await deps.producers.events!.publish(
44
+ buildStreamEvent(
45
+ "event.received",
46
+ {
47
+ projectId: ctx.projectId!,
48
+ eventName: parsed.data.name,
49
+ payload: parsed.data.properties,
50
+ },
51
+ "api",
52
+ eventId,
53
+ ),
54
+ );
55
+ logger.info({ messageId, eventId, eventName: parsed.data.name }, "event received");
56
+ sendJson(res, 202, { messageId, eventId });
57
+ }
58
+
59
+ async function getEventsStream(
60
+ req: IncomingMessage,
61
+ res: ServerResponse,
62
+ ctx: RouteContext,
63
+ ): Promise<void> {
64
+ let open = true;
65
+ let stop: (() => void) | undefined;
66
+ req.on("close", () => {
67
+ open = false;
68
+ stop?.();
69
+ });
70
+
71
+ const unlisten = await deps.liveEvents.listen((e) => {
72
+ // Only events that name this project. One naming none belongs to no
73
+ // tenant, so it goes to nobody rather than to everybody.
74
+ if (!ctx.projectId || e.projectId !== ctx.projectId) return;
75
+ res.write(`event: ${e.event}\n`);
76
+ const data =
77
+ e.event === "delivery:delivered"
78
+ ? { taskId: e.taskId, providerMessageId: e.providerMessageId, channel: e.channel }
79
+ : { taskId: e.taskId, error: e.error, channel: e.channel };
80
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
81
+ });
82
+ if (!open) return unlisten();
83
+ stop = unlisten;
84
+
85
+ // Only once subscribed: a client that has the headers is already listening,
86
+ // so whatever it triggers next cannot be missed.
87
+ res.writeHead(200, {
88
+ "Content-Type": "text/event-stream",
89
+ "Cache-Control": "no-cache",
90
+ Connection: "keep-alive",
91
+ });
92
+ res.write("retry: 10000\n\n");
93
+ }
94
+
95
+ return {
96
+ ingestEvent,
97
+ getEventsStream,
98
+ };
99
+ }