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
1 change: 1 addition & 0 deletions docs/reference/cli/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m
| `--skip-migrations` | Deploy without applying application or authentication SQL migrations; supported on Cloudflare and Void platforms |
| `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` |
| `--provision` | Run resource provisioning again even when every resource exists; requires `--platform cloudflare` |
| `--readiness-attempts <count>` | Maximum readiness probes for a Cloudflare deployment. Overrides `deploy.cloudflare.readinessAttempts`. |
| `--atomic` | Send traffic before checking readiness on an existing Worker with Durable Objects or Workflows |
| `--preview <name>` | Deploy a static site or SPA to a Cloudflare Preview; production is unchanged ([more](#void-deploy-preview)) |
| `--json` | With `--preview`, print one JSON object on stdout; everything else goes to stderr |
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,10 @@ Bindings declared here are typed on `c.env` after `void prepare` or starting a d

If you need to remove a value that Void previously generated, remove it from the `resolved` object in `void.lock.json`. Void refreshes the generated Cloudflare file on the next command. Put ongoing custom settings in `cloudflare` in `void.config.ts`.

### `deploy.cloudflare.readinessAttempts`

Set a positive integer to control how many times Void probes a Cloudflare deployment for readiness. Use `--readiness-attempts <count>` to override it for one deploy.

### `deploy.cloudflare.mode`

Void uses `staged` for direct Cloudflare deploys and checks the new version before it serves traffic. If Cloudflare cannot stage a Worker with Durable Objects or Workflows, review the pending code and database changes. Set the mode to `atomic` to send traffic to the new version before the check.
Expand Down
87 changes: 63 additions & 24 deletions packages/deploy-cloudflare/src/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1911,7 +1911,7 @@ async function activateCloudflareVersionWithSecretsFile(
// whose traffic can remain untouched while the new version is staged; a truly empty first
// deployment has no safe zero-percent fallback.
if (
ready === 'access-denied' &&
ready.status === 'access-denied' &&
!stagedVersionOverride &&
previous.versionId !== null &&
!options.requirePreviewForReadiness
Expand Down Expand Up @@ -1939,13 +1939,14 @@ async function activateCloudflareVersionWithSecretsFile(
ready = await probe(readinessUrl);
}
}
if (ready !== 'ready') {
if (ready.status !== 'ready') {
return {
ok: false,
reason: ready === 'access-denied' ? 'readiness-access-denied' : 'readiness-failed',
reason: ready.status === 'access-denied' ? 'readiness-access-denied' : 'readiness-failed',
versionId,
previousVersionId: previous.versionId,
...(ready === 'access-denied' && withholdsCustomRouteHeaders(readinessUrl)
...(ready.status === 'failed' && ready.diagnostic ? { diagnostic: ready.diagnostic } : {}),
...(ready.status === 'access-denied' && withholdsCustomRouteHeaders(readinessUrl)
? customRouteReadinessOriginField(readinessUrl)
: {}),
...(stagedVersionOverride
Expand Down Expand Up @@ -3011,11 +3012,21 @@ async function bootstrapFirstDeployment(
readinessTimeoutMs,
options.requireVersionMetadata ? versionId : undefined,
);
if (ready !== 'ready') {
if (ready.status !== 'ready') {
const customDomainDiagnostic =
'The Custom Domain may still be propagating DNS or its TLS certificate. Check the configured domain in Cloudflare, then retry `void deploy --platform cloudflare` once its /__void/ready endpoint is reachable.';
const diagnostic =
ready.status === 'failed'
? usesCustomDomain
? ready.diagnostic
? `${customDomainDiagnostic}\n\n${ready.diagnostic}`
: customDomainDiagnostic
: ready.diagnostic
: undefined;
return {
ok: false,
reason:
ready === 'access-denied'
ready.status === 'access-denied'
? atomic
? 'atomic-readiness-access-denied'
: 'bootstrap-readiness-access-denied'
Expand All @@ -3025,15 +3036,10 @@ async function bootstrapFirstDeployment(
versionId,
previousVersionId,
rollback: 'unavailable',
...(ready === 'access-denied' && withholdsCustomRouteHeaders
...(ready.status === 'access-denied' && withholdsCustomRouteHeaders
? customRouteReadinessOriginField(previewUrl)
: {}),
...(ready === 'failed' && usesCustomDomain
? {
diagnostic:
'The Custom Domain may still be propagating DNS or its TLS certificate. Check the configured domain in Cloudflare, then retry `void deploy --platform cloudflare` once its /__void/ready endpoint is reachable.',
}
: {}),
...(diagnostic ? { diagnostic } : {}),
};
}
if (!options.verifyUploader()) {
Expand Down Expand Up @@ -3351,6 +3357,18 @@ async function verifyReadinessStagingOwner(
return { ok: true, previousDeploymentId: owner.deploymentId };
}

type ReadinessProbeResult =
| { status: 'ready' }
| { status: 'access-denied' }
| { status: 'failed'; diagnostic?: string };

function formatReadinessProbeValue(value: unknown): string {
if (typeof value === 'string') {
return JSON.stringify(value.slice(0, 128));
}
return value === null || typeof value !== 'object' ? String(value) : '[invalid]';
}

async function probeReadiness(
url: string,
workerName: string,
Expand All @@ -3363,7 +3381,7 @@ async function probeReadiness(
attempts: number,
timeoutMs = Number.POSITIVE_INFINITY,
expectedVersionId?: string,
): Promise<'ready' | 'failed' | 'access-denied'> {
): Promise<ReadinessProbeResult> {
const headers = guardedReadinessHeaders(
url,
workerName,
Expand All @@ -3372,14 +3390,16 @@ async function probeReadiness(
trustedReadinessOrigin,
);
if (headers === null) {
return 'failed';
return { status: 'failed' };
}
const deadline = Date.now() + timeoutMs;
const history: Array<string> = [];
for (let attempt = 0; attempt < Math.max(1, attempts); attempt++) {
const remaining = deadline - Date.now();
if (remaining <= 0) {
break;
}
let reply: string;
let response: Response | undefined;
try {
response = await fetcher(url, {
Expand All @@ -3396,31 +3416,50 @@ async function probeReadiness(
signal: AbortSignal.timeout(Math.max(1, Math.min(10_000, remaining))),
});
if (response.ok) {
const body = await response.json<{ ready?: unknown; versionId?: unknown }>();
if (
body.ready === true &&
(expectedVersionId === undefined || body.versionId === expectedVersionId)
) {
return 'ready';
const body = await response.json<unknown>().catch(() => undefined);
if (isRecord(body)) {
if (
body.ready === true &&
(expectedVersionId === undefined || body.versionId === expectedVersionId)
) {
return { status: 'ready' };
}
reply = `HTTP ${response.status} (ready=${formatReadinessProbeValue(body.ready)}, versionId=${formatReadinessProbeValue(body.versionId)})`;
} else {
reply = `HTTP ${response.status} (invalid readiness body)`;
}
} else if (await isCloudflareAccessDenial(response)) {
return 'access-denied';
return { status: 'access-denied' };
} else {
reply = `HTTP ${response.status}`;
}
} catch {
} catch (error) {
// Preview propagation is eventually consistent; retry below.
reply = `Request failed: ${formatReadinessProbeValue(error instanceof Error ? error.message : String(error))}`;
} finally {
if (response && !response.bodyUsed) {
await response.body?.cancel().catch(() => {});
}
}
history.push(` ${attempt + 1}. ${reply}`);
if (history.length > 10) {
history.shift();
}
if (attempt + 1 < attempts) {
const waitMs = Math.min(250 * 2 ** attempt, 2000, deadline - Date.now());
if (waitMs > 0) {
await sleep(waitMs);
}
}
}
return 'failed';
const expected =
expectedVersionId === undefined ? '' : ` (expected versionId ${expectedVersionId})`;
return {
status: 'failed',
...(history.length && {
diagnostic: `Readiness probes to ${url}${expected}:\n${history.join('\n')}`,
}),
};
}

/**
Expand Down
34 changes: 33 additions & 1 deletion packages/deploy-cloudflare/test/unit/version.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3705,6 +3705,7 @@ describe('Cloudflare version activation', () => {
reason: 'readiness-failed',
versionId: NEXT,
rollback: 'not-needed',
diagnostic: expect.stringContaining('1. HTTP 503\n 2. HTTP 503'),
});
expect(uploadedSecrets).toEqual({ API_TOKEN: 'next-secret' });
expect(runWrangler.mock.calls.flatMap(([args]) => args)).not.toContain('next-secret');
Expand Down Expand Up @@ -5363,6 +5364,33 @@ describe('Cloudflare version activation', () => {
}
});

it('retains a version mismatch when the final readiness probe returns 503', async () => {
let attempts = 0;
const result = await activateCloudflareVersion({
runWrangler: runner(),
verifyUploader: () => true,
workerName: 'private-app',
requireVersionMetadata: true,
message: encodeCloudflareVersionMessage([], customDomainTriggers('app.example.com')),
readinessAttempts: 12,
sleep: async () => {},
fetch: async () =>
++attempts === 12
? new Response(null, { status: 503 })
: Response.json({ ready: true, versionId: CURRENT }),
});
expect(result).toMatchObject({
reason: 'readiness-failed',
diagnostic: expect.stringContaining(`expected versionId ${NEXT}`),
});
expect(result).toMatchObject({
diagnostic: expect.stringContaining(
`11. HTTP 200 (ready=true, versionId="${CURRENT}")\n 12. HTTP 503`,
),
});
expect(result).toMatchObject({ diagnostic: expect.not.stringContaining(' 1. ') });
});

it('bounds a staged readiness wait by elapsed time and restores the previous version', async () => {
const runWrangler = runner();
let time = 0;
Expand All @@ -5384,7 +5412,11 @@ describe('Cloudflare version activation', () => {
return Response.json({ ready: true, versionId: CURRENT });
},
});
expect(result).toMatchObject({ ok: false, reason: 'readiness-failed' });
expect(result).toMatchObject({
ok: false,
reason: 'readiness-failed',
diagnostic: expect.stringContaining(`HTTP 200 (ready=true, versionId="${CURRENT}")`),
});
expect(probes).toBeLessThanOrEqual(6);
expect(time).toBeLessThanOrEqual(70_000);
const deployments = runWrangler.mock.calls.filter(
Expand Down
6 changes: 6 additions & 0 deletions packages/void/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,12 @@
"type": "string",
"enum": ["staged", "atomic"],
"description": "Staged is the default and verifies readiness before traffic. Atomic publishes a Worker with Durable Objects or Workflows directly and verifies readiness afterward."
},
"readinessAttempts": {
"type": "integer",
"minimum": 1,
"maximum": 9007199254740991,
"description": "Maximum number of attempts to verify a Cloudflare deployment's readiness."
}
},
"additionalProperties": false
Expand Down
30 changes: 30 additions & 0 deletions packages/void/src/cli/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export function parseDeployArgs(
provision: { type: 'boolean' },
'require-email': { type: 'boolean' },
atomic: { type: 'boolean' },
'readiness-attempts': { type: 'string' },
preview: { type: 'string' },
json: { type: 'boolean' },
},
Expand All @@ -41,6 +42,11 @@ export function parseDeployArgs(
cause: error,
});
}
if (optionMatch?.[1] === '--readiness-attempts') {
throw new Error('deploy: --readiness-attempts must be a positive integer.', {
cause: error,
});
}
throw new Error('deploy: --project requires a slug.', { cause: error });
}

Expand Down Expand Up @@ -118,6 +124,29 @@ export function parseDeployArgs(
if (tokens.filter((token) => token.kind === 'option' && token.name === 'preview').length > 1) {
throw new Error('deploy: --preview can only be specified once.');
}
if (
tokens.filter((token) => token.kind === 'option' && token.name === 'readiness-attempts')
.length > 1
) {
throw new Error('deploy: --readiness-attempts can only be specified once.');
}
const readinessAttemptsRaw =
typeof parsed.values['readiness-attempts'] === 'string'
? parsed.values['readiness-attempts']
: undefined;
let readinessAttempts: number | undefined;
if (readinessAttemptsRaw !== undefined) {
if (!/^[1-9]\d*$/.test(readinessAttemptsRaw)) {
throw new Error('deploy: --readiness-attempts must be a positive integer.');
}
readinessAttempts = Number(readinessAttemptsRaw);
if (!Number.isSafeInteger(readinessAttempts)) {
throw new Error('deploy: --readiness-attempts must be a positive integer.');
}
if (platform !== 'cloudflare') {
throw new Error('deploy: --readiness-attempts requires --platform cloudflare.');
}
}
const preview = typeof parsed.values.preview === 'string' ? parsed.values.preview : undefined;
const json = parsed.values.json === true ? true : undefined;
if (preview !== undefined) {
Expand Down Expand Up @@ -155,5 +184,6 @@ export function parseDeployArgs(
provision,
requireEmail,
atomic,
...(readinessAttempts !== undefined ? { readinessAttempts } : {}),
};
}
10 changes: 6 additions & 4 deletions packages/void/src/cli/deploy-cloudflare-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,10 +739,12 @@ function formatCloudflareActivationFailure(
return `deploy: the atomic Worker deployment is live, but /__void/ready could not be verified. Inspect \`void project status\` and Worker logs immediately.${diagnostic}${accessHint}`;
}
case 'readiness-failed':
return [
'deploy: the uploaded Worker Version did not pass /__void/ready.',
formatCloudflareReadinessRestoration(result),
].join('\n');
return (
[
'deploy: the uploaded Worker Version did not pass /__void/ready.',
formatCloudflareReadinessRestoration(result),
].join('\n') + diagnostic
);
case 'readiness-access-denied':
if (result.customRouteReadinessOrigin) {
return [
Expand Down
4 changes: 4 additions & 0 deletions packages/void/src/cli/deploy-cloudflare-publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export async function publishCloudflareWorker(input: {
readonly cliLog: CliLogger;
readonly reporter: CloudflareChildReporter;
readonly atomic: boolean;
readonly readinessAttempts?: number;
readonly detectedFramework: ReturnType<typeof detectFramework>;
readonly initialCloudflareCandidate: CloudflareCandidateReceipt | null;
readonly source: CloudflareDeploySource;
Expand Down Expand Up @@ -140,6 +141,9 @@ export async function publishCloudflareWorker(input: {
allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning,
...(pinActiveSecrets ? { pinActiveSecrets } : {}),
atomic,
...(input.readinessAttempts !== undefined
? { readinessAttempts: input.readinessAttempts }
: {}),
...(initialAuthSecret
? { candidateSecrets: { [BETTER_AUTH_SECRET_NAME]: initialAuthSecret } }
: {}),
Expand Down
1 change: 1 addition & 0 deletions packages/void/src/cli/deploy-cloudflare-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,7 @@ export async function runCloudflareStaticDeploy(
}),
runWrangler: activationRunner,
verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned,
readinessAttempts: options.readinessAttempts,
requireVersionMetadata: existingWorker === null || versionMetadataBinding !== undefined,
requirePreviewForReadiness: existingWorker !== null && versionMetadataBinding === undefined,
message,
Expand Down
5 changes: 4 additions & 1 deletion packages/void/src/cli/deploy-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export async function runCloudflareDeploy(
!initialCloudflareLink && !options.reuseExistingWorker && !hasDeployConfigSource(root);
const voidConfig = readConfig(root);
const atomic = options.atomic === true || voidConfig.deploy?.cloudflare?.mode === 'atomic';
const readinessAttempts =
options.readinessAttempts ?? voidConfig.deploy?.cloudflare?.readinessAttempts;
if (atomic && (options.reuseExistingWorker || initialCloudflareLink)) {
log.error(
'deploy: atomic deployment is unavailable during the existing Worker handoff. Complete the handoff first.',
Expand Down Expand Up @@ -127,7 +129,7 @@ export async function runCloudflareDeploy(
}
return runCloudflareStaticDeploy(
root,
{ ...options, atomic },
{ ...options, atomic, readinessAttempts },
voidConfig,
staticPreset,
cliLog,
Expand Down Expand Up @@ -222,6 +224,7 @@ export async function runCloudflareDeploy(
...deployment,
reporter,
atomic,
readinessAttempts,
detectedFramework,
initialCloudflareCandidate,
migration,
Expand Down
2 changes: 2 additions & 0 deletions packages/void/src/cli/deploy-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export type RunDeployOptions = {
requireEmail?: boolean;
/** Publish an existing Worker with Durable Objects or Workflows atomically after explicit operator choice. */
atomic?: boolean;
/** Maximum readiness probe attempts for Cloudflare deployments (`--platform cloudflare`). */
readinessAttempts?: number;
/**
* Create or update this named Cloudflare Preview instead of deploying production.
* `--platform cloudflare` only; production traffic is never changed.
Expand Down
Loading