From 1c846354a1a41a8e4dc3cf69261a1541ab2580dd Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Tue, 1 Dec 2026 02:05:31 +0100 Subject: [PATCH 1/3] fix(deploy): set Email Routing routes to a Worker after the upload A rule or catch-all whose action is `worker` was reconciled in deploy preparation, before Wrangler uploaded the script. Cloudflare refuses such a route while the Worker does not exist (`2016: Workers Script Info not found`), so an app routing mail to its own Worker failed on its first deploy into an account. Preparation (`provisionZoneResources`) now skips every `worker` route and hands back `provisionAfterUpload`, bound to the same account and API. The deploy command runs it once the upload is proven (and, for a percentage rollout, after the traffic split), so a failed upload never reaches it. A failure there exits 1 with a message saying the Worker WAS uploaded, which route failed and why, and what this run had already set. Everything else (sending onboarding, enabling routing, destinations, forward/drop rules and catch-alls, DNS) keeps its place and order in preparation. Deferral covers every `worker` action, not only self-targeted ones: one predicate, deterministic, and harmless for a Worker that already exists. A version-only upload (percentage rollout) runs the step too, because the script exists after it and preparation has already reconciled the zone's other routes. Previews still have no zone work at all. `--dry-run` runs the step against the stubbed API and lists its would-creates as "after the upload". Rule priority stays the index in the whole declared list. Rule and catch-all reads and writes now throw `EmailRouteError`, naming the route and keeping Cloudflare's error as the cause. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-routing-after-upload.md | 5 + .../lib/docs/content/configuration/part-3.ts | 7 +- packages/devflare/LLM.md | 8 +- packages/devflare/src/cli/commands/deploy.ts | 48 +++- .../src/cli/commands/deploy/after-upload.ts | 56 ++++ .../devflare/src/config/deploy-resources.ts | 36 ++- packages/devflare/src/config/deploy-zones.ts | 222 ++++++++++++++-- .../devflare/src/config/schema-types-zones.ts | 6 + .../deploy-email-routing-after-upload.test.ts | 248 ++++++++++++++++++ .../unit/cli/deploy-after-upload.test.ts | 59 +++++ .../tests/unit/config/deploy-zones.test.ts | 221 +++++++++++++++- 11 files changed, 873 insertions(+), 43 deletions(-) create mode 100644 .changeset/email-routing-after-upload.md create mode 100644 packages/devflare/src/cli/commands/deploy/after-upload.ts create mode 100644 packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts create mode 100644 packages/devflare/tests/unit/cli/deploy-after-upload.test.ts diff --git a/.changeset/email-routing-after-upload.md b/.changeset/email-routing-after-upload.md new file mode 100644 index 00000000..e50018ea --- /dev/null +++ b/.changeset/email-routing-after-upload.md @@ -0,0 +1,5 @@ +--- +'devflare': patch +--- + +Email Routing rules and catch-alls whose action is `worker` are now set after Wrangler's upload instead of before it, so the first deploy of a Worker that routes mail to itself no longer fails with `2016: Workers Script Info not found`. If one of those routes fails after a successful upload, the deploy fails and says the Worker was uploaded and which route is missing; `--dry-run` lists them as "after the upload". diff --git a/apps/documentation/src/lib/docs/content/configuration/part-3.ts b/apps/documentation/src/lib/docs/content/configuration/part-3.ts index bd552a13..59064ee4 100644 --- a/apps/documentation/src/lib/docs/content/configuration/part-3.ts +++ b/apps/documentation/src/lib/docs/content/configuration/part-3.ts @@ -219,6 +219,7 @@ export const configurationDocsPart3: DocPage[] = [ 'Everything else Devflare provisions is account-scoped. Email Routing rules and DNS records are not: they belong to a zone, which is a different identifier reached by a different lookup and gated by a different token scope. The `zones` key is where they are declared, and a deploy reconciles them.', 'The key is a domain rather than a zone id, because a domain is what an author knows. Devflare walks the domain labels up to the apex to find the zone, so `mail.example.com` is configured under its own name and its records land in the `example.com` zone. A relative record name resolves against the domain it was declared under, not the zone apex — for a subdomain those differ, and the apex would be the wrong place.', 'Rules reconcile on the address they claim and records on their type and name, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever deleted: a zone almost always carries rules and records this config never mentioned.', + 'Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. If the upload fails those routes are not attempted; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded and which route is missing. A gradual rollout sets them after its traffic split.', '`emailSending` and `emailRouting` are different Cloudflare products that happen to share a zone. Routing is inbound — what happens to mail arriving for the domain. Sending is outbound — whether a `send_email` binding may send from an address here. A domain that does both is onboarded to both, separately, and a subdomain gets its own DKIM key rather than inheriting the apex one. Sending readiness is reported rather than waited on: Cloudflare writes the records at onboarding and they take minutes to propagate, so a deploy that failed on them would fail one that did everything right.' ], table: { @@ -231,12 +232,12 @@ export const configurationDocsPart3: DocPage[] = [ ], [ '`emailRouting.rules`', - 'Creates any rule whose address is not already claimed.', + 'Creates any rule whose address is not already claimed — a `worker` rule only after the upload.', 'Rewrite one that exists and points elsewhere — it reports the difference instead.' ], [ '`emailRouting.catchAll`', - 'Sets it, but only when it differs from what is live.', + 'Sets it, but only when it differs from what is live — a `worker` catch-all only after the upload.', 'Touch it at all when the key is omitted.' ], [ @@ -286,7 +287,7 @@ export const configurationDocsPart3: DocPage[] = [ tone: 'info', title: '`--dry-run` reads the live zone but changes nothing in it', body: [ - 'Every zone mutation is substituted in describe-only mode, enabling included, while the reads still happen for real — so the plan reflects the actual mix of what exists and what does not, without a single write. Preview-scoped deploys have no zone resources at all: a rule or a record is shared by the whole domain and would outlive the branch that created it.' + 'Every zone mutation is substituted in describe-only mode, enabling included, while the reads still happen for real — so the plan reflects the actual mix of what exists and what does not, without a single write. Routes to a Worker are listed with the rest, marked as after the upload. Preview-scoped deploys have no zone resources at all: a rule or a record is shared by the whole domain and would outlive the branch that created it.' ] } ] diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index 4504a23f..ff913848 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -3470,6 +3470,8 @@ The key is a domain rather than a zone id, because a domain is what an author kn Rules reconcile on the address they claim and records on their type and name, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever deleted: a zone almost always carries rules and records this config never mentioned. +Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. If the upload fails those routes are not attempted; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded and which route is missing. A gradual rollout sets them after its traffic split. + `emailSending` and `emailRouting` are different Cloudflare products that happen to share a zone. Routing is inbound — what happens to mail arriving for the domain. Sending is outbound — whether a `send_email` binding may send from an address here. A domain that does both is onboarded to both, separately, and a subdomain gets its own DKIM key rather than inheriting the apex one. Sending readiness is reported rather than waited on: Cloudflare writes the records at onboarding and they take minutes to propagate, so a deploy that failed on them would fail one that did everything right. ##### Reference table @@ -3477,8 +3479,8 @@ Rules reconcile on the address they claim and records on their type and name, so | Declared | What a deploy does | What it will not do | | --- | --- | --- | | `emailSending` | Checks the domain is onboarded and able to send, and reports its DNS readiness. | Onboard it without `enable: true` — it fails and names the fix instead. | -| `emailRouting.rules` | Creates any rule whose address is not already claimed. | Rewrite one that exists and points elsewhere — it reports the difference instead. | -| `emailRouting.catchAll` | Sets it, but only when it differs from what is live. | Touch it at all when the key is omitted. | +| `emailRouting.rules` | Creates any rule whose address is not already claimed — a `worker` rule only after the upload. | Rewrite one that exists and points elsewhere — it reports the difference instead. | +| `emailRouting.catchAll` | Sets it, but only when it differs from what is live — a `worker` catch-all only after the upload. | Touch it at all when the key is omitted. | | `emailRouting.enable` | Turns Email Routing on for the zone. | Turn it on without this — a zone with routing off fails the deploy instead. | | `dns` | Creates a missing record, and rewrites one that drifted in content, TTL or MX priority. | Guess which record it owns when several already share that type and name. | @@ -3500,7 +3502,7 @@ Rules reconcile on the address they claim and records on their type and name, so > **Note — `--dry-run` reads the live zone but changes nothing in it** > -> Every zone mutation is substituted in describe-only mode, enabling included, while the reads still happen for real — so the plan reflects the actual mix of what exists and what does not, without a single write. Preview-scoped deploys have no zone resources at all: a rule or a record is shared by the whole domain and would outlive the branch that created it. +> Every zone mutation is substituted in describe-only mode, enabling included, while the reads still happen for real — so the plan reflects the actual mix of what exists and what does not, without a single write. Routes to a Worker are listed with the rest, marked as after the upload. Preview-scoped deploys have no zone resources at all: a rule or a record is shared by the whole domain and would outlive the branch that created it. ##### Example — Email routing and DNS as authored config diff --git a/packages/devflare/src/cli/commands/deploy.ts b/packages/devflare/src/cli/commands/deploy.ts index 7ca5964f..a4b23b79 100644 --- a/packages/devflare/src/cli/commands/deploy.ts +++ b/packages/devflare/src/cli/commands/deploy.ts @@ -13,7 +13,7 @@ import { prepareConfigResourcesForDeploy } from '../../config' import { stringifyConfig } from '../../config/compiler' -import { ZoneProvisionError } from '../../config/deploy-zones' +import { ZoneProvisionError, type ZoneProvisionResult } from '../../config/deploy-zones' import { resolveConfigEnvVarsForEnvironment } from '../../config/env-vars-for-environment' import { generatedDir } from '../../utils/generated-dir' import { getDependencies } from '../dependencies' @@ -33,6 +33,7 @@ import { } from '../preview' import { createCliTheme, dim, green, logLine, yellow, yellowBold } from '../ui' import { prepareBuildArtifacts } from './build-artifacts' +import { describeAfterUploadRoutingFailure } from './deploy/after-upload' import { inferRecordSource, writeDeployResultMetadata } from './deploy/metadata' import { prepareDeployConfig, @@ -172,6 +173,10 @@ export async function runDeployCommand( dim('Resolved view (would-create placeholders for missing resources):', theme) ) logLine(logger, stringifyConfig(resolvedWranglerConfig)) + // The routes a real deploy writes only after the upload. Describe-only preparation bound + // this step to its stubbed API, so running it here reads live state and writes nothing. + const afterUpload: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + await describeResult.provisionAfterUpload?.(afterUpload) const wouldCreate = [ ...describeResult.created.kv.map((n) => `KV: ${n}`), ...describeResult.created.d1.map((n) => `D1: ${n}`), @@ -183,7 +188,8 @@ export async function runDeployCommand( // this list — both are resolve-only, so they can never appear in `created` and the omission // was invisible; included now so the next resolve-only family does not inherit the gap. ...describeResult.created.zones, - ...describeResult.created.subscriptions + ...describeResult.created.subscriptions, + ...afterUpload.created.map((label) => `${label} — after the upload`) ] if (wouldCreate.length > 0) { logLine(logger, dim(`Would create:\n - ${wouldCreate.join('\n - ')}`, theme)) @@ -717,6 +723,44 @@ export async function runDeployCommand( ) } + // → KEY: Email Routing to a Worker waits for the upload, because Cloudflare refuses a route + // naming a Worker that does not exist yet. It runs here — after the upload is PROVEN and, + // for a percentage rollout, after the traffic split — so a failed upload or rollout never + // reaches it. A version-only upload runs it too: the script exists once any version is + // uploaded, and preparation has already reconciled the zone's other routes, so skipping + // these would leave the zone half-reconciled. (A preview has no zone work at all.) + if (prepared.deployResources.provisionAfterUpload) { + const routed: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + logLine(logger, dim('Pointing Email Routing at the uploaded Worker…', theme)) + try { + await prepared.deployResources.provisionAfterUpload(routed) + } catch (error) { + const failure = describeAfterUploadRoutingFailure({ + workerName: prepared.config.name, + versionId: resolvedVersionId, + error, + progress: routed + }) + await persistDeployMetadata({ + status: 'failure', + exitCode: 1, + error: failure + }) + logger.error(failure) + return { exitCode: 1, output: structuredOutput } + } + + if (routed.created.length > 0) { + logLine(logger, `Provisioned after the upload: ${routed.created.join(', ')}`) + } + if (routed.existing.length > 0) { + logLine(logger, `Reused after the upload: ${routed.existing.join(', ')}`) + } + for (const warning of routed.warnings) { + logger.warn(warning) + } + } + if (resolvedAccountId) { const previewRegistryScope = isBranchScopedPreviewDeployment ? deployTarget.previewScope diff --git a/packages/devflare/src/cli/commands/deploy/after-upload.ts b/packages/devflare/src/cli/commands/deploy/after-upload.ts new file mode 100644 index 00000000..cc28cb49 --- /dev/null +++ b/packages/devflare/src/cli/commands/deploy/after-upload.ts @@ -0,0 +1,56 @@ +// ============================================================================= +// Deploy After-Upload Zone Work — Email Routing that needs the Worker to exist +// ============================================================================= +// +// Email Routing rules and catch-alls whose action is `worker` are reconciled +// AFTER Wrangler's upload rather than in deploy preparation, because Cloudflare +// refuses a route naming a Worker that does not exist yet (`2016: Workers Script +// Info not found`) — the first deploy of any app routing mail to itself. +// +// → KEY: a failure here comes after a SUCCESSFUL upload. The Worker is live, and +// an operator told only "Deployment failed" would reasonably believe nothing +// changed. The message therefore says what shipped, which route did not, and +// that re-running is safe. + +import { EmailRouteError, type ZoneProvisionResult } from '../../../config/deploy-zones' + +/** + * @description Say why the after-upload Email Routing step failed, in words an operator can act on. + * + * @param input.workerName - the Worker that was uploaded. + * @param input.versionId - its uploaded version, when known. + * @param input.error - what the step threw; an `EmailRouteError` names its route. + * @param input.progress - what the step set or found before it failed. + * @returns one message saying the Worker WAS uploaded, which route failed and why, and how to retry. + */ +export function describeAfterUploadRoutingFailure(input: { + workerName: string + versionId?: string + error: unknown + progress: ZoneProvisionResult +}): string { + const version = input.versionId ? ` (version ${input.versionId})` : '' + const route = + input.error instanceof EmailRouteError + ? input.error.route + : 'a Worker-targeted Email Routing route' + const cause = + input.error instanceof EmailRouteError && input.error.cause instanceof Error + ? input.error.cause.message + : input.error instanceof Error + ? input.error.message + : String(input.error) + + const parts = [ + `The Worker "${input.workerName}" WAS uploaded${version}, but Email Routing to it could not be completed: ${route} failed — ${cause}.`, + 'Mail for that route is not reaching the Worker until this is fixed.' + ] + if (input.progress.created.length > 0) { + parts.push(`Set by this deploy before the failure: ${input.progress.created.join('; ')}.`) + } + parts.push( + 'Re-run `devflare deploy` to retry; routes that are already correct are left as they are.' + ) + + return parts.join(' ') +} diff --git a/packages/devflare/src/config/deploy-resources.ts b/packages/devflare/src/config/deploy-resources.ts index 27d3bf50..2164176a 100644 --- a/packages/devflare/src/config/deploy-resources.ts +++ b/packages/devflare/src/config/deploy-resources.ts @@ -48,7 +48,13 @@ import { withResolvedIdBindings } from './binding-resolution-helpers' import { provisionEventSubscriptions, type SubscriptionProvisionApi } from './deploy-subscriptions' -import { provisionZoneResources, type ZoneProvisionApi } from './deploy-zones' +import { + hasWorkerEmailRoutes, + provisionWorkerEmailRoutes, + provisionZoneResources, + type ZoneProvisionApi, + type ZoneProvisionResult +} from './deploy-zones' import type { PreviewResolutionOptions } from './preview' import { brandAsDeployConfig, type DeployConfig, resolveResources } from './resolve-phased' import { ConfigResourceResolutionError } from './resource-resolution' @@ -181,6 +187,18 @@ export interface PrepareConfigResourcesForDeployResult { created: DeployResourceNames existing: DeployResourceNames warnings: string[] + /** + * The zone work this deploy owes AFTER Wrangler's upload — the Email Routing routes whose action + * is `worker` — bound to the account and the (dry-run-stubbed, when describing) API this + * preparation used. Absent when there is none, which includes every preview. + * + * → KEY: call it only once the upload has been PROVEN. Cloudflare refuses a route naming a Worker + * that does not exist yet, so on a first deploy it can only succeed after the upload; and after + * a failed upload nothing new is pointed at a Worker that may not be there. + * + * @param result - the caller's accumulator, appended to in place so a throw still reports progress. + */ + provisionAfterUpload?: (result: ZoneProvisionResult) => Promise } interface ResolvedResourceIdsByNameResult { @@ -710,6 +728,11 @@ export async function prepareMaterializedConfigResourcesForDeploy( // zone is touched — and a zone left half-provisioned is the one kind of orphan a user cannot // simply ignore, because it is already routing real mail. // + // → KEY: "last in preparation" is not last in the deploy for the routes whose action is + // `worker`. Cloudflare refuses those until the Worker exists, so `provisionZoneResources` + // skips them and `provisionAfterUpload` below carries them past the upload. Everything they + // need from the zone (routing enabled) still happens here, under the same fail-early rule. + // // → KEY: the accumulator arrays are passed IN rather than a result being returned. A returned // value is lost on a throw, which is exactly when the orphan report matters — the failure // this guards against is enabling Email Routing (rewriting the domain's MX records), then @@ -734,6 +757,14 @@ export async function prepareMaterializedConfigResourcesForDeploy( ) } + // Bound to the SAME `cloudflareApi` object, so a describe-only preparation hands back a step + // whose mutations are the stubs above — a dry-run can run it to plan, and change nothing. + const provisionAfterUpload = + hasZoneWork && hasWorkerEmailRoutes(resolvedConfig.zones) + ? (result: ZoneProvisionResult) => + provisionWorkerEmailRoutes(resolvedConfig.zones, accountId, cloudflareApi, result) + : undefined + const config = withResolvedIdBindings(resolvedConfig, { kv: kvBindings ? pendingKVNameBindings.length > 0 @@ -764,7 +795,8 @@ export async function prepareMaterializedConfigResourcesForDeploy( config: brandAsDeployConfig(config), created, existing, - warnings + warnings, + ...(provisionAfterUpload ? { provisionAfterUpload } : {}) } } catch (err) { throw decorateOrphanError(err, created) diff --git a/packages/devflare/src/config/deploy-zones.ts b/packages/devflare/src/config/deploy-zones.ts index 9144f9fa..f17f00ce 100644 --- a/packages/devflare/src/config/deploy-zones.ts +++ b/packages/devflare/src/config/deploy-zones.ts @@ -7,6 +7,12 @@ order, because sending is the precondition for the rest of a domain's mail and Cloudflare writes records of its own while onboarding it. Sending is OUTBOUND and routing is INBOUND; they are separate products sharing a zone. + + Two passes, at two moments of a deploy. `provisionZoneResources` runs in + deploy PREPARATION, before Wrangler uploads anything, and does all of the + above EXCEPT the routes whose action is `worker`. Those are + `provisionWorkerEmailRoutes`, which the deploy command runs only after the + upload has been proven. Lives beside `deploy-resources.ts` rather than inside it because everything there is account-scoped and shares one list/create shape, while these need a zone lookup first and reconcile on @@ -21,6 +27,13 @@ the orphan report — the thing that tells an operator their MX records were just rewritten before the deploy died — is only worth having if it survives exactly that. + → KEY: a route whose action is `worker` must not be written before the upload. + Cloudflare refuses a rule or catch-all naming a Worker that does not exist + yet (`2016: Workers Script Info not found`), so a config routing mail to + its OWN worker could never succeed on its first deploy into an account. All + worker routes wait, not only self-targeted ones: the rule is one predicate + rather than a name comparison, and waiting costs nothing when the Worker + already exists. → NOTE: rules are reconciled by ADDRESS and records by TYPE+NAME+CONTENT, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever DELETED — a zone always carries rules and records this config never mentioned. @@ -93,6 +106,47 @@ export class ZoneProvisionError extends Error { override name = 'ZoneProvisionError' } +/** + * Raised when an Email Routing route could not be read or written, naming the route. + * + * The bare Cloudflare error names an endpoint (`PUT …/rules/catch_all`), not the address whose mail + * is now going nowhere. That matters most after the upload: the Worker is already live there, and + * the deploy command has to tell the operator exactly which route is missing. + */ +export class EmailRouteError extends Error { + override name = 'EmailRouteError' + + /** + * @param route - the route in the same words the created/existing labels use, e.g. `Email catch-all (zone example.com)`. + * @param cause - what Cloudflare (or the lookup before it) actually said. + */ + constructor( + readonly route: string, + cause: unknown + ) { + super(`${route}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause }) + } +} + +/** A domain's `emailRouting` block, as declared. */ +type DeclaredEmailRouting = NonNullable< + NonNullable[string]['emailRouting'] +> + +/** One declared per-address rule. */ +type DeclaredRoutingRule = NonNullable[number] + +/** A declared rule with the priority its position in the WHOLE declared list gives it. */ +interface PrioritisedRoutingRule { + /** The rule as declared. */ + declared: DeclaredRoutingRule + /** + * 1-based, from the rule's index among ALL the domain's rules — never among the subset one pass + * handles, or splitting the passes would renumber every rule after the first worker rule. + */ + priority: number +} + /** The note Devflare writes onto records it created, so a later pass can tell which are its own. */ export const DEVFLARE_RECORD_COMMENT = 'Managed by Devflare' @@ -129,6 +183,22 @@ function toRoutingActions(declared: { return [{ type: 'drop' }] } +/** + * @description Whether a declared rule or catch-all hands mail to a Worker, which is what decides the + * pass it belongs to. + * + * @param declared - a rule or catch-all as declared. + * @returns true for a `worker` action, which Cloudflare refuses until that Worker exists. + */ +export function isWorkerTargeted(declared: { worker?: string }): boolean { + return declared.worker !== undefined +} + +/** Pair every declared rule with the priority its position in the full list gives it. */ +function prioritise(rules: DeclaredRoutingRule[]): PrioritisedRoutingRule[] { + return rules.map((declared, index) => ({ declared, priority: index + 1 })) +} + /** * Whether two action arrays say the same thing, for deciding if a write is needed. * @@ -159,6 +229,22 @@ function ruleAddress(rule: EmailRoutingRule): string | null { return literal?.value?.toLowerCase() ?? null } +/** + * @description Run one Cloudflare call for a route, and name that route if it fails. + * + * @param route - the route in the words the created/existing labels use. + * @param call - the read or write to make. + * @returns whatever the call returned. + * @throws {EmailRouteError} wrapping the call's own error as its `cause`. + */ +async function attributeTo(route: string, call: () => Promise): Promise { + try { + return await call() + } catch (error) { + throw new EmailRouteError(route, error) + } +} + /** * @description Make sure every address a rule forwards to exists as a destination on the account. * @@ -222,13 +308,16 @@ async function provisionForwardDestinations( } /** - * @description Bring one zone's Email Routing to the declared state. + * @description Bring one zone's Email Routing to the declared state, except the routes whose action + * is `worker` — those wait for the upload (`provisionWorkerEmailRoutes`). * + * @param accountId - the account destination addresses belong to. * @param zone - the resolved zone, and the domain it was reached through. * @param declared - the domain's `emailRouting` block. * @param api - the injected Cloudflare calls. * @param result - the caller's accumulator, appended to in place so a throw still reports progress. * @throws {ZoneProvisionError} when routing is off and `enable` was not given. + * @throws {EmailRouteError} when a rule or the catch-all cannot be read or written. */ async function provisionEmailRouting( accountId: string, @@ -263,25 +352,35 @@ async function provisionEmailRouting( // email somebody has to click. await provisionForwardDestinations(accountId, declared, api, result) - await provisionRoutingRules(zone, declared.rules ?? [], api, result) + // Worker-targeted routes are NOT written here; `provisionWorkerEmailRoutes` writes them once the + // upload has made the Worker exist. Everything they depend on — routing enabled — is done above. + const rules = prioritise(declared.rules ?? []).filter((rule) => !isWorkerTargeted(rule.declared)) + await provisionRoutingRules(zone, rules, api, result) - if (declared.catchAll) { + if (declared.catchAll && !isWorkerTargeted(declared.catchAll)) { await provisionCatchAll(zone, declared.catchAll, api, result) } } -/** Create the declared rules that are not already present, matching on address. */ +/** + * @description Create the given declared rules that are not already present, matching on address. + * + * @param zone - the resolved zone the rules live in. + * @param declaredRules - the rules this pass owns, each carrying its priority in the full declared list. + * @param api - the injected Cloudflare calls. + * @param result - the caller's accumulator, appended to in place. + */ async function provisionRoutingRules( zone: ResolvedZone, - declaredRules: NonNullable< - NonNullable[string]['emailRouting']>['rules'] - >, + declaredRules: PrioritisedRoutingRule[], api: ZoneProvisionApi, result: ZoneProvisionResult ): Promise { if (declaredRules.length === 0) return - const live = await api.listEmailRoutingRules(zone.id) + const live = await attributeTo(`Email rules (zone ${zone.name})`, () => + api.listEmailRoutingRules(zone.id) + ) const claimed = new Map( live.flatMap((rule) => { const address = ruleAddress(rule) @@ -289,7 +388,7 @@ async function provisionRoutingRules( }) ) - for (const [index, declared] of declaredRules.entries()) { + for (const { declared, priority } of declaredRules) { const address = declared.to.toLowerCase() const existing = claimed.get(address) const actions = toRoutingActions(declared) @@ -308,14 +407,17 @@ async function provisionRoutingRules( continue } - const created = await api.createEmailRoutingRule(zone.id, { - name: `devflare: ${address}`, - enabled: declared.enabled ?? true, - priority: index + 1, - matchers: [{ type: 'literal', field: 'to', value: address }], - actions - }) - result.created.push(`Email rule ${declared.to} (zone ${zone.name})`) + const label = `Email rule ${declared.to} (zone ${zone.name})` + const created = await attributeTo(label, () => + api.createEmailRoutingRule(zone.id, { + name: `devflare: ${address}`, + enabled: declared.enabled ?? true, + priority, + matchers: [{ type: 'literal', field: 'to', value: address }], + actions + }) + ) + result.created.push(label) // → KEY: the map learns what THIS pass created. Without it, two declarations of one address — // which differing case makes easy to write by accident — each miss the live list and create a @@ -335,24 +437,27 @@ async function provisionCatchAll( result: ZoneProvisionResult ): Promise { const actions = toRoutingActions(declared) - const live = await api.getEmailRoutingCatchAll(zone.id) + const label = `Email catch-all (zone ${zone.name})` + const live = await attributeTo(label, () => api.getEmailRoutingCatchAll(zone.id)) // → GOTCHA: `enabled` is half the state, and the writer below always sets it — so comparing only // the actions would skip a catch-all that says the right thing while switched OFF, and report it // as correct. Cloudflare's own default on a freshly enabled zone is exactly that (drop, disabled), // so the very first deploy of `catchAll: { drop: true }` hits it. if (live.enabled === true && sameActions(live.actions ?? [], actions)) { - result.existing.push(`Email catch-all (zone ${zone.name})`) + result.existing.push(label) return } - await api.setEmailRoutingCatchAll(zone.id, { - name: 'devflare: catch-all', - enabled: true, - matchers: [{ type: 'all' }], - actions - }) - result.created.push(`Email catch-all (zone ${zone.name}) — set to ${actions[0]?.type}`) + await attributeTo(label, () => + api.setEmailRoutingCatchAll(zone.id, { + name: 'devflare: catch-all', + enabled: true, + matchers: [{ type: 'all' }], + actions + }) + ) + result.created.push(`${label} — set to ${actions[0]?.type}`) } /** @@ -545,7 +650,9 @@ async function provisionDnsRecords( } /** - * @description Reconcile every declared domain's zone-scoped resources against Cloudflare. + * @description Reconcile every declared domain's zone-scoped resources against Cloudflare — all of + * them except the Email Routing routes whose action is `worker`, which `provisionWorkerEmailRoutes` + * reconciles after the upload. * * @param zones - the config's `zones` namespace. An empty or absent one does no work and makes no calls. * @param accountId - the account whose zones to search. @@ -585,3 +692,64 @@ export async function provisionZoneResources( } } } + +/** + * @description Whether any declared domain routes mail to a Worker, i.e. whether a deploy owes the + * after-upload pass at all. + * + * @param zones - the config's `zones` namespace. + * @returns true when some rule or catch-all declares a `worker` action. + */ +export function hasWorkerEmailRoutes(zones: DevflareConfig['zones']): boolean { + return Object.values(zones ?? {}).some(({ emailRouting }) => { + if (!emailRouting) return false + const workerRule = (emailRouting.rules ?? []).some(isWorkerTargeted) + return ( + workerRule || (emailRouting.catchAll !== undefined && isWorkerTargeted(emailRouting.catchAll)) + ) + }) +} + +/** + * @description Reconcile the Email Routing routes whose action is `worker` — per-address rules and + * the catch-all — once the Worker they name exists. + * + * @param zones - the config's `zones` namespace; domains with no worker route make no calls. + * @param accountId - the account whose zones to search. + * @param api - the injected Cloudflare calls; dry-run passes stubs for every mutation. + * @param result - the caller's accumulator, appended to IN PLACE so a throw still reports progress. + * @throws {EmailRouteError} naming the route that could not be read or written. + * + * → KEY: call it only AFTER a proven upload. Cloudflare refuses a route naming a Worker that does not + * exist (`2016: Workers Script Info not found`), which is the first deploy of any app routing mail + * to itself. Everything such a route depends on — routing enabled, the zone's other rules — was + * reconciled in preparation by `provisionZoneResources`, so this pass only reads and writes routes. + * → NOTE: same reconciliation as before the split: rules by address, the catch-all by + * enabled+actions, nothing ever deleted, so a second deploy reports every route as existing. + */ +export async function provisionWorkerEmailRoutes( + zones: DevflareConfig['zones'], + accountId: string, + api: ZoneProvisionApi, + result: ZoneProvisionResult +): Promise { + for (const [domain, declared] of Object.entries(zones ?? {})) { + const routing = declared.emailRouting + if (!routing) continue + + const rules = prioritise(routing.rules ?? []).filter((rule) => isWorkerTargeted(rule.declared)) + const catchAll = + routing.catchAll && isWorkerTargeted(routing.catchAll) ? routing.catchAll : undefined + if (rules.length === 0 && !catchAll) continue + + const zone = await attributeTo(`Email routing for ${domain}`, () => + api.resolveZone(domain, accountId) + ) + + await provisionRoutingRules(zone, rules, api, result) + + if (catchAll) { + await provisionCatchAll(zone, catchAll, api, result) + } + } +} diff --git a/packages/devflare/src/config/schema-types-zones.ts b/packages/devflare/src/config/schema-types-zones.ts index f0a55e09..45d2242a 100644 --- a/packages/devflare/src/config/schema-types-zones.ts +++ b/packages/devflare/src/config/schema-types-zones.ts @@ -27,6 +27,9 @@ export interface EmailRoutingRuleInput { * * One of `worker`, `forward` or `drop` — exactly one, never two. * + * Set after the deploy's upload rather than before it, because Cloudflare refuses a route to a + * Worker that does not exist yet — so naming the Worker this config deploys works on its first deploy. + * * @example * ```ts * worker: 'example-api' @@ -81,6 +84,9 @@ export interface EmailRoutingCatchAllInput { /** * Hand unclaimed mail to this Worker, by script name. * + * Set after the deploy's upload rather than before it, because Cloudflare refuses a route to a + * Worker that does not exist yet — so naming the Worker this config deploys works on its first deploy. + * * @example * ```ts * worker: 'example-api' diff --git a/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts b/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts new file mode 100644 index 00000000..5e600b02 --- /dev/null +++ b/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts @@ -0,0 +1,248 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test' +import { mkdtempSync } from 'node:fs' +import { mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { runDeployCommand } from '../../../src/cli/commands/deploy' +import { clearDependencies, type ExecResult, setDependencies } from '../../../src/cli/dependencies' +import { createLogger, renderMessages } from '../../helpers/mock-logger' +import { + captureDeployEnvironmentSnapshot, + cloudflareApiResponse, + createCliDependencies, + createProcessRunner, + type ExecInvocation, + restoreDeployEnvironmentSnapshot, + successResult, + TEST_ACCOUNT_ID +} from './build-deploy-worker-only.test-utils' + +/* + The deploy command's half of "Email Routing to a Worker waits for the upload". + + The reconciler's half is graded in `tests/unit/config/deploy-zones.test.ts`. What only this file + can see is the ORDER against the real upload: Cloudflare refuses a route naming a Worker that does + not exist yet, so the first deploy of an app routing mail to itself failed in preparation before + Wrangler ever ran. Every case records one timeline — zone writes from the Cloudflare mock, the + upload from the process runner — and reads the order off it. +*/ + +const VERSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + +/** The Cloudflare error a first deploy actually hit, as the API returns it. */ +function workerScriptNotFound(): Response { + return new Response( + JSON.stringify({ + success: false, + errors: [{ code: 2016, message: 'Workers Script Info not found' }], + messages: [], + result: null + }), + { status: 404, headers: { 'Content-Type': 'application/json' } } + ) +} + +/** + * @description Answer the zone calls of a zone with routing on, no rules, and Cloudflare's default + * catch-all (drop, disabled) — the state a first deploy meets — recording every write. + * + * @param timeline - receives `POST rule ` and `PUT catch_all ` as the writes arrive. + * @param options.catchAllFails - answer the catch-all write with error 2016, as for a missing Worker. + */ +function mockZone(timeline: string[], options: { catchAllFails?: boolean } = {}): void { + globalThis.fetch = mock(async (input: RequestInfo | URL, init?: RequestInit) => { + const method = init?.method ?? 'GET' + const url = String(input) + const body = init?.body ? JSON.parse(String(init.body)) : undefined + + if (url.includes('/zones?name=example.com')) { + return cloudflareApiResponse([{ id: 'zone_1', name: 'example.com' }]) + } + if (method === 'GET' && url.endsWith('/zones/zone_1/email/routing')) { + return cloudflareApiResponse({ enabled: true, status: 'ready' }) + } + if (method === 'GET' && url.includes('/email/routing/addresses')) { + return cloudflareApiResponse([ + { tag: 'da_1', email: 'someone@example.net', verified: '2026-01-01T00:00:00Z' } + ]) + } + if (method === 'GET' && url.includes('/zones/zone_1/email/routing/rules/catch_all')) { + return cloudflareApiResponse({ + enabled: false, + matchers: [{ type: 'all' }], + actions: [{ type: 'drop' }] + }) + } + if (method === 'GET' && url.includes('/zones/zone_1/email/routing/rules')) { + return cloudflareApiResponse([]) + } + if (method === 'POST' && url.endsWith('/zones/zone_1/email/routing/rules')) { + timeline.push(`POST rule ${body?.actions?.[0]?.type}`) + return cloudflareApiResponse(body) + } + if (method === 'PUT' && url.endsWith('/zones/zone_1/email/routing/rules/catch_all')) { + timeline.push(`PUT catch_all ${body?.actions?.[0]?.type}`) + return options.catchAllFails ? workerScriptNotFound() : cloudflareApiResponse(body) + } + + throw new Error(`Unexpected Cloudflare request: ${method} ${url}`) + }) as unknown as typeof fetch +} + +/** + * @description Install a process runner whose `wrangler deploy` records itself on the timeline. + * + * @param timeline - receives `upload` when Wrangler is asked to deploy. + * @param upload - what that Wrangler run returns. + * @returns the captured executions. + */ +function installWrangler(timeline: string[], upload: ExecResult): ExecInvocation[] { + const executions: ExecInvocation[] = [] + setDependencies( + createCliDependencies( + createProcessRunner((command, args) => { + if (command === 'bunx' && args[0] === 'wrangler' && args[1] === 'deploy') { + timeline.push('upload') + return upload + } + return successResult() + }, executions) + ) + ) + return executions +} + +describe('deploy — Email Routing to a Worker is set after the upload', () => { + const originalEnvironment = captureDeployEnvironmentSnapshot() + let projectDir = '' + + beforeEach(async () => { + process.env.CLOUDFLARE_API_TOKEN = 'cf_test_token' + delete process.env.DEVFLARE_VERIFY_DEPLOYMENT + projectDir = mkdtempSync(join(tmpdir(), 'devflare-deploy-email-order-')) + await writeFile( + join(projectDir, 'package.json'), + JSON.stringify({ name: 'deploy-email-order-tests', type: 'module' }, null, '\t') + ) + await mkdir(join(projectDir, 'src'), { recursive: true }) + // The consumer's shape: two forwards and a catch-all handing everything else to ITSELF. + await writeFile( + join(projectDir, 'devflare.config.ts'), + ` + export default { + name: 'demo-emailing', + accountId: '${TEST_ACCOUNT_ID}', + compatibilityDate: '2026-04-12', + files: { fetch: 'src/fetch.ts' }, + zones: { + 'example.com': { + emailRouting: { + rules: [{ to: 'press@example.com', forward: ['someone@example.net'] }], + catchAll: { worker: 'demo-emailing' } + } + } + } + } + ` + ) + await writeFile( + join(projectDir, 'src', 'fetch.ts'), + ` + export async function fetch(): Promise { + return new Response('ok') + } + ` + ) + }) + + afterEach(async () => { + clearDependencies() + restoreDeployEnvironmentSnapshot(originalEnvironment) + await rm(projectDir, { recursive: true, force: true }) + }) + + /** Run `devflare deploy --prod`, with any extra options. */ + async function deploy( + logger: ReturnType, + extra: Record = {} + ) { + return runDeployCommand( + { command: 'deploy', args: [], options: { prod: true, ...extra } }, + logger as never, + { cwd: projectDir } + ) + } + + test('the forward rule is written before the upload and the worker catch-all after it', async () => { + // Mutant: moving the catch-all back into preparation puts `PUT catch_all worker` ahead of + // `upload` — the order that made the first deploy fail. + const timeline: string[] = [] + mockZone(timeline) + installWrangler(timeline, successResult(`Worker Version ID: ${VERSION_ID}`)) + const logger = createLogger() + + const result = await deploy(logger) + + expect(result.exitCode).toBe(0) + expect(timeline).toEqual(['POST rule forward', 'upload', 'PUT catch_all worker']) + expect(renderMessages(logger).join('\n')).toContain( + 'Provisioned after the upload: Email catch-all (zone example.com) — set to worker' + ) + }) + + test('a failed upload never attempts the worker route', async () => { + // Mutant: running the after-upload step before the exit-code check (or regardless of it). + const timeline: string[] = [] + mockZone(timeline) + installWrangler(timeline, { + exitCode: 1, + stdout: '', + stderr: 'upload failed', + failed: true, + killed: false + }) + + const result = await deploy(createLogger()) + + expect(result.exitCode).toBe(1) + expect(timeline).toEqual(['POST rule forward', 'upload']) + }) + + test('a route that fails AFTER a good upload fails the deploy, saying the Worker shipped', async () => { + // An operator told only "Deployment failed" would believe nothing changed, while the Worker is + // live. Mutant: swallowing the step's error into a warning exits 0 here. + const timeline: string[] = [] + mockZone(timeline, { catchAllFails: true }) + installWrangler(timeline, successResult(`Worker Version ID: ${VERSION_ID}`)) + const logger = createLogger() + + const result = await deploy(logger) + + expect(result.exitCode).toBe(1) + expect(timeline).toEqual(['POST rule forward', 'upload', 'PUT catch_all worker']) + const output = renderMessages(logger).join('\n') + expect(output).toContain(`"demo-emailing" WAS uploaded (version ${VERSION_ID})`) + expect(output).toContain('Email catch-all (zone example.com) failed') + expect(output).toContain('Workers Script Info not found') + expect(output).not.toContain('Deployed successfully') + }) + + test('--dry-run lists the worker route as after the upload, and writes nothing', async () => { + // Mutant: dropping the after-upload step from the dry-run plan leaves the catch-all unlisted. + const timeline: string[] = [] + mockZone(timeline) + const executions = installWrangler(timeline, successResult()) + const logger = createLogger() + + const result = await deploy(logger, { 'dry-run': true }) + + expect(result.exitCode).toBe(0) + expect(timeline).toEqual([]) + expect(executions).toEqual([]) + const output = renderMessages(logger).join('\n') + expect(output).toContain('Email rule press@example.com (zone example.com)') + expect(output).toContain( + 'Email catch-all (zone example.com) — set to worker — after the upload' + ) + }) +}) diff --git a/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts b/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts new file mode 100644 index 00000000..2ffdb536 --- /dev/null +++ b/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, test } from 'bun:test' +import { describeAfterUploadRoutingFailure } from '../../../src/cli/commands/deploy/after-upload' +import { EmailRouteError } from '../../../src/config/deploy-zones' + +const NO_PROGRESS = { created: [], existing: [], warnings: [] } + +describe('describeAfterUploadRoutingFailure', () => { + test('says the Worker WAS uploaded, names the route, and keeps what Cloudflare said', () => { + const message = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + versionId: 'version-1', + error: new EmailRouteError( + 'Email catch-all (zone example.com)', + new Error('Cloudflare PUT failed (2016): Workers Script Info not found') + ), + progress: NO_PROGRESS + }) + + expect(message).toContain('"demo-emailing" WAS uploaded (version version-1)') + expect(message).toContain('Email catch-all (zone example.com) failed') + expect(message).toContain('Workers Script Info not found') + // The cause appears once — not again inside a route-prefixed copy of itself. + expect(message.split('Workers Script Info not found')).toHaveLength(2) + expect(message).toContain('Re-run `devflare deploy`') + }) + + test('an error that names no route still says the Worker shipped', () => { + const message = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + error: new Error('network down'), + progress: NO_PROGRESS + }) + + expect(message).toContain('"demo-emailing" WAS uploaded,') + expect(message).toContain('a Worker-targeted Email Routing route failed — network down') + }) + + test('lists the routes this deploy set before the failure, and only when there were any', () => { + const withProgress = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + error: new EmailRouteError('Email catch-all (zone example.com)', new Error('boom')), + progress: { + created: ['Email rule inbox@example.com (zone example.com)'], + existing: [], + warnings: [] + } + }) + const without = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + error: new EmailRouteError('Email catch-all (zone example.com)', new Error('boom')), + progress: NO_PROGRESS + }) + + expect(withProgress).toContain( + 'Set by this deploy before the failure: Email rule inbox@example.com (zone example.com).' + ) + expect(without).not.toContain('before the failure') + }) +}) diff --git a/packages/devflare/tests/unit/config/deploy-zones.test.ts b/packages/devflare/tests/unit/config/deploy-zones.test.ts index 9c8b3daf..ede86496 100644 --- a/packages/devflare/tests/unit/config/deploy-zones.test.ts +++ b/packages/devflare/tests/unit/config/deploy-zones.test.ts @@ -2,6 +2,8 @@ import { describe, expect, mock, test } from 'bun:test' import { prepareMaterializedConfigResourcesForDeploy } from '../../../src/config/deploy-resources' import { DEVFLARE_RECORD_COMMENT, + EmailRouteError, + provisionWorkerEmailRoutes, provisionZoneResources, qualifyRecordName, type ZoneProvisionApi, @@ -85,6 +87,20 @@ async function provision( return result } +/** Run the AFTER-UPLOAD pass — the Worker-targeted routes — and hand back what it filled. */ +async function provisionAfterUpload( + zones: DevflareConfig['zones'], + api: ZoneProvisionApi +): Promise { + const result: ZoneProvisionResult = { + created: [], + existing: [], + warnings: [] + } + await provisionWorkerEmailRoutes(zones, 'acct_1', api, result) + return result +} + describe('qualifyRecordName — where a declared record actually lands', () => { test('a relative name resolves against the domain it was declared under', () => { expect(qualifyRecordName('_dmarc', 'example.com')).toBe('_dmarc.example.com') @@ -112,11 +128,11 @@ describe('qualifyRecordName — where a declared record actually lands', () => { }) }) -describe('provisionZoneResources — Email Routing', () => { +describe('Email Routing rules and the catch-all', () => { test('creates a declared rule that is not there, matching Cloudflare shape', async () => { const api = makeZoneApi() - const result = await provision( + const result = await provisionAfterUpload( { 'example.com': { emailRouting: { @@ -155,7 +171,7 @@ describe('provisionZoneResources — Email Routing', () => { ]) }) - const result = await provision( + const result = await provisionAfterUpload( { 'example.com': { emailRouting: { @@ -191,7 +207,7 @@ describe('provisionZoneResources — Email Routing', () => { ]) }) - const result = await provision( + const result = await provisionAfterUpload( { 'example.com': { emailRouting: { @@ -213,7 +229,7 @@ describe('provisionZoneResources — Email Routing', () => { // rejects this too; the runtime must not depend on that being the only guard.) const api = makeZoneApi() - await provision( + await provisionAfterUpload( { 'example.com': { emailRouting: { @@ -315,6 +331,172 @@ describe('provisionZoneResources — Email Routing', () => { }) }) +describe('Email Routing to a Worker waits for the upload', () => { + /* + Cloudflare refuses a route naming a Worker that does not exist yet (`2016: Workers Script Info + not found`), so an app routing mail to ITS OWN worker could never pass its first deploy while + those routes were written in preparation. Preparation now skips every `worker` route and + `provisionWorkerEmailRoutes` writes them after the upload. + */ + const selfRouting: DevflareConfig['zones'] = { + 'example.com': { + emailRouting: { + rules: [ + { to: 'press@example.com', forward: ['someone@example.net'] }, + { to: 'inbox@example.com', worker: 'emailing' } + ], + catchAll: { worker: 'emailing' } + } + } + } + + test('preparation sets NO worker route — not the rule, not the catch-all', async () => { + // Mutant: dropping the `!isWorkerTargeted` filter on the catch-all or the rules in + // `provisionEmailRouting` puts the write back before the upload, which is the defect. + const api = makeZoneApi() + + const result = await provision(selfRouting, api) + + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + const ruleActions = api.createEmailRoutingRule.mock.calls.map( + (call) => call[1].actions[0]?.type + ) + expect(ruleActions).not.toContain('worker') + expect(result.created.join('\n')).not.toContain('inbox@example.com') + expect(result.created.join('\n')).not.toContain('catch-all') + }) + + test('preparation still creates the FORWARD rule, and its destination first', async () => { + // Only `worker` actions moved. Mutant: filtering every rule out of preparation (or skipping + // `provisionRoutingRules` there) leaves forwarding rules unwritten. + const order: string[] = [] + const api = makeZoneApi({ + listDestinationAddresses: mock(async () => []), + createDestinationAddress: mock(async (_accountId: string, email: string) => { + order.push('address') + return { email } + }), + createEmailRoutingRule: mock(async (_zoneId: string, rule) => { + order.push(`rule:${rule.actions[0]?.type}`) + return rule + }) + }) + + const result = await provision(selfRouting, api) + + expect(order).toEqual(['address', 'rule:forward']) + expect(result.created).toContain('Email rule press@example.com (zone example.com)') + }) + + test('the after-upload pass sets the worker rule and the worker catch-all, and only those', async () => { + const api = makeZoneApi() + + const result = await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) + expect(api.createEmailRoutingRule.mock.calls[0]?.[1].actions).toEqual([ + { type: 'worker', value: ['emailing'] } + ]) + expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(1) + expect(api.setEmailRoutingCatchAll.mock.calls[0]?.[1]).toMatchObject({ + enabled: true, + actions: [{ type: 'worker', value: ['emailing'] }] + }) + // It touches nothing preparation owns: no routing switch, no destination, no DNS. + expect(api.getEmailRoutingSettings).not.toHaveBeenCalled() + expect(api.listDestinationAddresses).not.toHaveBeenCalled() + expect(result.created).toEqual([ + 'Email rule inbox@example.com (zone example.com)', + 'Email catch-all (zone example.com) — set to worker' + ]) + }) + + test('a worker rule keeps the priority its place in the WHOLE list gives it', async () => { + // Mutant: numbering by index within the after-upload subset gives `inbox@` priority 1, the + // same as `press@`, so the split silently reorders the zone's rules. + const api = makeZoneApi() + + await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule.mock.calls[0]?.[1].priority).toBe(2) + }) + + test('a second deploy is a no-op that reports every worker route as existing', async () => { + const api = makeZoneApi({ + listEmailRoutingRules: mock(async () => [ + { + tag: 'r2', + matchers: [ + { + type: 'literal' as const, + field: 'to' as const, + value: 'inbox@example.com' + } + ], + actions: [{ type: 'worker' as const, value: ['emailing'] }] + } + ]), + getEmailRoutingCatchAll: mock(async () => ({ + enabled: true, + matchers: [{ type: 'all' as const }], + actions: [{ type: 'worker' as const, value: ['emailing'] }] + })) + }) + + const result = await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule).not.toHaveBeenCalled() + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + expect(result.created).toEqual([]) + expect(result.existing).toEqual([ + 'Email rule inbox@example.com (zone example.com)', + 'Email catch-all (zone example.com)' + ]) + }) + + test('a domain with no worker route costs the after-upload pass no request at all', async () => { + const api = makeZoneApi() + + await provisionAfterUpload( + { + 'example.com': { + emailRouting: { + rules: [{ to: 'a@example.com', drop: true }], + catchAll: { drop: true } + }, + dns: [{ type: 'TXT', name: '_dmarc', content: 'v=DMARC1; p=none' }] + } + }, + api + ) + + expect(api.resolveZone).not.toHaveBeenCalled() + }) + + test("a failed write names the route, keeping Cloudflare's own error as the cause", async () => { + const cloudflare = new Error( + 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found' + ) + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async () => { + throw cloudflare + }) + }) + const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + + const failure = provisionWorkerEmailRoutes(selfRouting, 'acct_1', api, result) + + await expect(failure).rejects.toBeInstanceOf(EmailRouteError) + await failure.catch((error: EmailRouteError) => { + expect(error.route).toBe('Email catch-all (zone example.com)') + expect(error.cause).toBe(cloudflare) + expect(error.message).toContain('Workers Script Info not found') + }) + // The rule before it was set, and the accumulator still says so after the throw. + expect(result.created).toEqual(['Email rule inbox@example.com (zone example.com)']) + }) +}) + describe('provisionZoneResources — forwarding destinations', () => { const forwards = { 'example.com': { @@ -899,6 +1081,26 @@ describe('the deploy path guards zone provisioning', () => { expect(result.created.zones.length).toBeGreaterThan(0) }) + test('describeOnly hands back an after-upload step that PLANS the worker routes and writes nothing', async () => { + // `--dry-run` runs this step to list what a real deploy would set after the upload. It is bound + // to the stubbed API, so the worker rule shows up as a would-create while no write leaves. + // Mutant: binding the step to a fresh, unstubbed API instead of the stubbed object makes + // `createEmailRoutingRule` fire here. + const api = worstCaseApi() + + const prepared = await prepareMaterializedConfigResourcesForDeploy(config, { + accountId: 'acct_1', + describeOnly: true, + cloudflare: api + }) + const afterUpload: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + await prepared.provisionAfterUpload?.(afterUpload) + + expectNoMutation(api) + expect(api.listEmailRoutingRules).toHaveBeenCalledTimes(1) + expect(afterUpload.created).toEqual(['Email rule support@example.com (zone example.com)']) + }) + test('a PREVIEW deploy provisions no zone resources, and does not even look', async () => { // A rule or a record belongs to the whole domain and has no branch-scoped form, so a preview // that provisioned them would redirect production mail from a feature branch and leave the @@ -915,17 +1117,24 @@ describe('the deploy path guards zone provisioning', () => { expectNoMutation(api) expect(api.resolveZone).not.toHaveBeenCalled() expect(result.created.zones).toEqual([]) + // Nor anything left for after the upload. + expect(result.provisionAfterUpload).toBeUndefined() }) test('a real deploy DOES perform them, so both guards above are measuring something', async () => { // The control for both. Same config, same mocks, neither guard engaged. const api = worstCaseApi() - await prepareMaterializedConfigResourcesForDeploy(config, { + const prepared = await prepareMaterializedConfigResourcesForDeploy(config, { accountId: 'acct_1', cloudflare: api }) + // The declared rule routes to a Worker, so preparation leaves it for after the upload… + expect(api.createEmailRoutingRule).not.toHaveBeenCalled() + await prepared.provisionAfterUpload?.({ created: [], existing: [], warnings: [] }) + + // …and the step it hands back writes it. expect(api.enableEmailRouting).toHaveBeenCalledTimes(1) expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(1) From 7a153cc6f4b7ef1ab483a119d23109337df398f4 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Tue, 1 Dec 2026 02:25:41 +0100 Subject: [PATCH 2/3] fix(deploy): grade and harden the after-upload Email Routing step Review follow-up to 1c84635. - Order: the step runs only after the upload is proven. New command-flow cases cover a Wrangler exit 0 with no upload evidence (no catch-all write) and a percentage rollout (split first, then the route; a failed split skips it). - Messages: `EmailRouteError` now carries the operation (read/write) and the target Worker. A failed read says nothing about the route changed; a failed write names the Worker it hands mail to; a route to ANOTHER Worker says to deploy that one first instead of suggesting a re-run that cannot fix it. - Early exits: a reused live version runs the step before a required-fresh deployment is refused (adding a worker rule never changes the upload, so that refusal used to block the route forever). The failed-upload, unproven-upload, unresolved-account, failed-verification and failed-rollout exits now name the Worker routes left unset (`describeWorkerEmailRoutes`). - Propagation: a write answered with 2016 is retried three times, 3 s apart (`DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS` overrides the delay; tests inject a sleep). Nothing else is retried. How long Email Routing actually takes to see a new Worker is not measured; the changeset and docs say only what the code does. - The after-upload result field is now `afterUpload: { routes, provision }`. - Dropped the "waiting costs nothing" claim: a route to a misspelled Worker now fails after the Worker ships. Co-Authored-By: Claude Opus 5.5 --- .changeset/email-routing-after-upload.md | 2 +- .../lib/docs/content/configuration/part-3.ts | 2 +- packages/devflare/LLM.md | 2 +- packages/devflare/src/cli/commands/deploy.ts | 120 +++++----- .../src/cli/commands/deploy/after-upload.ts | 66 ++++-- .../devflare/src/config/deploy-resources.ts | 59 +++-- packages/devflare/src/config/deploy-zones.ts | 179 +++++++++++---- .../deploy-email-routing-after-upload.test.ts | 205 ++++++++++++++++-- .../unit/cli/deploy-after-upload.test.ts | 82 ++++++- .../tests/unit/config/deploy-zones.test.ts | 127 ++++++++++- 10 files changed, 688 insertions(+), 156 deletions(-) diff --git a/.changeset/email-routing-after-upload.md b/.changeset/email-routing-after-upload.md index e50018ea..77622970 100644 --- a/.changeset/email-routing-after-upload.md +++ b/.changeset/email-routing-after-upload.md @@ -2,4 +2,4 @@ 'devflare': patch --- -Email Routing rules and catch-alls whose action is `worker` are now set after Wrangler's upload instead of before it, so the first deploy of a Worker that routes mail to itself no longer fails with `2016: Workers Script Info not found`. If one of those routes fails after a successful upload, the deploy fails and says the Worker was uploaded and which route is missing; `--dry-run` lists them as "after the upload". +Email Routing rules and catch-alls whose action is `worker` are now set after Wrangler's upload instead of before it, so the first deploy of a Worker that routes mail to itself is no longer refused before the Worker exists. If Cloudflare still answers `2016: Workers Script Info not found` right after the upload, the route is retried three times a few seconds apart before the deploy fails; any failure says the Worker was uploaded and which route was not set, and a deploy that stops before that step names the routes it left unset. `--dry-run` lists these routes as "after the upload". diff --git a/apps/documentation/src/lib/docs/content/configuration/part-3.ts b/apps/documentation/src/lib/docs/content/configuration/part-3.ts index 59064ee4..ed361521 100644 --- a/apps/documentation/src/lib/docs/content/configuration/part-3.ts +++ b/apps/documentation/src/lib/docs/content/configuration/part-3.ts @@ -219,7 +219,7 @@ export const configurationDocsPart3: DocPage[] = [ 'Everything else Devflare provisions is account-scoped. Email Routing rules and DNS records are not: they belong to a zone, which is a different identifier reached by a different lookup and gated by a different token scope. The `zones` key is where they are declared, and a deploy reconciles them.', 'The key is a domain rather than a zone id, because a domain is what an author knows. Devflare walks the domain labels up to the apex to find the zone, so `mail.example.com` is configured under its own name and its records land in the `example.com` zone. A relative record name resolves against the domain it was declared under, not the zone apex — for a subdomain those differ, and the apex would be the wrong place.', 'Rules reconcile on the address they claim and records on their type and name, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever deleted: a zone almost always carries rules and records this config never mentioned.', - 'Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. If the upload fails those routes are not attempted; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded and which route is missing. A gradual rollout sets them after its traffic split.', + 'Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. A write Cloudflare answers with that error (code 2016) is retried three times, a few seconds apart, in case Email Routing has not seen the new Worker yet. If the upload fails or cannot be proven, those routes are not attempted and the failure names them; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded, which route was not set, and which Worker it hands mail to. A gradual rollout sets them after its traffic split. One cost: a route to a different Worker that does not exist now fails after this Worker has shipped, not before.', '`emailSending` and `emailRouting` are different Cloudflare products that happen to share a zone. Routing is inbound — what happens to mail arriving for the domain. Sending is outbound — whether a `send_email` binding may send from an address here. A domain that does both is onboarded to both, separately, and a subdomain gets its own DKIM key rather than inheriting the apex one. Sending readiness is reported rather than waited on: Cloudflare writes the records at onboarding and they take minutes to propagate, so a deploy that failed on them would fail one that did everything right.' ], table: { diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index ff913848..8f856aaa 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -3470,7 +3470,7 @@ The key is a domain rather than a zone id, because a domain is what an author kn Rules reconcile on the address they claim and records on their type and name, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever deleted: a zone almost always carries rules and records this config never mentioned. -Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. If the upload fails those routes are not attempted; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded and which route is missing. A gradual rollout sets them after its traffic split. +Zone work runs at two points of a deploy. Sending onboarding, enabling routing, destination addresses, `forward` and `drop` rules and catch-alls, and DNS are reconciled before Wrangler uploads, after the account resources, so a config error fails before any zone is touched. A rule or catch-all whose action is `worker` waits until the upload has succeeded, because Cloudflare refuses a route naming a Worker that does not exist yet — which is exactly the first deploy of a Worker that routes mail to itself. A write Cloudflare answers with that error (code 2016) is retried three times, a few seconds apart, in case Email Routing has not seen the new Worker yet. If the upload fails or cannot be proven, those routes are not attempted and the failure names them; if one of them fails after a good upload, the deploy fails and says the Worker was uploaded, which route was not set, and which Worker it hands mail to. A gradual rollout sets them after its traffic split. One cost: a route to a different Worker that does not exist now fails after this Worker has shipped, not before. `emailSending` and `emailRouting` are different Cloudflare products that happen to share a zone. Routing is inbound — what happens to mail arriving for the domain. Sending is outbound — whether a `send_email` binding may send from an address here. A domain that does both is onboarded to both, separately, and a subdomain gets its own DKIM key rather than inheriting the apex one. Sending readiness is reported rather than waited on: Cloudflare writes the records at onboarding and they take minutes to propagate, so a deploy that failed on them would fail one that did everything right. diff --git a/packages/devflare/src/cli/commands/deploy.ts b/packages/devflare/src/cli/commands/deploy.ts index a4b23b79..85b79875 100644 --- a/packages/devflare/src/cli/commands/deploy.ts +++ b/packages/devflare/src/cli/commands/deploy.ts @@ -33,7 +33,7 @@ import { } from '../preview' import { createCliTheme, dim, green, logLine, yellow, yellowBold } from '../ui' import { prepareBuildArtifacts } from './build-artifacts' -import { describeAfterUploadRoutingFailure } from './deploy/after-upload' +import { describeAfterUploadRoutingFailure, describeRoutesNotSet } from './deploy/after-upload' import { inferRecordSource, writeDeployResultMetadata } from './deploy/metadata' import { prepareDeployConfig, @@ -176,7 +176,7 @@ export async function runDeployCommand( // The routes a real deploy writes only after the upload. Describe-only preparation bound // this step to its stubbed API, so running it here reads live state and writes nothing. const afterUpload: ZoneProvisionResult = { created: [], existing: [], warnings: [] } - await describeResult.provisionAfterUpload?.(afterUpload) + await describeResult.afterUpload?.provision(afterUpload) const wouldCreate = [ ...describeResult.created.kv.map((n) => `KV: ${n}`), ...describeResult.created.d1.map((n) => `D1: ${n}`), @@ -428,13 +428,57 @@ export async function runDeployCommand( }) } + // → KEY: Email Routing to a Worker waits for the upload, because Cloudflare refuses a route + // naming a Worker that does not exist yet. `runAfterUpload` is called once the upload is + // PROVEN — after the traffic split for a percentage rollout, or before refusing a reused + // live version, since the Worker exists there too — and every exit that stops short of it + // names the routes it left unset (`routesNotSet`). A version-only upload runs it as well: + // the script exists once any version is uploaded, and preparation has already reconciled + // the zone's other routes. A preview has no zone work, so no step at all. + const afterUpload = prepared.deployResources.afterUpload + let afterUploadSettled = false + const routesNotSet = (reason: string): string => + describeRoutesNotSet(afterUploadSettled ? [] : afterUpload?.routes, reason) + const runAfterUpload = async (): Promise => { + if (!afterUpload || afterUploadSettled) return undefined + afterUploadSettled = true + + const routed: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + logLine(logger, dim('Pointing Email Routing at the uploaded Worker…', theme)) + try { + await afterUpload.provision(routed) + } catch (error) { + const failure = describeAfterUploadRoutingFailure({ + workerName: prepared.config.name, + versionId: resolvedVersionId, + error, + progress: routed + }) + await persistDeployMetadata({ status: 'failure', exitCode: 1, error: failure }) + logger.error(failure) + return { exitCode: 1, output: structuredOutput } + } + + if (routed.created.length > 0) { + logLine(logger, `Provisioned after the upload: ${routed.created.join(', ')}`) + } + if (routed.existing.length > 0) { + logLine(logger, `Reused after the upload: ${routed.existing.join(', ')}`) + } + for (const warning of routed.warnings) { + logger.warn(warning) + } + return undefined + } + if (deployProc.exitCode !== 0) { + const notSet = routesNotSet('the upload failed') await persistDeployMetadata({ status: 'failure', exitCode: 1, - error: deployProc.stderr || deployProc.stdout || 'Wrangler deploy failed' + error: `${deployProc.stderr || deployProc.stdout || 'Wrangler deploy failed'}${notSet}` }) - logger.error('Deployment failed') + logger.error(`Deployment failed${notSet ? `.${notSet}` : ''}`) return { exitCode: 1, output: structuredOutput } } @@ -553,6 +597,12 @@ export async function runDeployCommand( verificationNote = reuseMessage if (requireFreshProductionDeployment) { + // The Worker exists — the live version proves it — so its Email Routing is set + // BEFORE refusing. Otherwise a deploy that only added a worker rule (which changes + // nothing Wrangler uploads, so the version is always reused) could never set it. + const routingFailure = await runAfterUpload() + if (routingFailure) return routingFailure + await persistDeployMetadata({ status: 'failure', exitCode: 1, @@ -607,9 +657,11 @@ export async function runDeployCommand( }) // A percentage rollout leaves traffic un-split as well as unproven, // so it owes the operator the extra half of the story. - const failure = usePercentageRollout - ? `${evidence} The ${rolloutPercentage}% gradual rollout was not started; re-run \`devflare deploy --prod --percentage ${rolloutPercentage}\`, or split traffic manually with \`wrangler versions deploy\`.` - : evidence + const failure = `${ + usePercentageRollout + ? `${evidence} The ${rolloutPercentage}% gradual rollout was not started; re-run \`devflare deploy --prod --percentage ${rolloutPercentage}\`, or split traffic manually with \`wrangler versions deploy\`.` + : evidence + }${routesNotSet('no upload could be proven')}` await persistDeployMetadata({ status: 'failure', exitCode: 1, @@ -636,13 +688,14 @@ export async function runDeployCommand( resolvedAccountId = await ensureResolvedAccountId() if (!resolvedAccountId) { + const notSet = routesNotSet('the upload could not be verified') await persistDeployMetadata({ status: 'failure', exitCode: 1, - error: 'Devflare could not resolve a Cloudflare account id.' + error: `Devflare could not resolve a Cloudflare account id.${notSet}` }) logger.error( - 'Deployment verification failed: Devflare could not resolve a Cloudflare account id. Pass cloudflare-account-id to the action or set accountId in devflare.config.ts.' + `Deployment verification failed: Devflare could not resolve a Cloudflare account id. Pass cloudflare-account-id to the action or set accountId in devflare.config.ts.${notSet}` ) return { exitCode: 1, output: structuredOutput } } @@ -663,7 +716,9 @@ export async function runDeployCommand( theme }) } catch (error) { - const message = error instanceof Error ? error.message : String(error) + const message = `${error instanceof Error ? error.message : String(error)}${routesNotSet( + 'the upload could not be verified' + )}` await persistDeployMetadata({ status: 'failure', exitCode: 1, @@ -708,11 +763,13 @@ export async function runDeployCommand( ) if (rolloutProc.exitCode !== 0) { - const rolloutError = `The new Worker version ${resolvedVersionId} was uploaded, but \`wrangler versions deploy\` failed to route ${rolloutPercentage}% of production traffic to it. Re-run the rollout, or split traffic manually with \`wrangler versions deploy\`.` + const notSet = routesNotSet('the traffic split failed') + const rolloutError = `The new Worker version ${resolvedVersionId} was uploaded, but \`wrangler versions deploy\` failed to route ${rolloutPercentage}% of production traffic to it. Re-run the rollout, or split traffic manually with \`wrangler versions deploy\`.${notSet}` + const wranglerOutput = rolloutProc.stderr || rolloutProc.stdout await persistDeployMetadata({ status: 'failure', exitCode: 1, - error: rolloutProc.stderr || rolloutProc.stdout || rolloutError + error: wranglerOutput ? `${wranglerOutput}${notSet}` : rolloutError }) logger.error(rolloutError) return { exitCode: 1, output: structuredOutput } @@ -723,43 +780,8 @@ export async function runDeployCommand( ) } - // → KEY: Email Routing to a Worker waits for the upload, because Cloudflare refuses a route - // naming a Worker that does not exist yet. It runs here — after the upload is PROVEN and, - // for a percentage rollout, after the traffic split — so a failed upload or rollout never - // reaches it. A version-only upload runs it too: the script exists once any version is - // uploaded, and preparation has already reconciled the zone's other routes, so skipping - // these would leave the zone half-reconciled. (A preview has no zone work at all.) - if (prepared.deployResources.provisionAfterUpload) { - const routed: ZoneProvisionResult = { created: [], existing: [], warnings: [] } - logLine(logger, dim('Pointing Email Routing at the uploaded Worker…', theme)) - try { - await prepared.deployResources.provisionAfterUpload(routed) - } catch (error) { - const failure = describeAfterUploadRoutingFailure({ - workerName: prepared.config.name, - versionId: resolvedVersionId, - error, - progress: routed - }) - await persistDeployMetadata({ - status: 'failure', - exitCode: 1, - error: failure - }) - logger.error(failure) - return { exitCode: 1, output: structuredOutput } - } - - if (routed.created.length > 0) { - logLine(logger, `Provisioned after the upload: ${routed.created.join(', ')}`) - } - if (routed.existing.length > 0) { - logLine(logger, `Reused after the upload: ${routed.existing.join(', ')}`) - } - for (const warning of routed.warnings) { - logger.warn(warning) - } - } + const routingFailure = await runAfterUpload() + if (routingFailure) return routingFailure if (resolvedAccountId) { const previewRegistryScope = isBranchScopedPreviewDeployment diff --git a/packages/devflare/src/cli/commands/deploy/after-upload.ts b/packages/devflare/src/cli/commands/deploy/after-upload.ts index cc28cb49..ba0b318a 100644 --- a/packages/devflare/src/cli/commands/deploy/after-upload.ts +++ b/packages/devflare/src/cli/commands/deploy/after-upload.ts @@ -9,8 +9,12 @@ // // → KEY: a failure here comes after a SUCCESSFUL upload. The Worker is live, and // an operator told only "Deployment failed" would reasonably believe nothing -// changed. The message therefore says what shipped, which route did not, and -// that re-running is safe. +// changed. So the message says what shipped, which route failed, whether it +// was only READ (nothing about it changed) or WRITTEN, which Worker it hands +// mail to, and suggests a re-run only where a re-run could help. +// → KEY: every OTHER exit between preparation and this step leaves those routes +// unset, and says so through `describeRoutesNotSet` — preparation may already +// have enabled routing and rewritten the zone's MX records. import { EmailRouteError, type ZoneProvisionResult } from '../../../config/deploy-zones' @@ -19,9 +23,9 @@ import { EmailRouteError, type ZoneProvisionResult } from '../../../config/deplo * * @param input.workerName - the Worker that was uploaded. * @param input.versionId - its uploaded version, when known. - * @param input.error - what the step threw; an `EmailRouteError` names its route. + * @param input.error - what the step threw; an `EmailRouteError` names its route, operation and target. * @param input.progress - what the step set or found before it failed. - * @returns one message saying the Worker WAS uploaded, which route failed and why, and how to retry. + * @returns one message saying the Worker WAS uploaded, which route failed and why, and what to do. */ export function describeAfterUploadRoutingFailure(input: { workerName: string @@ -29,28 +33,58 @@ export function describeAfterUploadRoutingFailure(input: { error: unknown progress: ZoneProvisionResult }): string { - const version = input.versionId ? ` (version ${input.versionId})` : '' - const route = - input.error instanceof EmailRouteError - ? input.error.route - : 'a Worker-targeted Email Routing route' + const failed = input.error instanceof EmailRouteError ? input.error : undefined const cause = - input.error instanceof EmailRouteError && input.error.cause instanceof Error - ? input.error.cause.message + failed?.cause instanceof Error + ? failed.cause.message : input.error instanceof Error ? input.error.message : String(input.error) + const version = input.versionId ? ` (version ${input.versionId})` : '' + const target = failed?.worker ? ` → Worker "${failed.worker}"` : '' + const route = failed ? `${failed.route}${target}` : 'a Worker-targeted Email Routing route' const parts = [ - `The Worker "${input.workerName}" WAS uploaded${version}, but Email Routing to it could not be completed: ${route} failed — ${cause}.`, - 'Mail for that route is not reaching the Worker until this is fixed.' + `The Worker "${input.workerName}" WAS uploaded${version}, but Email Routing failed.` ] + + if (failed?.operation === 'read') { + parts.push( + `${route} could not be read: ${cause}.`, + 'This deploy changed nothing about it, so whatever an earlier deploy set is still in place.', + 'Re-run `devflare deploy` to retry.' + ) + } else { + parts.push( + `${route} could not be set: ${cause}.`, + 'That route still does what it did before this deploy — nothing, if it is new.' + ) + parts.push( + failed?.worker && failed.worker !== input.workerName + ? `"${failed.worker}" is not the Worker this deploy uploads: if it does not exist in this account, deploy it (or correct the name) first — re-running this deploy cannot create it — then re-run \`devflare deploy\`.` + : 'Re-run `devflare deploy` to retry; routes that are already correct are left as they are.' + ) + } + if (input.progress.created.length > 0) { parts.push(`Set by this deploy before the failure: ${input.progress.created.join('; ')}.`) } - parts.push( - 'Re-run `devflare deploy` to retry; routes that are already correct are left as they are.' - ) return parts.join(' ') } + +/** + * @description Name the Worker routes a deploy that stopped early did NOT set. + * + * @param routes - the after-upload step's route labels; empty when it was not owed. + * @param reason - why the step did not run, as a clause (`the upload failed`). + * @returns a sentence to append to the failure, or an empty string when nothing was left unset. + */ +export function describeRoutesNotSet(routes: string[] | undefined, reason: string): string { + if (!routes || routes.length === 0) return '' + + return ( + ` Email Routing to a Worker was NOT set, because ${reason}: ${routes.join('; ')}. ` + + 'Any other zone changes listed above were already made. A later successful `devflare deploy` sets these routes.' + ) +} diff --git a/packages/devflare/src/config/deploy-resources.ts b/packages/devflare/src/config/deploy-resources.ts index 2164176a..14f43d54 100644 --- a/packages/devflare/src/config/deploy-resources.ts +++ b/packages/devflare/src/config/deploy-resources.ts @@ -49,7 +49,7 @@ import { } from './binding-resolution-helpers' import { provisionEventSubscriptions, type SubscriptionProvisionApi } from './deploy-subscriptions' import { - hasWorkerEmailRoutes, + describeWorkerEmailRoutes, provisionWorkerEmailRoutes, provisionZoneResources, type ZoneProvisionApi, @@ -189,16 +189,41 @@ export interface PrepareConfigResourcesForDeployResult { warnings: string[] /** * The zone work this deploy owes AFTER Wrangler's upload — the Email Routing routes whose action - * is `worker` — bound to the account and the (dry-run-stubbed, when describing) API this - * preparation used. Absent when there is none, which includes every preview. - * - * → KEY: call it only once the upload has been PROVEN. Cloudflare refuses a route naming a Worker - * that does not exist yet, so on a first deploy it can only succeed after the upload; and after - * a failed upload nothing new is pointed at a Worker that may not be there. + * is `worker`. Absent when there is none, which includes every preview. + */ + afterUpload?: AfterUploadZoneWork +} + +/** + * Email Routing a deploy sets only once its Worker exists, bound to the account and the + * (dry-run-stubbed, when describing) API the preparation used. + * + * → KEY: call `provision` only once the upload has been PROVEN. Cloudflare refuses a route naming a + * Worker that does not exist yet, so on a first deploy it can only succeed after the upload; and + * after a failed upload nothing new is pointed at a Worker that may not be there. Every exit that + * stops short of it names `routes`, so an operator learns what was left unset. + */ +export interface AfterUploadZoneWork { + /** The routes the step will reconcile, labelled without asking Cloudflare. */ + routes: string[] + /** + * Reconcile them. * * @param result - the caller's accumulator, appended to in place so a throw still reports progress. */ - provisionAfterUpload?: (result: ZoneProvisionResult) => Promise + provision: (result: ZoneProvisionResult) => Promise +} + +/** + * @description The wait between attempts at a route Email Routing answered 2016 for. + * + * @returns `DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS` when it is a non-negative number, else undefined + * for the reconciler's own default. Read here, at the composition point, like the deploy + * verification delays, so tests can run the real command without sleeping. + */ +function emailRouteRetryDelayMs(): number | undefined { + const configured = Number.parseInt(process.env.DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS ?? '', 10) + return Number.isFinite(configured) && configured >= 0 ? configured : undefined } interface ResolvedResourceIdsByNameResult { @@ -730,7 +755,7 @@ export async function prepareMaterializedConfigResourcesForDeploy( // // → KEY: "last in preparation" is not last in the deploy for the routes whose action is // `worker`. Cloudflare refuses those until the Worker exists, so `provisionZoneResources` - // skips them and `provisionAfterUpload` below carries them past the upload. Everything they + // skips them and `afterUpload` below carries them past the upload. Everything they // need from the zone (routing enabled) still happens here, under the same fail-early rule. // // → KEY: the accumulator arrays are passed IN rather than a result being returned. A returned @@ -759,10 +784,16 @@ export async function prepareMaterializedConfigResourcesForDeploy( // Bound to the SAME `cloudflareApi` object, so a describe-only preparation hands back a step // whose mutations are the stubs above — a dry-run can run it to plan, and change nothing. - const provisionAfterUpload = - hasZoneWork && hasWorkerEmailRoutes(resolvedConfig.zones) - ? (result: ZoneProvisionResult) => - provisionWorkerEmailRoutes(resolvedConfig.zones, accountId, cloudflareApi, result) + const afterUploadRoutes = hasZoneWork ? describeWorkerEmailRoutes(resolvedConfig.zones) : [] + const afterUpload: AfterUploadZoneWork | undefined = + afterUploadRoutes.length > 0 + ? { + routes: afterUploadRoutes, + provision: (result) => + provisionWorkerEmailRoutes(resolvedConfig.zones, accountId, cloudflareApi, result, { + delayMs: emailRouteRetryDelayMs() + }) + } : undefined const config = withResolvedIdBindings(resolvedConfig, { @@ -796,7 +827,7 @@ export async function prepareMaterializedConfigResourcesForDeploy( created, existing, warnings, - ...(provisionAfterUpload ? { provisionAfterUpload } : {}) + ...(afterUpload ? { afterUpload } : {}) } } catch (err) { throw decorateOrphanError(err, created) diff --git a/packages/devflare/src/config/deploy-zones.ts b/packages/devflare/src/config/deploy-zones.ts index f17f00ce..1448bb44 100644 --- a/packages/devflare/src/config/deploy-zones.ts +++ b/packages/devflare/src/config/deploy-zones.ts @@ -32,13 +32,18 @@ yet (`2016: Workers Script Info not found`), so a config routing mail to its OWN worker could never succeed on its first deploy into an account. All worker routes wait, not only self-targeted ones: the rule is one predicate - rather than a name comparison, and waiting costs nothing when the Worker - already exists. + rather than a name comparison. The cost is that a route to ANOTHER Worker + that does not exist (a typo, or one never deployed) now fails after this + Worker has shipped rather than before. + → GOTCHA: even after the upload, Email Routing may not see the new Worker at + once. Only a write answered with 2016 is retried, a few times and seconds + apart; whether that window is long enough is not measured. → NOTE: rules are reconciled by ADDRESS and records by TYPE+NAME+CONTENT, so deploying twice is a no-op rather than a pile of duplicates. Nothing is ever DELETED — a zone always carries rules and records this config never mentioned. */ +import { CloudflareAPIError } from '../cloudflare/api' import type { DestinationAddress } from '../cloudflare/email-addresses' import type { DnsRecord, @@ -110,24 +115,47 @@ export class ZoneProvisionError extends Error { * Raised when an Email Routing route could not be read or written, naming the route. * * The bare Cloudflare error names an endpoint (`PUT …/rules/catch_all`), not the address whose mail - * is now going nowhere. That matters most after the upload: the Worker is already live there, and - * the deploy command has to tell the operator exactly which route is missing. + * is affected. That matters most after the upload: the Worker is already live there, and the + * deploy command has to say which route failed, whether it was only READ (so nothing about it + * changed) or WRITTEN (so it is not what the config declares), and which Worker it hands mail to. */ export class EmailRouteError extends Error { override name = 'EmailRouteError' + /** The route in the same words the created/existing labels use, e.g. `Email catch-all (zone example.com)`. */ + readonly route: string + /** `read` when only a lookup failed, so this deploy changed nothing about the route; `write` otherwise. */ + readonly operation: 'read' | 'write' + /** The Worker the declared route hands mail to, when it is a `worker` route. */ + readonly worker?: string /** - * @param route - the route in the same words the created/existing labels use, e.g. `Email catch-all (zone example.com)`. + * @param failed - which route, what was being done to it, and the Worker it targets. * @param cause - what Cloudflare (or the lookup before it) actually said. */ constructor( - readonly route: string, + failed: { route: string; operation: 'read' | 'write'; worker?: string }, cause: unknown ) { - super(`${route}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause }) + super(`${failed.route}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause }) + this.route = failed.route + this.operation = failed.operation + if (failed.worker !== undefined) this.worker = failed.worker } } +/** The Cloudflare error code Email Routing answers for a route naming a Worker it cannot find. */ +export const WORKER_SCRIPT_NOT_FOUND = 2016 + +/** How the after-upload pass waits out a Worker Email Routing cannot see yet. */ +export interface WorkerRouteRetryOptions { + /** Retries after the first attempt, each only for a 2016 answer. Defaults to 3. */ + retries?: number + /** Milliseconds between attempts. Defaults to 3000. */ + delayMs?: number + /** The wait itself, injectable so tests do not sleep. */ + sleep?: (ms: number) => Promise +} + /** A domain's `emailRouting` block, as declared. */ type DeclaredEmailRouting = NonNullable< NonNullable[string]['emailRouting'] @@ -232,16 +260,78 @@ function ruleAddress(rule: EmailRoutingRule): string | null { /** * @description Run one Cloudflare call for a route, and name that route if it fails. * - * @param route - the route in the words the created/existing labels use. + * @param failed - the route in the words the created/existing labels use, whether the call reads or + * writes it, and the Worker it targets when it is a `worker` route. * @param call - the read or write to make. * @returns whatever the call returned. * @throws {EmailRouteError} wrapping the call's own error as its `cause`. */ -async function attributeTo(route: string, call: () => Promise): Promise { +async function attributeTo( + failed: ConstructorParameters[0], + call: () => Promise +): Promise { try { return await call() } catch (error) { - throw new EmailRouteError(route, error) + throw new EmailRouteError(failed, error) + } +} + +/** Whether Cloudflare answered that it cannot find the Worker a route names. */ +function isWorkerScriptNotFound(error: unknown): boolean { + return ( + error instanceof CloudflareAPIError && + error.errors.some((entry) => entry.code === WORKER_SCRIPT_NOT_FOUND) + ) +} + +/** + * @description Repeat one write while Cloudflare answers 2016, up to `retries` more times. + * + * @param write - the write to attempt. + * @param options - how many retries and how far apart. + * @returns what the first successful attempt returned. + * @throws whatever the last attempt threw, or the first error that is not a 2016. + */ +async function retryWhileWorkerUnseen( + write: () => Promise, + options: WorkerRouteRetryOptions +): Promise { + const retries = options.retries ?? 3 + const delayMs = options.delayMs ?? 3000 + const sleep = options.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))) + + for (let attempt = 0; ; attempt++) { + try { + return await write() + } catch (error) { + if (attempt >= retries || !isWorkerScriptNotFound(error)) throw error + await sleep(delayMs) + } + } +} + +/** + * @description The API with its two Worker-route writes retried on 2016, everything else untouched. + * + * @param api - the injected Cloudflare calls, dry-run stubs included. + * @param options - how many retries and how far apart. + * @returns a copy of `api` for the after-upload pass. + * + * → KEY: 2016 ONLY. Any other answer is a real failure and must surface at once; retrying it would + * only delay the message. And a Worker that genuinely does not exist (a typo) costs the retries + * before failing, which is the price of not knowing how long Email Routing takes to see a new one. + */ +function withWorkerRouteRetry( + api: ZoneProvisionApi, + options: WorkerRouteRetryOptions +): ZoneProvisionApi { + return { + ...api, + createEmailRoutingRule: (zoneId, rule) => + retryWhileWorkerUnseen(() => api.createEmailRoutingRule(zoneId, rule), options), + setEmailRoutingCatchAll: (zoneId, rule) => + retryWhileWorkerUnseen(() => api.setEmailRoutingCatchAll(zoneId, rule), options) } } @@ -378,8 +468,9 @@ async function provisionRoutingRules( ): Promise { if (declaredRules.length === 0) return - const live = await attributeTo(`Email rules (zone ${zone.name})`, () => - api.listEmailRoutingRules(zone.id) + const live = await attributeTo( + { route: `Email rules (zone ${zone.name})`, operation: 'read' }, + () => api.listEmailRoutingRules(zone.id) ) const claimed = new Map( live.flatMap((rule) => { @@ -408,14 +499,16 @@ async function provisionRoutingRules( } const label = `Email rule ${declared.to} (zone ${zone.name})` - const created = await attributeTo(label, () => - api.createEmailRoutingRule(zone.id, { - name: `devflare: ${address}`, - enabled: declared.enabled ?? true, - priority, - matchers: [{ type: 'literal', field: 'to', value: address }], - actions - }) + const created = await attributeTo( + { route: label, operation: 'write', worker: declared.worker }, + () => + api.createEmailRoutingRule(zone.id, { + name: `devflare: ${address}`, + enabled: declared.enabled ?? true, + priority, + matchers: [{ type: 'literal', field: 'to', value: address }], + actions + }) ) result.created.push(label) @@ -438,7 +531,9 @@ async function provisionCatchAll( ): Promise { const actions = toRoutingActions(declared) const label = `Email catch-all (zone ${zone.name})` - const live = await attributeTo(label, () => api.getEmailRoutingCatchAll(zone.id)) + const live = await attributeTo({ route: label, operation: 'read', worker: declared.worker }, () => + api.getEmailRoutingCatchAll(zone.id) + ) // → GOTCHA: `enabled` is half the state, and the writer below always sets it — so comparing only // the actions would skip a catch-all that says the right thing while switched OFF, and report it @@ -449,7 +544,7 @@ async function provisionCatchAll( return } - await attributeTo(label, () => + await attributeTo({ route: label, operation: 'write', worker: declared.worker }, () => api.setEmailRoutingCatchAll(zone.id, { name: 'devflare: catch-all', enabled: true, @@ -694,19 +789,24 @@ export async function provisionZoneResources( } /** - * @description Whether any declared domain routes mail to a Worker, i.e. whether a deploy owes the - * after-upload pass at all. + * @description Name every Email Routing route that hands mail to a Worker, without asking Cloudflare — + * which is what a deploy that stops before the after-upload pass must tell its operator was NOT set. * * @param zones - the config's `zones` namespace. - * @returns true when some rule or catch-all declares a `worker` action. + * @returns one label per route, in declaration order, e.g. `Email catch-all for example.com → Worker api`. + * Empty when no route targets a Worker, so its length also answers whether the pass is owed. */ -export function hasWorkerEmailRoutes(zones: DevflareConfig['zones']): boolean { - return Object.values(zones ?? {}).some(({ emailRouting }) => { - if (!emailRouting) return false - const workerRule = (emailRouting.rules ?? []).some(isWorkerTargeted) - return ( - workerRule || (emailRouting.catchAll !== undefined && isWorkerTargeted(emailRouting.catchAll)) - ) +export function describeWorkerEmailRoutes(zones: DevflareConfig['zones']): string[] { + return Object.entries(zones ?? {}).flatMap(([domain, { emailRouting }]) => { + if (!emailRouting) return [] + + const rules = (emailRouting.rules ?? []) + .filter(isWorkerTargeted) + .map((rule) => `Email rule ${rule.to} → Worker ${rule.worker}`) + const catchAll = emailRouting.catchAll + return catchAll && isWorkerTargeted(catchAll) + ? [...rules, `Email catch-all for ${domain} → Worker ${catchAll.worker}`] + : rules }) } @@ -718,6 +818,7 @@ export function hasWorkerEmailRoutes(zones: DevflareConfig['zones']): boolean { * @param accountId - the account whose zones to search. * @param api - the injected Cloudflare calls; dry-run passes stubs for every mutation. * @param result - the caller's accumulator, appended to IN PLACE so a throw still reports progress. + * @param retry - how long to wait out a Worker Email Routing cannot see yet (2016 only). * @throws {EmailRouteError} naming the route that could not be read or written. * * → KEY: call it only AFTER a proven upload. Cloudflare refuses a route naming a Worker that does not @@ -731,8 +832,11 @@ export async function provisionWorkerEmailRoutes( zones: DevflareConfig['zones'], accountId: string, api: ZoneProvisionApi, - result: ZoneProvisionResult + result: ZoneProvisionResult, + retry: WorkerRouteRetryOptions = {} ): Promise { + const retrying = withWorkerRouteRetry(api, retry) + for (const [domain, declared] of Object.entries(zones ?? {})) { const routing = declared.emailRouting if (!routing) continue @@ -742,14 +846,15 @@ export async function provisionWorkerEmailRoutes( routing.catchAll && isWorkerTargeted(routing.catchAll) ? routing.catchAll : undefined if (rules.length === 0 && !catchAll) continue - const zone = await attributeTo(`Email routing for ${domain}`, () => - api.resolveZone(domain, accountId) + const zone = await attributeTo( + { route: `Email routing for ${domain}`, operation: 'read' }, + () => api.resolveZone(domain, accountId) ) - await provisionRoutingRules(zone, rules, api, result) + await provisionRoutingRules(zone, rules, retrying, result) if (catchAll) { - await provisionCatchAll(zone, catchAll, api, result) + await provisionCatchAll(zone, catchAll, retrying, result) } } } diff --git a/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts b/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts index 5e600b02..372c97d6 100644 --- a/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts +++ b/packages/devflare/tests/integration/cli/deploy-email-routing-after-upload.test.ts @@ -11,6 +11,10 @@ import { cloudflareApiResponse, createCliDependencies, createProcessRunner, + createWorkerDeployment, + createWorkerDeploymentsList, + createWorkerVersionDetail, + createWorkerVersionsList, type ExecInvocation, restoreDeployEnvironmentSnapshot, successResult, @@ -24,10 +28,16 @@ import { can see is the ORDER against the real upload: Cloudflare refuses a route naming a Worker that does not exist yet, so the first deploy of an app routing mail to itself failed in preparation before Wrangler ever ran. Every case records one timeline — zone writes from the Cloudflare mock, the - upload from the process runner — and reads the order off it. + upload and the traffic split from the process runner — and reads the order off it. */ const VERSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const WAITING_ROUTE = 'Email catch-all for example.com → Worker demo-emailing' + +/** A Wrangler run that failed. */ +function failedRun(stderr: string): ExecResult { + return { exitCode: 1, stdout: '', stderr, failed: true, killed: false } +} /** The Cloudflare error a first deploy actually hit, as the API returns it. */ function workerScriptNotFound(): Response { @@ -42,19 +52,72 @@ function workerScriptNotFound(): Response { ) } +/** + * @description Answer every Worker lookup with Cloudflare's "no such Worker", which is not retried. + * + * @param url - the request URL. + * @returns the answer, or undefined for a URL that is not a Worker lookup. + */ +function noSuchWorker(url: string): Response | undefined { + if (!url.includes('/workers/')) return undefined + return new Response( + JSON.stringify({ + success: false, + errors: [{ code: 10007, message: 'This Worker does not exist on your account' }], + messages: [], + result: null + }), + { status: 404, headers: { 'Content-Type': 'application/json' } } + ) +} + +/** + * @description Answer the Worker version and deployment lookups for a Worker whose only version is an + * OLD one that is still live — what Cloudflare shows when an upload changed nothing. + * + * @param url - the request URL. + * @returns the answer, or undefined for a URL that is not a Worker lookup. + */ +function reusedLiveVersion(url: string): Response | undefined { + if (!url.includes('/workers/scripts/demo-emailing')) return undefined + if (url.includes('/versions?page=1')) { + return createWorkerVersionsList([ + createWorkerVersionDetail('version-existing', { + createdOn: '2020-01-01T00:00:00.000Z', + modifiedOn: '2020-01-01T00:00:00.000Z' + }) + ]) + } + if (url.endsWith('/deployments')) { + return createWorkerDeploymentsList([ + createWorkerDeployment('deployment-existing', 'version-existing', { + createdOn: '2020-01-01T00:00:00.000Z' + }) + ]) + } + return cloudflareApiResponse(createWorkerVersionDetail('version-existing')) +} + /** * @description Answer the zone calls of a zone with routing on, no rules, and Cloudflare's default * catch-all (drop, disabled) — the state a first deploy meets — recording every write. * * @param timeline - receives `POST rule ` and `PUT catch_all ` as the writes arrive. * @param options.catchAllFails - answer the catch-all write with error 2016, as for a missing Worker. + * @param options.workers - answers Worker version lookups; anything it leaves unanswered throws. */ -function mockZone(timeline: string[], options: { catchAllFails?: boolean } = {}): void { +function mockZone( + timeline: string[], + options: { catchAllFails?: boolean; workers?: (url: string) => Response | undefined } = {} +): void { globalThis.fetch = mock(async (input: RequestInfo | URL, init?: RequestInit) => { const method = init?.method ?? 'GET' const url = String(input) const body = init?.body ? JSON.parse(String(init.body)) : undefined + const workerAnswer = options.workers?.(url) + if (workerAnswer) return workerAnswer + if (url.includes('/zones?name=example.com')) { return cloudflareApiResponse([{ id: 'zone_1', name: 'example.com' }]) } @@ -90,20 +153,31 @@ function mockZone(timeline: string[], options: { catchAllFails?: boolean } = {}) } /** - * @description Install a process runner whose `wrangler deploy` records itself on the timeline. + * @description Install a process runner whose Wrangler calls record themselves on the timeline. * - * @param timeline - receives `upload` when Wrangler is asked to deploy. - * @param upload - what that Wrangler run returns. + * @param timeline - receives `upload` for `wrangler deploy` / `versions upload`, `rollout` for `versions deploy`. + * @param results.upload - what the upload returns. + * @param results.rollout - what the traffic split returns; succeeds when omitted. * @returns the captured executions. */ -function installWrangler(timeline: string[], upload: ExecResult): ExecInvocation[] { +function installWrangler( + timeline: string[], + results: { upload: ExecResult; rollout?: ExecResult } +): ExecInvocation[] { const executions: ExecInvocation[] = [] setDependencies( createCliDependencies( createProcessRunner((command, args) => { - if (command === 'bunx' && args[0] === 'wrangler' && args[1] === 'deploy') { + if (command !== 'bunx' || args[0] !== 'wrangler') return successResult() + + const isUpload = args[1] === 'deploy' || (args[1] === 'versions' && args[2] === 'upload') + if (isUpload) { timeline.push('upload') - return upload + return results.upload + } + if (args[1] === 'versions' && args[2] === 'deploy') { + timeline.push('rollout') + return results.rollout ?? successResult('split applied') } return successResult() }, executions) @@ -114,18 +188,24 @@ function installWrangler(timeline: string[], upload: ExecResult): ExecInvocation describe('deploy — Email Routing to a Worker is set after the upload', () => { const originalEnvironment = captureDeployEnvironmentSnapshot() + const originalRetryDelay = process.env.DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS let projectDir = '' beforeEach(async () => { process.env.CLOUDFLARE_API_TOKEN = 'cf_test_token' delete process.env.DEVFLARE_VERIFY_DEPLOYMENT + delete process.env.DEVFLARE_REQUIRE_FRESH_PRODUCTION_DEPLOYMENT + // Keep the version-lookup and 2016 retries instant. + process.env.DEVFLARE_VERIFY_DEPLOYMENT_ATTEMPTS = '1' + process.env.DEVFLARE_VERIFY_DEPLOYMENT_DELAY_MS = '0' + process.env.DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS = '0' projectDir = mkdtempSync(join(tmpdir(), 'devflare-deploy-email-order-')) await writeFile( join(projectDir, 'package.json'), JSON.stringify({ name: 'deploy-email-order-tests', type: 'module' }, null, '\t') ) await mkdir(join(projectDir, 'src'), { recursive: true }) - // The consumer's shape: two forwards and a catch-all handing everything else to ITSELF. + // The consumer's shape: a forward and a catch-all handing everything else to ITSELF. await writeFile( join(projectDir, 'devflare.config.ts'), ` @@ -158,6 +238,11 @@ describe('deploy — Email Routing to a Worker is set after the upload', () => { afterEach(async () => { clearDependencies() restoreDeployEnvironmentSnapshot(originalEnvironment) + if (originalRetryDelay === undefined) { + delete process.env.DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS + } else { + process.env.DEVFLARE_EMAIL_ROUTE_RETRY_DELAY_MS = originalRetryDelay + } await rm(projectDir, { recursive: true, force: true }) }) @@ -178,7 +263,7 @@ describe('deploy — Email Routing to a Worker is set after the upload', () => { // `upload` — the order that made the first deploy fail. const timeline: string[] = [] mockZone(timeline) - installWrangler(timeline, successResult(`Worker Version ID: ${VERSION_ID}`)) + installWrangler(timeline, { upload: successResult(`Worker Version ID: ${VERSION_ID}`) }) const logger = createLogger() const result = await deploy(logger) @@ -190,22 +275,86 @@ describe('deploy — Email Routing to a Worker is set after the upload', () => { ) }) - test('a failed upload never attempts the worker route', async () => { - // Mutant: running the after-upload step before the exit-code check (or regardless of it). + test('a failed upload never attempts the worker route, and names it as NOT set', async () => { + // Preparation may already have rewritten MX records here, so "Deployment failed" alone would + // hide a zone left half-done. Mutant: running the step regardless of the exit code. + const timeline: string[] = [] + mockZone(timeline) + installWrangler(timeline, { upload: failedRun('upload failed') }) + const logger = createLogger() + + const result = await deploy(logger) + + expect(result.exitCode).toBe(1) + expect(timeline).toEqual(['POST rule forward', 'upload']) + const output = renderMessages(logger).join('\n') + expect(output).toContain('was NOT set, because the upload failed') + expect(output).toContain(WAITING_ROUTE) + }) + + test('an exit 0 with no proof of an upload never attempts the worker route', async () => { + // Wrangler exits 0 on runs that uploaded nothing. Mutant: running the step right after the + // exit-code check, ahead of the upload-evidence check, sets the catch-all here. + const timeline: string[] = [] + mockZone(timeline, { workers: noSuchWorker }) + installWrangler(timeline, { upload: successResult('') }) + const logger = createLogger() + + const result = await deploy(logger) + + expect(result.exitCode).toBe(1) + expect(timeline).toEqual(['POST rule forward', 'upload']) + const output = renderMessages(logger).join('\n') + expect(output).toContain('was NOT set, because no upload could be proven') + expect(output).toContain(WAITING_ROUTE) + }) + + test('a reused live version still gets its routes before a fresh deployment is refused', async () => { + // Adding a worker rule changes nothing Wrangler uploads, so Cloudflare keeps the live version + // and a fresh-deployment requirement refuses it — every run, forever, if the routes waited for + // the success path. Mutant: removing the step from that branch leaves the catch-all unset. + process.env.DEVFLARE_REQUIRE_FRESH_PRODUCTION_DEPLOYMENT = 'true' + const timeline: string[] = [] + mockZone(timeline, { workers: reusedLiveVersion }) + installWrangler(timeline, { upload: successResult('') }) + const logger = createLogger() + + const result = await deploy(logger) + + expect(result.exitCode).toBe(1) + expect(timeline).toEqual(['POST rule forward', 'upload', 'PUT catch_all worker']) + const output = renderMessages(logger).join('\n') + expect(output).toContain('requires a fresh production deployment') + }) + + test('a percentage rollout splits traffic first, then sets the worker route', async () => { + // Mutant: running the step ahead of the rollout puts `PUT catch_all worker` before `rollout`. + const timeline: string[] = [] + mockZone(timeline) + installWrangler(timeline, { upload: successResult(`Worker Version ID: ${VERSION_ID}`) }) + + const result = await deploy(createLogger(), { percentage: '10' }) + + expect(result.exitCode).toBe(0) + expect(timeline).toEqual(['POST rule forward', 'upload', 'rollout', 'PUT catch_all worker']) + }) + + test('a failed rollout skips the worker route and names it as NOT set', async () => { const timeline: string[] = [] mockZone(timeline) installWrangler(timeline, { - exitCode: 1, - stdout: '', - stderr: 'upload failed', - failed: true, - killed: false + upload: successResult(`Worker Version ID: ${VERSION_ID}`), + rollout: failedRun('split refused') }) + const logger = createLogger() - const result = await deploy(createLogger()) + const result = await deploy(logger, { percentage: '10' }) expect(result.exitCode).toBe(1) - expect(timeline).toEqual(['POST rule forward', 'upload']) + expect(timeline).toEqual(['POST rule forward', 'upload', 'rollout']) + const output = renderMessages(logger).join('\n') + expect(output).toContain('was NOT set, because the traffic split failed') + expect(output).toContain(WAITING_ROUTE) }) test('a route that fails AFTER a good upload fails the deploy, saying the Worker shipped', async () => { @@ -213,16 +362,26 @@ describe('deploy — Email Routing to a Worker is set after the upload', () => { // live. Mutant: swallowing the step's error into a warning exits 0 here. const timeline: string[] = [] mockZone(timeline, { catchAllFails: true }) - installWrangler(timeline, successResult(`Worker Version ID: ${VERSION_ID}`)) + installWrangler(timeline, { upload: successResult(`Worker Version ID: ${VERSION_ID}`) }) const logger = createLogger() const result = await deploy(logger) expect(result.exitCode).toBe(1) - expect(timeline).toEqual(['POST rule forward', 'upload', 'PUT catch_all worker']) + // A 2016 is retried three times before it is reported. + expect(timeline).toEqual([ + 'POST rule forward', + 'upload', + 'PUT catch_all worker', + 'PUT catch_all worker', + 'PUT catch_all worker', + 'PUT catch_all worker' + ]) const output = renderMessages(logger).join('\n') expect(output).toContain(`"demo-emailing" WAS uploaded (version ${VERSION_ID})`) - expect(output).toContain('Email catch-all (zone example.com) failed') + expect(output).toContain( + 'Email catch-all (zone example.com) → Worker "demo-emailing" could not be set' + ) expect(output).toContain('Workers Script Info not found') expect(output).not.toContain('Deployed successfully') }) @@ -231,7 +390,7 @@ describe('deploy — Email Routing to a Worker is set after the upload', () => { // Mutant: dropping the after-upload step from the dry-run plan leaves the catch-all unlisted. const timeline: string[] = [] mockZone(timeline) - const executions = installWrangler(timeline, successResult()) + const executions = installWrangler(timeline, { upload: successResult() }) const logger = createLogger() const result = await deploy(logger, { 'dry-run': true }) diff --git a/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts b/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts index 2ffdb536..75c36c22 100644 --- a/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts +++ b/packages/devflare/tests/unit/cli/deploy-after-upload.test.ts @@ -1,27 +1,68 @@ import { describe, expect, test } from 'bun:test' -import { describeAfterUploadRoutingFailure } from '../../../src/cli/commands/deploy/after-upload' +import { + describeAfterUploadRoutingFailure, + describeRoutesNotSet +} from '../../../src/cli/commands/deploy/after-upload' import { EmailRouteError } from '../../../src/config/deploy-zones' const NO_PROGRESS = { created: [], existing: [], warnings: [] } +const CATCH_ALL = 'Email catch-all (zone example.com)' + +/** A failed write of the catch-all, handing mail to `worker`. */ +function failedWrite(worker: string, message = 'Workers Script Info not found'): EmailRouteError { + return new EmailRouteError( + { route: CATCH_ALL, operation: 'write', worker }, + new Error(`Cloudflare PUT failed (2016): ${message}`) + ) +} describe('describeAfterUploadRoutingFailure', () => { - test('says the Worker WAS uploaded, names the route, and keeps what Cloudflare said', () => { + test('says the Worker WAS uploaded, names the route and its target, and keeps what Cloudflare said', () => { const message = describeAfterUploadRoutingFailure({ workerName: 'demo-emailing', versionId: 'version-1', - error: new EmailRouteError( - 'Email catch-all (zone example.com)', - new Error('Cloudflare PUT failed (2016): Workers Script Info not found') - ), + error: failedWrite('demo-emailing'), progress: NO_PROGRESS }) expect(message).toContain('"demo-emailing" WAS uploaded (version version-1)') - expect(message).toContain('Email catch-all (zone example.com) failed') + expect(message).toContain(`${CATCH_ALL} → Worker "demo-emailing" could not be set`) expect(message).toContain('Workers Script Info not found') // The cause appears once — not again inside a route-prefixed copy of itself. expect(message.split('Workers Script Info not found')).toHaveLength(2) - expect(message).toContain('Re-run `devflare deploy`') + expect(message).not.toContain('to it') + expect(message).toContain('Re-run `devflare deploy` to retry') + }) + + test('a route to ANOTHER Worker says to deploy that one first, not that a re-run will fix it', () => { + // Mutant: one message for every write failure tells the operator to re-run a deploy that + // cannot create `billing`. + const message = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + error: failedWrite('billing'), + progress: NO_PROGRESS + }) + + expect(message).toContain('→ Worker "billing" could not be set') + expect(message).toContain('re-running this deploy cannot create it') + expect(message).not.toContain('Re-run `devflare deploy` to retry') + }) + + test('a failed READ says nothing changed, not that mail is lost', () => { + // Mutant: treating a read like a write tells the operator a live route is gone. + const message = describeAfterUploadRoutingFailure({ + workerName: 'demo-emailing', + error: new EmailRouteError( + { route: CATCH_ALL, operation: 'read', worker: 'demo-emailing' }, + new Error('Cloudflare GET failed: 503') + ), + progress: NO_PROGRESS + }) + + expect(message).toContain('could not be read: Cloudflare GET failed: 503') + expect(message).toContain('whatever an earlier deploy set is still in place') + expect(message).not.toContain('could not be set') + expect(message).not.toContain('not reaching') }) test('an error that names no route still says the Worker shipped', () => { @@ -32,13 +73,15 @@ describe('describeAfterUploadRoutingFailure', () => { }) expect(message).toContain('"demo-emailing" WAS uploaded,') - expect(message).toContain('a Worker-targeted Email Routing route failed — network down') + expect(message).toContain( + 'a Worker-targeted Email Routing route could not be set: network down' + ) }) test('lists the routes this deploy set before the failure, and only when there were any', () => { const withProgress = describeAfterUploadRoutingFailure({ workerName: 'demo-emailing', - error: new EmailRouteError('Email catch-all (zone example.com)', new Error('boom')), + error: failedWrite('demo-emailing', 'boom'), progress: { created: ['Email rule inbox@example.com (zone example.com)'], existing: [], @@ -47,7 +90,7 @@ describe('describeAfterUploadRoutingFailure', () => { }) const without = describeAfterUploadRoutingFailure({ workerName: 'demo-emailing', - error: new EmailRouteError('Email catch-all (zone example.com)', new Error('boom')), + error: failedWrite('demo-emailing', 'boom'), progress: NO_PROGRESS }) @@ -57,3 +100,20 @@ describe('describeAfterUploadRoutingFailure', () => { expect(without).not.toContain('before the failure') }) }) + +describe('describeRoutesNotSet', () => { + test('names each route and why it was not set', () => { + const sentence = describeRoutesNotSet( + ['Email catch-all for example.com → Worker demo-emailing'], + 'the upload failed' + ) + + expect(sentence).toContain('was NOT set, because the upload failed') + expect(sentence).toContain('Email catch-all for example.com → Worker demo-emailing') + }) + + test('says nothing when no route was owed', () => { + expect(describeRoutesNotSet(undefined, 'the upload failed')).toBe('') + expect(describeRoutesNotSet([], 'the upload failed')).toBe('') + }) +}) diff --git a/packages/devflare/tests/unit/config/deploy-zones.test.ts b/packages/devflare/tests/unit/config/deploy-zones.test.ts index ede86496..0dba72c2 100644 --- a/packages/devflare/tests/unit/config/deploy-zones.test.ts +++ b/packages/devflare/tests/unit/config/deploy-zones.test.ts @@ -1,7 +1,9 @@ import { describe, expect, mock, test } from 'bun:test' +import { CloudflareAPIError } from '../../../src/cloudflare/api' import { prepareMaterializedConfigResourcesForDeploy } from '../../../src/config/deploy-resources' import { DEVFLARE_RECORD_COMMENT, + describeWorkerEmailRoutes, EmailRouteError, provisionWorkerEmailRoutes, provisionZoneResources, @@ -489,12 +491,131 @@ describe('Email Routing to a Worker waits for the upload', () => { await expect(failure).rejects.toBeInstanceOf(EmailRouteError) await failure.catch((error: EmailRouteError) => { expect(error.route).toBe('Email catch-all (zone example.com)') + expect(error.operation).toBe('write') + expect(error.worker).toBe('emailing') expect(error.cause).toBe(cloudflare) expect(error.message).toContain('Workers Script Info not found') }) // The rule before it was set, and the accumulator still says so after the throw. expect(result.created).toEqual(['Email rule inbox@example.com (zone example.com)']) }) + + test('a failed READ is reported as a read, so nobody is told a live route was lost', async () => { + // Mutant: tagging the catch-all lookup as a `write` makes the deploy say the route is unset + // when an earlier deploy's route is still in place. + const api = makeZoneApi({ + getEmailRoutingCatchAll: mock(async () => { + throw new Error('Cloudflare GET failed: 503') + }) + }) + + const failure = provisionAfterUpload(selfRouting, api) + + await expect(failure).rejects.toBeInstanceOf(EmailRouteError) + await failure.catch((error: EmailRouteError) => { + expect(error.operation).toBe('read') + expect(error.route).toBe('Email catch-all (zone example.com)') + }) + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + }) + + test('every worker route is named up front, without a Cloudflare call', () => { + // What an early exit lists as NOT set. Mutant: dropping the catch-all from the list leaves a + // failed upload silent about it. + expect(describeWorkerEmailRoutes(selfRouting)).toEqual([ + 'Email rule inbox@example.com → Worker emailing', + 'Email catch-all for example.com → Worker emailing' + ]) + expect( + describeWorkerEmailRoutes({ + 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', drop: true }] } } + }) + ).toEqual([]) + }) +}) + +describe('Email Routing may not see a just-uploaded Worker at once', () => { + const catchAllOnly: DevflareConfig['zones'] = { + 'example.com': { emailRouting: { catchAll: { worker: 'emailing' } } } + } + + /** The error Cloudflare's client raises for a route naming a Worker it cannot find. */ + function scriptNotFound(): CloudflareAPIError { + return new CloudflareAPIError( + 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found', + 404, + [{ code: 2016, message: 'Workers Script Info not found' }] + ) + } + + test('a 2016 is retried, a few seconds apart, until the write lands', async () => { + // Mutant: removing `withWorkerRouteRetry` from the pass fails on the first 2016. + let attempts = 0 + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async (_zoneId: string, rule) => { + attempts += 1 + if (attempts < 3) throw scriptNotFound() + return rule + }) + }) + const waits: number[] = [] + const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + + await provisionWorkerEmailRoutes(catchAllOnly, 'acct_1', api, result, { + sleep: async (ms) => { + waits.push(ms) + } + }) + + expect(attempts).toBe(3) + expect(waits).toEqual([3000, 3000]) + expect(result.created).toEqual(['Email catch-all (zone example.com) — set to worker']) + }) + + test('it gives up after three retries and reports the 2016', async () => { + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async () => { + throw scriptNotFound() + }) + }) + const sleep = mock(async (_ms: number) => {}) + + const failure = provisionWorkerEmailRoutes( + catchAllOnly, + 'acct_1', + api, + { created: [], existing: [], warnings: [] }, + { sleep, delayMs: 5 } + ) + + await expect(failure).rejects.toThrow('Workers Script Info not found') + expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(4) + expect(sleep.mock.calls.map((call) => call[0])).toEqual([5, 5, 5]) + }) + + test('any other Cloudflare error fails at once, with no retry', async () => { + // Mutant: retrying every CloudflareAPIError turns a real failure into a delayed one. + const api = makeZoneApi({ + createEmailRoutingRule: mock(async () => { + throw new CloudflareAPIError('Cloudflare POST failed (10000): Authentication error', 403, [ + { code: 10000, message: 'Authentication error' } + ]) + }) + }) + const sleep = mock(async (_ms: number) => {}) + + const failure = provisionWorkerEmailRoutes( + { 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', worker: 'emailing' }] } } }, + 'acct_1', + api, + { created: [], existing: [], warnings: [] }, + { sleep } + ) + + await expect(failure).rejects.toThrow('Authentication error') + expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) + expect(sleep).not.toHaveBeenCalled() + }) }) describe('provisionZoneResources — forwarding destinations', () => { @@ -1094,7 +1215,7 @@ describe('the deploy path guards zone provisioning', () => { cloudflare: api }) const afterUpload: ZoneProvisionResult = { created: [], existing: [], warnings: [] } - await prepared.provisionAfterUpload?.(afterUpload) + await prepared.afterUpload?.provision(afterUpload) expectNoMutation(api) expect(api.listEmailRoutingRules).toHaveBeenCalledTimes(1) @@ -1118,7 +1239,7 @@ describe('the deploy path guards zone provisioning', () => { expect(api.resolveZone).not.toHaveBeenCalled() expect(result.created.zones).toEqual([]) // Nor anything left for after the upload. - expect(result.provisionAfterUpload).toBeUndefined() + expect(result.afterUpload).toBeUndefined() }) test('a real deploy DOES perform them, so both guards above are measuring something', async () => { @@ -1132,7 +1253,7 @@ describe('the deploy path guards zone provisioning', () => { // The declared rule routes to a Worker, so preparation leaves it for after the upload… expect(api.createEmailRoutingRule).not.toHaveBeenCalled() - await prepared.provisionAfterUpload?.({ created: [], existing: [], warnings: [] }) + await prepared.afterUpload?.provision({ created: [], existing: [], warnings: [] }) // …and the step it hands back writes it. expect(api.enableEmailRouting).toHaveBeenCalledTimes(1) From fc5de950f9a1610e9ae423d61922eaa4696a1f5d Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Tue, 1 Dec 2026 02:35:46 +0100 Subject: [PATCH 3/3] test(deploy-zones): split the after-upload routing tests into their own file, under the size ceiling The after-upload deferral and the 2016 retry took deploy-zones.test.ts from 950 to 1281 lines, past the 1000-line ceiling source-file-size.test.ts enforces. The two describe blocks for the routes set after the upload move to deploy-zones-after-upload.test.ts, and the mock zone API and the two pass runners both files use move to tests/helpers/zone-provision-api.ts. 54 tests before, 54 after. Co-Authored-By: Claude Opus 5.5 --- .../tests/helpers/zone-provision-api.ts | 91 +++++ .../config/deploy-zones-after-upload.test.ts | 302 ++++++++++++++ .../tests/unit/config/deploy-zones.test.ts | 368 +----------------- 3 files changed, 394 insertions(+), 367 deletions(-) create mode 100644 packages/devflare/tests/helpers/zone-provision-api.ts create mode 100644 packages/devflare/tests/unit/config/deploy-zones-after-upload.test.ts diff --git a/packages/devflare/tests/helpers/zone-provision-api.ts b/packages/devflare/tests/helpers/zone-provision-api.ts new file mode 100644 index 00000000..71388123 --- /dev/null +++ b/packages/devflare/tests/helpers/zone-provision-api.ts @@ -0,0 +1,91 @@ +import { mock } from 'bun:test' +import { + provisionWorkerEmailRoutes, + provisionZoneResources, + type ZoneProvisionApi, + type ZoneProvisionResult +} from '../../src/config/deploy-zones' +import type { DevflareConfig } from '../../src/config/schema' + +/* + The mock Cloudflare zone API and the two pass runners shared by the zone-provisioning tests + (`deploy-zones.test.ts` for the preparation pass, `deploy-zones-after-upload.test.ts` for the + Worker-targeted routes set after the upload). +*/ + +/** A zone lookup that answers for `example.com` and treats anything under it as a subdomain. */ +export function zoneFor(domain: string) { + return { + id: 'zone_1', + name: 'example.com', + domain, + isSubdomain: domain !== 'example.com' + } +} + +/** Every zone call as a mock, with read-only defaults a test can override per case. */ +export function makeZoneApi(overrides: Partial = {}) { + return { + resolveZone: mock(async (domain: string) => zoneFor(domain)), + listDestinationAddresses: mock(async () => [ + { + tag: 'da_1', + email: 'someone@example.net', + verified: '2026-01-01T00:00:00Z' + } + ]), + createDestinationAddress: mock(async (_accountId: string, email: string) => ({ email })), + getEmailRoutingSettings: mock(async () => ({ + enabled: true, + status: 'ready' + })), + enableEmailRouting: mock(async () => ({ enabled: true })), + listEmailRoutingRules: mock(async () => []), + createEmailRoutingRule: mock(async (_zoneId: string, rule) => rule), + getEmailRoutingCatchAll: mock(async () => ({ + enabled: true, + matchers: [{ type: 'all' as const }], + actions: [{ type: 'drop' as const }] + })), + setEmailRoutingCatchAll: mock(async (_zoneId: string, rule) => rule), + listSendingDomains: mock(async () => [{ tag: 'sd_1', name: 'example.com', enabled: true }]), + createSendingDomain: mock(async (_zoneId: string, name: string) => ({ + tag: 'sd_new', + name, + enabled: true + })), + getSendingDomainDnsStatus: mock(async () => ({ status: 'ready' as const })), + listDnsRecords: mock(async () => []), + createDnsRecord: mock(async (_zoneId: string, record) => record), + updateDnsRecord: mock(async (_zoneId: string, _recordId: string, record) => record), + ...overrides + } satisfies ZoneProvisionApi +} + +/** Run a pass and hand back the accumulator it filled, so a test reads one value. */ +export async function provision( + zones: DevflareConfig['zones'], + api: ZoneProvisionApi +): Promise { + const result: ZoneProvisionResult = { + created: [], + existing: [], + warnings: [] + } + await provisionZoneResources(zones, 'acct_1', api, result) + return result +} + +/** Run the AFTER-UPLOAD pass — the Worker-targeted routes — and hand back what it filled. */ +export async function provisionAfterUpload( + zones: DevflareConfig['zones'], + api: ZoneProvisionApi +): Promise { + const result: ZoneProvisionResult = { + created: [], + existing: [], + warnings: [] + } + await provisionWorkerEmailRoutes(zones, 'acct_1', api, result) + return result +} diff --git a/packages/devflare/tests/unit/config/deploy-zones-after-upload.test.ts b/packages/devflare/tests/unit/config/deploy-zones-after-upload.test.ts new file mode 100644 index 00000000..c2832a7c --- /dev/null +++ b/packages/devflare/tests/unit/config/deploy-zones-after-upload.test.ts @@ -0,0 +1,302 @@ +import { describe, expect, mock, test } from 'bun:test' +import { CloudflareAPIError } from '../../../src/cloudflare/api' +import { + describeWorkerEmailRoutes, + EmailRouteError, + provisionWorkerEmailRoutes, + type ZoneProvisionResult +} from '../../../src/config/deploy-zones' +import type { DevflareConfig } from '../../../src/config/schema' +import { makeZoneApi, provision, provisionAfterUpload } from '../../helpers/zone-provision-api' + +/* + Worker-targeted Email Routing — the routes devflare sets AFTER the upload, because Cloudflare + refuses a route to a Worker that does not exist yet (error 2016). Split from `deploy-zones.test.ts`, + which covers the preparation pass, to keep both files under the source-size ceiling; the mock API + and the two pass runners they share live in `tests/helpers/zone-provision-api.ts`. +*/ + +describe('Email Routing to a Worker waits for the upload', () => { + /* + Cloudflare refuses a route naming a Worker that does not exist yet (`2016: Workers Script Info + not found`), so an app routing mail to ITS OWN worker could never pass its first deploy while + those routes were written in preparation. Preparation now skips every `worker` route and + `provisionWorkerEmailRoutes` writes them after the upload. + */ + const selfRouting: DevflareConfig['zones'] = { + 'example.com': { + emailRouting: { + rules: [ + { to: 'press@example.com', forward: ['someone@example.net'] }, + { to: 'inbox@example.com', worker: 'emailing' } + ], + catchAll: { worker: 'emailing' } + } + } + } + + test('preparation sets NO worker route — not the rule, not the catch-all', async () => { + // Mutant: dropping the `!isWorkerTargeted` filter on the catch-all or the rules in + // `provisionEmailRouting` puts the write back before the upload, which is the defect. + const api = makeZoneApi() + + const result = await provision(selfRouting, api) + + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + const ruleActions = api.createEmailRoutingRule.mock.calls.map( + (call) => call[1].actions[0]?.type + ) + expect(ruleActions).not.toContain('worker') + expect(result.created.join('\n')).not.toContain('inbox@example.com') + expect(result.created.join('\n')).not.toContain('catch-all') + }) + + test('preparation still creates the FORWARD rule, and its destination first', async () => { + // Only `worker` actions moved. Mutant: filtering every rule out of preparation (or skipping + // `provisionRoutingRules` there) leaves forwarding rules unwritten. + const order: string[] = [] + const api = makeZoneApi({ + listDestinationAddresses: mock(async () => []), + createDestinationAddress: mock(async (_accountId: string, email: string) => { + order.push('address') + return { email } + }), + createEmailRoutingRule: mock(async (_zoneId: string, rule) => { + order.push(`rule:${rule.actions[0]?.type}`) + return rule + }) + }) + + const result = await provision(selfRouting, api) + + expect(order).toEqual(['address', 'rule:forward']) + expect(result.created).toContain('Email rule press@example.com (zone example.com)') + }) + + test('the after-upload pass sets the worker rule and the worker catch-all, and only those', async () => { + const api = makeZoneApi() + + const result = await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) + expect(api.createEmailRoutingRule.mock.calls[0]?.[1].actions).toEqual([ + { type: 'worker', value: ['emailing'] } + ]) + expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(1) + expect(api.setEmailRoutingCatchAll.mock.calls[0]?.[1]).toMatchObject({ + enabled: true, + actions: [{ type: 'worker', value: ['emailing'] }] + }) + // It touches nothing preparation owns: no routing switch, no destination, no DNS. + expect(api.getEmailRoutingSettings).not.toHaveBeenCalled() + expect(api.listDestinationAddresses).not.toHaveBeenCalled() + expect(result.created).toEqual([ + 'Email rule inbox@example.com (zone example.com)', + 'Email catch-all (zone example.com) — set to worker' + ]) + }) + + test('a worker rule keeps the priority its place in the WHOLE list gives it', async () => { + // Mutant: numbering by index within the after-upload subset gives `inbox@` priority 1, the + // same as `press@`, so the split silently reorders the zone's rules. + const api = makeZoneApi() + + await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule.mock.calls[0]?.[1].priority).toBe(2) + }) + + test('a second deploy is a no-op that reports every worker route as existing', async () => { + const api = makeZoneApi({ + listEmailRoutingRules: mock(async () => [ + { + tag: 'r2', + matchers: [ + { + type: 'literal' as const, + field: 'to' as const, + value: 'inbox@example.com' + } + ], + actions: [{ type: 'worker' as const, value: ['emailing'] }] + } + ]), + getEmailRoutingCatchAll: mock(async () => ({ + enabled: true, + matchers: [{ type: 'all' as const }], + actions: [{ type: 'worker' as const, value: ['emailing'] }] + })) + }) + + const result = await provisionAfterUpload(selfRouting, api) + + expect(api.createEmailRoutingRule).not.toHaveBeenCalled() + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + expect(result.created).toEqual([]) + expect(result.existing).toEqual([ + 'Email rule inbox@example.com (zone example.com)', + 'Email catch-all (zone example.com)' + ]) + }) + + test('a domain with no worker route costs the after-upload pass no request at all', async () => { + const api = makeZoneApi() + + await provisionAfterUpload( + { + 'example.com': { + emailRouting: { + rules: [{ to: 'a@example.com', drop: true }], + catchAll: { drop: true } + }, + dns: [{ type: 'TXT', name: '_dmarc', content: 'v=DMARC1; p=none' }] + } + }, + api + ) + + expect(api.resolveZone).not.toHaveBeenCalled() + }) + + test("a failed write names the route, keeping Cloudflare's own error as the cause", async () => { + const cloudflare = new Error( + 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found' + ) + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async () => { + throw cloudflare + }) + }) + const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + + const failure = provisionWorkerEmailRoutes(selfRouting, 'acct_1', api, result) + + await expect(failure).rejects.toBeInstanceOf(EmailRouteError) + await failure.catch((error: EmailRouteError) => { + expect(error.route).toBe('Email catch-all (zone example.com)') + expect(error.operation).toBe('write') + expect(error.worker).toBe('emailing') + expect(error.cause).toBe(cloudflare) + expect(error.message).toContain('Workers Script Info not found') + }) + // The rule before it was set, and the accumulator still says so after the throw. + expect(result.created).toEqual(['Email rule inbox@example.com (zone example.com)']) + }) + + test('a failed READ is reported as a read, so nobody is told a live route was lost', async () => { + // Mutant: tagging the catch-all lookup as a `write` makes the deploy say the route is unset + // when an earlier deploy's route is still in place. + const api = makeZoneApi({ + getEmailRoutingCatchAll: mock(async () => { + throw new Error('Cloudflare GET failed: 503') + }) + }) + + const failure = provisionAfterUpload(selfRouting, api) + + await expect(failure).rejects.toBeInstanceOf(EmailRouteError) + await failure.catch((error: EmailRouteError) => { + expect(error.operation).toBe('read') + expect(error.route).toBe('Email catch-all (zone example.com)') + }) + expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() + }) + + test('every worker route is named up front, without a Cloudflare call', () => { + // What an early exit lists as NOT set. Mutant: dropping the catch-all from the list leaves a + // failed upload silent about it. + expect(describeWorkerEmailRoutes(selfRouting)).toEqual([ + 'Email rule inbox@example.com → Worker emailing', + 'Email catch-all for example.com → Worker emailing' + ]) + expect( + describeWorkerEmailRoutes({ + 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', drop: true }] } } + }) + ).toEqual([]) + }) +}) + +describe('Email Routing may not see a just-uploaded Worker at once', () => { + const catchAllOnly: DevflareConfig['zones'] = { + 'example.com': { emailRouting: { catchAll: { worker: 'emailing' } } } + } + + /** The error Cloudflare's client raises for a route naming a Worker it cannot find. */ + function scriptNotFound(): CloudflareAPIError { + return new CloudflareAPIError( + 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found', + 404, + [{ code: 2016, message: 'Workers Script Info not found' }] + ) + } + + test('a 2016 is retried, a few seconds apart, until the write lands', async () => { + // Mutant: removing `withWorkerRouteRetry` from the pass fails on the first 2016. + let attempts = 0 + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async (_zoneId: string, rule) => { + attempts += 1 + if (attempts < 3) throw scriptNotFound() + return rule + }) + }) + const waits: number[] = [] + const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } + + await provisionWorkerEmailRoutes(catchAllOnly, 'acct_1', api, result, { + sleep: async (ms) => { + waits.push(ms) + } + }) + + expect(attempts).toBe(3) + expect(waits).toEqual([3000, 3000]) + expect(result.created).toEqual(['Email catch-all (zone example.com) — set to worker']) + }) + + test('it gives up after three retries and reports the 2016', async () => { + const api = makeZoneApi({ + setEmailRoutingCatchAll: mock(async () => { + throw scriptNotFound() + }) + }) + const sleep = mock(async (_ms: number) => {}) + + const failure = provisionWorkerEmailRoutes( + catchAllOnly, + 'acct_1', + api, + { created: [], existing: [], warnings: [] }, + { sleep, delayMs: 5 } + ) + + await expect(failure).rejects.toThrow('Workers Script Info not found') + expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(4) + expect(sleep.mock.calls.map((call) => call[0])).toEqual([5, 5, 5]) + }) + + test('any other Cloudflare error fails at once, with no retry', async () => { + // Mutant: retrying every CloudflareAPIError turns a real failure into a delayed one. + const api = makeZoneApi({ + createEmailRoutingRule: mock(async () => { + throw new CloudflareAPIError('Cloudflare POST failed (10000): Authentication error', 403, [ + { code: 10000, message: 'Authentication error' } + ]) + }) + }) + const sleep = mock(async (_ms: number) => {}) + + const failure = provisionWorkerEmailRoutes( + { 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', worker: 'emailing' }] } } }, + 'acct_1', + api, + { created: [], existing: [], warnings: [] }, + { sleep } + ) + + await expect(failure).rejects.toThrow('Authentication error') + expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) + expect(sleep).not.toHaveBeenCalled() + }) +}) diff --git a/packages/devflare/tests/unit/config/deploy-zones.test.ts b/packages/devflare/tests/unit/config/deploy-zones.test.ts index 0dba72c2..e706c1f3 100644 --- a/packages/devflare/tests/unit/config/deploy-zones.test.ts +++ b/packages/devflare/tests/unit/config/deploy-zones.test.ts @@ -1,18 +1,14 @@ import { describe, expect, mock, test } from 'bun:test' -import { CloudflareAPIError } from '../../../src/cloudflare/api' import { prepareMaterializedConfigResourcesForDeploy } from '../../../src/config/deploy-resources' import { DEVFLARE_RECORD_COMMENT, - describeWorkerEmailRoutes, - EmailRouteError, - provisionWorkerEmailRoutes, provisionZoneResources, qualifyRecordName, - type ZoneProvisionApi, ZoneProvisionError, type ZoneProvisionResult } from '../../../src/config/deploy-zones' import type { DevflareConfig } from '../../../src/config/schema' +import { makeZoneApi, provision, provisionAfterUpload } from '../../helpers/zone-provision-api' /* Two layers, and the second matters most. @@ -26,83 +22,6 @@ import type { DevflareConfig } from '../../../src/config/schema' either: both failure modes are a mutation reaching the live API because a caller did not stop it. */ -/** A zone lookup that answers for `example.com` and treats anything under it as a subdomain. */ -function zoneFor(domain: string) { - return { - id: 'zone_1', - name: 'example.com', - domain, - isSubdomain: domain !== 'example.com' - } -} - -/** Every zone call as a mock, with read-only defaults a test can override per case. */ -function makeZoneApi(overrides: Partial = {}) { - return { - resolveZone: mock(async (domain: string) => zoneFor(domain)), - listDestinationAddresses: mock(async () => [ - { - tag: 'da_1', - email: 'someone@example.net', - verified: '2026-01-01T00:00:00Z' - } - ]), - createDestinationAddress: mock(async (_accountId: string, email: string) => ({ email })), - getEmailRoutingSettings: mock(async () => ({ - enabled: true, - status: 'ready' - })), - enableEmailRouting: mock(async () => ({ enabled: true })), - listEmailRoutingRules: mock(async () => []), - createEmailRoutingRule: mock(async (_zoneId: string, rule) => rule), - getEmailRoutingCatchAll: mock(async () => ({ - enabled: true, - matchers: [{ type: 'all' as const }], - actions: [{ type: 'drop' as const }] - })), - setEmailRoutingCatchAll: mock(async (_zoneId: string, rule) => rule), - listSendingDomains: mock(async () => [{ tag: 'sd_1', name: 'example.com', enabled: true }]), - createSendingDomain: mock(async (_zoneId: string, name: string) => ({ - tag: 'sd_new', - name, - enabled: true - })), - getSendingDomainDnsStatus: mock(async () => ({ status: 'ready' as const })), - listDnsRecords: mock(async () => []), - createDnsRecord: mock(async (_zoneId: string, record) => record), - updateDnsRecord: mock(async (_zoneId: string, _recordId: string, record) => record), - ...overrides - } satisfies ZoneProvisionApi -} - -/** Run a pass and hand back the accumulator it filled, so a test reads one value. */ -async function provision( - zones: DevflareConfig['zones'], - api: ZoneProvisionApi -): Promise { - const result: ZoneProvisionResult = { - created: [], - existing: [], - warnings: [] - } - await provisionZoneResources(zones, 'acct_1', api, result) - return result -} - -/** Run the AFTER-UPLOAD pass — the Worker-targeted routes — and hand back what it filled. */ -async function provisionAfterUpload( - zones: DevflareConfig['zones'], - api: ZoneProvisionApi -): Promise { - const result: ZoneProvisionResult = { - created: [], - existing: [], - warnings: [] - } - await provisionWorkerEmailRoutes(zones, 'acct_1', api, result) - return result -} - describe('qualifyRecordName — where a declared record actually lands', () => { test('a relative name resolves against the domain it was declared under', () => { expect(qualifyRecordName('_dmarc', 'example.com')).toBe('_dmarc.example.com') @@ -333,291 +252,6 @@ describe('Email Routing rules and the catch-all', () => { }) }) -describe('Email Routing to a Worker waits for the upload', () => { - /* - Cloudflare refuses a route naming a Worker that does not exist yet (`2016: Workers Script Info - not found`), so an app routing mail to ITS OWN worker could never pass its first deploy while - those routes were written in preparation. Preparation now skips every `worker` route and - `provisionWorkerEmailRoutes` writes them after the upload. - */ - const selfRouting: DevflareConfig['zones'] = { - 'example.com': { - emailRouting: { - rules: [ - { to: 'press@example.com', forward: ['someone@example.net'] }, - { to: 'inbox@example.com', worker: 'emailing' } - ], - catchAll: { worker: 'emailing' } - } - } - } - - test('preparation sets NO worker route — not the rule, not the catch-all', async () => { - // Mutant: dropping the `!isWorkerTargeted` filter on the catch-all or the rules in - // `provisionEmailRouting` puts the write back before the upload, which is the defect. - const api = makeZoneApi() - - const result = await provision(selfRouting, api) - - expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() - const ruleActions = api.createEmailRoutingRule.mock.calls.map( - (call) => call[1].actions[0]?.type - ) - expect(ruleActions).not.toContain('worker') - expect(result.created.join('\n')).not.toContain('inbox@example.com') - expect(result.created.join('\n')).not.toContain('catch-all') - }) - - test('preparation still creates the FORWARD rule, and its destination first', async () => { - // Only `worker` actions moved. Mutant: filtering every rule out of preparation (or skipping - // `provisionRoutingRules` there) leaves forwarding rules unwritten. - const order: string[] = [] - const api = makeZoneApi({ - listDestinationAddresses: mock(async () => []), - createDestinationAddress: mock(async (_accountId: string, email: string) => { - order.push('address') - return { email } - }), - createEmailRoutingRule: mock(async (_zoneId: string, rule) => { - order.push(`rule:${rule.actions[0]?.type}`) - return rule - }) - }) - - const result = await provision(selfRouting, api) - - expect(order).toEqual(['address', 'rule:forward']) - expect(result.created).toContain('Email rule press@example.com (zone example.com)') - }) - - test('the after-upload pass sets the worker rule and the worker catch-all, and only those', async () => { - const api = makeZoneApi() - - const result = await provisionAfterUpload(selfRouting, api) - - expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) - expect(api.createEmailRoutingRule.mock.calls[0]?.[1].actions).toEqual([ - { type: 'worker', value: ['emailing'] } - ]) - expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(1) - expect(api.setEmailRoutingCatchAll.mock.calls[0]?.[1]).toMatchObject({ - enabled: true, - actions: [{ type: 'worker', value: ['emailing'] }] - }) - // It touches nothing preparation owns: no routing switch, no destination, no DNS. - expect(api.getEmailRoutingSettings).not.toHaveBeenCalled() - expect(api.listDestinationAddresses).not.toHaveBeenCalled() - expect(result.created).toEqual([ - 'Email rule inbox@example.com (zone example.com)', - 'Email catch-all (zone example.com) — set to worker' - ]) - }) - - test('a worker rule keeps the priority its place in the WHOLE list gives it', async () => { - // Mutant: numbering by index within the after-upload subset gives `inbox@` priority 1, the - // same as `press@`, so the split silently reorders the zone's rules. - const api = makeZoneApi() - - await provisionAfterUpload(selfRouting, api) - - expect(api.createEmailRoutingRule.mock.calls[0]?.[1].priority).toBe(2) - }) - - test('a second deploy is a no-op that reports every worker route as existing', async () => { - const api = makeZoneApi({ - listEmailRoutingRules: mock(async () => [ - { - tag: 'r2', - matchers: [ - { - type: 'literal' as const, - field: 'to' as const, - value: 'inbox@example.com' - } - ], - actions: [{ type: 'worker' as const, value: ['emailing'] }] - } - ]), - getEmailRoutingCatchAll: mock(async () => ({ - enabled: true, - matchers: [{ type: 'all' as const }], - actions: [{ type: 'worker' as const, value: ['emailing'] }] - })) - }) - - const result = await provisionAfterUpload(selfRouting, api) - - expect(api.createEmailRoutingRule).not.toHaveBeenCalled() - expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() - expect(result.created).toEqual([]) - expect(result.existing).toEqual([ - 'Email rule inbox@example.com (zone example.com)', - 'Email catch-all (zone example.com)' - ]) - }) - - test('a domain with no worker route costs the after-upload pass no request at all', async () => { - const api = makeZoneApi() - - await provisionAfterUpload( - { - 'example.com': { - emailRouting: { - rules: [{ to: 'a@example.com', drop: true }], - catchAll: { drop: true } - }, - dns: [{ type: 'TXT', name: '_dmarc', content: 'v=DMARC1; p=none' }] - } - }, - api - ) - - expect(api.resolveZone).not.toHaveBeenCalled() - }) - - test("a failed write names the route, keeping Cloudflare's own error as the cause", async () => { - const cloudflare = new Error( - 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found' - ) - const api = makeZoneApi({ - setEmailRoutingCatchAll: mock(async () => { - throw cloudflare - }) - }) - const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } - - const failure = provisionWorkerEmailRoutes(selfRouting, 'acct_1', api, result) - - await expect(failure).rejects.toBeInstanceOf(EmailRouteError) - await failure.catch((error: EmailRouteError) => { - expect(error.route).toBe('Email catch-all (zone example.com)') - expect(error.operation).toBe('write') - expect(error.worker).toBe('emailing') - expect(error.cause).toBe(cloudflare) - expect(error.message).toContain('Workers Script Info not found') - }) - // The rule before it was set, and the accumulator still says so after the throw. - expect(result.created).toEqual(['Email rule inbox@example.com (zone example.com)']) - }) - - test('a failed READ is reported as a read, so nobody is told a live route was lost', async () => { - // Mutant: tagging the catch-all lookup as a `write` makes the deploy say the route is unset - // when an earlier deploy's route is still in place. - const api = makeZoneApi({ - getEmailRoutingCatchAll: mock(async () => { - throw new Error('Cloudflare GET failed: 503') - }) - }) - - const failure = provisionAfterUpload(selfRouting, api) - - await expect(failure).rejects.toBeInstanceOf(EmailRouteError) - await failure.catch((error: EmailRouteError) => { - expect(error.operation).toBe('read') - expect(error.route).toBe('Email catch-all (zone example.com)') - }) - expect(api.setEmailRoutingCatchAll).not.toHaveBeenCalled() - }) - - test('every worker route is named up front, without a Cloudflare call', () => { - // What an early exit lists as NOT set. Mutant: dropping the catch-all from the list leaves a - // failed upload silent about it. - expect(describeWorkerEmailRoutes(selfRouting)).toEqual([ - 'Email rule inbox@example.com → Worker emailing', - 'Email catch-all for example.com → Worker emailing' - ]) - expect( - describeWorkerEmailRoutes({ - 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', drop: true }] } } - }) - ).toEqual([]) - }) -}) - -describe('Email Routing may not see a just-uploaded Worker at once', () => { - const catchAllOnly: DevflareConfig['zones'] = { - 'example.com': { emailRouting: { catchAll: { worker: 'emailing' } } } - } - - /** The error Cloudflare's client raises for a route naming a Worker it cannot find. */ - function scriptNotFound(): CloudflareAPIError { - return new CloudflareAPIError( - 'Cloudflare PUT /zones/zone_1/email/routing/rules/catch_all failed (2016): Workers Script Info not found', - 404, - [{ code: 2016, message: 'Workers Script Info not found' }] - ) - } - - test('a 2016 is retried, a few seconds apart, until the write lands', async () => { - // Mutant: removing `withWorkerRouteRetry` from the pass fails on the first 2016. - let attempts = 0 - const api = makeZoneApi({ - setEmailRoutingCatchAll: mock(async (_zoneId: string, rule) => { - attempts += 1 - if (attempts < 3) throw scriptNotFound() - return rule - }) - }) - const waits: number[] = [] - const result: ZoneProvisionResult = { created: [], existing: [], warnings: [] } - - await provisionWorkerEmailRoutes(catchAllOnly, 'acct_1', api, result, { - sleep: async (ms) => { - waits.push(ms) - } - }) - - expect(attempts).toBe(3) - expect(waits).toEqual([3000, 3000]) - expect(result.created).toEqual(['Email catch-all (zone example.com) — set to worker']) - }) - - test('it gives up after three retries and reports the 2016', async () => { - const api = makeZoneApi({ - setEmailRoutingCatchAll: mock(async () => { - throw scriptNotFound() - }) - }) - const sleep = mock(async (_ms: number) => {}) - - const failure = provisionWorkerEmailRoutes( - catchAllOnly, - 'acct_1', - api, - { created: [], existing: [], warnings: [] }, - { sleep, delayMs: 5 } - ) - - await expect(failure).rejects.toThrow('Workers Script Info not found') - expect(api.setEmailRoutingCatchAll).toHaveBeenCalledTimes(4) - expect(sleep.mock.calls.map((call) => call[0])).toEqual([5, 5, 5]) - }) - - test('any other Cloudflare error fails at once, with no retry', async () => { - // Mutant: retrying every CloudflareAPIError turns a real failure into a delayed one. - const api = makeZoneApi({ - createEmailRoutingRule: mock(async () => { - throw new CloudflareAPIError('Cloudflare POST failed (10000): Authentication error', 403, [ - { code: 10000, message: 'Authentication error' } - ]) - }) - }) - const sleep = mock(async (_ms: number) => {}) - - const failure = provisionWorkerEmailRoutes( - { 'example.com': { emailRouting: { rules: [{ to: 'a@example.com', worker: 'emailing' }] } } }, - 'acct_1', - api, - { created: [], existing: [], warnings: [] }, - { sleep } - ) - - await expect(failure).rejects.toThrow('Authentication error') - expect(api.createEmailRoutingRule).toHaveBeenCalledTimes(1) - expect(sleep).not.toHaveBeenCalled() - }) -}) - describe('provisionZoneResources — forwarding destinations', () => { const forwards = { 'example.com': {