Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/email-routing-after-upload.md
Original file line number Diff line number Diff line change
@@ -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 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".
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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: {
Expand All @@ -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.'
],
[
Expand Down Expand Up @@ -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.'
]
}
]
Expand Down
8 changes: 5 additions & 3 deletions packages/devflare/LLM.md
Original file line number Diff line number Diff line change
Expand Up @@ -3470,15 +3470,17 @@ 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. 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.

##### Reference table

| 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. |

Expand All @@ -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

Expand Down
90 changes: 78 additions & 12 deletions packages/devflare/src/cli/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -33,6 +33,7 @@ import {
} from '../preview'
import { createCliTheme, dim, green, logLine, yellow, yellowBold } from '../ui'
import { prepareBuildArtifacts } from './build-artifacts'
import { describeAfterUploadRoutingFailure, describeRoutesNotSet } from './deploy/after-upload'
import { inferRecordSource, writeDeployResultMetadata } from './deploy/metadata'
import {
prepareDeployConfig,
Expand Down Expand Up @@ -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.afterUpload?.provision(afterUpload)
const wouldCreate = [
...describeResult.created.kv.map((n) => `KV: ${n}`),
...describeResult.created.d1.map((n) => `D1: ${n}`),
Expand All @@ -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))
Expand Down Expand Up @@ -422,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<CliResult | undefined> => {
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 }
}

Expand Down Expand Up @@ -547,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,
Expand Down Expand Up @@ -601,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,
Expand All @@ -630,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 }
}
Expand All @@ -657,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,
Expand Down Expand Up @@ -702,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 }
Expand All @@ -717,6 +780,9 @@ export async function runDeployCommand(
)
}

const routingFailure = await runAfterUpload()
if (routingFailure) return routingFailure

if (resolvedAccountId) {
const previewRegistryScope = isBranchScopedPreviewDeployment
? deployTarget.previewScope
Expand Down
Loading
Loading