@hogsend/engine 0.39.0 → 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 +7 -7
- package/src/campaigns/define-campaign.ts +122 -0
- package/src/campaigns/reconcile.ts +297 -0
- package/src/container.ts +20 -0
- package/src/env.ts +14 -0
- package/src/index.ts +16 -1
- package/src/lib/auth.ts +33 -1
- package/src/routes/admin/campaigns.ts +165 -0
- package/src/routes/admin/index.ts +2 -0
- package/src/routes/campaigns/index.ts +259 -50
- package/src/worker.ts +22 -0
- package/src/workflows/send-campaign.ts +167 -15
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Admin-plane campaigns routes for Studio (session-cookie auth via the parent
|
|
3
|
+
* adminRouter's `requireAdmin`; Studio cannot use the hsk_-keyed data-plane
|
|
4
|
+
* routes). Observe + cancel only — campaigns are AUTHORED in code
|
|
5
|
+
* (`defineCampaign()`) or via the data-plane `POST /v1/campaigns`, never from
|
|
6
|
+
* Studio. The list/get/cancel semantics mirror `routes/campaigns/index.ts`
|
|
7
|
+
* exactly (same serializer, same cancel CAS).
|
|
8
|
+
*/
|
|
9
|
+
import { campaigns } from "@hogsend/db";
|
|
10
|
+
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
11
|
+
import { and, desc, eq, inArray } from "drizzle-orm";
|
|
12
|
+
import type { AppEnv } from "../../app.js";
|
|
13
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
14
|
+
import { campaignSchema, serializeCampaign } from "../campaigns/index.js";
|
|
15
|
+
|
|
16
|
+
const listRouteDef = createRoute({
|
|
17
|
+
method: "get",
|
|
18
|
+
path: "/",
|
|
19
|
+
tags: ["Admin"],
|
|
20
|
+
summary: "List campaigns (Studio)",
|
|
21
|
+
request: {
|
|
22
|
+
query: z.object({
|
|
23
|
+
status: z.string().optional(),
|
|
24
|
+
limit: z.coerce.number().int().min(1).max(200).default(50),
|
|
25
|
+
offset: z.coerce.number().int().min(0).default(0),
|
|
26
|
+
}),
|
|
27
|
+
},
|
|
28
|
+
responses: {
|
|
29
|
+
200: {
|
|
30
|
+
content: {
|
|
31
|
+
"application/json": {
|
|
32
|
+
schema: z.object({
|
|
33
|
+
campaigns: z.array(campaignSchema),
|
|
34
|
+
hasMore: z.boolean(),
|
|
35
|
+
}),
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
description: "Campaigns, newest first",
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const getRouteDef = createRoute({
|
|
44
|
+
method: "get",
|
|
45
|
+
path: "/{id}",
|
|
46
|
+
tags: ["Admin"],
|
|
47
|
+
summary: "Get a campaign (Studio)",
|
|
48
|
+
request: {
|
|
49
|
+
params: z.object({ id: z.string() }),
|
|
50
|
+
},
|
|
51
|
+
responses: {
|
|
52
|
+
200: {
|
|
53
|
+
content: { "application/json": { schema: campaignSchema } },
|
|
54
|
+
description: "The campaign",
|
|
55
|
+
},
|
|
56
|
+
404: {
|
|
57
|
+
content: { "application/json": { schema: errorSchema } },
|
|
58
|
+
description: "Unknown campaign id",
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const cancelRouteDef = createRoute({
|
|
64
|
+
method: "post",
|
|
65
|
+
path: "/{id}/cancel",
|
|
66
|
+
tags: ["Admin"],
|
|
67
|
+
summary: "Cancel a campaign (Studio)",
|
|
68
|
+
request: {
|
|
69
|
+
params: z.object({ id: z.string() }),
|
|
70
|
+
},
|
|
71
|
+
responses: {
|
|
72
|
+
200: {
|
|
73
|
+
content: { "application/json": { schema: campaignSchema } },
|
|
74
|
+
description: "The canceled campaign",
|
|
75
|
+
},
|
|
76
|
+
404: {
|
|
77
|
+
content: { "application/json": { schema: errorSchema } },
|
|
78
|
+
description: "Unknown campaign id",
|
|
79
|
+
},
|
|
80
|
+
409: {
|
|
81
|
+
content: { "application/json": { schema: errorSchema } },
|
|
82
|
+
description: "Campaign is in a terminal state and cannot be canceled",
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
export const adminCampaignsRouter = new OpenAPIHono<AppEnv>()
|
|
88
|
+
.openapi(listRouteDef, async (c) => {
|
|
89
|
+
const { db } = c.get("container");
|
|
90
|
+
const { status, limit, offset } = c.req.valid("query");
|
|
91
|
+
|
|
92
|
+
const statuses = status
|
|
93
|
+
?.split(",")
|
|
94
|
+
.map((s) => s.trim())
|
|
95
|
+
.filter(Boolean);
|
|
96
|
+
|
|
97
|
+
const rows = await db
|
|
98
|
+
.select()
|
|
99
|
+
.from(campaigns)
|
|
100
|
+
.where(
|
|
101
|
+
statuses && statuses.length > 0
|
|
102
|
+
? inArray(campaigns.status, statuses)
|
|
103
|
+
: undefined,
|
|
104
|
+
)
|
|
105
|
+
.orderBy(desc(campaigns.createdAt))
|
|
106
|
+
.limit(limit + 1)
|
|
107
|
+
.offset(offset);
|
|
108
|
+
|
|
109
|
+
return c.json(
|
|
110
|
+
{
|
|
111
|
+
campaigns: rows.slice(0, limit).map(serializeCampaign),
|
|
112
|
+
hasMore: rows.length > limit,
|
|
113
|
+
},
|
|
114
|
+
200,
|
|
115
|
+
);
|
|
116
|
+
})
|
|
117
|
+
.openapi(getRouteDef, async (c) => {
|
|
118
|
+
const { db } = c.get("container");
|
|
119
|
+
const { id } = c.req.valid("param");
|
|
120
|
+
|
|
121
|
+
const rows = await db
|
|
122
|
+
.select()
|
|
123
|
+
.from(campaigns)
|
|
124
|
+
.where(eq(campaigns.id, id))
|
|
125
|
+
.limit(1);
|
|
126
|
+
if (!rows[0]) {
|
|
127
|
+
return c.json({ error: `Unknown campaign: ${id}` }, 404);
|
|
128
|
+
}
|
|
129
|
+
return c.json(serializeCampaign(rows[0]), 200);
|
|
130
|
+
})
|
|
131
|
+
.openapi(cancelRouteDef, async (c) => {
|
|
132
|
+
const { db } = c.get("container");
|
|
133
|
+
const { id } = c.req.valid("param");
|
|
134
|
+
|
|
135
|
+
const canceled = await db
|
|
136
|
+
.update(campaigns)
|
|
137
|
+
.set({
|
|
138
|
+
status: "canceled",
|
|
139
|
+
canceledAt: new Date(),
|
|
140
|
+
updatedAt: new Date(),
|
|
141
|
+
})
|
|
142
|
+
.where(
|
|
143
|
+
and(
|
|
144
|
+
eq(campaigns.id, id),
|
|
145
|
+
inArray(campaigns.status, ["scheduled", "queued", "sending"]),
|
|
146
|
+
),
|
|
147
|
+
)
|
|
148
|
+
.returning();
|
|
149
|
+
if (canceled[0]) {
|
|
150
|
+
return c.json(serializeCampaign(canceled[0]), 200);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const existing = await db
|
|
154
|
+
.select()
|
|
155
|
+
.from(campaigns)
|
|
156
|
+
.where(eq(campaigns.id, id))
|
|
157
|
+
.limit(1);
|
|
158
|
+
if (!existing[0]) {
|
|
159
|
+
return c.json({ error: `Unknown campaign: ${id}` }, 404);
|
|
160
|
+
}
|
|
161
|
+
return c.json(
|
|
162
|
+
{ error: `Campaign is ${existing[0].status} and cannot be canceled` },
|
|
163
|
+
409,
|
|
164
|
+
);
|
|
165
|
+
});
|
|
@@ -10,6 +10,7 @@ import { apiKeysRouter } from "./api-keys.js";
|
|
|
10
10
|
import { auditLogsRouter } from "./audit-logs.js";
|
|
11
11
|
import { bucketsRouter } from "./buckets.js";
|
|
12
12
|
import { bulkRouter } from "./bulk.js";
|
|
13
|
+
import { adminCampaignsRouter } from "./campaigns.js";
|
|
13
14
|
import { adminConnectorsRouter } from "./connectors.js";
|
|
14
15
|
import { contactsRouter } from "./contacts.js";
|
|
15
16
|
import { dlqRouter } from "./dlq.js";
|
|
@@ -41,6 +42,7 @@ adminRouter.route("/contacts", timelineRouter);
|
|
|
41
42
|
adminRouter.route("/journeys", journeysRouter);
|
|
42
43
|
adminRouter.route("/open-in-editor", openEditorRouter);
|
|
43
44
|
adminRouter.route("/buckets", bucketsRouter);
|
|
45
|
+
adminRouter.route("/campaigns", adminCampaignsRouter);
|
|
44
46
|
adminRouter.route("/events", eventsRouter);
|
|
45
47
|
adminRouter.route("/emails", emailsRouter);
|
|
46
48
|
adminRouter.route("/links", linksRouter);
|
|
@@ -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
|
});
|
package/src/worker.ts
CHANGED
|
@@ -4,6 +4,8 @@ import {
|
|
|
4
4
|
selectBucketReactionTasks,
|
|
5
5
|
selectBucketTasks,
|
|
6
6
|
} from "./buckets/registry.js";
|
|
7
|
+
import type { DefinedCampaign } from "./campaigns/define-campaign.js";
|
|
8
|
+
import { reconcileDefinedCampaigns } from "./campaigns/reconcile.js";
|
|
7
9
|
import {
|
|
8
10
|
type ConnectorRuntimeFactory,
|
|
9
11
|
startConnectorRuntimes,
|
|
@@ -40,6 +42,11 @@ export interface CreateWorkerOptions {
|
|
|
40
42
|
journeys: DefinedJourney[];
|
|
41
43
|
/** Buckets whose fast-expiry timer tasks are registered. Defaults to none. */
|
|
42
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[];
|
|
43
50
|
/** Defaults to `container.env.ENABLED_JOURNEYS`. */
|
|
44
51
|
enabledJourneys?: string;
|
|
45
52
|
/** Defaults to `container.env.ENABLED_BUCKETS`. */
|
|
@@ -209,6 +216,21 @@ export function createWorker(opts: CreateWorkerOptions): Worker {
|
|
|
209
216
|
});
|
|
210
217
|
});
|
|
211
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
|
+
|
|
212
234
|
await _worker.start();
|
|
213
235
|
}
|
|
214
236
|
|