Skip to content
Open
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
82 changes: 58 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,20 @@ async function verifyReadinessStagingOwner(
return { ok: true, previousDeploymentId: owner.deploymentId };
}

type ReadinessProbeBody = { ready?: unknown; versionId?: unknown };

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

function formatReadinessProbeValue(value: unknown): string {
if (typeof value === 'string') {
return value;
}
return value === undefined ? 'undefined' : JSON.stringify(value);
}

async function probeReadiness(
url: string,
workerName: string,
Expand All @@ -3363,7 +3383,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,9 +3392,10 @@ async function probeReadiness(
trustedReadinessOrigin,
);
if (headers === null) {
return 'failed';
return { status: 'failed' };
}
const deadline = Date.now() + timeoutMs;
let lastReply: string | undefined;
for (let attempt = 0; attempt < Math.max(1, attempts); attempt++) {
const remaining = deadline - Date.now();
if (remaining <= 0) {
Expand All @@ -3396,18 +3417,31 @@ 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';
let body: ReadinessProbeBody | undefined;
try {
body = await response.json<ReadinessProbeBody>();
} catch {
lastReply = `Last readiness reply from ${url}: HTTP ${response.status} (invalid JSON body).`;
}
if (body !== undefined) {
if (
body.ready === true &&
(expectedVersionId === undefined || body.versionId === expectedVersionId)
) {
return { status: 'ready' };
}
const expectedNote =
expectedVersionId !== undefined ? ` (expected versionId ${expectedVersionId})` : '';
lastReply = `Last readiness reply from ${url}: HTTP ${response.status} (ready=${formatReadinessProbeValue(body.ready)}, versionId=${formatReadinessProbeValue(body.versionId)})${expectedNote}.`;
}
} else if (await isCloudflareAccessDenial(response)) {
return 'access-denied';
return { status: 'access-denied' };
} else {
lastReply = `Last readiness reply from ${url}: HTTP ${response.status}.`;
}
} catch {
} catch (error) {
// Preview propagation is eventually consistent; retry below.
lastReply = `Last readiness probe to ${url} failed: ${error instanceof Error ? error.message : String(error)}.`;
} finally {
if (response && !response.bodyUsed) {
await response.body?.cancel().catch(() => {});
Expand All @@ -3420,7 +3454,7 @@ async function probeReadiness(
}
}
}
return 'failed';
return { status: 'failed', ...(lastReply ? { diagnostic: lastReply } : {}) };
}

/**
Expand Down
8 changes: 7 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,8 @@ describe('Cloudflare version activation', () => {
reason: 'readiness-failed',
versionId: NEXT,
rollback: 'not-needed',
diagnostic:
'Last readiness reply from https://ready.example.workers.dev/__void/ready: HTTP 503.',
});
expect(uploadedSecrets).toEqual({ API_TOKEN: 'next-secret' });
expect(runWrangler.mock.calls.flatMap(([args]) => args)).not.toContain('next-secret');
Expand Down Expand Up @@ -5384,7 +5386,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: `Last readiness reply from https://app.example.com/__void/ready: HTTP 200 (ready=true, versionId=${CURRENT}) (expected versionId ${NEXT}).`,
});
expect(probes).toBeLessThanOrEqual(6);
expect(time).toBeLessThanOrEqual(70_000);
const deployments = runWrangler.mock.calls.filter(
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
3 changes: 3 additions & 0 deletions 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 @@ -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
3 changes: 3 additions & 0 deletions packages/void/src/cli/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ async function runDeployInner(
if (options?.atomic && platform !== 'cloudflare') {
throw new Error('deploy: --atomic is available only for Cloudflare Workers.');
}
if (options?.readinessAttempts !== undefined && platform !== 'cloudflare') {
throw new Error('deploy: --readiness-attempts is available only for Cloudflare Workers.');
}

if (platform === 'none') {
throw new Error(
Expand Down
5 changes: 5 additions & 0 deletions packages/void/src/cli/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ const HELP_TREE = {
description:
'Publish a Worker with Durable Objects or Workflows before checking readiness (Cloudflare only)',
},
{
command: '--readiness-attempts <count>',
description:
'Maximum /__void/ready probe attempts before failing or rolling back (Cloudflare only)',
},
{
command: '--preview <name>',
description:
Expand Down
16 changes: 13 additions & 3 deletions packages/void/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export type EmailConfig = {

/** Deployment choices owned by Void rather than passed to the Worker config. */
export type DeployConfig = {
cloudflare?: { mode?: 'staged' | 'atomic' };
cloudflare?: { mode?: 'staged' | 'atomic'; readinessAttempts?: number };
};

/** Cloudflare Worker configuration passed through to the native deploy artifact. */
Expand Down Expand Up @@ -960,9 +960,9 @@ function validateConfigObject(obj: unknown): VoidConfig {
}
const cloudflareDeploy = deploy.cloudflare;
for (const key of Object.keys(cloudflareDeploy)) {
if (key !== 'mode') {
if (key !== 'mode' && key !== 'readinessAttempts') {
throw new Error(
`config: Unknown key 'deploy.cloudflare.${key}' in ${CONFIG_FILE}. Valid: mode.`,
`config: Unknown key 'deploy.cloudflare.${key}' in ${CONFIG_FILE}. Valid: mode, readinessAttempts.`,
);
}
}
Expand All @@ -975,6 +975,16 @@ function validateConfigObject(obj: unknown): VoidConfig {
`config: "deploy.cloudflare.mode" in ${CONFIG_FILE} must be "staged" or "atomic".`,
);
}
if (
cloudflareDeploy.readinessAttempts !== undefined &&
(typeof cloudflareDeploy.readinessAttempts !== 'number' ||
!Number.isInteger(cloudflareDeploy.readinessAttempts) ||
cloudflareDeploy.readinessAttempts < 1)
) {
throw new Error(
`config: "deploy.cloudflare.readinessAttempts" in ${CONFIG_FILE} must be a positive integer.`,
);
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions packages/void/test/unit/cloudflare-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,21 @@ describe('Cloudflare activation diagnostics', () => {
);
});

it('renders the readiness diagnostic for staged readiness failures when available', () => {
const message = formatCloudflareActivationError({
ok: false,
reason: 'readiness-failed',
rollback: 'succeeded',
diagnostic:
'Last readiness reply from https://app.example.com/__void/ready: HTTP 200 (ready=true, versionId=prev-v1) (expected versionId next-v2).',
});
expect(message).toContain('did not pass /__void/ready');
expect(message).toContain('traffic was restored to the previous version.');
expect(message).toContain(
'HTTP 200 (ready=true, versionId=prev-v1) (expected versionId next-v2)',
);
});

it('recommends reinstalling dependencies when uploader verification blocks readiness cleanup', () => {
const message = formatCloudflareActivationError({
ok: false,
Expand Down
Loading