@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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hogsend/engine",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -45,14 +45,14 @@
|
|
|
45
45
|
"svix": "^1.95.1",
|
|
46
46
|
"winston": "^3.19.0",
|
|
47
47
|
"zod": "^4.4.3",
|
|
48
|
-
"@hogsend/core": "^0.
|
|
49
|
-
"@hogsend/db": "^0.
|
|
50
|
-
"@hogsend/email": "^0.
|
|
51
|
-
"@hogsend/plugin-posthog": "^0.
|
|
52
|
-
"@hogsend/plugin-resend": "^0.
|
|
48
|
+
"@hogsend/core": "^0.40.0",
|
|
49
|
+
"@hogsend/db": "^0.40.0",
|
|
50
|
+
"@hogsend/email": "^0.40.0",
|
|
51
|
+
"@hogsend/plugin-posthog": "^0.40.0",
|
|
52
|
+
"@hogsend/plugin-resend": "^0.40.0"
|
|
53
53
|
},
|
|
54
54
|
"optionalDependencies": {
|
|
55
|
-
"@hogsend/plugin-postmark": "^0.
|
|
55
|
+
"@hogsend/plugin-postmark": "^0.40.0"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@types/node": "^22.15.3",
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code-defined campaigns (broadcasts) — a one-shot scheduled send committed to
|
|
3
|
+
* the repo, mirroring `defineJourney()` / `defineList()`: write a file, deploy,
|
|
4
|
+
* and the worker's boot reconciler schedules it; once sent it is retired
|
|
5
|
+
* (redeploys no-op via the campaign's definition idempotency key).
|
|
6
|
+
*
|
|
7
|
+
* A defined campaign is NOT a new runtime — it reconciles into the same
|
|
8
|
+
* `campaigns` row + durable `send-campaign` task the `POST /v1/campaigns`
|
|
9
|
+
* data-plane uses, so scheduling, cancel, counts, and Studio visibility are
|
|
10
|
+
* identical regardless of how the campaign was created.
|
|
11
|
+
*/
|
|
12
|
+
import type { TemplateName } from "@hogsend/email";
|
|
13
|
+
|
|
14
|
+
/** Allowed campaign-id shape (mirrors list ids): alnum, dash, underscore. */
|
|
15
|
+
const CAMPAIGN_ID_PATTERN = /^[a-z0-9_-]+$/i;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The `campaigns.idempotency_key` namespace for code-defined campaigns. A
|
|
19
|
+
* definition's row key is `campaign-def:<id>` — the reconciler resolves the
|
|
20
|
+
* existing row through it, which is what makes a redeploy after `sent` a no-op
|
|
21
|
+
* instead of a second blast.
|
|
22
|
+
*/
|
|
23
|
+
export const DEFINED_CAMPAIGN_KEY_PREFIX = "campaign-def:";
|
|
24
|
+
|
|
25
|
+
/** The audience selector — exactly one of `list` or `bucket` (validated). */
|
|
26
|
+
export type CampaignAudience = { list: string } | { bucket: string };
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The validated, fully-defaulted campaign metadata. `sendAt` is always a
|
|
30
|
+
* `Date` after `defineCampaign` (authoring input also accepts an ISO string);
|
|
31
|
+
* `enabled` defaults to `true`, `name` to the id.
|
|
32
|
+
*/
|
|
33
|
+
export interface CampaignMeta {
|
|
34
|
+
id: string;
|
|
35
|
+
name: string;
|
|
36
|
+
audience: CampaignAudience;
|
|
37
|
+
template: TemplateName;
|
|
38
|
+
props?: Record<string, unknown>;
|
|
39
|
+
subject?: string;
|
|
40
|
+
from?: string;
|
|
41
|
+
sendAt: Date;
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A defined campaign. `id` is surfaced for literal-typed consumption. */
|
|
46
|
+
export interface DefinedCampaign<Id extends string = string> {
|
|
47
|
+
readonly meta: CampaignMeta;
|
|
48
|
+
readonly id: Id;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Define a one-shot campaign (broadcast) in code. Validates the id shape, the
|
|
53
|
+
* audience XOR (exactly one of `list` / `bucket`), and that `sendAt` parses to
|
|
54
|
+
* a real instant. Whether `sendAt` is still in the future is deliberately NOT
|
|
55
|
+
* checked here — that is a deploy-time question the reconciler answers (a
|
|
56
|
+
* definition whose `sendAt` is already stale at first reconcile becomes
|
|
57
|
+
* `expired`, never a surprise blast).
|
|
58
|
+
*
|
|
59
|
+
* @throws if `id` is empty/malformed, the audience is not exactly one of
|
|
60
|
+
* list/bucket, or `sendAt` does not parse.
|
|
61
|
+
*/
|
|
62
|
+
export function defineCampaign<const Id extends string>(meta: {
|
|
63
|
+
id: Id;
|
|
64
|
+
name?: string;
|
|
65
|
+
audience: CampaignAudience;
|
|
66
|
+
template: TemplateName;
|
|
67
|
+
props?: Record<string, unknown>;
|
|
68
|
+
subject?: string;
|
|
69
|
+
from?: string;
|
|
70
|
+
sendAt: Date | string;
|
|
71
|
+
enabled?: boolean;
|
|
72
|
+
}): DefinedCampaign<Id> {
|
|
73
|
+
const { id } = meta;
|
|
74
|
+
|
|
75
|
+
if (!id || !CAMPAIGN_ID_PATTERN.test(id)) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
`Invalid campaign id "${id}": must match /^[a-z0-9_-]+$/i (letters, digits, "-", "_").`,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const audience = meta.audience as { list?: string; bucket?: string };
|
|
82
|
+
const selectors = (audience.list ? 1 : 0) + (audience.bucket ? 1 : 0);
|
|
83
|
+
if (selectors !== 1) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Campaign "${id}": audience must be exactly one of { list } or { bucket }.`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const sendAt =
|
|
90
|
+
meta.sendAt instanceof Date ? meta.sendAt : new Date(meta.sendAt);
|
|
91
|
+
if (Number.isNaN(sendAt.getTime())) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Campaign "${id}": sendAt "${String(meta.sendAt)}" is not a valid Date/ISO instant.`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
meta: {
|
|
99
|
+
id,
|
|
100
|
+
name: meta.name ?? id,
|
|
101
|
+
audience: meta.audience,
|
|
102
|
+
template: meta.template,
|
|
103
|
+
...(meta.props !== undefined ? { props: meta.props } : {}),
|
|
104
|
+
...(meta.subject !== undefined ? { subject: meta.subject } : {}),
|
|
105
|
+
...(meta.from !== undefined ? { from: meta.from } : {}),
|
|
106
|
+
sendAt,
|
|
107
|
+
enabled: meta.enabled ?? true,
|
|
108
|
+
},
|
|
109
|
+
id,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Narrowing helper: the audience kind + id as stored on the campaigns row. */
|
|
114
|
+
export function audienceOf(meta: CampaignMeta): {
|
|
115
|
+
audienceKind: "list" | "bucket";
|
|
116
|
+
audienceId: string;
|
|
117
|
+
} {
|
|
118
|
+
if ("list" in meta.audience) {
|
|
119
|
+
return { audienceKind: "list", audienceId: meta.audience.list };
|
|
120
|
+
}
|
|
121
|
+
return { audienceKind: "bucket", audienceId: meta.audience.bucket };
|
|
122
|
+
}
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot-time reconciler for code-defined campaigns ({@link defineCampaign}).
|
|
3
|
+
*
|
|
4
|
+
* Runs once at worker start (before the Hatchet listener blocks), mirroring
|
|
5
|
+
* `enqueueBucketBackfills`: fire-and-forget, best-effort, never blocks or
|
|
6
|
+
* crashes boot. For each definition it upserts the `campaigns` row keyed by
|
|
7
|
+
* `campaign-def:<id>` (the definition idempotency key):
|
|
8
|
+
*
|
|
9
|
+
* - No row yet + `sendAt` in the future → insert `scheduled` and create a
|
|
10
|
+
* Hatchet scheduled run at `sendAt` (punctual primary; the reaper's
|
|
11
|
+
* due-scheduled sweep is the backstop if the schedule call fails).
|
|
12
|
+
* - No row yet + `sendAt` recently due (within {@link defineGraceMs}) → the
|
|
13
|
+
* deploy simply landed a beat after the send time; insert + enqueue now.
|
|
14
|
+
* - No row yet + `sendAt` stale (past the grace window) → insert `expired`
|
|
15
|
+
* and warn loudly. A late deploy NEVER fires a surprise blast; bump
|
|
16
|
+
* `sendAt` (or delete the file) to resolve.
|
|
17
|
+
* - Row exists and is still `scheduled` → sync mutable fields (name,
|
|
18
|
+
* audience, template, props, subject, from, sendAt) so editing the file and
|
|
19
|
+
* redeploying updates the pending broadcast — the git-ops loop. A moved
|
|
20
|
+
* `sendAt` gets a fresh scheduled run; the stale run no-ops via the send
|
|
21
|
+
* task's early-fire guard.
|
|
22
|
+
* - Row exists in any other status (`sent`/`canceled`/`expired`/`failed`/
|
|
23
|
+
* in-flight) → no-op. `sent` is the natural "retired" end state; an
|
|
24
|
+
* operator `canceled` is never resurrected by a redeploy.
|
|
25
|
+
*/
|
|
26
|
+
import { campaigns } from "@hogsend/db";
|
|
27
|
+
import { getTemplateNames } from "@hogsend/email";
|
|
28
|
+
import { and, eq, sql } from "drizzle-orm";
|
|
29
|
+
import type { HogsendClient } from "../container.js";
|
|
30
|
+
import { sendCampaignTask } from "../workflows/send-campaign.js";
|
|
31
|
+
import {
|
|
32
|
+
audienceOf,
|
|
33
|
+
DEFINED_CAMPAIGN_KEY_PREFIX,
|
|
34
|
+
type DefinedCampaign,
|
|
35
|
+
} from "./define-campaign.js";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* How far past its `sendAt` a NEVER-SEEN definition may be and still send at
|
|
39
|
+
* first reconcile (covers a deploy that lands minutes after the scheduled
|
|
40
|
+
* instant). Anything staler is stamped `expired` instead — a definition
|
|
41
|
+
* committed with last week's date must not blast on deploy.
|
|
42
|
+
*/
|
|
43
|
+
function defineGraceMs(): number {
|
|
44
|
+
return Number(process.env.CAMPAIGN_DEFINE_GRACE_MS ?? 60 * 60 * 1000);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ReconcileResult {
|
|
48
|
+
created: number;
|
|
49
|
+
updated: number;
|
|
50
|
+
expired: number;
|
|
51
|
+
skipped: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function reconcileDefinedCampaigns(opts: {
|
|
55
|
+
client: HogsendClient;
|
|
56
|
+
campaigns: DefinedCampaign[];
|
|
57
|
+
}): Promise<ReconcileResult> {
|
|
58
|
+
const { client } = opts;
|
|
59
|
+
const { db, logger, listRegistry, bucketRegistry, templates } = client;
|
|
60
|
+
const result: ReconcileResult = {
|
|
61
|
+
created: 0,
|
|
62
|
+
updated: 0,
|
|
63
|
+
expired: 0,
|
|
64
|
+
skipped: 0,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const templateNames = new Set<string>(getTemplateNames(templates));
|
|
68
|
+
const seenIds = new Set<string>();
|
|
69
|
+
|
|
70
|
+
for (const campaign of opts.campaigns) {
|
|
71
|
+
const meta = campaign.meta;
|
|
72
|
+
if (seenIds.has(meta.id)) {
|
|
73
|
+
logger.error("campaigns: duplicate defineCampaign id — skipping", {
|
|
74
|
+
campaignId: meta.id,
|
|
75
|
+
});
|
|
76
|
+
result.skipped++;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
seenIds.add(meta.id);
|
|
80
|
+
|
|
81
|
+
if (!meta.enabled) {
|
|
82
|
+
result.skipped++;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Validate against the wired registries (same checks POST /v1/campaigns
|
|
87
|
+
// applies). Warn + skip rather than throw: one broken definition must not
|
|
88
|
+
// take down worker boot for every journey.
|
|
89
|
+
const { audienceKind, audienceId } = audienceOf(meta);
|
|
90
|
+
const audienceKnown =
|
|
91
|
+
audienceKind === "list"
|
|
92
|
+
? listRegistry.has(audienceId)
|
|
93
|
+
: bucketRegistry.has(audienceId);
|
|
94
|
+
if (!audienceKnown) {
|
|
95
|
+
logger.error("campaigns: unknown audience — skipping definition", {
|
|
96
|
+
campaignId: meta.id,
|
|
97
|
+
audienceKind,
|
|
98
|
+
audienceId,
|
|
99
|
+
});
|
|
100
|
+
result.skipped++;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (!templateNames.has(meta.template)) {
|
|
104
|
+
logger.error("campaigns: unknown template — skipping definition", {
|
|
105
|
+
campaignId: meta.id,
|
|
106
|
+
template: meta.template,
|
|
107
|
+
});
|
|
108
|
+
result.skipped++;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const idempotencyKey = `${DEFINED_CAMPAIGN_KEY_PREFIX}${meta.id}`;
|
|
113
|
+
const existingRows = await db
|
|
114
|
+
.select({
|
|
115
|
+
id: campaigns.id,
|
|
116
|
+
status: campaigns.status,
|
|
117
|
+
name: campaigns.name,
|
|
118
|
+
audienceKind: campaigns.audienceKind,
|
|
119
|
+
audienceId: campaigns.audienceId,
|
|
120
|
+
templateKey: campaigns.templateKey,
|
|
121
|
+
props: campaigns.props,
|
|
122
|
+
fromEmail: campaigns.fromEmail,
|
|
123
|
+
subject: campaigns.subject,
|
|
124
|
+
scheduledAt: campaigns.scheduledAt,
|
|
125
|
+
})
|
|
126
|
+
.from(campaigns)
|
|
127
|
+
.where(eq(campaigns.idempotencyKey, idempotencyKey))
|
|
128
|
+
.limit(1);
|
|
129
|
+
const existing = existingRows[0];
|
|
130
|
+
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
const due = meta.sendAt.getTime() <= now;
|
|
133
|
+
const stale = meta.sendAt.getTime() < now - defineGraceMs();
|
|
134
|
+
|
|
135
|
+
if (!existing) {
|
|
136
|
+
if (stale) {
|
|
137
|
+
await db.insert(campaigns).values({
|
|
138
|
+
name: meta.name,
|
|
139
|
+
status: "expired",
|
|
140
|
+
audienceKind,
|
|
141
|
+
audienceId,
|
|
142
|
+
templateKey: meta.template,
|
|
143
|
+
props: meta.props ?? {},
|
|
144
|
+
fromEmail: meta.from ?? null,
|
|
145
|
+
subject: meta.subject ?? null,
|
|
146
|
+
scheduledAt: meta.sendAt,
|
|
147
|
+
idempotencyKey,
|
|
148
|
+
});
|
|
149
|
+
logger.warn(
|
|
150
|
+
"campaigns: defined campaign sendAt is stale — marked expired, NOT sent",
|
|
151
|
+
{
|
|
152
|
+
campaignId: meta.id,
|
|
153
|
+
sendAt: meta.sendAt.toISOString(),
|
|
154
|
+
graceMs: defineGraceMs(),
|
|
155
|
+
},
|
|
156
|
+
);
|
|
157
|
+
result.expired++;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const inserted = await db
|
|
162
|
+
.insert(campaigns)
|
|
163
|
+
.values({
|
|
164
|
+
name: meta.name,
|
|
165
|
+
status: "scheduled",
|
|
166
|
+
audienceKind,
|
|
167
|
+
audienceId,
|
|
168
|
+
templateKey: meta.template,
|
|
169
|
+
props: meta.props ?? {},
|
|
170
|
+
fromEmail: meta.from ?? null,
|
|
171
|
+
subject: meta.subject ?? null,
|
|
172
|
+
scheduledAt: meta.sendAt,
|
|
173
|
+
idempotencyKey,
|
|
174
|
+
})
|
|
175
|
+
// Two worker replicas reconciling concurrently: the loser of the
|
|
176
|
+
// partial-unique insert race simply defers to the winner's row. The
|
|
177
|
+
// `targetWhere` predicate must match the PARTIAL unique index
|
|
178
|
+
// (`WHERE idempotency_key IS NOT NULL`) or Postgres cannot infer the
|
|
179
|
+
// conflict arbiter (42P10).
|
|
180
|
+
.onConflictDoNothing({
|
|
181
|
+
target: campaigns.idempotencyKey,
|
|
182
|
+
where: sql`idempotency_key is not null`,
|
|
183
|
+
})
|
|
184
|
+
.returning({ id: campaigns.id });
|
|
185
|
+
const rowId = inserted[0]?.id;
|
|
186
|
+
if (!rowId) {
|
|
187
|
+
result.skipped++;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
await scheduleOrEnqueue({ client, rowId, sendAt: meta.sendAt, due });
|
|
192
|
+
logger.info("campaigns: defined campaign scheduled", {
|
|
193
|
+
campaignId: meta.id,
|
|
194
|
+
rowId,
|
|
195
|
+
sendAt: meta.sendAt.toISOString(),
|
|
196
|
+
});
|
|
197
|
+
result.created++;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (existing.status !== "scheduled") {
|
|
202
|
+
// sent (retired) / canceled / expired / failed / in-flight — the row is
|
|
203
|
+
// the source of truth once it has left `scheduled`.
|
|
204
|
+
result.skipped++;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const changed =
|
|
209
|
+
existing.name !== meta.name ||
|
|
210
|
+
existing.audienceKind !== audienceKind ||
|
|
211
|
+
existing.audienceId !== audienceId ||
|
|
212
|
+
existing.templateKey !== meta.template ||
|
|
213
|
+
JSON.stringify(existing.props ?? {}) !==
|
|
214
|
+
JSON.stringify(meta.props ?? {}) ||
|
|
215
|
+
(existing.fromEmail ?? null) !== (meta.from ?? null) ||
|
|
216
|
+
(existing.subject ?? null) !== (meta.subject ?? null) ||
|
|
217
|
+
existing.scheduledAt?.getTime() !== meta.sendAt.getTime();
|
|
218
|
+
|
|
219
|
+
if (!changed) {
|
|
220
|
+
result.skipped++;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const sendAtMoved =
|
|
225
|
+
existing.scheduledAt?.getTime() !== meta.sendAt.getTime();
|
|
226
|
+
|
|
227
|
+
// CAS on `scheduled` so an edit never clobbers a row that went live (or
|
|
228
|
+
// was canceled) between the read above and this write.
|
|
229
|
+
const updated = await db
|
|
230
|
+
.update(campaigns)
|
|
231
|
+
.set({
|
|
232
|
+
name: meta.name,
|
|
233
|
+
audienceKind,
|
|
234
|
+
audienceId,
|
|
235
|
+
templateKey: meta.template,
|
|
236
|
+
props: meta.props ?? {},
|
|
237
|
+
fromEmail: meta.from ?? null,
|
|
238
|
+
subject: meta.subject ?? null,
|
|
239
|
+
scheduledAt: meta.sendAt,
|
|
240
|
+
updatedAt: new Date(),
|
|
241
|
+
})
|
|
242
|
+
.where(
|
|
243
|
+
and(eq(campaigns.id, existing.id), eq(campaigns.status, "scheduled")),
|
|
244
|
+
)
|
|
245
|
+
.returning({ id: campaigns.id });
|
|
246
|
+
|
|
247
|
+
if (updated.length > 0 && sendAtMoved) {
|
|
248
|
+
// Fresh run at the new instant; the run created for the OLD instant
|
|
249
|
+
// finds `scheduledAt` still in the future when it fires and skips
|
|
250
|
+
// (send task early-fire guard), or finds the row terminal.
|
|
251
|
+
await scheduleOrEnqueue({
|
|
252
|
+
client,
|
|
253
|
+
rowId: existing.id,
|
|
254
|
+
sendAt: meta.sendAt,
|
|
255
|
+
due,
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
logger.info("campaigns: defined campaign updated", {
|
|
259
|
+
campaignId: meta.id,
|
|
260
|
+
rowId: existing.id,
|
|
261
|
+
sendAt: meta.sendAt.toISOString(),
|
|
262
|
+
});
|
|
263
|
+
result.updated++;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Create the punctual trigger for a scheduled row: a Hatchet scheduled run at
|
|
271
|
+
* `sendAt`, or an immediate enqueue when already due (within grace).
|
|
272
|
+
* Best-effort — on failure the row stays `scheduled` and the reaper's
|
|
273
|
+
* due-scheduled sweep promotes it.
|
|
274
|
+
*/
|
|
275
|
+
async function scheduleOrEnqueue(opts: {
|
|
276
|
+
client: HogsendClient;
|
|
277
|
+
rowId: string;
|
|
278
|
+
sendAt: Date;
|
|
279
|
+
due: boolean;
|
|
280
|
+
}): Promise<void> {
|
|
281
|
+
const { client, rowId, sendAt, due } = opts;
|
|
282
|
+
try {
|
|
283
|
+
if (due) {
|
|
284
|
+
await sendCampaignTask.runNoWait({ campaignId: rowId });
|
|
285
|
+
} else {
|
|
286
|
+
await sendCampaignTask.schedule(sendAt, { campaignId: rowId });
|
|
287
|
+
}
|
|
288
|
+
} catch (err) {
|
|
289
|
+
client.logger.warn(
|
|
290
|
+
"campaigns: schedule/enqueue failed (reaper will promote)",
|
|
291
|
+
{
|
|
292
|
+
rowId,
|
|
293
|
+
error: err instanceof Error ? err.message : String(err),
|
|
294
|
+
},
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
}
|
package/src/container.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
buildBucketRegistry,
|
|
23
23
|
collectBucketReactionJourneys,
|
|
24
24
|
} from "./buckets/registry.js";
|
|
25
|
+
import type { DefinedCampaign } from "./campaigns/define-campaign.js";
|
|
25
26
|
import {
|
|
26
27
|
ConnectorActionRegistry,
|
|
27
28
|
setConnectorActionRegistry,
|
|
@@ -183,6 +184,12 @@ export interface HogsendClient {
|
|
|
183
184
|
* elsewhere via `getListRegistry()`). Empty when no lists are wired.
|
|
184
185
|
*/
|
|
185
186
|
listRegistry: ListRegistry;
|
|
187
|
+
/**
|
|
188
|
+
* Code-defined one-shot campaigns (broadcasts), verbatim from
|
|
189
|
+
* `opts.campaigns`. The worker's boot reconciler turns them into scheduled
|
|
190
|
+
* `campaigns` rows; empty when none are wired.
|
|
191
|
+
*/
|
|
192
|
+
campaigns: DefinedCampaign[];
|
|
186
193
|
/**
|
|
187
194
|
* The unified inbound CONNECTOR registry, keyed by `meta.id`. Holds every
|
|
188
195
|
* transport: webhook (the `:sourceId` dispatch + legacy webhookSources),
|
|
@@ -226,6 +233,13 @@ export interface HogsendClientOptions {
|
|
|
226
233
|
* preference center. Defaults to none (empty registry ⇒ legacy opt-in).
|
|
227
234
|
*/
|
|
228
235
|
lists?: DefinedList[];
|
|
236
|
+
/**
|
|
237
|
+
* Code-defined one-shot campaigns (broadcasts) — `defineCampaign()` files.
|
|
238
|
+
* Carried on the client so the worker's boot reconciler can schedule them
|
|
239
|
+
* (see `reconcileDefinedCampaigns`); the API process only stores them.
|
|
240
|
+
* Defaults to none.
|
|
241
|
+
*/
|
|
242
|
+
campaigns?: DefinedCampaign[];
|
|
229
243
|
/**
|
|
230
244
|
* Email is a first-class channel. Its config is grouped here rather than
|
|
231
245
|
* spread across top-level args — the engine owns the cohesive email pipeline
|
|
@@ -660,6 +674,11 @@ export function createHogsendClient(
|
|
|
660
674
|
db,
|
|
661
675
|
secret: env.BETTER_AUTH_SECRET,
|
|
662
676
|
baseURL: env.BETTER_AUTH_URL,
|
|
677
|
+
// Give the engine (Studio/dogfood, e.g. t.hogsend.com) its OWN cookie
|
|
678
|
+
// namespace so its session cookie stops colliding with a sibling web
|
|
679
|
+
// app's `.hogsend.com` cross-subdomain SSO cookie. Env default is
|
|
680
|
+
// "hogsend"; no deploy needs to set AUTH_COOKIE_PREFIX explicitly.
|
|
681
|
+
cookiePrefix: env.AUTH_COOKIE_PREFIX,
|
|
663
682
|
secondaryStorage: authSecondaryStorage,
|
|
664
683
|
// Always trust the public API origin; add any explicitly configured ones
|
|
665
684
|
// (e.g. a remote Studio origin) on top. baseURL is trusted automatically.
|
|
@@ -898,6 +917,7 @@ export function createHogsendClient(
|
|
|
898
917
|
journeySourceLocations: getJourneySourceLocations(),
|
|
899
918
|
bucketRegistry,
|
|
900
919
|
listRegistry,
|
|
920
|
+
campaigns: opts.campaigns ?? [],
|
|
901
921
|
connectorRegistry,
|
|
902
922
|
connectorActionRegistry,
|
|
903
923
|
hatchet: opts.overrides?.hatchet ?? hatchet,
|
package/src/env.ts
CHANGED
|
@@ -55,6 +55,20 @@ export const env = createEnv({
|
|
|
55
55
|
// comma-separated. Needed when the Studio is served from a different origin
|
|
56
56
|
// than the API — e.g. the `hogsend studio` CLI pointing at a remote instance.
|
|
57
57
|
BETTER_AUTH_TRUSTED_ORIGINS: z.string().optional(),
|
|
58
|
+
// Cookie NAMESPACE for the engine's own Better Auth (the Studio/dogfood at
|
|
59
|
+
// e.g. t.hogsend.com). Better Auth derives the session cookie name as
|
|
60
|
+
// `<__Secure->?<prefix>.session_token`; with Better Auth's default
|
|
61
|
+
// "better-auth" prefix the engine cookie shares a NAME with any sibling web
|
|
62
|
+
// app that sets a cross-subdomain cookie on the shared parent (e.g.
|
|
63
|
+
// course/docs on `.hogsend.com`), which the browser also delivers to the
|
|
64
|
+
// Studio host — same name, DIFFERENT database → null session → Studio login
|
|
65
|
+
// loop. Defaulting to "hogsend" gives the engine its own namespace
|
|
66
|
+
// (__Secure-hogsend.session_token) so that sibling cookie is simply ignored
|
|
67
|
+
// here. MUST stay optional-with-default — a required value would fail env
|
|
68
|
+
// validation on every deploy that doesn't set it. Prefix affects the cookie
|
|
69
|
+
// NAME only; it is orthogonal to crossSubDomainCookies (the Domain attr),
|
|
70
|
+
// which the engine never sets (host-only).
|
|
71
|
+
AUTH_COOKIE_PREFIX: z.string().min(1).default("hogsend"),
|
|
58
72
|
// Optional: a deploy may run a non-Resend provider (Postmark, SES…) and set
|
|
59
73
|
// no Resend key at all. Read directly ONLY in the lazy-resend default branch
|
|
60
74
|
// (container.ts) and the future `emailProvidersFromEnv` preset. With this
|
package/src/index.ts
CHANGED
|
@@ -96,6 +96,18 @@ export {
|
|
|
96
96
|
resetBucketRegistry,
|
|
97
97
|
setBucketRegistry,
|
|
98
98
|
} from "./buckets/registry-singleton.js";
|
|
99
|
+
// --- Campaigns (one-shot broadcasts) ---
|
|
100
|
+
export {
|
|
101
|
+
type CampaignAudience,
|
|
102
|
+
type CampaignMeta,
|
|
103
|
+
DEFINED_CAMPAIGN_KEY_PREFIX,
|
|
104
|
+
type DefinedCampaign,
|
|
105
|
+
defineCampaign,
|
|
106
|
+
} from "./campaigns/define-campaign.js";
|
|
107
|
+
export {
|
|
108
|
+
type ReconcileResult,
|
|
109
|
+
reconcileDefinedCampaigns,
|
|
110
|
+
} from "./campaigns/reconcile.js";
|
|
99
111
|
// --- Cold-connect (email-confirmed chat-platform contact linking) ---
|
|
100
112
|
export {
|
|
101
113
|
type ColdConnect,
|
|
@@ -595,7 +607,10 @@ export {
|
|
|
595
607
|
type SuppressionImportRow,
|
|
596
608
|
type SuppressionReason,
|
|
597
609
|
} from "./workflows/import-suppressions.js";
|
|
598
|
-
export {
|
|
610
|
+
export {
|
|
611
|
+
reapStuckCampaignsTask,
|
|
612
|
+
sendCampaignTask,
|
|
613
|
+
} from "./workflows/send-campaign.js";
|
|
599
614
|
// --- Built-in Hatchet workflow tasks ---
|
|
600
615
|
export { sendEmailTask } from "./workflows/send-email.js";
|
|
601
616
|
export { sendFeedTask } from "./workflows/send-feed.js";
|
package/src/lib/auth.ts
CHANGED
|
@@ -53,12 +53,44 @@ export function createAuth(opts: {
|
|
|
53
53
|
* better-auth's in-memory store on a bare instance with no Redis.
|
|
54
54
|
*/
|
|
55
55
|
secondaryStorage?: AuthSecondaryStorage;
|
|
56
|
+
/**
|
|
57
|
+
* Cookie-name namespace for THIS engine instance's Better Auth (passed to
|
|
58
|
+
* better-auth `advanced.cookiePrefix`). Better Auth names the session cookie
|
|
59
|
+
* `<__Secure->?<prefix>.session_token`; the default "better-auth" prefix
|
|
60
|
+
* collides with a sibling web app's cross-subdomain SSO cookie of the SAME
|
|
61
|
+
* name (e.g. course/docs on `.hogsend.com`) that the browser also delivers to
|
|
62
|
+
* the Studio host — but which resolves against a DIFFERENT database → null
|
|
63
|
+
* session → Studio login loop. Defaulting to "hogsend" gives the engine its
|
|
64
|
+
* own namespace (`__Secure-hogsend.session_token`) so that sibling cookie is
|
|
65
|
+
* simply ignored here. `cookiePrefix` only affects the cookie NAME — it is
|
|
66
|
+
* orthogonal to `crossSubDomainCookies` (the Domain attribute), which the
|
|
67
|
+
* engine never sets (host-only). `createHogsendClient` wires this from
|
|
68
|
+
* `env.AUTH_COOKIE_PREFIX`; the default is baked in below so every call site
|
|
69
|
+
* (including the headless CLI, which issues no cookie) stays aligned.
|
|
70
|
+
*/
|
|
71
|
+
cookiePrefix?: string;
|
|
56
72
|
}) {
|
|
57
|
-
const {
|
|
73
|
+
const {
|
|
74
|
+
db,
|
|
75
|
+
secret,
|
|
76
|
+
baseURL,
|
|
77
|
+
trustedOrigins,
|
|
78
|
+
sendResetPassword,
|
|
79
|
+
cookiePrefix,
|
|
80
|
+
} = opts;
|
|
58
81
|
return betterAuth({
|
|
59
82
|
basePath: "/api/auth",
|
|
60
83
|
secret,
|
|
61
84
|
baseURL,
|
|
85
|
+
// Namespace the engine's Better Auth cookies so its session cookie no longer
|
|
86
|
+
// shares a NAME with a sibling web app's `.hogsend.com` cross-subdomain SSO
|
|
87
|
+
// cookie that is also delivered to the Studio host (same name, different DB
|
|
88
|
+
// → null session → Studio login loop). Prefix-only; the Domain attribute
|
|
89
|
+
// (crossSubDomainCookies) is left UNSET → host-only cookie. Default
|
|
90
|
+
// "hogsend" → prod cookie `__Secure-hogsend.session_token`.
|
|
91
|
+
advanced: {
|
|
92
|
+
cookiePrefix: cookiePrefix ?? "hogsend",
|
|
93
|
+
},
|
|
62
94
|
...(trustedOrigins && trustedOrigins.length > 0 ? { trustedOrigins } : {}),
|
|
63
95
|
// Passing `secondaryStorage` flips better-auth's rate-limit storage from the
|
|
64
96
|
// per-instance in-memory default to this shared store (see option doc).
|