@pithy-sh/email 0.1.6 → 0.2.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.
@@ -26,6 +26,8 @@ import { type ManagedEnvironment } from "@pithy-sh/secrets/src/scope";
26
26
  */
27
27
  /** The capability segment every email-owned name carries — the migration namespace and error domain too. */
28
28
  export declare const EMAIL_CAPABILITY = "email";
29
+ /** The D1 binding the suppression database is bound to, in every Worker and every environment. */
30
+ export declare const EMAIL_SUPPRESSIONS_BINDING = "EMAIL_SUPPRESSIONS";
29
31
  /**
30
32
  * The shared, durable suppression database — **one per project, shared across that project's
31
33
  * environments**: `<project>-global-email-suppressions`.
@@ -44,6 +46,17 @@ export declare const EMAIL_CAPABILITY = "email";
44
46
  *
45
47
  * Composed through core's naming facade under the **`d1`** namespace, so the name is measured against
46
48
  * a D1 database name's limit rather than the single 63 the generic composer defaults to.
49
+ *
50
+ * **Through {@link bindingResourceName}, the same expression `pithy add` and `pithy provision` compose
51
+ * with — because until #513 it was a *different* expression, and that was the defect.** This function
52
+ * said `<project>-global-email-suppressions` while the two writers said `<project>-<env>-email-
53
+ * suppressions`, so `pithy add email` wrote three per-environment databases into `wrangler.jsonc` and
54
+ * `pithy email provision` created the one this names. The app Worker and the email Worker then read
55
+ * different suppression lists, and an unsubscribe recorded on either was invisible to the other. One
56
+ * expression, driven by one declaration, is what makes that unexpressible rather than merely fixed.
57
+ *
58
+ * The output is byte-identical to what it always was: `kebab("EMAIL_SUPPRESSIONS")` is
59
+ * `email-suppressions`, and the composer's `global` branch is the facade call this used to make directly.
47
60
  */
48
61
  export declare function suppressionDatabaseName(project: string): string;
49
62
  /**
@@ -108,12 +121,17 @@ export interface EmailProvisionResult {
108
121
  }
109
122
  /**
110
123
  * Provision the email infrastructure: create + migrate the shared suppression DB once, then deploy the
111
- * email worker for every managed environment. The order matters — the suppression DB exists and is
124
+ * email worker for every environment given. The order matters — the suppression DB exists and is
112
125
  * migrated before any worker that binds it is deployed. Idempotent end to end (each step is).
113
126
  *
114
- * `environments` is the project's declaration from the root `pithy.config.ts` (#241). Every declared
115
- * environment is provisioned; an environment this skipped would be one the project deploys to with no
116
- * resources behind it — the silence the closed `ManagedEnvironment` enum used to produce.
127
+ * `environments` is **what the caller determined it can act on**, which the CLI narrows from the project's
128
+ * declaration (#241) to the environments whose app database exists (pithy-sh/pithy#512). Nothing is
129
+ * skipped here and nothing decides here: an environment reaching this list is provisioned, and one that
130
+ * did not was already reported to the operator by name, with why and with the command that fixes it.
131
+ *
132
+ * The suppression database is created **whatever the list holds, including nothing**. It is one per
133
+ * project, shared across every environment, and making it wait for the last environment to be provisioned
134
+ * is exactly the ordering this change exists to undo.
117
135
  */
118
136
  export declare function provisionEmail(provisioner: EmailProvisioner, environments: DeclaredEnvironments | readonly string[]): Promise<EmailProvisionResult>;
119
137
  /** The teardown seam — the inverse of {@link EmailProvisioner}. Every step idempotent (a missing resource is a no-op). */
@@ -1 +1 @@
1
- {"version":3,"file":"provisionEmail.d.ts","sourceRoot":"","sources":["../../src/provision/provisionEmail.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAIlF,OAAO,EAAE,KAAK,kBAAkB,EAAuB,MAAM,6BAA6B,CAAC;AAE3F;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,4GAA4G;AAC5G,eAAO,MAAM,gBAAgB,UAAU,CAAC;AAExC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,kBAAkB,GAAG,MAAM,CAEhF;AAED,uEAAuE;AACvE,MAAM,WAAW,gBAAg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B,IAAI,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CACtE;AAED,kCAAkC;AAClC,MAAM,WAAW,oBAAoB;IACnC,qBAAqB,EAAE,MAAM,CAAC;IAC9B,YAAY,EAAE,kBAAkB,EAAE,CAAC;IACnC,kGAAkG;IAClG,OAAO,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;CACjD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,gBAAgB,EAC7B,YAAY,EAAE,oBAAoB,GAAG,SAAS,MAAM,EAAE,GACrD,OAAO,CAAC,oBAAoB,CAAC,CAc/B;AAED,0HAA0H;AAC1H,MAAM,WAAW,kBAAkB;IACjC,+EAA+E;IAC/E,YAAY,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD;;;;OAIG;IACH,yBAAyB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C;AAED,+GAA+G;AAC/G,MAAM,WAAW,uBAAuB;IACtC,gGAAgG;IAChG,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CACpC,aAAa,EAAE,kBAAkB,EACjC,YAAY,EAAE,oBAAoB,GAAG,SAAS,MAAM,EAAE,EACtD,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,IAAI,CAAC,CAKf"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { GLOBAL_SCOPE } from "@pithy-sh/core/src/naming/environment";
4
+ import { bindingResourceName } from "@pithy-sh/core/src/naming/provisionScope";
4
5
  import { resourceName } from "@pithy-sh/core/src/naming/resource";
5
6
  import { resourceNames } from "@pithy-sh/core/src/naming/resourceNames";
6
7
  import { managedEnvironments } from "@pithy-sh/secrets/src/scope";
@@ -29,6 +30,16 @@ import { managedEnvironments } from "@pithy-sh/secrets/src/scope";
29
30
  */
30
31
  /** The capability segment every email-owned name carries — the migration namespace and error domain too. */
31
32
  const EMAIL_CAPABILITY = "email";
33
+ /** The D1 binding the suppression database is bound to, in every Worker and every environment. */
34
+ const EMAIL_SUPPRESSIONS_BINDING = "EMAIL_SUPPRESSIONS";
35
+ /**
36
+ * What `packages/email/pithy.manifest.json` declares about naming {@link EMAIL_SUPPRESSIONS_BINDING} —
37
+ * restated here because a bundled Worker package cannot read its own manifest, and **pinned to it by
38
+ * `cli/src/ci/bindingResourceNames.test.ts`**, which fails the moment the two answers differ.
39
+ *
40
+ * No `resource`: `email-suppressions` is the kebabbed binding, which is what the composer already uses.
41
+ */
42
+ const EMAIL_SUPPRESSIONS_NAMING = { scope: GLOBAL_SCOPE };
32
43
  /**
33
44
  * The shared, durable suppression database — **one per project, shared across that project's
34
45
  * environments**: `<project>-global-email-suppressions`.
@@ -47,9 +58,20 @@ const EMAIL_CAPABILITY = "email";
47
58
  *
48
59
  * Composed through core's naming facade under the **`d1`** namespace, so the name is measured against
49
60
  * a D1 database name's limit rather than the single 63 the generic composer defaults to.
61
+ *
62
+ * **Through {@link bindingResourceName}, the same expression `pithy add` and `pithy provision` compose
63
+ * with — because until #513 it was a *different* expression, and that was the defect.** This function
64
+ * said `<project>-global-email-suppressions` while the two writers said `<project>-<env>-email-
65
+ * suppressions`, so `pithy add email` wrote three per-environment databases into `wrangler.jsonc` and
66
+ * `pithy email provision` created the one this names. The app Worker and the email Worker then read
67
+ * different suppression lists, and an unsubscribe recorded on either was invisible to the other. One
68
+ * expression, driven by one declaration, is what makes that unexpressible rather than merely fixed.
69
+ *
70
+ * The output is byte-identical to what it always was: `kebab("EMAIL_SUPPRESSIONS")` is
71
+ * `email-suppressions`, and the composer's `global` branch is the facade call this used to make directly.
50
72
  */
51
73
  function suppressionDatabaseName(project) {
52
- return resourceNames(project).global.d1(`${EMAIL_CAPABILITY}-suppressions`);
74
+ return bindingResourceName(project, EMAIL_SUPPRESSIONS_BINDING, "d1", EMAIL_SUPPRESSIONS_NAMING);
53
75
  }
54
76
  /**
55
77
  * The name of the inbound Email Routing rule that delivers bounce and complaint mail to the app worker.
@@ -84,23 +106,31 @@ function emailWorkerName(project, env) {
84
106
  }
85
107
  /**
86
108
  * Provision the email infrastructure: create + migrate the shared suppression DB once, then deploy the
87
- * email worker for every managed environment. The order matters — the suppression DB exists and is
109
+ * email worker for every environment given. The order matters — the suppression DB exists and is
88
110
  * migrated before any worker that binds it is deployed. Idempotent end to end (each step is).
89
111
  *
90
- * `environments` is the project's declaration from the root `pithy.config.ts` (#241). Every declared
91
- * environment is provisioned; an environment this skipped would be one the project deploys to with no
92
- * resources behind it — the silence the closed `ManagedEnvironment` enum used to produce.
112
+ * `environments` is **what the caller determined it can act on**, which the CLI narrows from the project's
113
+ * declaration (#241) to the environments whose app database exists (pithy-sh/pithy#512). Nothing is
114
+ * skipped here and nothing decides here: an environment reaching this list is provisioned, and one that
115
+ * did not was already reported to the operator by name, with why and with the command that fixes it.
116
+ *
117
+ * The suppression database is created **whatever the list holds, including nothing**. It is one per
118
+ * project, shared across every environment, and making it wait for the last environment to be provisioned
119
+ * is exactly the ordering this change exists to undo.
93
120
  */
94
121
  async function provisionEmail(provisioner, environments) {
95
122
  await provisioner.preflight();
96
123
  const { databaseId } = await provisioner.ensureSuppressionDatabase();
97
124
  await provisioner.migrateSuppression(databaseId);
98
- for (const env of managedEnvironments(environments)) await provisioner.deployWorker(env, databaseId);
99
- const routing = await provisioner.ensureRoutingRule();
125
+ const deployed = managedEnvironments(environments);
126
+ for (const env of deployed) await provisioner.deployWorker(env, databaseId);
100
127
  return {
101
128
  suppressionDatabaseId: databaseId,
102
- environments: managedEnvironments(environments),
103
- routing
129
+ environments: deployed,
130
+ routing: deployed.length > 0 ? await provisioner.ensureRoutingRule() : {
131
+ created: false,
132
+ skipped: true
133
+ }
104
134
  };
105
135
  }
106
136
  /**
@@ -117,4 +147,4 @@ async function deprovisionEmail(deprovisioner, environments, options = {}) {
117
147
  if (options.deleteSuppression) await deprovisioner.deleteSuppressionDatabase();
118
148
  }
119
149
  //#endregion
120
- export { EMAIL_CAPABILITY, bounceRoutingRuleName, deprovisionEmail, emailWorkerName, provisionEmail, suppressionDatabaseName };
150
+ export { EMAIL_CAPABILITY, EMAIL_SUPPRESSIONS_BINDING, bounceRoutingRuleName, deprovisionEmail, emailWorkerName, provisionEmail, suppressionDatabaseName };
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/email";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.1.6";
6
+ export declare const PACKAGE_VERSION = "0.2.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/email";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.1.6";
7
+ const PACKAGE_VERSION = "0.2.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -1 +1 @@
1
- {"version":3,"file":"hostApp.d.ts","sourceRoot":"","sources":["../../src/workflows/hostApp.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAGjE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAI5B;;;;;;;;;;;;;;;;;;GAkBG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;CAClB;AAED,mGAAmG;AACnG,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAAC,YAAY,CAAC,CAYxF"}
1
+ {"version":3,"file":"hostApp.d.ts","sourceRoot":"","sources":["../../src/workflows/hostApp.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAGjE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAI5B;;;;;;;;;;;;;;;;;;GAkBG;AAEH,2EAA2E;AAC3E,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;CAClB;AAED,mGAAmG;AACnG,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,IAAI,CAAC,YAAY,CAAC,CAaxF"}
@@ -2,14 +2,14 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { EMAIL_CAPABILITY } from "../provision/provisionEmail.js";
4
4
  import { emailWorkflowRegistry } from "../provision/resolveEmailConfig.js";
5
- import { pithyErrorHandler } from "@pithy-sh/core/src/error/http";
5
+ import { loggingErrorHandler } from "@pithy-sh/core/src/logger/errorHandler";
6
6
  import { registerWorkflowDispatchRoute } from "@pithy-sh/core/src/workflow/dispatchRoute";
7
7
  import { Hono } from "hono";
8
8
  //#region src/workflows/hostApp.ts
9
9
  /** Build the email host worker's app: the Pithy error handler, and the workflow dispatch route. */
10
10
  function createEmailHostApp(options = {}) {
11
11
  const app = new Hono();
12
- app.onError(pithyErrorHandler);
12
+ app.onError(loggingErrorHandler);
13
13
  registerWorkflowDispatchRoute(app, {
14
14
  capability: EMAIL_CAPABILITY,
15
15
  registry: emailWorkflowRegistry,
@@ -97,7 +97,7 @@ const EmailHostEnv = z.object({
97
97
  ENVIRONMENT: z.string().min(1).optional().describe("The environment this host was deployed for. Stamped on every send as `X-Pithy-Env`, which is how the single inbound bounce worker attributes a bounce back to the environment that sent it."),
98
98
  LINK_TTL_DAYS: tunedNumber(90).describe("How long a signed tracking or unsubscribe link stays valid, in days. Long by design: the link is minted into mail nobody can recall, and an unsubscribe that has expired is a complaint."),
99
99
  MAX_ATTEMPTS: tunedNumber(5).describe("How many times one job may be attempted before it is failed terminally. Spent attempts are what separates a provider hiccup from an address that will never accept mail."),
100
- SCHEDULER_ENABLED: z.enum(["true", "false"]).describe("The var as wrangler binds it — a string, and only these two spellings of it.").default("true").transform((value) => value === "true").describe("Whether the every-minute scheduler Workflow runs. `false` stops due jobs being claimed at all — the cron still fires and does nothing — so it is a maintenance switch, not a tuning knob."),
100
+ SCHEDULER_ENABLED: z.enum(["true", "false"]).describe("The var as wrangler binds it — a string, and only these two spellings of it.").default("true").transform((value) => value === "true").describe("Whether the every-minute scheduler Workflow runs. `false` stops due jobs being claimed at all — the cron still fires, and does not even look — so it is a maintenance switch, not a tuning knob."),
101
101
  SCHEDULER_BATCH_SIZE: tunedNumber(50).describe("How many jobs one send Workflow instance takes. Each job is a durable step, so this is the unit of retry and of the instance's report."),
102
102
  SCHEDULER_MAX_JOBS: tunedNumber(500).describe("The most rows one scheduler tick will claim. A ceiling on the work a single minute can start, so a backlog drains steadily rather than in one instance-creating burst."),
103
103
  SCHEDULER_GRACE_MS: tunedNumber(12e4).describe("How long an immediate job is left alone before the safety net treats it as stranded, in milliseconds. The window a freshly-enqueued job's own dispatch has to land in; too short re-drives sends that were already on their way."),
@@ -6,8 +6,9 @@ import type { EmailDatabase } from "../data/tables";
6
6
  * arrived, plus the safety net of `pending` and `undispatched` immediate jobs that never dispatched and
7
7
  * `sending` jobs left stale by a dead dispatch — claims them (status → `sending`, so the next tick won't
8
8
  * repick them), and fans them out into sender batches. **The fan-out scales with volume:** the more rows are due, the
9
- * more batches are dispatched, each its own durable send Workflow. Cron is cheap; this runs every
10
- * minute and does nothing when nothing is due.
9
+ * more batches are dispatched, each its own durable send Workflow. The cron probes for a due row
10
+ * first ({@link hasDueJobs}) and creates no instance at all when there is none, so an idle minute
11
+ * costs one read rather than a Workflow and a billed step (pithy-sh/pithy#538).
11
12
  *
12
13
  * Jobs are claimed before dispatch, so a dispatch failure strands a row in `sending` rather than
13
14
  * double-sending; the `sending` re-drive recovers it on a later tick, and `runSend`'s idempotency makes
@@ -19,9 +20,16 @@ import type { EmailDatabase } from "../data/tables";
19
20
  * the re-drive decision (pithy-sh/pithy#342), and it costs the claim one column and the tick one question
20
21
  * per batch.
21
22
  */
22
- /** Inputs the scheduler needs. `dispatch` creates one send Workflow per batch. */
23
- export interface SchedulerDeps {
23
+ /**
24
+ * What it takes to ask whether anything is due — the database and the three numbers that define
25
+ * "due", and nothing else.
26
+ *
27
+ * It is the front half of {@link SchedulerDeps} rather than a type beside it, so the cron's probe and
28
+ * the tick cannot be pointed at different databases or measured against different windows.
29
+ */
30
+ export interface DueProbeDeps {
24
31
  db: EmailDatabase;
32
+ /** The instant this tick measures every cutoff from. */
25
33
  now: Date;
26
34
  /** How stale (ms) a `pending`/`undispatched` immediate job must be before the safety net re-drives it. */
27
35
  graceMs: number;
@@ -38,6 +46,9 @@ export interface SchedulerDeps {
38
46
  * slower horse, and the queue gets longer.
39
47
  */
40
48
  stuckMs: number;
49
+ }
50
+ /** Inputs the scheduler needs. `dispatch` creates one send Workflow per batch. */
51
+ export interface SchedulerDeps extends DueProbeDeps {
41
52
  /**
42
53
  * Jobs per dispatched batch — one send Workflow each. From `SCHEDULER_BATCH_SIZE`.
43
54
  *
@@ -79,6 +90,38 @@ export interface SchedulerResult {
79
90
  /** How many stale-looking jobs were left alone because the batch holding them is still alive. */
80
91
  held: number;
81
92
  }
93
+ /**
94
+ * Is anything due? The question the every-minute cron asks **before** it creates a Workflow instance
95
+ * (pithy-sh/pithy#538).
96
+ *
97
+ * It used to be asked from inside the instance, so an idle minute cost a Workflow creation and a
98
+ * billed step to discover there was nothing to do — 1,440 of each per day per environment, against a
99
+ * Workers Free allowance of 3,000 steps a day for the whole account. Now an idle minute costs one
100
+ * indexed read and creates nothing.
101
+ *
102
+ * **It is deliberately the wider question.** It reads rows, not batches, so a stale row whose batch is
103
+ * still alive wakes the scheduler and the tick then declines to re-drive it — one instance, spent
104
+ * being right. The opposite asymmetry is the one that loses mail, which is why both sides share
105
+ * {@link isDue} rather than agreeing by inspection.
106
+ */
107
+ export declare function hasDueJobs(deps: DueProbeDeps): Promise<boolean>;
108
+ /**
109
+ * The whole of what the cron asks before it creates anything: **is this scheduler configured, and is
110
+ * anything due** — in that order (pithy-sh/pithy#538).
111
+ *
112
+ * The order is the point. {@link assertBatchSize} was written to run before the tick does any work, so
113
+ * that a misconfigured worker says so on its first tick rather than on its first busy one; the probe
114
+ * that now stands in front of the tick would have postponed it to the first minute a job came due. An
115
+ * idle cron that quietly accepts a broken batch size is the shape of the bug this file has already
116
+ * been bitten by twice, and "quietly" is what the probe would have restored.
117
+ *
118
+ * It takes the tick's own {@link SchedulerDeps} rather than the probe's {@link DueProbeDeps}, because
119
+ * the question is about the configuration the tick would run under. The email host validates the same
120
+ * number a second way — `SCHEDULER_BATCH_SIZE` is coerced and refused by `hostEnv.ts` before this is
121
+ * reached — so on that path this is a second lock on one door. It is the module's own invariant, and
122
+ * it holds for any caller that assembles deps itself.
123
+ */
124
+ export declare function schedulerHasWork(deps: SchedulerDeps): Promise<boolean>;
82
125
  /** Run one scheduler tick: find due rows, claim them, fan out batches. */
83
126
  export declare function runScheduler(deps: SchedulerDeps): Promise<SchedulerResult>;
84
127
  //# sourceMappingURL=scheduler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../src/workflows/scheduler.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;;;;;;;;;GAiBG;AAEH,kFAAkF;AAClF,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,aAAa,CAAC;IAClB,GAAG,EAAE,IAAI,CAAC;IACV,0GAA0G;IAC1G,OAAO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C1C,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,EAAE,MAAM,MAAM,CAAC;IACzB;;;;;;;;;;;;OAYG;IACH,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACpD,8FAA8F;IAC9F,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChE;AAED,mCAAmC;AACnC,MAAM,WAAW,eAAe;IAC9B,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,iGAAiG;IACjG,IAAI,EAAE,MAAM,CAAC;CACd;AAuHD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAQrE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,CAG5E;AAED,0EAA0E;AAC1E,wBAAsB,YAAY,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,eAAe,CAAC,CA0ChF"}
@@ -68,17 +68,76 @@ async function strandedIds(deps, rows) {
68
68
  }
69
69
  return stranded;
70
70
  }
71
+ /** Derive this tick's cutoffs. The tick claims against the same `nowMs` it selected against. */
72
+ function dueCutoffs(deps) {
73
+ const nowMs = deps.now.getTime();
74
+ return {
75
+ nowMs,
76
+ graceCutoff: nowMs - deps.graceMs,
77
+ stuckCutoff: nowMs - deps.stuckMs
78
+ };
79
+ }
80
+ /**
81
+ * **"Due" — the one definition.** Three branches over four statuses: a `scheduled` job whose `sendAt`
82
+ * has arrived, a `pending` or `undispatched` immediate job past its grace, and a `sending` job past
83
+ * `stuckMs`.
84
+ *
85
+ * It is a function rather than a clause typed into a query because two callers ask it now: the tick
86
+ * below, and the cron's probe ({@link hasDueJobs}) that decides whether to create the tick at all
87
+ * (pithy-sh/pithy#538). A second copy would be a second definition, and the drift is silent in the
88
+ * worst way — a probe that stops matching a branch never wakes the scheduler for those rows, and they
89
+ * sit there with nothing logged. This file has been bitten twice by that shape already: the `NaN`
90
+ * batch size that produced one empty batch a minute, and the `undispatched` dead end (#410).
91
+ */
92
+ function isDue(cutoffs) {
93
+ return (eb) => eb.or([
94
+ eb.and([eb("status", "=", "scheduled"), eb("sendAt", "<=", cutoffs.nowMs)]),
95
+ eb.and([eb("status", "in", ["pending", "undispatched"]), eb("createdAt", "<=", cutoffs.graceCutoff)]),
96
+ eb.and([eb("status", "=", "sending"), eb("updatedAt", "<=", cutoffs.stuckCutoff)])
97
+ ]);
98
+ }
99
+ /**
100
+ * Is anything due? The question the every-minute cron asks **before** it creates a Workflow instance
101
+ * (pithy-sh/pithy#538).
102
+ *
103
+ * It used to be asked from inside the instance, so an idle minute cost a Workflow creation and a
104
+ * billed step to discover there was nothing to do — 1,440 of each per day per environment, against a
105
+ * Workers Free allowance of 3,000 steps a day for the whole account. Now an idle minute costs one
106
+ * indexed read and creates nothing.
107
+ *
108
+ * **It is deliberately the wider question.** It reads rows, not batches, so a stale row whose batch is
109
+ * still alive wakes the scheduler and the tick then declines to re-drive it — one instance, spent
110
+ * being right. The opposite asymmetry is the one that loses mail, which is why both sides share
111
+ * {@link isDue} rather than agreeing by inspection.
112
+ */
113
+ async function hasDueJobs(deps) {
114
+ return await deps.db.selectFrom("pithyEmailJobs").select("id").where(isDue(dueCutoffs(deps))).limit(1).executeTakeFirst() !== void 0;
115
+ }
116
+ /**
117
+ * The whole of what the cron asks before it creates anything: **is this scheduler configured, and is
118
+ * anything due** — in that order (pithy-sh/pithy#538).
119
+ *
120
+ * The order is the point. {@link assertBatchSize} was written to run before the tick does any work, so
121
+ * that a misconfigured worker says so on its first tick rather than on its first busy one; the probe
122
+ * that now stands in front of the tick would have postponed it to the first minute a job came due. An
123
+ * idle cron that quietly accepts a broken batch size is the shape of the bug this file has already
124
+ * been bitten by twice, and "quietly" is what the probe would have restored.
125
+ *
126
+ * It takes the tick's own {@link SchedulerDeps} rather than the probe's {@link DueProbeDeps}, because
127
+ * the question is about the configuration the tick would run under. The email host validates the same
128
+ * number a second way — `SCHEDULER_BATCH_SIZE` is coerced and refused by `hostEnv.ts` before this is
129
+ * reached — so on that path this is a second lock on one door. It is the module's own invariant, and
130
+ * it holds for any caller that assembles deps itself.
131
+ */
132
+ async function schedulerHasWork(deps) {
133
+ assertBatchSize(deps.batchSize);
134
+ return await hasDueJobs(deps);
135
+ }
71
136
  /** Run one scheduler tick: find due rows, claim them, fan out batches. */
72
137
  async function runScheduler(deps) {
73
138
  assertBatchSize(deps.batchSize);
74
- const nowMs = deps.now.getTime();
75
- const graceCutoff = nowMs - deps.graceMs;
76
- const stuckCutoff = nowMs - deps.stuckMs;
77
- const rows = await deps.db.selectFrom("pithyEmailJobs").select(["id", "batchId"]).where((eb) => eb.or([
78
- eb.and([eb("status", "=", "scheduled"), eb("sendAt", "<=", nowMs)]),
79
- eb.and([eb("status", "in", ["pending", "undispatched"]), eb("createdAt", "<=", graceCutoff)]),
80
- eb.and([eb("status", "=", "sending"), eb("updatedAt", "<=", stuckCutoff)])
81
- ])).orderBy("sendAt", "asc").limit(deps.maxJobs).execute();
139
+ const cutoffs = dueCutoffs(deps);
140
+ const rows = await deps.db.selectFrom("pithyEmailJobs").select(["id", "batchId"]).where(isDue(cutoffs)).orderBy("sendAt", "asc").limit(deps.maxJobs).execute();
82
141
  if (rows.length === 0) return {
83
142
  due: 0,
84
143
  batches: 0,
@@ -97,7 +156,7 @@ async function runScheduler(deps) {
97
156
  const batchId = deps.newBatchId();
98
157
  for (const claim of chunkByBoundParameters(batch, CLAIM_FIXED_PARAMETERS)) await deps.db.updateTable("pithyEmailJobs").set({
99
158
  status: "sending",
100
- updatedAt: nowMs,
159
+ updatedAt: cutoffs.nowMs,
101
160
  batchId
102
161
  }).where("id", "in", claim).execute();
103
162
  await deps.dispatch(batchId, batch);
@@ -110,4 +169,4 @@ async function runScheduler(deps) {
110
169
  };
111
170
  }
112
171
  //#endregion
113
- export { runScheduler };
172
+ export { hasDueJobs, runScheduler, schedulerHasWork };
@@ -14,7 +14,7 @@ import { type BatchSendReport } from "./sendBatch";
14
14
  * - `EmailSendWorkflow` — sends a batch of jobs durably (dispatch target for immediate sends and
15
15
  * the scheduler's fan-out).
16
16
  * - `EmailSchedulerWorkflow` — finds due jobs and fans them out into send batches.
17
- * - `scheduled()` — the every-minute cron that fires the scheduler Workflow.
17
+ * - `scheduled()` — the every-minute cron that fires the scheduler Workflow when a row is due.
18
18
  * - `fetch()` — the loopback dispatch door, served only in `dev` (see {@link createEmailHostApp}).
19
19
  *
20
20
  * The bodies (`runSendBatch`, `runScheduler`, `runSend`) are tested against Miniflare; these classes are
@@ -85,7 +85,28 @@ export declare class EmailSchedulerWorkflow extends WorkflowEntrypoint<EmailWork
85
85
  run(_event: WorkflowEvent<unknown>, step: WorkflowStep): Promise<void>;
86
86
  }
87
87
  declare const _default: {
88
- /** Cron entry: fire the scheduler Workflow every minute, unless disabled. */
88
+ /**
89
+ * Cron entry: fire the scheduler Workflow every minute — when there is something to fire it for.
90
+ *
91
+ * The instance used to be created unconditionally, and the "is anything due" question was asked
92
+ * inside it. At `* * * * *` that spends 1,440 instance creations and 1,440 billed steps a day, per
93
+ * environment, discovering nothing to do; Workers Free allows 3,000 steps a day for the whole
94
+ * account, so a default project's staging and prod burn 96% of it sending no mail, and the sends
95
+ * that do happen compete for the rest (pithy-sh/pithy#538).
96
+ *
97
+ * So the question moved out in front: one indexed read on `pithy_email_jobs`, asked with the tick's
98
+ * own predicate rather than a second copy of it, and an instance only when it finds a row. Nothing
99
+ * is lost with the tick that never starts: this is not the path an immediate send takes (`enqueue`
100
+ * starts that Workflow itself), the work is a pure re-derivation from D1, and a lost minute is
101
+ * recovered by the next one exactly as a throwing `create()` has always been.
102
+ *
103
+ * What it does give up is the per-minute instance in the dashboard that proved the scheduler was
104
+ * alive. An idle minute now leaves no trace, by design — the trace was costing a billed step.
105
+ *
106
+ * **Through {@link schedulerHasWork}, so the tick's configuration is checked before the probe.** The
107
+ * batch-size check inside `runScheduler` exists to complain on the first tick rather than the first
108
+ * busy one, and a probe in front of the instance is in front of that check too.
109
+ */
89
110
  scheduled(_controller: unknown, env: EmailWorkerEnv): Promise<void>;
90
111
  /**
91
112
  * The loopback dispatch door — how a sibling worker under `pithy dev` starts a send batch on this
@@ -1 +1 @@
1
- {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../src/workflows/worker.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAE/F,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAG9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAK1E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAKlD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,KAAK,eAAe,EAAoC,MAAM,aAAa,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;;;;;GAMG;AACH,MAAM,WAAW,cAAe,SAAQ,eAAe;IACrD,uEAAuE;IACvE,EAAE,EAAE,UAAU,CAAC;IACf,gDAAgD;IAChD,kBAAkB,EAAE,UAAU,CAAC;IAC/B,iDAAiD;IACjD,KAAK,EAAE,WAAW,CAAC;IACnB,gGAAgG;IAChG,YAAY,EAAE,mBAAmB,GAAG,qBAAqB,CAAC;IAC1D,yDAAyD;IACzD,eAAe,EAAE;QAAE,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,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B;AA2ED;;;;;;;GAOG;AACH,qBAAa,iBAAkB,SAAQ,kBAAkB,CAAC,cAAc,EAAE;IAAE,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;IAI9E,GAAG,CAAC,KAAK,EAAE,aAAa,CAAC;QAAE,MAAM,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAM3G;CACF;AAED,0FAA0F;AAC1F,qBAAa,sBAAuB,SAAQ,kBAAkB,CAAC,cAAc,EAAE,OAAO,CAAC;IACtE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAIpF;CACF;;IAGC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,SAAS,cAAc,OAAO,OAAO,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAOzE;;;;;;;;OAQG;IACG,KAAK,UAAU,OAAO,OAAO,cAAc,OAAO,gBAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC"}
@@ -8,7 +8,7 @@ import { emailHostEnv } from "./hostEnv.js";
8
8
  import { emailWorkflowRetry } from "../send/retryPolicy.js";
9
9
  import { createEmailHostApp } from "./hostApp.js";
10
10
  import { isLiveInstanceStatus } from "./instanceLiveness.js";
11
- import { runScheduler } from "./scheduler.js";
11
+ import { runScheduler, schedulerHasWork } from "./scheduler.js";
12
12
  import { runSendBatch } from "./sendBatch.js";
13
13
  import { configureSharedSecrets } from "@pithy-sh/secrets/src/sharedSecretsStore";
14
14
  import { requireHostEnv } from "@pithy-sh/core/src/workflow/hostEnv";
@@ -48,9 +48,14 @@ async function buildSendDeps(env) {
48
48
  heartbeatAt: () => /* @__PURE__ */ new Date()
49
49
  };
50
50
  }
51
- /** Assemble the scheduler dependencies, dispatching each batch as a send Workflow. */
52
- function buildSchedulerDeps(env) {
53
- const config = hostConfig(env);
51
+ /**
52
+ * Assemble the scheduler dependencies, dispatching each batch as a send Workflow.
53
+ *
54
+ * `config` is a parameter so the cron can validate the env once and hand the answer on: it reads
55
+ * `SCHEDULER_ENABLED` before it probes, and re-parsing the same env object a second line later would
56
+ * be one Zod pass per minute for nothing.
57
+ */
58
+ function buildSchedulerDeps(env, config = hostConfig(env)) {
54
59
  return {
55
60
  db: emailDatabase(env.DB),
56
61
  now: /* @__PURE__ */ new Date(),
@@ -97,9 +102,33 @@ var EmailSchedulerWorkflow = class extends WorkflowEntrypoint {
97
102
  }
98
103
  };
99
104
  var worker_default = {
100
- /** Cron entry: fire the scheduler Workflow every minute, unless disabled. */
105
+ /**
106
+ * Cron entry: fire the scheduler Workflow every minute — when there is something to fire it for.
107
+ *
108
+ * The instance used to be created unconditionally, and the "is anything due" question was asked
109
+ * inside it. At `* * * * *` that spends 1,440 instance creations and 1,440 billed steps a day, per
110
+ * environment, discovering nothing to do; Workers Free allows 3,000 steps a day for the whole
111
+ * account, so a default project's staging and prod burn 96% of it sending no mail, and the sends
112
+ * that do happen compete for the rest (pithy-sh/pithy#538).
113
+ *
114
+ * So the question moved out in front: one indexed read on `pithy_email_jobs`, asked with the tick's
115
+ * own predicate rather than a second copy of it, and an instance only when it finds a row. Nothing
116
+ * is lost with the tick that never starts: this is not the path an immediate send takes (`enqueue`
117
+ * starts that Workflow itself), the work is a pure re-derivation from D1, and a lost minute is
118
+ * recovered by the next one exactly as a throwing `create()` has always been.
119
+ *
120
+ * What it does give up is the per-minute instance in the dashboard that proved the scheduler was
121
+ * alive. An idle minute now leaves no trace, by design — the trace was costing a billed step.
122
+ *
123
+ * **Through {@link schedulerHasWork}, so the tick's configuration is checked before the probe.** The
124
+ * batch-size check inside `runScheduler` exists to complain on the first tick rather than the first
125
+ * busy one, and a probe in front of the instance is in front of that check too.
126
+ */
101
127
  async scheduled(_controller, env) {
102
- if (hostConfig(env).SCHEDULER_ENABLED) await env.EMAIL_SCHEDULER.create();
128
+ const config = hostConfig(env);
129
+ if (!config.SCHEDULER_ENABLED) return;
130
+ if (!await schedulerHasWork(buildSchedulerDeps(env, config))) return;
131
+ await env.EMAIL_SCHEDULER.create();
103
132
  },
104
133
  /**
105
134
  * The loopback dispatch door — how a sibling worker under `pithy dev` starts a send batch on this
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/email",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,14 +38,21 @@
38
38
  "dependencies": {
39
39
  "@cloudflare/workers-types": "^5.20260729.1",
40
40
  "@hono/zod-validator": "^0.9.0",
41
- "@pithy-sh/core": "^0.2.0",
42
- "@pithy-sh/secrets": "^0.1.5",
43
41
  "handlebars": "^4.7.9",
44
42
  "postal-mime": "^3.0.0"
45
43
  },
44
+ "peerDependencies": {
45
+ "@pithy-sh/core": "^0.4.0",
46
+ "@pithy-sh/secrets": "^0.2.0",
47
+ "hono": "^4.13.2",
48
+ "kysely": "^0.29.0",
49
+ "zod": "^4.4.0"
50
+ },
46
51
  "devDependencies": {
47
52
  "@cloudflare/vitest-plugin": "^1.0.0",
48
53
  "@pithy-sh/cloudflare": "workspace:*",
54
+ "@pithy-sh/core": "workspace:*",
55
+ "@pithy-sh/secrets": "workspace:*",
49
56
  "@pithy-sh/tsconfig": "workspace:*",
50
57
  "@types/node": "^22.15.0",
51
58
  "@vitest/coverage-v8": "^4.1.0",
@@ -57,10 +64,5 @@
57
64
  "vitest": "^4.1.0",
58
65
  "wrangler": "^4.115.0",
59
66
  "zod": "^4.4.0"
60
- },
61
- "peerDependencies": {
62
- "hono": "^4.13.2",
63
- "kysely": "^0.29.0",
64
- "zod": "^4.4.0"
65
67
  }
66
68
  }
@@ -3,7 +3,7 @@
3
3
  "package": "@pithy-sh/email",
4
4
  "requiredBindings": [
5
5
  { "type": "d1", "name": "DB" },
6
- { "type": "d1", "name": "EMAIL_SUPPRESSIONS" },
6
+ { "type": "d1", "name": "EMAIL_SUPPRESSIONS", "scope": "global" },
7
7
  { "type": "workflow", "name": "EMAIL_SENDER", "job": "send", "className": "EmailSendWorkflow" }
8
8
  ],
9
9
  "peerCapabilities": ["secrets"],
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { DeclaredEnvironments } from "@pithy-sh/core/src/naming/environment";
5
5
  import { GLOBAL_SCOPE } from "@pithy-sh/core/src/naming/environment";
6
+ import { bindingResourceName, type ProjectGlobalNaming } from "@pithy-sh/core/src/naming/provisionScope";
6
7
  import { resourceName } from "@pithy-sh/core/src/naming/resource";
7
8
  import { resourceNames } from "@pithy-sh/core/src/naming/resourceNames";
8
9
  import { type ManagedEnvironment, managedEnvironments } from "@pithy-sh/secrets/src/scope";
@@ -33,6 +34,18 @@ import { type ManagedEnvironment, managedEnvironments } from "@pithy-sh/secrets/
33
34
  /** The capability segment every email-owned name carries — the migration namespace and error domain too. */
34
35
  export const EMAIL_CAPABILITY = "email";
35
36
 
37
+ /** The D1 binding the suppression database is bound to, in every Worker and every environment. */
38
+ export const EMAIL_SUPPRESSIONS_BINDING = "EMAIL_SUPPRESSIONS";
39
+
40
+ /**
41
+ * What `packages/email/pithy.manifest.json` declares about naming {@link EMAIL_SUPPRESSIONS_BINDING} —
42
+ * restated here because a bundled Worker package cannot read its own manifest, and **pinned to it by
43
+ * `cli/src/ci/bindingResourceNames.test.ts`**, which fails the moment the two answers differ.
44
+ *
45
+ * No `resource`: `email-suppressions` is the kebabbed binding, which is what the composer already uses.
46
+ */
47
+ const EMAIL_SUPPRESSIONS_NAMING: ProjectGlobalNaming = { scope: GLOBAL_SCOPE };
48
+
36
49
  /**
37
50
  * The shared, durable suppression database — **one per project, shared across that project's
38
51
  * environments**: `<project>-global-email-suppressions`.
@@ -51,9 +64,20 @@ export const EMAIL_CAPABILITY = "email";
51
64
  *
52
65
  * Composed through core's naming facade under the **`d1`** namespace, so the name is measured against
53
66
  * a D1 database name's limit rather than the single 63 the generic composer defaults to.
67
+ *
68
+ * **Through {@link bindingResourceName}, the same expression `pithy add` and `pithy provision` compose
69
+ * with — because until #513 it was a *different* expression, and that was the defect.** This function
70
+ * said `<project>-global-email-suppressions` while the two writers said `<project>-<env>-email-
71
+ * suppressions`, so `pithy add email` wrote three per-environment databases into `wrangler.jsonc` and
72
+ * `pithy email provision` created the one this names. The app Worker and the email Worker then read
73
+ * different suppression lists, and an unsubscribe recorded on either was invisible to the other. One
74
+ * expression, driven by one declaration, is what makes that unexpressible rather than merely fixed.
75
+ *
76
+ * The output is byte-identical to what it always was: `kebab("EMAIL_SUPPRESSIONS")` is
77
+ * `email-suppressions`, and the composer's `global` branch is the facade call this used to make directly.
54
78
  */
55
79
  export function suppressionDatabaseName(project: string): string {
56
- return resourceNames(project).global.d1(`${EMAIL_CAPABILITY}-suppressions`);
80
+ return bindingResourceName(project, EMAIL_SUPPRESSIONS_BINDING, "d1", EMAIL_SUPPRESSIONS_NAMING);
57
81
  }
58
82
 
59
83
  /**
@@ -118,12 +142,17 @@ export interface EmailProvisionResult {
118
142
 
119
143
  /**
120
144
  * Provision the email infrastructure: create + migrate the shared suppression DB once, then deploy the
121
- * email worker for every managed environment. The order matters — the suppression DB exists and is
145
+ * email worker for every environment given. The order matters — the suppression DB exists and is
122
146
  * migrated before any worker that binds it is deployed. Idempotent end to end (each step is).
123
147
  *
124
- * `environments` is the project's declaration from the root `pithy.config.ts` (#241). Every declared
125
- * environment is provisioned; an environment this skipped would be one the project deploys to with no
126
- * resources behind it — the silence the closed `ManagedEnvironment` enum used to produce.
148
+ * `environments` is **what the caller determined it can act on**, which the CLI narrows from the project's
149
+ * declaration (#241) to the environments whose app database exists (pithy-sh/pithy#512). Nothing is
150
+ * skipped here and nothing decides here: an environment reaching this list is provisioned, and one that
151
+ * did not was already reported to the operator by name, with why and with the command that fixes it.
152
+ *
153
+ * The suppression database is created **whatever the list holds, including nothing**. It is one per
154
+ * project, shared across every environment, and making it wait for the last environment to be provisioned
155
+ * is exactly the ordering this change exists to undo.
127
156
  */
128
157
  export async function provisionEmail(
129
158
  provisioner: EmailProvisioner,
@@ -132,12 +161,16 @@ export async function provisionEmail(
132
161
  await provisioner.preflight();
133
162
  const { databaseId } = await provisioner.ensureSuppressionDatabase();
134
163
  await provisioner.migrateSuppression(databaseId);
135
- for (const env of managedEnvironments(environments)) {
164
+ const deployed = managedEnvironments(environments);
165
+ for (const env of deployed) {
136
166
  await provisioner.deployWorker(env, databaseId);
137
167
  }
138
- // One inbound routing rule per domain (production app worker), after the workers are up.
139
- const routing = await provisioner.ensureRoutingRule();
140
- return { suppressionDatabaseId: databaseId, environments: managedEnvironments(environments), routing };
168
+ // One inbound routing rule per domain (production app worker), after the workers are up — and only when
169
+ // at least one is. A rule created over an empty run starts delivering real bounce mail to a handler that
170
+ // was never deployed, which is the window this ordering exists to close.
171
+ const routing =
172
+ deployed.length > 0 ? await provisioner.ensureRoutingRule() : { created: false, skipped: true as const };
173
+ return { suppressionDatabaseId: databaseId, environments: deployed, routing };
141
174
  }
142
175
 
143
176
  /** The teardown seam — the inverse of {@link EmailProvisioner}. Every step idempotent (a missing resource is a no-op). */
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/email";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.1.6";
16
+ export const PACKAGE_VERSION = "0.2.0";
@@ -3,7 +3,7 @@
3
3
 
4
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
5
  import type { AmbientEnv } from "@pithy-sh/core/src/env/ambient";
6
- import { pithyErrorHandler } from "@pithy-sh/core/src/error/http";
6
+ import { loggingErrorHandler } from "@pithy-sh/core/src/logger/errorHandler";
7
7
  import { registerWorkflowDispatchRoute } from "@pithy-sh/core/src/workflow/dispatchRoute";
8
8
  import { Hono } from "hono";
9
9
  import { EMAIL_CAPABILITY } from "../provision/provisionEmail";
@@ -43,8 +43,9 @@ export function createEmailHostApp(options: EmailHostAppOptions = {}): Hono<Pith
43
43
  const app = new Hono<PithyHonoEnv>();
44
44
  // The same handler every composed Pithy app mounts, so a refusal on this door renders as a
45
45
  // `PithyError` on the wire rather than as a stack trace the loopback dispatcher would report as an
46
- // unreadable body.
47
- app.onError(pithyErrorHandler);
46
+ // unreadable body — and lands in Workers Logs with its `action`, which the wire body strips. This
47
+ // app has no base middleware binding `c.var.log`, so the handler's own CF-native fallback writes it.
48
+ app.onError(loggingErrorHandler);
48
49
  registerWorkflowDispatchRoute(app, {
49
50
  capability: EMAIL_CAPABILITY,
50
51
  registry: emailWorkflowRegistry,
@@ -148,7 +148,7 @@ export const EmailHostEnv = z
148
148
  .default("true")
149
149
  .transform((value) => value === "true")
150
150
  .describe(
151
- "Whether the every-minute scheduler Workflow runs. `false` stops due jobs being claimed at all — the cron still fires and does nothing — so it is a maintenance switch, not a tuning knob.",
151
+ "Whether the every-minute scheduler Workflow runs. `false` stops due jobs being claimed at all — the cron still fires, and does not even look — so it is a maintenance switch, not a tuning knob.",
152
152
  ),
153
153
  SCHEDULER_BATCH_SIZE: tunedNumber(50).describe(
154
154
  "How many jobs one send Workflow instance takes. Each job is a durable step, so this is the unit of retry and of the instance's report.",
@@ -2,16 +2,19 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { chunkByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
5
+ import type { DatabaseSchema } from "@pithy-sh/core/src/data/db";
5
6
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
6
- import type { EmailDatabase } from "../data/tables";
7
+ import type { Expression, ExpressionBuilder, SqlBool } from "kysely";
8
+ import type { EmailDatabase, EmailTables } from "../data/tables";
7
9
 
8
10
  /**
9
11
  * The every-minute scheduler. It finds due rows — `scheduled`/`timezone` jobs whose `sendAt` has
10
12
  * arrived, plus the safety net of `pending` and `undispatched` immediate jobs that never dispatched and
11
13
  * `sending` jobs left stale by a dead dispatch — claims them (status → `sending`, so the next tick won't
12
14
  * repick them), and fans them out into sender batches. **The fan-out scales with volume:** the more rows are due, the
13
- * more batches are dispatched, each its own durable send Workflow. Cron is cheap; this runs every
14
- * minute and does nothing when nothing is due.
15
+ * more batches are dispatched, each its own durable send Workflow. The cron probes for a due row
16
+ * first ({@link hasDueJobs}) and creates no instance at all when there is none, so an idle minute
17
+ * costs one read rather than a Workflow and a billed step (pithy-sh/pithy#538).
15
18
  *
16
19
  * Jobs are claimed before dispatch, so a dispatch failure strands a row in `sending` rather than
17
20
  * double-sending; the `sending` re-drive recovers it on a later tick, and `runSend`'s idempotency makes
@@ -24,9 +27,16 @@ import type { EmailDatabase } from "../data/tables";
24
27
  * per batch.
25
28
  */
26
29
 
27
- /** Inputs the scheduler needs. `dispatch` creates one send Workflow per batch. */
28
- export interface SchedulerDeps {
30
+ /**
31
+ * What it takes to ask whether anything is due — the database and the three numbers that define
32
+ * "due", and nothing else.
33
+ *
34
+ * It is the front half of {@link SchedulerDeps} rather than a type beside it, so the cron's probe and
35
+ * the tick cannot be pointed at different databases or measured against different windows.
36
+ */
37
+ export interface DueProbeDeps {
29
38
  db: EmailDatabase;
39
+ /** The instant this tick measures every cutoff from. */
30
40
  now: Date;
31
41
  /** How stale (ms) a `pending`/`undispatched` immediate job must be before the safety net re-drives it. */
32
42
  graceMs: number;
@@ -43,6 +53,10 @@ export interface SchedulerDeps {
43
53
  * slower horse, and the queue gets longer.
44
54
  */
45
55
  stuckMs: number;
56
+ }
57
+
58
+ /** Inputs the scheduler needs. `dispatch` creates one send Workflow per batch. */
59
+ export interface SchedulerDeps extends DueProbeDeps {
46
60
  /**
47
61
  * Jobs per dispatched batch — one send Workflow each. From `SCHEDULER_BATCH_SIZE`.
48
62
  *
@@ -160,32 +174,106 @@ async function strandedIds(
160
174
  return stranded;
161
175
  }
162
176
 
177
+ /** The instants "due" is measured against, derived once from one clock. */
178
+ interface DueCutoffs {
179
+ /** Now, as ms since the epoch — what `sendAt` is compared against, and what a claim stamps. */
180
+ nowMs: number;
181
+ /** Before this, an immediate job that never dispatched is the safety net's. */
182
+ graceCutoff: number;
183
+ /** Before this, a `sending` job is old enough to ask the runtime about. */
184
+ stuckCutoff: number;
185
+ }
186
+
187
+ /** Derive this tick's cutoffs. The tick claims against the same `nowMs` it selected against. */
188
+ function dueCutoffs(deps: DueProbeDeps): DueCutoffs {
189
+ const nowMs = deps.now.getTime();
190
+ return { nowMs, graceCutoff: nowMs - deps.graceMs, stuckCutoff: nowMs - deps.stuckMs };
191
+ }
192
+
193
+ /**
194
+ * **"Due" — the one definition.** Three branches over four statuses: a `scheduled` job whose `sendAt`
195
+ * has arrived, a `pending` or `undispatched` immediate job past its grace, and a `sending` job past
196
+ * `stuckMs`.
197
+ *
198
+ * It is a function rather than a clause typed into a query because two callers ask it now: the tick
199
+ * below, and the cron's probe ({@link hasDueJobs}) that decides whether to create the tick at all
200
+ * (pithy-sh/pithy#538). A second copy would be a second definition, and the drift is silent in the
201
+ * worst way — a probe that stops matching a branch never wakes the scheduler for those rows, and they
202
+ * sit there with nothing logged. This file has been bitten twice by that shape already: the `NaN`
203
+ * batch size that produced one empty batch a minute, and the `undispatched` dead end (#410).
204
+ */
205
+ function isDue(cutoffs: DueCutoffs) {
206
+ return (eb: ExpressionBuilder<DatabaseSchema<EmailTables>, "pithyEmailJobs">): Expression<SqlBool> =>
207
+ eb.or([
208
+ eb.and([eb("status", "=", "scheduled"), eb("sendAt", "<=", cutoffs.nowMs)]),
209
+ // `undispatched` beside `pending`, and it is the whole recovery path for one
210
+ // (pithy-sh/pithy#410). A row born `undispatched` was enqueued by a composition that binds no
211
+ // send Workflow — deployed before `pithy <capability> provision`, or a plain `wrangler dev` —
212
+ // and the tick reading this query is running on the host that composition was missing. So the
213
+ // first tick after the host exists is what drains that backlog; without this line the row is a
214
+ // dead end, because `retryJob` takes only `failed` and no command moves it.
215
+ eb.and([eb("status", "in", ["pending", "undispatched"]), eb("createdAt", "<=", cutoffs.graceCutoff)]),
216
+ eb.and([eb("status", "=", "sending"), eb("updatedAt", "<=", cutoffs.stuckCutoff)]),
217
+ ]);
218
+ }
219
+
220
+ /**
221
+ * Is anything due? The question the every-minute cron asks **before** it creates a Workflow instance
222
+ * (pithy-sh/pithy#538).
223
+ *
224
+ * It used to be asked from inside the instance, so an idle minute cost a Workflow creation and a
225
+ * billed step to discover there was nothing to do — 1,440 of each per day per environment, against a
226
+ * Workers Free allowance of 3,000 steps a day for the whole account. Now an idle minute costs one
227
+ * indexed read and creates nothing.
228
+ *
229
+ * **It is deliberately the wider question.** It reads rows, not batches, so a stale row whose batch is
230
+ * still alive wakes the scheduler and the tick then declines to re-drive it — one instance, spent
231
+ * being right. The opposite asymmetry is the one that loses mail, which is why both sides share
232
+ * {@link isDue} rather than agreeing by inspection.
233
+ */
234
+ export async function hasDueJobs(deps: DueProbeDeps): Promise<boolean> {
235
+ const row = await deps.db
236
+ .selectFrom("pithyEmailJobs")
237
+ .select("id")
238
+ .where(isDue(dueCutoffs(deps)))
239
+ .limit(1)
240
+ .executeTakeFirst();
241
+ return row !== undefined;
242
+ }
243
+
244
+ /**
245
+ * The whole of what the cron asks before it creates anything: **is this scheduler configured, and is
246
+ * anything due** — in that order (pithy-sh/pithy#538).
247
+ *
248
+ * The order is the point. {@link assertBatchSize} was written to run before the tick does any work, so
249
+ * that a misconfigured worker says so on its first tick rather than on its first busy one; the probe
250
+ * that now stands in front of the tick would have postponed it to the first minute a job came due. An
251
+ * idle cron that quietly accepts a broken batch size is the shape of the bug this file has already
252
+ * been bitten by twice, and "quietly" is what the probe would have restored.
253
+ *
254
+ * It takes the tick's own {@link SchedulerDeps} rather than the probe's {@link DueProbeDeps}, because
255
+ * the question is about the configuration the tick would run under. The email host validates the same
256
+ * number a second way — `SCHEDULER_BATCH_SIZE` is coerced and refused by `hostEnv.ts` before this is
257
+ * reached — so on that path this is a second lock on one door. It is the module's own invariant, and
258
+ * it holds for any caller that assembles deps itself.
259
+ */
260
+ export async function schedulerHasWork(deps: SchedulerDeps): Promise<boolean> {
261
+ assertBatchSize(deps.batchSize);
262
+ return await hasDueJobs(deps);
263
+ }
264
+
163
265
  /** Run one scheduler tick: find due rows, claim them, fan out batches. */
164
266
  export async function runScheduler(deps: SchedulerDeps): Promise<SchedulerResult> {
165
267
  // Before the query, so a misconfigured worker says so on its first tick rather than on its first
166
268
  // busy one. An idle cron that quietly accepts a broken batch size is the shape of the bug, not a
167
269
  // reason to postpone the complaint.
168
270
  assertBatchSize(deps.batchSize);
169
- const nowMs = deps.now.getTime();
170
- const graceCutoff = nowMs - deps.graceMs;
171
- const stuckCutoff = nowMs - deps.stuckMs;
271
+ const cutoffs = dueCutoffs(deps);
172
272
 
173
273
  const rows = await deps.db
174
274
  .selectFrom("pithyEmailJobs")
175
275
  .select(["id", "batchId"])
176
- .where((eb) =>
177
- eb.or([
178
- eb.and([eb("status", "=", "scheduled"), eb("sendAt", "<=", nowMs)]),
179
- // `undispatched` beside `pending`, and it is the whole recovery path for one
180
- // (pithy-sh/pithy#410). A row born `undispatched` was enqueued by a composition that binds no
181
- // send Workflow — deployed before `pithy <capability> provision`, or a plain `wrangler dev` —
182
- // and the tick reading this query is running on the host that composition was missing. So the
183
- // first tick after the host exists is what drains that backlog; without this line the row is a
184
- // dead end, because `retryJob` takes only `failed` and no command moves it.
185
- eb.and([eb("status", "in", ["pending", "undispatched"]), eb("createdAt", "<=", graceCutoff)]),
186
- eb.and([eb("status", "=", "sending"), eb("updatedAt", "<=", stuckCutoff)]),
187
- ]),
188
- )
276
+ .where(isDue(cutoffs))
189
277
  .orderBy("sendAt", "asc")
190
278
  .limit(deps.maxJobs)
191
279
  .execute();
@@ -208,7 +296,7 @@ export async function runScheduler(deps: SchedulerDeps): Promise<SchedulerResult
208
296
  for (const claim of chunkByBoundParameters(batch, CLAIM_FIXED_PARAMETERS)) {
209
297
  await deps.db
210
298
  .updateTable("pithyEmailJobs")
211
- .set({ status: "sending", updatedAt: nowMs, batchId })
299
+ .set({ status: "sending", updatedAt: cutoffs.nowMs, batchId })
212
300
  .where("id", "in", claim)
213
301
  .execute();
214
302
  }
@@ -19,7 +19,7 @@ import { createEmailHostApp } from "./hostApp";
19
19
  import { type EmailHostEnv, emailHostEnv } from "./hostEnv";
20
20
  import { isLiveInstanceStatus } from "./instanceLiveness";
21
21
  import type { SendWorkflowInstances } from "./instances";
22
- import { runScheduler, type SchedulerDeps } from "./scheduler";
22
+ import { runScheduler, type SchedulerDeps, schedulerHasWork } from "./scheduler";
23
23
  import { type BatchSendReport, runSendBatch, type SendBatchDeps } from "./sendBatch";
24
24
 
25
25
  /**
@@ -29,7 +29,7 @@ import { type BatchSendReport, runSendBatch, type SendBatchDeps } from "./sendBa
29
29
  * - `EmailSendWorkflow` — sends a batch of jobs durably (dispatch target for immediate sends and
30
30
  * the scheduler's fan-out).
31
31
  * - `EmailSchedulerWorkflow` — finds due jobs and fans them out into send batches.
32
- * - `scheduled()` — the every-minute cron that fires the scheduler Workflow.
32
+ * - `scheduled()` — the every-minute cron that fires the scheduler Workflow when a row is due.
33
33
  * - `fetch()` — the loopback dispatch door, served only in `dev` (see {@link createEmailHostApp}).
34
34
  *
35
35
  * The bodies (`runSendBatch`, `runScheduler`, `runSend`) are tested against Miniflare; these classes are
@@ -119,9 +119,14 @@ async function buildSendDeps(env: EmailWorkerEnv): Promise<SendBatchDeps> {
119
119
  };
120
120
  }
121
121
 
122
- /** Assemble the scheduler dependencies, dispatching each batch as a send Workflow. */
123
- function buildSchedulerDeps(env: EmailWorkerEnv): SchedulerDeps {
124
- const config = hostConfig(env);
122
+ /**
123
+ * Assemble the scheduler dependencies, dispatching each batch as a send Workflow.
124
+ *
125
+ * `config` is a parameter so the cron can validate the env once and hand the answer on: it reads
126
+ * `SCHEDULER_ENABLED` before it probes, and re-parsing the same env object a second line later would
127
+ * be one Zod pass per minute for nothing.
128
+ */
129
+ function buildSchedulerDeps(env: EmailWorkerEnv, config: EmailHostEnv = hostConfig(env)): SchedulerDeps {
125
130
  return {
126
131
  db: emailDatabase(env.DB),
127
132
  now: new Date(),
@@ -180,11 +185,33 @@ export class EmailSchedulerWorkflow extends WorkflowEntrypoint<EmailWorkerEnv, u
180
185
  }
181
186
 
182
187
  export default {
183
- /** Cron entry: fire the scheduler Workflow every minute, unless disabled. */
188
+ /**
189
+ * Cron entry: fire the scheduler Workflow every minute — when there is something to fire it for.
190
+ *
191
+ * The instance used to be created unconditionally, and the "is anything due" question was asked
192
+ * inside it. At `* * * * *` that spends 1,440 instance creations and 1,440 billed steps a day, per
193
+ * environment, discovering nothing to do; Workers Free allows 3,000 steps a day for the whole
194
+ * account, so a default project's staging and prod burn 96% of it sending no mail, and the sends
195
+ * that do happen compete for the rest (pithy-sh/pithy#538).
196
+ *
197
+ * So the question moved out in front: one indexed read on `pithy_email_jobs`, asked with the tick's
198
+ * own predicate rather than a second copy of it, and an instance only when it finds a row. Nothing
199
+ * is lost with the tick that never starts: this is not the path an immediate send takes (`enqueue`
200
+ * starts that Workflow itself), the work is a pure re-derivation from D1, and a lost minute is
201
+ * recovered by the next one exactly as a throwing `create()` has always been.
202
+ *
203
+ * What it does give up is the per-minute instance in the dashboard that proved the scheduler was
204
+ * alive. An idle minute now leaves no trace, by design — the trace was costing a billed step.
205
+ *
206
+ * **Through {@link schedulerHasWork}, so the tick's configuration is checked before the probe.** The
207
+ * batch-size check inside `runScheduler` exists to complain on the first tick rather than the first
208
+ * busy one, and a probe in front of the instance is in front of that check too.
209
+ */
184
210
  async scheduled(_controller: unknown, env: EmailWorkerEnv): Promise<void> {
185
- if (hostConfig(env).SCHEDULER_ENABLED) {
186
- await env.EMAIL_SCHEDULER.create();
187
- }
211
+ const config = hostConfig(env);
212
+ if (!config.SCHEDULER_ENABLED) return;
213
+ if (!(await schedulerHasWork(buildSchedulerDeps(env, config)))) return;
214
+ await env.EMAIL_SCHEDULER.create();
188
215
  },
189
216
 
190
217
  /**
@@ -58,8 +58,9 @@
58
58
  { "binding": "EMAIL_SCHEDULER", "name": "pithy-email-schedule", "class_name": "EmailSchedulerWorkflow" }
59
59
  ],
60
60
 
61
- // The every-minute scheduler cron. Cheap: scheduled() fires the scheduler Workflow, which sends
62
- // nothing when nothing is due.
61
+ // The every-minute scheduler cron. Cheap because it stays cheap when idle: scheduled() probes
62
+ // pithy_email_jobs for a due row and creates a Workflow instance only when it finds one, so an idle
63
+ // minute costs one read rather than an instance and a billed step (pithy-sh/pithy#538).
63
64
  "triggers": { "crons": ["* * * * *"] },
64
65
 
65
66
  "vars": {