From 0e762f6b279b31493aabc6490d610b9a7a2d602d Mon Sep 17 00:00:00 2001 From: SHANNWD <167665311+SHANNWD@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:21:04 +0530 Subject: [PATCH] fix(deploy): add readiness attempts config/flag and surface last probe reply --- packages/deploy-cloudflare/src/version.ts | 82 +++++++++++++------ .../test/unit/version.test.ts | 8 +- packages/void/src/cli/args.ts | 30 +++++++ .../void/src/cli/deploy-cloudflare-helpers.ts | 10 ++- .../void/src/cli/deploy-cloudflare-publish.ts | 4 + packages/void/src/cli/deploy-cloudflare.ts | 3 + packages/void/src/cli/deploy-types.ts | 2 + packages/void/src/cli/deploy.ts | 3 + packages/void/src/cli/help.ts | 5 ++ packages/void/src/config.ts | 16 +++- .../void/test/unit/cloudflare-deploy.test.ts | 15 ++++ packages/void/test/unit/config.test.ts | 20 +++++ packages/void/test/unit/deploy-args.test.ts | 15 ++++ 13 files changed, 181 insertions(+), 32 deletions(-) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 6f46706b0..a2a6b169e 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -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 @@ -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 @@ -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' @@ -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()) { @@ -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, @@ -3363,7 +3383,7 @@ async function probeReadiness( attempts: number, timeoutMs = Number.POSITIVE_INFINITY, expectedVersionId?: string, -): Promise<'ready' | 'failed' | 'access-denied'> { +): Promise { const headers = guardedReadinessHeaders( url, workerName, @@ -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) { @@ -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(); + } 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(() => {}); @@ -3420,7 +3454,7 @@ async function probeReadiness( } } } - return 'failed'; + return { status: 'failed', ...(lastReply ? { diagnostic: lastReply } : {}) }; } /** diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index a4e573078..916ba0235 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -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'); @@ -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( diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index d5f706dda..474a4b8fc 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -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' }, }, @@ -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 }); } @@ -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) { @@ -155,5 +184,6 @@ export function parseDeployArgs( provision, requireEmail, atomic, + ...(readinessAttempts !== undefined ? { readinessAttempts } : {}), }; } diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 4cfbc4f87..b959f0899 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -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 [ diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index faafd6b4f..2e4d812a8 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -33,6 +33,7 @@ export async function publishCloudflareWorker(input: { readonly cliLog: CliLogger; readonly reporter: CloudflareChildReporter; readonly atomic: boolean; + readonly readinessAttempts?: number; readonly detectedFramework: ReturnType; readonly initialCloudflareCandidate: CloudflareCandidateReceipt | null; readonly source: CloudflareDeploySource; @@ -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 } } : {}), diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 3b09150cf..467a21763 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -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.', @@ -222,6 +224,7 @@ export async function runCloudflareDeploy( ...deployment, reporter, atomic, + readinessAttempts, detectedFramework, initialCloudflareCandidate, migration, diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index 266033f10..4bb5ad77e 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -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. diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 5b9d4eab6..338f4ae60 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -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( diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 69371d7d4..3ad5558dd 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -194,6 +194,11 @@ const HELP_TREE = { description: 'Publish a Worker with Durable Objects or Workflows before checking readiness (Cloudflare only)', }, + { + command: '--readiness-attempts ', + description: + 'Maximum /__void/ready probe attempts before failing or rolling back (Cloudflare only)', + }, { command: '--preview ', description: diff --git a/packages/void/src/config.ts b/packages/void/src/config.ts index b1c5dcdfd..a8388793a 100644 --- a/packages/void/src/config.ts +++ b/packages/void/src/config.ts @@ -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. */ @@ -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.`, ); } } @@ -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.`, + ); + } } } diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 151fd254f..d41e537b6 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -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, diff --git a/packages/void/test/unit/config.test.ts b/packages/void/test/unit/config.test.ts index 95ca8c57f..2829f8e03 100644 --- a/packages/void/test/unit/config.test.ts +++ b/packages/void/test/unit/config.test.ts @@ -260,6 +260,26 @@ describe('readConfig', () => { cleanup(); }); + it('accepts deploy.cloudflare.readinessAttempts', () => { + setup(JSON.stringify({ deploy: { cloudflare: { mode: 'staged', readinessAttempts: 24 } } })); + expect(readConfig(tmpDir).deploy?.cloudflare).toEqual({ + mode: 'staged', + readinessAttempts: 24, + }); + cleanup(); + }); + + it.each([0, -1, 1.5, '12', null])( + 'rejects invalid deploy.cloudflare.readinessAttempts: %j', + (readinessAttempts) => { + setup(JSON.stringify({ deploy: { cloudflare: { readinessAttempts } } })); + expect(() => readConfig(tmpDir)).toThrow( + '"deploy.cloudflare.readinessAttempts" in void.json must be a positive integer', + ); + cleanup(); + }, + ); + it.each([true, false])('accepts routing.isr: %s', (isr) => { setup(JSON.stringify({ routing: { isr } })); expect(readConfig(tmpDir).routing?.isr).toBe(isr); diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 6973985ed..b91532b31 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -194,4 +194,19 @@ describe('parseDeployArgs --preview', () => { '--json is available only with --preview', ); }); + + it('parses --readiness-attempts for Cloudflare deploys and validates positive integers', () => { + expect( + parseDeployArgs(['--platform', 'cloudflare', '--readiness-attempts', '25']).readinessAttempts, + ).toBe(25); + expect(() => parseDeployArgs(['--readiness-attempts', '5'])).toThrow( + '--readiness-attempts requires --platform cloudflare', + ); + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--readiness-attempts'])).toThrow( + '--readiness-attempts must be a positive integer', + ); + expect(() => + parseDeployArgs(['--platform', 'cloudflare', '--readiness-attempts', '0']), + ).toThrow('--readiness-attempts must be a positive integer'); + }); });