@hogsend/engine 0.38.2 → 0.40.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.
- package/package.json +10 -7
- package/src/campaigns/define-campaign.ts +122 -0
- package/src/campaigns/reconcile.ts +297 -0
- package/src/container.ts +153 -10
- package/src/env.ts +14 -0
- package/src/index.ts +39 -1
- package/src/journeys/define-journey.ts +142 -2
- package/src/journeys/graph/build-graph.ts +1159 -0
- package/src/journeys/journey-boundary.ts +33 -0
- package/src/journeys/journey-context.ts +58 -8
- package/src/journeys/journey-log.ts +64 -0
- package/src/journeys/journey-source-locations-singleton.ts +19 -0
- package/src/journeys/journey-sources-singleton.ts +14 -0
- package/src/journeys/registry.ts +148 -5
- package/src/lib/auth.ts +33 -1
- package/src/lib/email.ts +17 -6
- package/src/lib/ingestion.ts +13 -0
- package/src/lib/tracked.ts +32 -0
- package/src/lists/define-list.ts +19 -3
- package/src/routes/admin/campaigns.ts +165 -0
- package/src/routes/admin/index.ts +4 -0
- package/src/routes/admin/journeys.ts +278 -0
- package/src/routes/admin/open-editor.ts +106 -0
- package/src/routes/campaigns/index.ts +259 -50
- package/src/routes/emails/index.ts +25 -1
- package/src/worker.ts +37 -2
- package/src/workflows/send-campaign.ts +167 -15
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { campaigns } from "@hogsend/db";
|
|
2
2
|
import { getTemplateNames, type TemplateName } from "@hogsend/email";
|
|
3
3
|
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
4
|
-
import { eq } from "drizzle-orm";
|
|
4
|
+
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
|
5
5
|
import type { AppEnv } from "../../app.js";
|
|
6
6
|
import { errorSchema } from "../../lib/schemas.js";
|
|
7
7
|
import { sendCampaignTask } from "../../workflows/send-campaign.js";
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* How far in the past a `sendAt` may lie and still be accepted (treated as an
|
|
11
|
+
* immediate send). Anything staler is a 400 — a client submitting last week's
|
|
12
|
+
* timestamp almost certainly did not mean "blast right now".
|
|
13
|
+
*/
|
|
14
|
+
const SEND_AT_PAST_TOLERANCE_MS = 60 * 1000;
|
|
15
|
+
|
|
9
16
|
const createCampaignSchema = z
|
|
10
17
|
.object({
|
|
11
18
|
name: z.string().min(1).optional(),
|
|
@@ -15,6 +22,12 @@ const createCampaignSchema = z
|
|
|
15
22
|
props: z.record(z.string(), z.unknown()).optional(),
|
|
16
23
|
from: z.string().optional(),
|
|
17
24
|
subject: z.string().optional(),
|
|
25
|
+
/**
|
|
26
|
+
* Optional future send instant (ISO 8601). Present → the campaign is
|
|
27
|
+
* created `scheduled` and delivered at that instant (Hatchet scheduled run,
|
|
28
|
+
* with the reaper sweep as backstop). Absent → immediate enqueue.
|
|
29
|
+
*/
|
|
30
|
+
sendAt: z.string().datetime({ offset: true }).optional(),
|
|
18
31
|
/**
|
|
19
32
|
* Optional client idempotency key. A retried create with the same key
|
|
20
33
|
* resolves to the EXISTING campaign instead of spawning a second broadcast
|
|
@@ -31,9 +44,10 @@ const createCampaignSchema = z
|
|
|
31
44
|
const createResponseSchema = z.object({
|
|
32
45
|
campaignId: z.string(),
|
|
33
46
|
status: z.string(),
|
|
47
|
+
scheduledAt: z.string().nullable().optional(),
|
|
34
48
|
});
|
|
35
49
|
|
|
36
|
-
const campaignSchema = z.object({
|
|
50
|
+
export const campaignSchema = z.object({
|
|
37
51
|
id: z.string(),
|
|
38
52
|
name: z.string(),
|
|
39
53
|
status: z.string(),
|
|
@@ -44,18 +58,44 @@ const campaignSchema = z.object({
|
|
|
44
58
|
sentCount: z.number(),
|
|
45
59
|
skippedCount: z.number(),
|
|
46
60
|
failedCount: z.number(),
|
|
61
|
+
scheduledAt: z.string().nullable(),
|
|
62
|
+
canceledAt: z.string().nullable(),
|
|
47
63
|
startedAt: z.string().nullable(),
|
|
48
64
|
completedAt: z.string().nullable(),
|
|
49
65
|
createdAt: z.string(),
|
|
50
66
|
});
|
|
51
67
|
|
|
68
|
+
type CampaignRow = typeof campaigns.$inferSelect;
|
|
69
|
+
|
|
70
|
+
export function serializeCampaign(
|
|
71
|
+
campaign: CampaignRow,
|
|
72
|
+
): z.infer<typeof campaignSchema> {
|
|
73
|
+
return {
|
|
74
|
+
id: campaign.id,
|
|
75
|
+
name: campaign.name,
|
|
76
|
+
status: campaign.status,
|
|
77
|
+
audienceKind: campaign.audienceKind,
|
|
78
|
+
audienceId: campaign.audienceId,
|
|
79
|
+
templateKey: campaign.templateKey,
|
|
80
|
+
totalRecipients: campaign.totalRecipients,
|
|
81
|
+
sentCount: campaign.sentCount,
|
|
82
|
+
skippedCount: campaign.skippedCount,
|
|
83
|
+
failedCount: campaign.failedCount,
|
|
84
|
+
scheduledAt: campaign.scheduledAt?.toISOString() ?? null,
|
|
85
|
+
canceledAt: campaign.canceledAt?.toISOString() ?? null,
|
|
86
|
+
startedAt: campaign.startedAt?.toISOString() ?? null,
|
|
87
|
+
completedAt: campaign.completedAt?.toISOString() ?? null,
|
|
88
|
+
createdAt: campaign.createdAt.toISOString(),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
52
92
|
const createRouteDef = createRoute({
|
|
53
93
|
method: "post",
|
|
54
94
|
path: "/",
|
|
55
95
|
tags: ["Campaigns"],
|
|
56
|
-
summary: "Create + enqueue a campaign",
|
|
96
|
+
summary: "Create + enqueue (or schedule) a campaign",
|
|
57
97
|
description:
|
|
58
|
-
"Sends one template to every subscribed member of a list (or every active member of a bucket). Validates the template + audience, inserts
|
|
98
|
+
"Sends one template to every subscribed member of a list (or every active member of a bucket). Validates the template + audience, inserts the campaign, and either enqueues the durable `send-campaign` task immediately or — when `sendAt` is supplied — schedules it for that instant. Exactly one of `list` or `bucket` is required.",
|
|
59
99
|
request: {
|
|
60
100
|
body: {
|
|
61
101
|
content: {
|
|
@@ -103,6 +143,61 @@ const getRouteDef = createRoute({
|
|
|
103
143
|
},
|
|
104
144
|
});
|
|
105
145
|
|
|
146
|
+
const listRouteDef = createRoute({
|
|
147
|
+
method: "get",
|
|
148
|
+
path: "/",
|
|
149
|
+
tags: ["Campaigns"],
|
|
150
|
+
summary: "List campaigns",
|
|
151
|
+
description:
|
|
152
|
+
"Newest first. Filter with `status` (comma-separated, e.g. `scheduled,sending`).",
|
|
153
|
+
request: {
|
|
154
|
+
query: z.object({
|
|
155
|
+
status: z.string().optional(),
|
|
156
|
+
limit: z.coerce.number().int().min(1).max(200).default(50),
|
|
157
|
+
offset: z.coerce.number().int().min(0).default(0),
|
|
158
|
+
}),
|
|
159
|
+
},
|
|
160
|
+
responses: {
|
|
161
|
+
200: {
|
|
162
|
+
content: {
|
|
163
|
+
"application/json": {
|
|
164
|
+
schema: z.object({
|
|
165
|
+
campaigns: z.array(campaignSchema),
|
|
166
|
+
hasMore: z.boolean(),
|
|
167
|
+
}),
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
description: "Campaigns, newest first",
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
const cancelRouteDef = createRoute({
|
|
176
|
+
method: "post",
|
|
177
|
+
path: "/{id}/cancel",
|
|
178
|
+
tags: ["Campaigns"],
|
|
179
|
+
summary: "Cancel a campaign",
|
|
180
|
+
description:
|
|
181
|
+
"Cancels a `scheduled`, `queued`, or `sending` campaign. A mid-send cancel stops the blast at the next chunk boundary — recipients not yet dispatched are spared; already-dispatched sends are not recalled.",
|
|
182
|
+
request: {
|
|
183
|
+
params: z.object({ id: z.string() }),
|
|
184
|
+
},
|
|
185
|
+
responses: {
|
|
186
|
+
200: {
|
|
187
|
+
content: { "application/json": { schema: campaignSchema } },
|
|
188
|
+
description: "The canceled campaign",
|
|
189
|
+
},
|
|
190
|
+
404: {
|
|
191
|
+
content: { "application/json": { schema: errorSchema } },
|
|
192
|
+
description: "Unknown campaign id",
|
|
193
|
+
},
|
|
194
|
+
409: {
|
|
195
|
+
content: { "application/json": { schema: errorSchema } },
|
|
196
|
+
description: "Campaign is in a terminal state and cannot be canceled",
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
|
|
106
201
|
// The campaigns router does NOT re-apply auth internally — the data-plane prefix
|
|
107
202
|
// guards in `routes/index.ts` (decision #16) apply `requireApiKey` +
|
|
108
203
|
// `requireScope("ingest")` to `/v1/campaigns` (bare + `/*`) before requests
|
|
@@ -113,19 +208,46 @@ export const campaignsRouter = new OpenAPIHono<AppEnv>()
|
|
|
113
208
|
c.get("container");
|
|
114
209
|
const body = c.req.valid("json");
|
|
115
210
|
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
211
|
+
// Parse + bound `sendAt` BEFORE any row is written. A stale timestamp is
|
|
212
|
+
// rejected (not "blast right now"); within tolerance it degrades to an
|
|
213
|
+
// immediate send.
|
|
214
|
+
let scheduledAt: Date | null = null;
|
|
215
|
+
if (body.sendAt) {
|
|
216
|
+
const at = new Date(body.sendAt);
|
|
217
|
+
if (at.getTime() < Date.now() - SEND_AT_PAST_TOLERANCE_MS) {
|
|
218
|
+
return c.json({ error: `sendAt is in the past: ${body.sendAt}` }, 400);
|
|
219
|
+
}
|
|
220
|
+
scheduledAt = at;
|
|
221
|
+
}
|
|
222
|
+
const isScheduled =
|
|
223
|
+
scheduledAt !== null && scheduledAt.getTime() > Date.now();
|
|
224
|
+
|
|
225
|
+
// Fire the row's trigger: a punctual Hatchet scheduled run for a future
|
|
226
|
+
// `scheduledAt`, else an immediate enqueue (runNoWait — `.run()` would
|
|
227
|
+
// block this request until the whole blast completes). Best-effort,
|
|
228
|
+
// swallowing a transient broker/transport failure: the campaign row is
|
|
229
|
+
// already committed, so a failed dispatch is recovered by the reaper cron
|
|
230
|
+
// (re-enqueue / due-scheduled promotion) rather than 500-ing the request
|
|
231
|
+
// (which a keyless client would retry into a duplicate broadcast).
|
|
232
|
+
const dispatch = async (row: {
|
|
233
|
+
id: string;
|
|
234
|
+
scheduledAt?: Date | null;
|
|
235
|
+
}): Promise<void> => {
|
|
122
236
|
try {
|
|
123
|
-
|
|
237
|
+
const at = row.scheduledAt;
|
|
238
|
+
if (at && at.getTime() > Date.now()) {
|
|
239
|
+
await sendCampaignTask.schedule(at, { campaignId: row.id });
|
|
240
|
+
} else {
|
|
241
|
+
await sendCampaignTask.runNoWait({ campaignId: row.id });
|
|
242
|
+
}
|
|
124
243
|
} catch (err) {
|
|
125
|
-
logger.warn(
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
244
|
+
logger.warn(
|
|
245
|
+
"POST /v1/campaigns: dispatch failed (reaper will recover)",
|
|
246
|
+
{
|
|
247
|
+
campaignId: row.id,
|
|
248
|
+
error: err instanceof Error ? err.message : String(err),
|
|
249
|
+
},
|
|
250
|
+
);
|
|
129
251
|
}
|
|
130
252
|
};
|
|
131
253
|
|
|
@@ -154,66 +276,130 @@ export const campaignsRouter = new OpenAPIHono<AppEnv>()
|
|
|
154
276
|
|
|
155
277
|
if (idempotencyKey) {
|
|
156
278
|
const existing = await db
|
|
157
|
-
.select({
|
|
279
|
+
.select({
|
|
280
|
+
id: campaigns.id,
|
|
281
|
+
status: campaigns.status,
|
|
282
|
+
scheduledAt: campaigns.scheduledAt,
|
|
283
|
+
})
|
|
158
284
|
.from(campaigns)
|
|
159
285
|
.where(eq(campaigns.idempotencyKey, idempotencyKey))
|
|
160
286
|
.limit(1);
|
|
161
287
|
const prior = existing[0];
|
|
162
288
|
if (prior) {
|
|
163
|
-
// Re-
|
|
164
|
-
// dedups
|
|
165
|
-
//
|
|
166
|
-
//
|
|
167
|
-
|
|
168
|
-
|
|
289
|
+
// Re-dispatch is safe (terminal statuses short-circuit; the per-send
|
|
290
|
+
// key dedups; an early fire of a still-future scheduled row skips), so
|
|
291
|
+
// an idempotent retry both returns the existing campaign AND ensures
|
|
292
|
+
// its trigger exists — covering a first attempt that committed the row
|
|
293
|
+
// but failed to dispatch.
|
|
294
|
+
await dispatch(prior);
|
|
295
|
+
return c.json(
|
|
296
|
+
{
|
|
297
|
+
campaignId: prior.id,
|
|
298
|
+
status: prior.status,
|
|
299
|
+
scheduledAt: prior.scheduledAt?.toISOString() ?? null,
|
|
300
|
+
},
|
|
301
|
+
202,
|
|
302
|
+
);
|
|
169
303
|
}
|
|
170
304
|
}
|
|
171
305
|
|
|
172
306
|
const baseInsert = db.insert(campaigns).values({
|
|
173
307
|
name: body.name ?? `Campaign to ${audienceKind} ${audienceId}`,
|
|
174
|
-
status: "queued",
|
|
308
|
+
status: isScheduled ? "scheduled" : "queued",
|
|
175
309
|
audienceKind,
|
|
176
310
|
audienceId,
|
|
177
311
|
templateKey: body.template,
|
|
178
312
|
props: (body.props ?? {}) as Record<string, unknown>,
|
|
179
313
|
fromEmail: body.from ?? null,
|
|
180
314
|
subject: body.subject ?? null,
|
|
315
|
+
scheduledAt,
|
|
181
316
|
idempotencyKey,
|
|
182
317
|
});
|
|
183
318
|
|
|
184
319
|
// With a key, swallow a concurrent-insert collision on the partial-unique
|
|
185
320
|
// index (the select-then-insert above is not atomic) and resolve the winner.
|
|
321
|
+
// The `targetWhere` predicate must match the PARTIAL unique index
|
|
322
|
+
// (`WHERE idempotency_key IS NOT NULL`) or Postgres cannot infer the
|
|
323
|
+
// conflict arbiter (42P10) and the keyed insert fails outright.
|
|
186
324
|
const insertRows = idempotencyKey
|
|
187
325
|
? await baseInsert
|
|
188
|
-
.onConflictDoNothing({
|
|
326
|
+
.onConflictDoNothing({
|
|
327
|
+
target: campaigns.idempotencyKey,
|
|
328
|
+
where: sql`idempotency_key is not null`,
|
|
329
|
+
})
|
|
189
330
|
.returning({ id: campaigns.id })
|
|
190
331
|
: await baseInsert.returning({ id: campaigns.id });
|
|
191
332
|
|
|
192
333
|
const campaignId = insertRows[0]?.id;
|
|
193
334
|
if (!campaignId && idempotencyKey) {
|
|
194
335
|
const winner = await db
|
|
195
|
-
.select({
|
|
336
|
+
.select({
|
|
337
|
+
id: campaigns.id,
|
|
338
|
+
status: campaigns.status,
|
|
339
|
+
scheduledAt: campaigns.scheduledAt,
|
|
340
|
+
})
|
|
196
341
|
.from(campaigns)
|
|
197
342
|
.where(eq(campaigns.idempotencyKey, idempotencyKey))
|
|
198
343
|
.limit(1);
|
|
199
344
|
if (winner[0]) {
|
|
200
|
-
await
|
|
345
|
+
await dispatch(winner[0]);
|
|
201
346
|
return c.json(
|
|
202
|
-
{
|
|
347
|
+
{
|
|
348
|
+
campaignId: winner[0].id,
|
|
349
|
+
status: winner[0].status,
|
|
350
|
+
scheduledAt: winner[0].scheduledAt?.toISOString() ?? null,
|
|
351
|
+
},
|
|
203
352
|
202,
|
|
204
353
|
);
|
|
205
354
|
}
|
|
206
355
|
}
|
|
207
356
|
if (!campaignId) throw new Error("Failed to create campaign");
|
|
208
357
|
|
|
209
|
-
//
|
|
210
|
-
//
|
|
211
|
-
//
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
await
|
|
358
|
+
// Fire the trigger. The campaign row is already committed, so a transient
|
|
359
|
+
// dispatch failure (broker down) is NON-fatal: we still return 202 and the
|
|
360
|
+
// reaper cron recovers the orphaned row. This keeps the request from
|
|
361
|
+
// 500-ing AFTER a committed row, which a client would otherwise retry into
|
|
362
|
+
// a duplicate (sans idempotency key).
|
|
363
|
+
await dispatch({ id: campaignId, scheduledAt });
|
|
215
364
|
|
|
216
|
-
return c.json(
|
|
365
|
+
return c.json(
|
|
366
|
+
{
|
|
367
|
+
campaignId,
|
|
368
|
+
status: isScheduled ? "scheduled" : "queued",
|
|
369
|
+
scheduledAt: scheduledAt?.toISOString() ?? null,
|
|
370
|
+
},
|
|
371
|
+
202,
|
|
372
|
+
);
|
|
373
|
+
})
|
|
374
|
+
.openapi(listRouteDef, async (c) => {
|
|
375
|
+
const { db } = c.get("container");
|
|
376
|
+
const { status, limit, offset } = c.req.valid("query");
|
|
377
|
+
|
|
378
|
+
const statuses = status
|
|
379
|
+
?.split(",")
|
|
380
|
+
.map((s) => s.trim())
|
|
381
|
+
.filter(Boolean);
|
|
382
|
+
|
|
383
|
+
// Fetch one extra row to derive `hasMore` without a COUNT.
|
|
384
|
+
const rows = await db
|
|
385
|
+
.select()
|
|
386
|
+
.from(campaigns)
|
|
387
|
+
.where(
|
|
388
|
+
statuses && statuses.length > 0
|
|
389
|
+
? inArray(campaigns.status, statuses)
|
|
390
|
+
: undefined,
|
|
391
|
+
)
|
|
392
|
+
.orderBy(desc(campaigns.createdAt))
|
|
393
|
+
.limit(limit + 1)
|
|
394
|
+
.offset(offset);
|
|
395
|
+
|
|
396
|
+
return c.json(
|
|
397
|
+
{
|
|
398
|
+
campaigns: rows.slice(0, limit).map(serializeCampaign),
|
|
399
|
+
hasMore: rows.length > limit,
|
|
400
|
+
},
|
|
401
|
+
200,
|
|
402
|
+
);
|
|
217
403
|
})
|
|
218
404
|
.openapi(getRouteDef, async (c) => {
|
|
219
405
|
const { db } = c.get("container");
|
|
@@ -229,24 +415,47 @@ export const campaignsRouter = new OpenAPIHono<AppEnv>()
|
|
|
229
415
|
return c.json({ error: `Unknown campaign: ${id}` }, 404);
|
|
230
416
|
}
|
|
231
417
|
|
|
418
|
+
return c.json(serializeCampaign(campaign), 200);
|
|
419
|
+
})
|
|
420
|
+
.openapi(cancelRouteDef, async (c) => {
|
|
421
|
+
const { db } = c.get("container");
|
|
422
|
+
const { id } = c.req.valid("param");
|
|
423
|
+
|
|
424
|
+
// CAS: only a cancelable status transitions, so a concurrent completion
|
|
425
|
+
// (or a second cancel) is never overwritten. The punctual Hatchet
|
|
426
|
+
// scheduled run for a canceled campaign still fires but no-ops on the
|
|
427
|
+
// terminal guard; a `sending` blast stops at its next chunk boundary.
|
|
428
|
+
const canceled = await db
|
|
429
|
+
.update(campaigns)
|
|
430
|
+
.set({
|
|
431
|
+
status: "canceled",
|
|
432
|
+
canceledAt: new Date(),
|
|
433
|
+
updatedAt: new Date(),
|
|
434
|
+
})
|
|
435
|
+
.where(
|
|
436
|
+
and(
|
|
437
|
+
eq(campaigns.id, id),
|
|
438
|
+
inArray(campaigns.status, ["scheduled", "queued", "sending"]),
|
|
439
|
+
),
|
|
440
|
+
)
|
|
441
|
+
.returning();
|
|
442
|
+
const row = canceled[0];
|
|
443
|
+
if (row) {
|
|
444
|
+
return c.json(serializeCampaign(row), 200);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const existing = await db
|
|
448
|
+
.select()
|
|
449
|
+
.from(campaigns)
|
|
450
|
+
.where(eq(campaigns.id, id))
|
|
451
|
+
.limit(1);
|
|
452
|
+
if (!existing[0]) {
|
|
453
|
+
return c.json({ error: `Unknown campaign: ${id}` }, 404);
|
|
454
|
+
}
|
|
232
455
|
return c.json(
|
|
233
456
|
{
|
|
234
|
-
|
|
235
|
-
name: campaign.name,
|
|
236
|
-
status: campaign.status,
|
|
237
|
-
audienceKind: campaign.audienceKind,
|
|
238
|
-
audienceId: campaign.audienceId,
|
|
239
|
-
templateKey: campaign.templateKey,
|
|
240
|
-
totalRecipients: campaign.totalRecipients,
|
|
241
|
-
sentCount: campaign.sentCount,
|
|
242
|
-
skippedCount: campaign.skippedCount,
|
|
243
|
-
failedCount: campaign.failedCount,
|
|
244
|
-
startedAt: campaign.startedAt ? campaign.startedAt.toISOString() : null,
|
|
245
|
-
completedAt: campaign.completedAt
|
|
246
|
-
? campaign.completedAt.toISOString()
|
|
247
|
-
: null,
|
|
248
|
-
createdAt: campaign.createdAt.toISOString(),
|
|
457
|
+
error: `Campaign is ${existing[0].status} and cannot be canceled`,
|
|
249
458
|
},
|
|
250
|
-
|
|
459
|
+
409,
|
|
251
460
|
);
|
|
252
461
|
});
|
|
@@ -3,6 +3,7 @@ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
|
3
3
|
import type { AppEnv } from "../../app.js";
|
|
4
4
|
import { resolveRecipient } from "../../lib/contacts.js";
|
|
5
5
|
import { errorSchema } from "../../lib/schemas.js";
|
|
6
|
+
import { isReservedListId } from "../../lists/define-list.js";
|
|
6
7
|
import { hasScope } from "../../middleware/api-key.js";
|
|
7
8
|
import { requireIdentity } from "../_shared.js";
|
|
8
9
|
|
|
@@ -64,7 +65,7 @@ const sendRoute = createRoute({
|
|
|
64
65
|
export const emailsRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
65
66
|
sendRoute,
|
|
66
67
|
async (c) => {
|
|
67
|
-
const { db, emailService, templates } = c.get("container");
|
|
68
|
+
const { db, emailService, templates, listRegistry } = c.get("container");
|
|
68
69
|
const apiKey = c.get("apiKey");
|
|
69
70
|
const body = c.req.valid("json");
|
|
70
71
|
|
|
@@ -91,6 +92,29 @@ export const emailsRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
91
92
|
return c.json({ error: `Unknown template: ${body.template}` }, 400);
|
|
92
93
|
}
|
|
93
94
|
|
|
95
|
+
// Validate a caller-supplied `category` server-side (request-time twin of
|
|
96
|
+
// the boot-time template-category guard). A caller `category` OVERRIDES the
|
|
97
|
+
// template's category at send time; an unknown/registry-excluded category
|
|
98
|
+
// silently defaults to opt-in (ListRegistry.isSubscribedByDefault returns
|
|
99
|
+
// `true` for an id it doesn't hold) → the send would bypass
|
|
100
|
+
// suppression/consent. Valid iff it's a reserved built-in or an ENABLED
|
|
101
|
+
// registered list (fail-closed — the route can't see excluded lists, and
|
|
102
|
+
// honoring an excluded opt-in list would re-open the same consent flip).
|
|
103
|
+
// Only checked when present; an absent category uses the boot-validated
|
|
104
|
+
// template default.
|
|
105
|
+
if (
|
|
106
|
+
body.category !== undefined &&
|
|
107
|
+
!isReservedListId(body.category) &&
|
|
108
|
+
!listRegistry.has(body.category)
|
|
109
|
+
) {
|
|
110
|
+
return c.json(
|
|
111
|
+
{
|
|
112
|
+
error: `Unknown category: ${body.category} — not a reserved built-in or a registered email list. An unknown category silently defaults to opt-in and bypasses suppression/consent.`,
|
|
113
|
+
},
|
|
114
|
+
400,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
94
118
|
const recipient = await resolveRecipient({
|
|
95
119
|
db,
|
|
96
120
|
userId: body.userId,
|
package/src/worker.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import type { DefinedBucket } from "./buckets/define-bucket.js";
|
|
2
2
|
import {
|
|
3
|
+
collectBucketReactionJourneys,
|
|
3
4
|
selectBucketReactionTasks,
|
|
4
5
|
selectBucketTasks,
|
|
5
6
|
} from "./buckets/registry.js";
|
|
7
|
+
import type { DefinedCampaign } from "./campaigns/define-campaign.js";
|
|
8
|
+
import { reconcileDefinedCampaigns } from "./campaigns/reconcile.js";
|
|
6
9
|
import {
|
|
7
10
|
type ConnectorRuntimeFactory,
|
|
8
11
|
startConnectorRuntimes,
|
|
@@ -39,6 +42,11 @@ export interface CreateWorkerOptions {
|
|
|
39
42
|
journeys: DefinedJourney[];
|
|
40
43
|
/** Buckets whose fast-expiry timer tasks are registered. Defaults to none. */
|
|
41
44
|
buckets?: DefinedBucket[];
|
|
45
|
+
/**
|
|
46
|
+
* Code-defined one-shot campaigns (broadcasts) reconciled at boot into
|
|
47
|
+
* scheduled `campaigns` rows. Defaults to `container.campaigns`.
|
|
48
|
+
*/
|
|
49
|
+
campaigns?: DefinedCampaign[];
|
|
42
50
|
/** Defaults to `container.env.ENABLED_JOURNEYS`. */
|
|
43
51
|
enabledJourneys?: string;
|
|
44
52
|
/** Defaults to `container.env.ENABLED_BUCKETS`. */
|
|
@@ -63,7 +71,20 @@ export interface Worker {
|
|
|
63
71
|
export function createWorker(opts: CreateWorkerOptions): Worker {
|
|
64
72
|
const { container, journeys } = opts;
|
|
65
73
|
const enabled = opts.enabledJourneys ?? container.env.ENABLED_JOURNEYS;
|
|
66
|
-
const
|
|
74
|
+
const enabledBuckets = opts.enabledBuckets ?? container.env.ENABLED_BUCKETS;
|
|
75
|
+
// Bucket-reaction journey ids (`bucket-<id>-on-<kind>`) are registered
|
|
76
|
+
// separately (via selectBucketReactionTasks) bypassing ENABLED_JOURNEYS, but
|
|
77
|
+
// they ARE registered journeys — include them in the known set so listing a
|
|
78
|
+
// real reaction id in ENABLED_JOURNEYS is not rejected as an unknown-id typo.
|
|
79
|
+
const reactionJourneyIds = collectBucketReactionJourneys(
|
|
80
|
+
opts.buckets ?? [],
|
|
81
|
+
enabledBuckets,
|
|
82
|
+
).map((r) => r.meta.id);
|
|
83
|
+
const journeyTasks = selectJourneyTasks(
|
|
84
|
+
journeys,
|
|
85
|
+
enabled,
|
|
86
|
+
reactionJourneyIds,
|
|
87
|
+
);
|
|
67
88
|
// The enabled journey IDs, logged at startup so a stale worker (one missing a
|
|
68
89
|
// newly added journey because the dev watcher never restarted it) is visible
|
|
69
90
|
// at a glance — counts alone can't show WHICH journeys are registered.
|
|
@@ -72,7 +93,6 @@ export function createWorker(opts: CreateWorkerOptions): Worker {
|
|
|
72
93
|
.filter((j) => journeyFilter === "*" || journeyFilter.has(j.meta.id))
|
|
73
94
|
.map((j) => j.meta.id);
|
|
74
95
|
|
|
75
|
-
const enabledBuckets = opts.enabledBuckets ?? container.env.ENABLED_BUCKETS;
|
|
76
96
|
// The single place a bucket's per-user fast-expiry timer task is constructed
|
|
77
97
|
// (Section 9.4): the shared `bucket:arm-expiry` durableTask, registered once iff
|
|
78
98
|
// any enabled bucket opts into fastExpiry. The engine-wide time-based-leave
|
|
@@ -196,6 +216,21 @@ export function createWorker(opts: CreateWorkerOptions): Worker {
|
|
|
196
216
|
});
|
|
197
217
|
});
|
|
198
218
|
|
|
219
|
+
// Reconcile code-defined campaigns into scheduled rows (create / sync /
|
|
220
|
+
// expire — see `reconcileDefinedCampaigns`). Same fire-and-forget stance
|
|
221
|
+
// as the bucket backfills above: best-effort, never blocks the listener.
|
|
222
|
+
const definedCampaigns = opts.campaigns ?? container.campaigns;
|
|
223
|
+
if (definedCampaigns.length > 0) {
|
|
224
|
+
reconcileDefinedCampaigns({
|
|
225
|
+
client: container,
|
|
226
|
+
campaigns: definedCampaigns,
|
|
227
|
+
}).catch((err) => {
|
|
228
|
+
container.logger.warn("Campaign reconcile (boot) failed", {
|
|
229
|
+
error: err instanceof Error ? err.message : String(err),
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
199
234
|
await _worker.start();
|
|
200
235
|
}
|
|
201
236
|
|