@pithy-sh/email 0.1.2 → 0.1.4
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/dist/analytics.d.ts +21 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +15 -0
- package/dist/audit/actions.d.ts +47 -0
- package/dist/audit/actions.d.ts.map +1 -0
- package/dist/audit/actions.js +47 -0
- package/dist/bounce/classify.d.ts +40 -0
- package/dist/bounce/classify.d.ts.map +1 -0
- package/dist/bounce/classify.js +48 -0
- package/dist/bounce/handler.d.ts +34 -0
- package/dist/bounce/handler.d.ts.map +1 -0
- package/dist/bounce/handler.js +83 -0
- package/dist/capability.d.ts +160 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/capability.js +257 -0
- package/dist/crypto/signingKey.d.ts +38 -0
- package/dist/crypto/signingKey.d.ts.map +1 -0
- package/dist/crypto/signingKey.js +38 -0
- package/dist/crypto/token.d.ts +49 -0
- package/dist/crypto/token.d.ts.map +1 -0
- package/dist/crypto/token.js +101 -0
- package/dist/data/emailEvent.d.ts +30 -0
- package/dist/data/emailEvent.d.ts.map +1 -0
- package/dist/data/emailEvent.js +24 -0
- package/dist/data/emailJob.d.ts +78 -0
- package/dist/data/emailJob.d.ts.map +1 -0
- package/dist/data/emailJob.js +64 -0
- package/dist/data/emailSuppression.d.ts +25 -0
- package/dist/data/emailSuppression.d.ts.map +1 -0
- package/dist/data/emailSuppression.js +23 -0
- package/dist/data/enums.d.ts +78 -0
- package/dist/data/enums.d.ts.map +1 -0
- package/dist/data/enums.js +67 -0
- package/dist/data/tables.d.ts +116 -0
- package/dist/data/tables.d.ts.map +1 -0
- package/dist/data/tables.js +32 -0
- package/dist/error/errors.d.ts +62 -0
- package/dist/error/errors.d.ts.map +1 -0
- package/dist/error/errors.js +84 -0
- package/dist/http/callbacks.d.ts +23 -0
- package/dist/http/callbacks.d.ts.map +1 -0
- package/dist/http/callbacks.js +112 -0
- package/dist/http/guards.d.ts +101 -0
- package/dist/http/guards.d.ts.map +1 -0
- package/dist/http/guards.js +146 -0
- package/dist/http/responses.d.ts +297 -0
- package/dist/http/responses.d.ts.map +1 -0
- package/dist/http/responses.js +117 -0
- package/dist/http/routes.d.ts +73 -0
- package/dist/http/routes.d.ts.map +1 -0
- package/dist/http/routes.js +294 -0
- package/dist/http/schemas.d.ts +92 -0
- package/dist/http/schemas.d.ts.map +1 -0
- package/dist/http/schemas.js +93 -0
- package/dist/http/view.d.ts +80 -0
- package/dist/http/view.d.ts.map +1 -0
- package/dist/http/view.js +132 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/jobs/read.d.ts +193 -0
- package/dist/jobs/read.d.ts.map +1 -0
- package/dist/jobs/read.js +145 -0
- package/dist/jobs/retry.d.ts +101 -0
- package/dist/jobs/retry.d.ts.map +1 -0
- package/dist/jobs/retry.js +69 -0
- package/dist/migrations/0001_init.d.ts +34 -0
- package/dist/migrations/0001_init.d.ts.map +1 -0
- package/dist/migrations/0001_init.js +62 -0
- package/dist/migrations/0001_suppressions.d.ts +12 -0
- package/dist/migrations/0001_suppressions.d.ts.map +1 -0
- package/dist/migrations/0001_suppressions.js +22 -0
- package/dist/provision/devDelivery.d.ts +34 -0
- package/dist/provision/devDelivery.d.ts.map +1 -0
- package/dist/provision/devDelivery.js +39 -0
- package/dist/provision/hostCatalogs.d.ts +12 -0
- package/dist/provision/hostCatalogs.d.ts.map +1 -0
- package/dist/provision/hostCatalogs.js +80 -0
- package/dist/provision/provisionEmail.d.ts +145 -0
- package/dist/provision/provisionEmail.d.ts.map +1 -0
- package/dist/provision/provisionEmail.js +120 -0
- package/dist/provision/resolveEmailConfig.d.ts +124 -0
- package/dist/provision/resolveEmailConfig.d.ts.map +1 -0
- package/dist/provision/resolveEmailConfig.js +126 -0
- package/dist/provision/settingsCheck.d.ts +42 -0
- package/dist/provision/settingsCheck.d.ts.map +1 -0
- package/dist/provision/settingsCheck.js +140 -0
- package/dist/send/batchIdentity.d.ts +44 -0
- package/dist/send/batchIdentity.d.ts.map +1 -0
- package/dist/send/batchIdentity.js +48 -0
- package/dist/send/enqueue.d.ts +218 -0
- package/dist/send/enqueue.d.ts.map +1 -0
- package/dist/send/enqueue.js +155 -0
- package/dist/send/errorMapping.d.ts +29 -0
- package/dist/send/errorMapping.d.ts.map +1 -0
- package/dist/send/errorMapping.js +54 -0
- package/dist/send/events.d.ts +17 -0
- package/dist/send/events.d.ts.map +1 -0
- package/dist/send/events.js +19 -0
- package/dist/send/fromComposition.d.ts +49 -0
- package/dist/send/fromComposition.d.ts.map +1 -0
- package/dist/send/fromComposition.js +55 -0
- package/dist/send/retryPolicy.d.ts +34 -0
- package/dist/send/retryPolicy.d.ts.map +1 -0
- package/dist/send/retryPolicy.js +41 -0
- package/dist/send/runSend.d.ts +108 -0
- package/dist/send/runSend.d.ts.map +1 -0
- package/dist/send/runSend.js +220 -0
- package/dist/send/sendAt.d.ts +8 -0
- package/dist/send/sendAt.d.ts.map +1 -0
- package/dist/send/sendAt.js +64 -0
- package/dist/send/sender.d.ts +44 -0
- package/dist/send/sender.d.ts.map +1 -0
- package/dist/send/sender.js +2 -0
- package/dist/send/senderBinding.d.ts +46 -0
- package/dist/send/senderBinding.d.ts.map +1 -0
- package/dist/send/senderBinding.js +23 -0
- package/dist/send/suppression.d.ts +95 -0
- package/dist/send/suppression.d.ts.map +1 -0
- package/dist/send/suppression.js +134 -0
- package/dist/templates/engine.d.ts +111 -0
- package/dist/templates/engine.d.ts.map +1 -0
- package/dist/templates/engine.js +260 -0
- package/dist/templates/messages.d.ts +96 -0
- package/dist/templates/messages.d.ts.map +1 -0
- package/dist/templates/messages.es.d.ts +31 -0
- package/dist/templates/messages.es.d.ts.map +1 -0
- package/dist/templates/messages.es.js +84 -0
- package/dist/templates/messages.js +268 -0
- package/dist/templates/partials.d.ts +7 -0
- package/dist/templates/partials.d.ts.map +1 -0
- package/dist/templates/partials.js +61 -0
- package/dist/templates/precompiled.generated.d.ts +268 -0
- package/dist/templates/precompiled.generated.d.ts.map +1 -0
- package/dist/templates/precompiled.generated.js +4041 -0
- package/dist/templates/registry.d.ts +120 -0
- package/dist/templates/registry.d.ts.map +1 -0
- package/dist/templates/registry.js +325 -0
- package/dist/templates/samples.d.ts +9 -0
- package/dist/templates/samples.d.ts.map +1 -0
- package/dist/templates/samples.js +100 -0
- package/dist/templates/severity.d.ts +42 -0
- package/dist/templates/severity.d.ts.map +1 -0
- package/dist/templates/severity.js +83 -0
- package/dist/templates/theme.d.ts +195 -0
- package/dist/templates/theme.d.ts.map +1 -0
- package/dist/templates/theme.js +170 -0
- package/dist/version.generated.d.ts +7 -0
- package/dist/version.generated.d.ts.map +1 -0
- package/dist/version.generated.js +9 -0
- package/dist/workflows/hostApp.d.ts +35 -0
- package/dist/workflows/hostApp.d.ts.map +1 -0
- package/dist/workflows/hostApp.js +21 -0
- package/dist/workflows/hostEnv.d.ts +131 -0
- package/dist/workflows/hostEnv.d.ts.map +1 -0
- package/dist/workflows/hostEnv.js +149 -0
- package/dist/workflows/instanceLiveness.d.ts +5 -0
- package/dist/workflows/instanceLiveness.d.ts.map +1 -0
- package/dist/workflows/instanceLiveness.js +39 -0
- package/dist/workflows/instances.d.ts +20 -0
- package/dist/workflows/instances.d.ts.map +1 -0
- package/dist/workflows/instances.js +2 -0
- package/dist/workflows/params.d.ts +25 -0
- package/dist/workflows/params.d.ts.map +1 -0
- package/dist/workflows/params.js +23 -0
- package/dist/workflows/scheduler.d.ts +84 -0
- package/dist/workflows/scheduler.d.ts.map +1 -0
- package/dist/workflows/scheduler.js +113 -0
- package/dist/workflows/sendBatch.d.ts +87 -0
- package/dist/workflows/sendBatch.d.ts.map +1 -0
- package/dist/workflows/sendBatch.js +52 -0
- package/dist/workflows/worker.d.ts +102 -0
- package/dist/workflows/worker.d.ts.map +1 -0
- package/dist/workflows/worker.js +119 -0
- package/package.json +22 -11
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"settingsCheck.d.ts","sourceRoot":"","sources":["../../src/provision/settingsCheck.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,wCAAwC,CAAC;AAIhD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAIrD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uGAAuG;AACvG,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,WAAW,EAAE,MAAM,CAAC;IACpB,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,iEAAiE;IACjE,KAAK,CAAC,EAAE,UAAU,CAAC;CACpB;AAyJD,wGAAwG;AACxG,wBAAgB,aAAa,CAAC,MAAM,EAAE,kBAAkB,GAAG,kBAAkB,CAK5E"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { EMAIL_LINK_SIGNING_KEY } from "../crypto/signingKey.js";
|
|
4
|
+
import { emailHostEnv } from "../workflows/hostEnv.js";
|
|
5
|
+
import { suppressionDatabaseName } from "./provisionEmail.js";
|
|
6
|
+
import { hostEnvFindings } from "@pithy-sh/core/src/capability/settings";
|
|
7
|
+
import { checkHostEnv } from "@pithy-sh/core/src/workflow/hostEnv";
|
|
8
|
+
//#region src/provision/settingsCheck.ts
|
|
9
|
+
/**
|
|
10
|
+
* A stand-in for a binding, so the local tier judges values rather than wiring.
|
|
11
|
+
*
|
|
12
|
+
* `EmailHostEnv` duck-types its bindings — it asserts the method the host calls, because these are host
|
|
13
|
+
* objects the runtime hands over and there is no class to compare against. That is what makes a stub
|
|
14
|
+
* possible here at all, and it is why the stub carries the methods rather than being an empty object: the
|
|
15
|
+
* schema would refuse `{}` and the report would fill with wiring faults doctor already states elsewhere.
|
|
16
|
+
*/
|
|
17
|
+
function stubBindings() {
|
|
18
|
+
const d1 = { prepare: () => void 0 };
|
|
19
|
+
return {
|
|
20
|
+
DB: d1,
|
|
21
|
+
EMAIL_SUPPRESSIONS: d1,
|
|
22
|
+
SECRETS: d1,
|
|
23
|
+
SECRETS_ENCRYPTION_KEYS: "checked elsewhere",
|
|
24
|
+
EMAIL: { send: () => void 0 },
|
|
25
|
+
EMAIL_SENDER: {
|
|
26
|
+
create: () => void 0,
|
|
27
|
+
get: () => void 0
|
|
28
|
+
},
|
|
29
|
+
EMAIL_SCHEDULER: { create: () => void 0 }
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** The domain half of an address, lowercased, or `null` where the address carries none usable. */
|
|
33
|
+
function domainOf(address) {
|
|
34
|
+
const at = address.lastIndexOf("@");
|
|
35
|
+
if (at < 0) return null;
|
|
36
|
+
const domain = address.slice(at + 1).trim().toLowerCase();
|
|
37
|
+
return domain.includes(".") ? domain : null;
|
|
38
|
+
}
|
|
39
|
+
/** The origin of a URL, or `null` when it is not one. Compared origin-to-origin, never string-to-string. */
|
|
40
|
+
function originOf(url) {
|
|
41
|
+
try {
|
|
42
|
+
return new URL(url).origin;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The host's own parse of the values this composition would hand it.
|
|
49
|
+
*
|
|
50
|
+
* Run **once**, not once per environment, and reported with no environment named: `email({ … })` is one
|
|
51
|
+
* config object per Worker, so a `BASE_URL` that is not a URL is one edit however many environments a
|
|
52
|
+
* project declares. Three lines about one key is how a report stops being read.
|
|
53
|
+
*/
|
|
54
|
+
function localHostEnv(config) {
|
|
55
|
+
const candidate = {
|
|
56
|
+
...stubBindings(),
|
|
57
|
+
BASE_URL: config.baseUrl,
|
|
58
|
+
...config.theme ? { EMAIL_THEME: JSON.stringify(config.theme) } : {}
|
|
59
|
+
};
|
|
60
|
+
return hostEnvFindings(checkHostEnv(emailHostEnv, candidate), null);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Whether the configured base URL is an origin this project actually answers on.
|
|
64
|
+
*
|
|
65
|
+
* `pithy email provision` stamps each host's `BASE_URL` from that environment's *resolved worker address*,
|
|
66
|
+
* so a deployed host is right by construction — but `email({ baseUrl })` is what `pithy dev` renders links
|
|
67
|
+
* against and what the repository states its intent with, and a value matching no declared origin is a
|
|
68
|
+
* link to a host nothing serves. Asked only when some environment declares one: a project before its first
|
|
69
|
+
* domain has nothing to compare against, and `Origins:` already reports that.
|
|
70
|
+
*/
|
|
71
|
+
function localBaseUrlOrigin(config, context) {
|
|
72
|
+
const declared = context.environments.map((environment) => environment.origin === null ? null : originOf(environment.origin)).filter((origin) => origin !== null);
|
|
73
|
+
const configured = originOf(config.baseUrl);
|
|
74
|
+
if (declared.length === 0 || configured === null || declared.includes(configured)) return [];
|
|
75
|
+
return [{
|
|
76
|
+
setting: "BASE_URL",
|
|
77
|
+
environment: null,
|
|
78
|
+
problem: `Links are built against ${configured}, and no environment this project declares answers on it.`,
|
|
79
|
+
action: `Set \`email({ baseUrl })\` to an origin this project serves: ${declared.join(", ")}.`
|
|
80
|
+
}];
|
|
81
|
+
}
|
|
82
|
+
/** The address question, asked once: it is one config key, and one edit fixes every environment. */
|
|
83
|
+
function localForAddress(config) {
|
|
84
|
+
if (domainOf(config.fromAddress) !== null) return [];
|
|
85
|
+
return [{
|
|
86
|
+
setting: "fromAddress",
|
|
87
|
+
environment: null,
|
|
88
|
+
problem: `${config.fromAddress} is not an address a sending domain can be read from.`,
|
|
89
|
+
action: "Set `email({ fromAddress })` to an address on a domain you have onboarded onto Email Service."
|
|
90
|
+
}];
|
|
91
|
+
}
|
|
92
|
+
/** The last declared environment — the one a project-wide remedy is named for. */
|
|
93
|
+
function lastEnvironment(context) {
|
|
94
|
+
return context.environments.at(-1)?.name ?? "prod";
|
|
95
|
+
}
|
|
96
|
+
/** The account half: the zone, the suppression database, and the signing key. */
|
|
97
|
+
async function accountFindings(config, context) {
|
|
98
|
+
const findings = [];
|
|
99
|
+
const domain = domainOf(config.fromAddress);
|
|
100
|
+
if (domain !== null && !await context.account.zone(domain)) findings.push({
|
|
101
|
+
setting: "fromAddress",
|
|
102
|
+
environment: null,
|
|
103
|
+
problem: `${domain} is not a zone on this Cloudflare account, so it cannot be onboarded onto Email Service.`,
|
|
104
|
+
action: `Add ${domain} to this Cloudflare account, then onboard it onto Email Service in the dashboard.`
|
|
105
|
+
});
|
|
106
|
+
const suppressions = suppressionDatabaseName(context.project);
|
|
107
|
+
if (!(await context.account.d1Databases()).includes(suppressions)) findings.push({
|
|
108
|
+
setting: "EMAIL_SUPPRESSIONS",
|
|
109
|
+
environment: null,
|
|
110
|
+
problem: `No D1 database named ${suppressions} exists on this account.`,
|
|
111
|
+
action: `Run \`pithy email provision --env ${lastEnvironment(context)}\`. Nothing is suppressed until it exists.`
|
|
112
|
+
});
|
|
113
|
+
for (const environment of context.environments) {
|
|
114
|
+
if (environment.name === "dev") continue;
|
|
115
|
+
if (await context.account.secret({
|
|
116
|
+
name: "email-link-signing-key",
|
|
117
|
+
environment: environment.name
|
|
118
|
+
})) continue;
|
|
119
|
+
findings.push({
|
|
120
|
+
setting: EMAIL_LINK_SIGNING_KEY,
|
|
121
|
+
environment: environment.name,
|
|
122
|
+
problem: `The link-signing key has no value in ${environment.name}, so no tracking or unsubscribe link can be signed.`,
|
|
123
|
+
action: `Run \`pithy secrets provision --env ${environment.name}\`.`
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return findings;
|
|
127
|
+
}
|
|
128
|
+
/** Email's settings check, built from one composition's resolved config. Declared on the capability. */
|
|
129
|
+
function emailSettings(config) {
|
|
130
|
+
return {
|
|
131
|
+
local: (context) => [
|
|
132
|
+
...localHostEnv(config),
|
|
133
|
+
...localForAddress(config),
|
|
134
|
+
...localBaseUrlOrigin(config, context)
|
|
135
|
+
],
|
|
136
|
+
account: (context) => accountFindings(config, context)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
//#endregion
|
|
140
|
+
export { emailSettings };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* Batch identity — the one rule every dispatcher of a send Workflow keeps (pithy-sh/pithy#342).
|
|
5
|
+
*
|
|
6
|
+
* **A job's `batchId` names the send Workflow instance that is coming for it, and nothing else.** Null
|
|
7
|
+
* means no instance is. There is no third meaning, and in particular it is not a history of which batch
|
|
8
|
+
* touched the row last.
|
|
9
|
+
*
|
|
10
|
+
* It binds over every row in a status `runScheduler` queries — `scheduled`, `pending`, `sending` — which
|
|
11
|
+
* is every row the id can be read from. A terminal row (`sent`, `failed`, `suppressed`, `bounced`,
|
|
12
|
+
* `canceled`) keeps whatever it last carried, because no tick will ever look at it and clearing it
|
|
13
|
+
* would be a write bought for nobody. What that costs is exactly one obligation, and it is `retryJob`'s:
|
|
14
|
+
* the write that brings a terminal row back into the queried set must set this in the same statement.
|
|
15
|
+
*
|
|
16
|
+
* So the rule for a future writer is short. **If you move a job into `scheduled`, `pending` or
|
|
17
|
+
* `sending`, you own this column in that statement.** Three places do today.
|
|
18
|
+
*
|
|
19
|
+
* That is the whole basis of the scheduler's veto. `runScheduler` leaves a stale-looking row alone when
|
|
20
|
+
* the runtime says the instance it names is alive, so a row naming an instance that is *not* the one
|
|
21
|
+
* working it turns the veto into a lie in one of two directions:
|
|
22
|
+
*
|
|
23
|
+
* - It names a **dead** instance and a live one is working the row anyway — the tick re-drives, a second
|
|
24
|
+
* Workflow renders and sends, and one person gets two copies.
|
|
25
|
+
* - It names a **live** instance that is not working the row — the tick holds a genuinely stranded job
|
|
26
|
+
* for as long as some unrelated batch keeps running, and the mail does not go out.
|
|
27
|
+
*
|
|
28
|
+
* Three places set a job to a status the scheduler queries, so three places must uphold it: `enqueueEmail`
|
|
29
|
+
* (immediate dispatch), `retryJob` (an operator re-queueing a failure), and `runScheduler` itself (the
|
|
30
|
+
* claim). Each mints the id *before* the write that makes the row queryable and creates the instance
|
|
31
|
+
* under it afterwards, so the worst an interrupted dispatch can leave behind is a row naming an instance
|
|
32
|
+
* that does not exist — which the runtime disowns, which reads as dead, which is recovered. The failure
|
|
33
|
+
* mode of this design is a duplicate render that `runSend` short-circuits, never a duplicate send.
|
|
34
|
+
*/
|
|
35
|
+
/**
|
|
36
|
+
* Mint a batch id. A UUID, and deliberately nothing more.
|
|
37
|
+
*
|
|
38
|
+
* It becomes a Workflow instance id, so uniqueness is the only property it needs and the only one
|
|
39
|
+
* anything may read from it: a batch id is not a timestamp, not a shard key, and not sortable. It is
|
|
40
|
+
* here rather than inline at each dispatcher so that the three of them cannot drift into three id
|
|
41
|
+
* schemes, one of which collides and rejects a `create` nobody sees fail.
|
|
42
|
+
*/
|
|
43
|
+
export declare function mintBatchId(): string;
|
|
44
|
+
//# sourceMappingURL=batchIdentity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batchIdentity.d.ts","sourceRoot":"","sources":["../../src/send/batchIdentity.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH;;;;;;;GAOG;AACH,wBAAgB,WAAW,IAAI,MAAM,CAEpC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
//#region src/send/batchIdentity.ts
|
|
4
|
+
/**
|
|
5
|
+
* Batch identity — the one rule every dispatcher of a send Workflow keeps (pithy-sh/pithy#342).
|
|
6
|
+
*
|
|
7
|
+
* **A job's `batchId` names the send Workflow instance that is coming for it, and nothing else.** Null
|
|
8
|
+
* means no instance is. There is no third meaning, and in particular it is not a history of which batch
|
|
9
|
+
* touched the row last.
|
|
10
|
+
*
|
|
11
|
+
* It binds over every row in a status `runScheduler` queries — `scheduled`, `pending`, `sending` — which
|
|
12
|
+
* is every row the id can be read from. A terminal row (`sent`, `failed`, `suppressed`, `bounced`,
|
|
13
|
+
* `canceled`) keeps whatever it last carried, because no tick will ever look at it and clearing it
|
|
14
|
+
* would be a write bought for nobody. What that costs is exactly one obligation, and it is `retryJob`'s:
|
|
15
|
+
* the write that brings a terminal row back into the queried set must set this in the same statement.
|
|
16
|
+
*
|
|
17
|
+
* So the rule for a future writer is short. **If you move a job into `scheduled`, `pending` or
|
|
18
|
+
* `sending`, you own this column in that statement.** Three places do today.
|
|
19
|
+
*
|
|
20
|
+
* That is the whole basis of the scheduler's veto. `runScheduler` leaves a stale-looking row alone when
|
|
21
|
+
* the runtime says the instance it names is alive, so a row naming an instance that is *not* the one
|
|
22
|
+
* working it turns the veto into a lie in one of two directions:
|
|
23
|
+
*
|
|
24
|
+
* - It names a **dead** instance and a live one is working the row anyway — the tick re-drives, a second
|
|
25
|
+
* Workflow renders and sends, and one person gets two copies.
|
|
26
|
+
* - It names a **live** instance that is not working the row — the tick holds a genuinely stranded job
|
|
27
|
+
* for as long as some unrelated batch keeps running, and the mail does not go out.
|
|
28
|
+
*
|
|
29
|
+
* Three places set a job to a status the scheduler queries, so three places must uphold it: `enqueueEmail`
|
|
30
|
+
* (immediate dispatch), `retryJob` (an operator re-queueing a failure), and `runScheduler` itself (the
|
|
31
|
+
* claim). Each mints the id *before* the write that makes the row queryable and creates the instance
|
|
32
|
+
* under it afterwards, so the worst an interrupted dispatch can leave behind is a row naming an instance
|
|
33
|
+
* that does not exist — which the runtime disowns, which reads as dead, which is recovered. The failure
|
|
34
|
+
* mode of this design is a duplicate render that `runSend` short-circuits, never a duplicate send.
|
|
35
|
+
*/
|
|
36
|
+
/**
|
|
37
|
+
* Mint a batch id. A UUID, and deliberately nothing more.
|
|
38
|
+
*
|
|
39
|
+
* It becomes a Workflow instance id, so uniqueness is the only property it needs and the only one
|
|
40
|
+
* anything may read from it: a batch id is not a timestamp, not a shard key, and not sortable. It is
|
|
41
|
+
* here rather than inline at each dispatcher so that the three of them cannot drift into three id
|
|
42
|
+
* schemes, one of which collides and rejects a `create` nobody sees fail.
|
|
43
|
+
*/
|
|
44
|
+
function mintBatchId() {
|
|
45
|
+
return crypto.randomUUID();
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { mintBatchId };
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { EmailJobStatus, SendMode, SuppressionReason } from "../data/enums";
|
|
4
|
+
import type { EmailDatabase, EmailSuppressionDatabase } from "../data/tables";
|
|
5
|
+
import { type EmailMessageLayers } from "../templates/messages";
|
|
6
|
+
import type { EmailTheme } from "../templates/theme";
|
|
7
|
+
/**
|
|
8
|
+
* Enqueue an email. A request handler only ever does this — it never sends inline. Every email becomes
|
|
9
|
+
* a `pithy_email_jobs` row; an `immediate` job also kicks the send Workflow now (lowest latency), while
|
|
10
|
+
* `scheduled` and `timezone` jobs are left for the every-minute scheduler to pick up. The payload is
|
|
11
|
+
* validated against the template schema here, so a bad call fails at enqueue, not mid-send.
|
|
12
|
+
*
|
|
13
|
+
* **Suppression is consulted here too, and no caller asks for it** (pithy-sh/pithy#355). A blocked
|
|
14
|
+
* recipient never becomes a queued send: the row is born `suppressed`, no Workflow is started, and the
|
|
15
|
+
* reason comes back on the result. The point is not a second gate — `runSend` is and stays the
|
|
16
|
+
* authority, because whether an address is blocked is a question about the instant of sending and a
|
|
17
|
+
* scheduled job is enqueued days before that. The point is that the caller **learns**, at the moment it
|
|
18
|
+
* asked, without holding the suppression database itself. A three-person account whose addresses have
|
|
19
|
+
* all hard-bounced is otherwise three ordinary skips in a send log nobody reads, rather than one notice
|
|
20
|
+
* that reached nobody, said at the moment it went out.
|
|
21
|
+
*
|
|
22
|
+
* **The kind comes from the template, never from a caller** — {@link templateKind}, the same accessor
|
|
23
|
+
* `runSend` uses. That is what keeps an unsubscribe from a newsletter from withholding an invitation:
|
|
24
|
+
* the four suppression reasons stopped being interchangeable, and a check that restated
|
|
25
|
+
* `"transactional"` at the call site would be making a claim about somebody else's template.
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* The Workflow binding used to start a send (Cloudflare `Workflow.create`). At enqueue it sends a batch
|
|
29
|
+
* of one; the scheduler's fan-out starts one instance per batch through the same binding.
|
|
30
|
+
*
|
|
31
|
+
* `id` names the instance being created, and **every dispatcher passes one** (pithy-sh/pithy#342): the
|
|
32
|
+
* scheduler passes its batch's, an enqueue passes the one it just stamped on the row, and a retry passes
|
|
33
|
+
* the one it minted to replace the failed batch's. It is optional here only because the platform allows
|
|
34
|
+
* omitting it, and omitting it is what made an immediate send unattributable to any instance — so the
|
|
35
|
+
* row could not say a Workflow was coming and the safety net sent a second one. See
|
|
36
|
+
* `send/batchIdentity.ts`.
|
|
37
|
+
*/
|
|
38
|
+
export interface SendWorkflowBinding {
|
|
39
|
+
create(options: {
|
|
40
|
+
id?: string;
|
|
41
|
+
params: {
|
|
42
|
+
jobIds: string[];
|
|
43
|
+
};
|
|
44
|
+
}): Promise<unknown>;
|
|
45
|
+
}
|
|
46
|
+
/** What the caller provides to enqueue an email. */
|
|
47
|
+
export interface EnqueueInput {
|
|
48
|
+
/** The recipient address. */
|
|
49
|
+
to: string;
|
|
50
|
+
/** The template id (e.g. `magicLink`). */
|
|
51
|
+
template: string;
|
|
52
|
+
/** The template input variables; validated against the template's payload schema. */
|
|
53
|
+
payload: unknown;
|
|
54
|
+
/** Send mode; defaults to `immediate`. */
|
|
55
|
+
mode?: SendMode;
|
|
56
|
+
/** For `scheduled` mode: the absolute time to send. */
|
|
57
|
+
sendAt?: Date;
|
|
58
|
+
/** For `timezone` mode: the recipient-local time-of-day, `HH:MM`. */
|
|
59
|
+
localTime?: string;
|
|
60
|
+
/** For `timezone` mode: the recipient's IANA timezone. */
|
|
61
|
+
timezone?: string;
|
|
62
|
+
/** The marketing campaign id, for attribution. */
|
|
63
|
+
campaignId?: string;
|
|
64
|
+
/**
|
|
65
|
+
* The language to write this message in, as a BCP-47 tag. Omit where the recipient has not chosen one.
|
|
66
|
+
*
|
|
67
|
+
* **The recipient's, never the caller's.** A magic link is answered by the person who asked for it,
|
|
68
|
+
* and the request that triggers it is theirs — but a nudge, an invitation and an operational notice
|
|
69
|
+
* are all enqueued by somebody else's request, or by a cron with no request at all. So the tag comes
|
|
70
|
+
* from what is known about the *recipient* (`pithy_auth_users.locale` for a signed-up reader, the
|
|
71
|
+
* negotiated request locale for somebody signing in for the first time), and it is stored on the row
|
|
72
|
+
* so the send Workflow renders the body in the language the subject was already written in.
|
|
73
|
+
*
|
|
74
|
+
* Omitted renders the kit's English, which is the seam's behavior everywhere: a project that never
|
|
75
|
+
* composed an i18n capability sends exactly what it sent before any of this landed.
|
|
76
|
+
*/
|
|
77
|
+
locale?: string;
|
|
78
|
+
/**
|
|
79
|
+
* What this message is *about*, when the template id does not say it on its own.
|
|
80
|
+
*
|
|
81
|
+
* The discriminator for a template that carries more than one kind of message (pithy-sh/pithy#382).
|
|
82
|
+
* `sentSince` matches on it, so a caller deciding whether to send — or whether to send a *correction* —
|
|
83
|
+
* can tell two messages apart that share a template and a recipient. Opaque: nothing here parses it,
|
|
84
|
+
* renders it, or puts it on a header or a link.
|
|
85
|
+
*
|
|
86
|
+
* **Not `campaignId`.** That one is marketing attribution and it leaves this row — onto every event,
|
|
87
|
+
* into `campaignStats`, and signed into the tracking token that travels in a delivered email's URLs.
|
|
88
|
+
* See the column's own note on `EmailJob`.
|
|
89
|
+
*
|
|
90
|
+
* Omit it where the template id already answers "what is this", which is most templates.
|
|
91
|
+
*/
|
|
92
|
+
correlation?: string;
|
|
93
|
+
/** Override click-link rewriting (defaults on for marketing, off for transactional). */
|
|
94
|
+
clickTracking?: boolean;
|
|
95
|
+
/** Override open-pixel injection (defaults on for marketing, off for transactional). */
|
|
96
|
+
openTracking?: boolean;
|
|
97
|
+
/**
|
|
98
|
+
* The address a recipient's answer should go to, when it is not `fromAddress`.
|
|
99
|
+
*
|
|
100
|
+
* `@pithy-sh/support` is what this is for: a reply is sent as the adopter's onboarded sending
|
|
101
|
+
* identity (Cloudflare validates the `From` domain against exactly what was onboarded) while the
|
|
102
|
+
* conversation has to come back to the support inbox, which is usually a different subdomain.
|
|
103
|
+
*/
|
|
104
|
+
replyTo?: string;
|
|
105
|
+
/**
|
|
106
|
+
* The `Message-ID` this job answers, angle brackets included — the `In-Reply-To` header.
|
|
107
|
+
*
|
|
108
|
+
* Set together with {@link references}. Threading on ids is what keeps a customer's client showing
|
|
109
|
+
* one conversation instead of one message per answer, and only the Worker holds the chain, which
|
|
110
|
+
* is why a reply is enqueued here rather than composed by whatever surface a human typed it into.
|
|
111
|
+
*/
|
|
112
|
+
inReplyTo?: string;
|
|
113
|
+
/** The `References` chain, angle-bracketed and space-separated. Built by the caller from the parent. */
|
|
114
|
+
references?: string;
|
|
115
|
+
}
|
|
116
|
+
/** Dependencies enqueue needs: the database, the from identity, optional send-Workflow binding, time, ids. */
|
|
117
|
+
export interface EnqueueDeps {
|
|
118
|
+
db: EmailDatabase;
|
|
119
|
+
fromAddress: string;
|
|
120
|
+
fromName: string;
|
|
121
|
+
theme: EmailTheme;
|
|
122
|
+
/**
|
|
123
|
+
* Where the words for a locale come from — the composed project's catalogs.
|
|
124
|
+
*
|
|
125
|
+
* Absent walks this package's own English, which is what keeps the i18n capability optional. The
|
|
126
|
+
* email capability fills it from a composed `i18n` at assembly; nothing here imports that package.
|
|
127
|
+
*/
|
|
128
|
+
layersFor?: EmailMessageLayers;
|
|
129
|
+
/** The send Workflow binding. When present, an immediate job is dispatched now; absent, the scheduler takes it. */
|
|
130
|
+
sender?: SendWorkflowBinding;
|
|
131
|
+
/**
|
|
132
|
+
* The global suppression list. When present, a blocked recipient is recorded here and never queued.
|
|
133
|
+
*
|
|
134
|
+
* Optional for the same reason {@link EnqueueDeps.sender} is, and it is worth being exact about which
|
|
135
|
+
* reason: absence does not mean "send to blocked addresses". The capability declares
|
|
136
|
+
* `EMAIL_SUPPRESSIONS` a required binding, so a composed app worker always has one; and where a caller
|
|
137
|
+
* genuinely has none, `runSend` still refuses the recipient before anything leaves. Making it fatal
|
|
138
|
+
* here would mean refusing to *queue* a message because a list that will be consulted again before it
|
|
139
|
+
* goes could not be consulted yet, which is strictly worse than queueing it.
|
|
140
|
+
*/
|
|
141
|
+
suppressionDb?: EmailSuppressionDatabase;
|
|
142
|
+
now: Date;
|
|
143
|
+
/** Generate a job id (a UUID in production). */
|
|
144
|
+
newId: () => string;
|
|
145
|
+
/**
|
|
146
|
+
* Mint the id of the batch this enqueue dispatches — **the send Workflow instance's id**
|
|
147
|
+
* (pithy-sh/pithy#342). Defaults to {@link mintBatchId}; injected only so a test can name it.
|
|
148
|
+
*/
|
|
149
|
+
newBatchId?: () => string;
|
|
150
|
+
}
|
|
151
|
+
/** The result of enqueuing: the new job id and its initial status. */
|
|
152
|
+
export interface EnqueueResult {
|
|
153
|
+
jobId: string;
|
|
154
|
+
/**
|
|
155
|
+
* What the row was born as — and, for the caller, whether anything is coming for it.
|
|
156
|
+
*
|
|
157
|
+
* `pending` and `scheduled` both mean a send is on its way. `suppressed` means the address is
|
|
158
|
+
* blocked. **`undispatched` means this composition binds no send Workflow**, so nothing was started
|
|
159
|
+
* and nothing is coming while it stays that way (pithy-sh/pithy#410): a caller that renders "check
|
|
160
|
+
* your inbox" off it is reporting a delivery that cannot happen. It is the one status here that
|
|
161
|
+
* describes the *deployment* rather than the message — and the scheduler drains those rows once a
|
|
162
|
+
* host exists, so it is not the end of the job.
|
|
163
|
+
*/
|
|
164
|
+
status: EmailJobStatus;
|
|
165
|
+
/**
|
|
166
|
+
* Why nothing was queued, when the recipient is on the suppression list.
|
|
167
|
+
*
|
|
168
|
+
* The same field {@link import("./runSend").SendOutcome} carries and for the same reason: a caller
|
|
169
|
+
* that only saw a status other than `failed` would report a delivery that never happened. "Suppressed"
|
|
170
|
+
* alone is not enough either — whether the mailbox bounced, complained, or opted out is what an
|
|
171
|
+
* operator's next move depends on.
|
|
172
|
+
*/
|
|
173
|
+
suppressionReason?: SuppressionReason;
|
|
174
|
+
/**
|
|
175
|
+
* The **enqueue-time** render — the sentence this call wrote to `pithy_email_jobs.subject`, in the
|
|
176
|
+
* recipient's language, and the value the row is born with (pithy-sh/pithy#443).
|
|
177
|
+
*
|
|
178
|
+
* **For the caller that has to say what it queued.** Enqueuing is what a surface does; auditing it is
|
|
179
|
+
* what a surface with an administrative trail also does. Without this, that caller had to render the
|
|
180
|
+
* same key a second time — restating the theme it configured and the layer stack it composed, then
|
|
181
|
+
* holding a test pinning its own copy against the kit's catalog to notice when the kit's wording
|
|
182
|
+
* moved. An audit row written at enqueue now reads the same string the job row was written with,
|
|
183
|
+
* rather than a second rendering free to disagree with it.
|
|
184
|
+
*
|
|
185
|
+
* **Locale is what makes it more than a convenience.** A caller that mirrored the English sentence by
|
|
186
|
+
* hand agreed with the row by coincidence, for as long as there was one language. Pass a `locale` and
|
|
187
|
+
* the template renders the recipient's catalog while the mirror keeps restating English, and the trail
|
|
188
|
+
* then claims a subject nobody was ever sent.
|
|
189
|
+
*
|
|
190
|
+
* **{@link import("./runSend").runSend} remains the authority on what was *delivered***, because it
|
|
191
|
+
* renders again — in the send Worker, at the moment the message leaves — and rewrites this column
|
|
192
|
+
* from that render. Three things part the two renders — the three `runSend` names at the line where
|
|
193
|
+
* it rewrites: a template corrected, a theme renamed, or a catalog sentence retranslated. A subject
|
|
194
|
+
* can interpolate the theme (`welcome`'s takes `theme.appName`), so a rename parts them with no
|
|
195
|
+
* catalog movement at all.
|
|
196
|
+
*
|
|
197
|
+
* **And the gap between the two is not only the wait in the queue.** Waiting sets one bound on it,
|
|
198
|
+
* seconds for an immediate send and days for a `scheduled` one. The other is that the send Workflow
|
|
199
|
+
* is its own deploy: it carries the kit's email copy in its own bundle, and the theme and any
|
|
200
|
+
* override sentences in vars stamped at provision (`docs/I18N.md`). So a send Worker whose copy has
|
|
201
|
+
* drifted from the Worker that enqueued is not a window a fast send outruns — it stands until the two
|
|
202
|
+
* are back in step, and an immediate send lands inside it like any other. This is a record of what
|
|
203
|
+
* was queued, never a promise about the delivered sentence — a trail that must reflect delivery reads
|
|
204
|
+
* the row back after the send.
|
|
205
|
+
*
|
|
206
|
+
* Present on every result, including a `suppressed` one: the withheld row carries a rendered subject
|
|
207
|
+
* like any other, no send will ever rewrite it, and a message that reached nobody is the one an
|
|
208
|
+
* operator most needs on the record.
|
|
209
|
+
*
|
|
210
|
+
* **Deliberately not the body.** A body is large, it is the thing this capability is careful never to
|
|
211
|
+
* log, and no caller has a reason to hold one — `runSend` renders it inside the Workflow, at the
|
|
212
|
+
* moment it leaves, and that is the only place it exists.
|
|
213
|
+
*/
|
|
214
|
+
subject: string;
|
|
215
|
+
}
|
|
216
|
+
/** Enqueue an email job, dispatching the send Workflow immediately when the mode is `immediate`. */
|
|
217
|
+
export declare function enqueueEmail(deps: EnqueueDeps, input: EnqueueInput): Promise<EnqueueResult>;
|
|
218
|
+
//# sourceMappingURL=enqueue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enqueue.d.ts","sourceRoot":"","sources":["../../src/send/enqueue.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,EAAE,KAAK,kBAAkB,EAAmC,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAMrD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAmB;IAClC,MAAM,CAAC,OAAO,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE;YAAE,MAAM,EAAE,MAAM,EAAE,CAAA;SAAE,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAClF;AAED,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,6BAA6B;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,qFAAqF;IACrF,OAAO,EAAE,OAAO,CAAC;IACjB,0CAA0C;IAC1C,IAAI,CAAC,EAAE,QAAQ,CAAC;IAChB,uDAAuD;IACvD,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kDAAkD;IAClD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,wFAAwF;IACxF,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,wFAAwF;IACxF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wGAAwG;IACxG,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,8GAA8G;AAC9G,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,aAAa,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,UAAU,CAAC;IAClB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,mHAAmH;IACnH,MAAM,CAAC,EAAE,mBAAmB,CAAC;IAC7B;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,wBAAwB,CAAC;IACzC,GAAG,EAAE,IAAI,CAAC;IACV,gDAAgD;IAChD,KAAK,EAAE,MAAM,MAAM,CAAC;IACpB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,MAAM,CAAC;CAC3B;AAED,sEAAsE;AACtE,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd;;;;;;;;;OASG;IACH,MAAM,EAAE,cAAc,CAAC;IACvB;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAgBD,oGAAoG;AACpG,wBAAsB,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAoJjG"}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { EmailJob } from "../data/emailJob.js";
|
|
4
|
+
import { recordEvent } from "./events.js";
|
|
5
|
+
import { blockingSuppression } from "./suppression.js";
|
|
6
|
+
import { EmailInvalidPayloadError } from "../error/errors.js";
|
|
7
|
+
import { emailTranslator, kitEmailLayers } from "../templates/messages.js";
|
|
8
|
+
import { getTemplate, renderSubject, templateKind } from "../templates/engine.js";
|
|
9
|
+
import { mintBatchId } from "./batchIdentity.js";
|
|
10
|
+
import { resolveTimezoneSendAt } from "./sendAt.js";
|
|
11
|
+
import { normalizeAddress } from "@pithy-sh/core/src/address/address";
|
|
12
|
+
import { isLocale } from "@pithy-sh/core/src/i18n/locale";
|
|
13
|
+
//#region src/send/enqueue.ts
|
|
14
|
+
/** Resolve the absolute send time and initial status from the requested mode. */
|
|
15
|
+
function resolveSchedule(input, now) {
|
|
16
|
+
const mode = input.mode ?? "immediate";
|
|
17
|
+
if (mode === "immediate") return {
|
|
18
|
+
mode,
|
|
19
|
+
sendAt: now,
|
|
20
|
+
status: "pending"
|
|
21
|
+
};
|
|
22
|
+
if (mode === "scheduled") {
|
|
23
|
+
if (!input.sendAt) throw new EmailInvalidPayloadError({ detail: "scheduled mode requires an absolute sendAt" });
|
|
24
|
+
return {
|
|
25
|
+
mode,
|
|
26
|
+
sendAt: input.sendAt,
|
|
27
|
+
status: "scheduled"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
if (!input.localTime || !input.timezone) throw new EmailInvalidPayloadError({ detail: "timezone mode requires localTime and timezone" });
|
|
31
|
+
return {
|
|
32
|
+
mode,
|
|
33
|
+
sendAt: resolveTimezoneSendAt(input.localTime, input.timezone, now),
|
|
34
|
+
status: "scheduled"
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Enqueue an email job, dispatching the send Workflow immediately when the mode is `immediate`. */
|
|
38
|
+
async function enqueueEmail(deps, input) {
|
|
39
|
+
const template = getTemplate(input.template);
|
|
40
|
+
const translator = emailTranslator(input.locale, deps.layersFor ?? kitEmailLayers);
|
|
41
|
+
const subject = renderSubject(input.template, input.payload, deps.theme, translator);
|
|
42
|
+
const { mode, sendAt, status: scheduled } = resolveSchedule(input, deps.now);
|
|
43
|
+
/**
|
|
44
|
+
* Whether the suppression list withholds *this* message from *this* address.
|
|
45
|
+
*
|
|
46
|
+
* `templateKind(input.template)` and never a literal — `runSend` reads the same accessor, and the two
|
|
47
|
+
* agreeing is what makes a hard bounce withhold an invitation while an unsubscribe does not. A caller
|
|
48
|
+
* cannot influence this and is not asked to: it is the template's own declaration.
|
|
49
|
+
*/
|
|
50
|
+
const blocked = deps.suppressionDb ? await blockingSuppression(deps.suppressionDb, input.to, deps.now, templateKind(input.template)) : null;
|
|
51
|
+
const recipient = normalizeAddress(input.to);
|
|
52
|
+
const sender = !blocked && mode === "immediate" ? deps.sender : void 0;
|
|
53
|
+
/**
|
|
54
|
+
* An immediate job with nothing to dispatch it on (pithy-sh/pithy#410).
|
|
55
|
+
*
|
|
56
|
+
* A missing binding is a **configuration fact known at compose time**, not a transient failure, and
|
|
57
|
+
* the two used to be recorded identically: both left the row `pending` and told the caller "on its
|
|
58
|
+
* way". That reads as deferral because of the scheduler's safety net — but the net is the
|
|
59
|
+
* every-minute cron on the host worker, and a composition with no send Workflow binding has no host
|
|
60
|
+
* worker either. So there is nothing to defer to *yet*, and `pending` was a promise the deployment
|
|
61
|
+
* could not keep. A magic link enqueued under `pithy dev` sat in that state forever while the sign-in
|
|
62
|
+
* screen said "check your inbox".
|
|
63
|
+
*
|
|
64
|
+
* It is a truthful status, never a grave. The day a host is deployed, its first tick claims these
|
|
65
|
+
* rows exactly as it claims a stranded `pending` one — a tick running at all is the host existing —
|
|
66
|
+
* so mail enqueued before `pithy email provision` is delayed and not lost.
|
|
67
|
+
*
|
|
68
|
+
* A `scheduled` or `timezone` job is deliberately not this: the scheduler claims it by `sendAt` and
|
|
69
|
+
* never needed a binding at enqueue. Nor is a suppressed recipient, which has its own status and its
|
|
70
|
+
* own event. This is only the case where the caller asked for a send now and nothing exists to make
|
|
71
|
+
* one.
|
|
72
|
+
*/
|
|
73
|
+
const undispatchable = !blocked && mode === "immediate" && !deps.sender;
|
|
74
|
+
const status = blocked ? "suppressed" : undispatchable ? "undispatched" : scheduled;
|
|
75
|
+
/**
|
|
76
|
+
* The batch this enqueue is about to start — named here, before the row exists, because the row has to
|
|
77
|
+
* carry it (pithy-sh/pithy#342).
|
|
78
|
+
*
|
|
79
|
+
* Without it the row is born naming nobody, and a row naming nobody is stranded by definition: the
|
|
80
|
+
* scheduler's safety net claims any `pending` job older than `graceMs` and starts a *second* send
|
|
81
|
+
* Workflow for it. That is not a hypothetical race with a slow enqueue — it is the ordinary shape of a
|
|
82
|
+
* transient send failure. `runSend` throws on a retryable error so the Workflow step backs off, and a
|
|
83
|
+
* backoff writes nothing at all, so the very first retry leaves the row looking exactly like a dispatch
|
|
84
|
+
* that died. `runSend` short-circuits only a job already `sent`, so both instances would render and
|
|
85
|
+
* both would call the Email Service. One person, two emails.
|
|
86
|
+
*
|
|
87
|
+
* Null for a `scheduled` or `timezone` job, and for an immediate one with no binding, because in those
|
|
88
|
+
* cases nothing is coming for the row and saying otherwise would hold it against a batch that does not
|
|
89
|
+
* exist.
|
|
90
|
+
*/
|
|
91
|
+
const batchId = sender ? (deps.newBatchId ?? mintBatchId)() : null;
|
|
92
|
+
const marketing = template.category === "marketing";
|
|
93
|
+
const job = {
|
|
94
|
+
id: deps.newId(),
|
|
95
|
+
toAddress: input.to,
|
|
96
|
+
recipientKey: recipient,
|
|
97
|
+
fromAddress: deps.fromAddress,
|
|
98
|
+
fromName: deps.fromName,
|
|
99
|
+
subject,
|
|
100
|
+
template: input.template,
|
|
101
|
+
category: template.category,
|
|
102
|
+
payload: input.payload,
|
|
103
|
+
payloadRedactedAt: null,
|
|
104
|
+
status,
|
|
105
|
+
mode,
|
|
106
|
+
attempts: 0,
|
|
107
|
+
batchId,
|
|
108
|
+
sendAt,
|
|
109
|
+
timezone: input.timezone ?? null,
|
|
110
|
+
localTime: input.localTime ?? null,
|
|
111
|
+
campaignId: input.campaignId ?? null,
|
|
112
|
+
locale: isLocale(input.locale ?? "") ? input.locale ?? null : null,
|
|
113
|
+
correlation: input.correlation ?? null,
|
|
114
|
+
openTracking: input.openTracking ?? marketing,
|
|
115
|
+
clickTracking: input.clickTracking ?? marketing,
|
|
116
|
+
messageId: null,
|
|
117
|
+
error: blocked ? `recipient suppressed: ${blocked}` : undispatchable ? "no EMAIL_SENDER binding: this composition can start no send Workflow" : null,
|
|
118
|
+
bounceCode: null,
|
|
119
|
+
bounceType: null,
|
|
120
|
+
replyTo: input.replyTo ?? null,
|
|
121
|
+
inReplyTo: input.inReplyTo ?? null,
|
|
122
|
+
references: input.references ?? null,
|
|
123
|
+
createdAt: deps.now,
|
|
124
|
+
updatedAt: deps.now,
|
|
125
|
+
sentAt: null
|
|
126
|
+
};
|
|
127
|
+
await deps.db.insertInto("pithyEmailJobs").values(EmailJob.encode(job)).execute();
|
|
128
|
+
if (blocked) {
|
|
129
|
+
await recordEvent(deps.db, {
|
|
130
|
+
jobId: job.id,
|
|
131
|
+
recipient,
|
|
132
|
+
type: "suppressed",
|
|
133
|
+
detail: blocked
|
|
134
|
+
}, deps.now);
|
|
135
|
+
return {
|
|
136
|
+
jobId: job.id,
|
|
137
|
+
status,
|
|
138
|
+
subject,
|
|
139
|
+
suppressionReason: blocked
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
if (sender && batchId) try {
|
|
143
|
+
await sender.create({
|
|
144
|
+
id: batchId,
|
|
145
|
+
params: { jobIds: [job.id] }
|
|
146
|
+
});
|
|
147
|
+
} catch {}
|
|
148
|
+
return {
|
|
149
|
+
jobId: job.id,
|
|
150
|
+
status,
|
|
151
|
+
subject
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
//#endregion
|
|
155
|
+
export { enqueueEmail };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
|
|
4
|
+
/**
|
|
5
|
+
* Map a Cloudflare Email Service binding error (thrown with an `E_*` `.code`) to a Pithy error and a
|
|
6
|
+
* retry decision. The codes are documented at
|
|
7
|
+
* https://developers.cloudflare.com/email-service/api/send-emails/rest-api/ and in the binding's error
|
|
8
|
+
* table. Retryable codes (rate/quota/transient delivery) are surfaced so the send Workflow re-drives
|
|
9
|
+
* them with backoff; validation/sender/content codes are terminal — retrying cannot help.
|
|
10
|
+
*/
|
|
11
|
+
/** How a given send error is handled: which Pithy error to raise, and whether the send Workflow retries. */
|
|
12
|
+
export interface ClassifiedSendError {
|
|
13
|
+
/** The `E_*` code reported by the binding, or `E_UNKNOWN` when none was present. */
|
|
14
|
+
code: string;
|
|
15
|
+
/** Whether the send should be retried with backoff. */
|
|
16
|
+
retryable: boolean;
|
|
17
|
+
/** Whether the failure means the recipient is suppressed (so the address should be locally suppressed). */
|
|
18
|
+
suppressed: boolean;
|
|
19
|
+
/** The Pithy error carrying the public-safe message and the code/detail for logs. */
|
|
20
|
+
error: PithyError;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Classify a send failure. `E_RECIPIENT_SUPPRESSED` is terminal and means the address must be
|
|
24
|
+
* suppressed locally too; rate/quota and transient delivery codes are retryable; everything else
|
|
25
|
+
* (validation, sender, content, headers) is terminal. An unknown code is treated as a transient
|
|
26
|
+
* failure so a momentary fault gets one bounded retry rather than failing the job outright.
|
|
27
|
+
*/
|
|
28
|
+
export declare function classifySendError(err: unknown): ClassifiedSendError;
|
|
29
|
+
//# sourceMappingURL=errorMapping.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorMapping.d.ts","sourceRoot":"","sources":["../../src/send/errorMapping.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AAGtE;;;;;;GAMG;AAEH,4GAA4G;AAC5G,MAAM,WAAW,mBAAmB;IAClC,oFAAoF;IACpF,IAAI,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,SAAS,EAAE,OAAO,CAAC;IACnB,2GAA2G;IAC3G,UAAU,EAAE,OAAO,CAAC;IACpB,qFAAqF;IACrF,KAAK,EAAE,UAAU,CAAC;CACnB;AAuBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,GAAG,mBAAmB,CAmBnE"}
|