diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 82d7c3b40..d3a639907 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -121,6 +121,8 @@ export type CloudflareVersionActivation = diagnostic?: string; /** Wrangler reached Cloudflare's Containers entitlement endpoint and received a 403. */ containersUnavailable?: boolean; + /** The deployment stopped after upload and before activation. */ + beforeActivation?: true; versionId?: string; previousVersionId?: string | null; rollback?: 'not-needed' | 'succeeded' | 'failed' | 'unavailable' | 'unsafe'; @@ -167,6 +169,7 @@ type CurrentProductionVersion = kind: 'ok'; versionId: string | null; versions: ReadonlyArray; + deploymentId?: string; } | { kind: 'failed'; status: number } | { kind: 'split' }; @@ -877,7 +880,7 @@ export type CloudflareVersionActivationOptions = { fetch?: typeof globalThis.fetch; sleep?: (milliseconds: number) => Promise; /** - * Waits between reads of Cloudflare's Worker version list while it lags behind a write. + * Waits between reads while Cloudflare's Worker version list or staged deployment status lags. * Defaults to {@link STALE_VERSION_HISTORY_DELAYS_MS}. */ versionHistoryRetryDelaysMs?: ReadonlyArray; @@ -1557,7 +1560,7 @@ async function activateCloudflareVersionWithSecretsFile( : undefined; let readinessUrl = reportedPreviewUrl; let readinessUsesCustomRoute = false; - let stagedVersionOverride = false; + let stagedVersionOverride: Extract | undefined; if (!readinessUrl) { if ( !options.preserveTriggers && @@ -1582,16 +1585,16 @@ async function activateCloudflareVersionWithSecretsFile( if (fallbackSubdomain && fallbackSubdomain === options.readinessHeadersWorkersDevSubdomain) { authenticatedWorkersDevSubdomain = fallbackSubdomain; } - const stagingFailure = await stageCandidateForReadiness( + const staging = await stageCandidateForReadiness( options, previous.versionId, versionId, message, ); - if (stagingFailure) { - return stagingFailure; + if (!staging.ok) { + return staging; } - stagedVersionOverride = true; + stagedVersionOverride = staging; } else if ( desiredTriggerConfig.workers_dev || desiredTriggerConfig.routes.length > 0 || @@ -1653,19 +1656,19 @@ async function activateCloudflareVersionWithSecretsFile( ) : customRouteReadinessUrl(desiredTriggerConfig.routes); if (stableReadinessUrl && stableReadinessUrl !== readinessUrl) { - const stagingFailure = await stageCandidateForReadiness( + const staging = await stageCandidateForReadiness( options, previous.versionId, versionId, message, ); - if (stagingFailure) { - return stagingFailure; + if (!staging.ok) { + return staging; } readinessUrl = stableReadinessUrl; authenticatedWorkersDevSubdomain = extractWorkersDevSubdomain(stableReadinessUrl); readinessUsesCustomRoute = !desiredTriggerConfig.workers_dev; - stagedVersionOverride = true; + stagedVersionOverride = staging; ready = await probe(readinessUrl); } } @@ -1679,9 +1682,13 @@ async function activateCloudflareVersionWithSecretsFile( ? customRouteReadinessOriginField(readinessUrl) : {}), ...(stagedVersionOverride - ? await restorePreviousVersion(options, previous.versionId, 'readiness failed', [ - stagedVersionPercentages(previous.versionId, versionId), - ]) + ? await restorePreviousVersion( + options, + previous.versionId, + 'readiness failed', + [stagedVersionPercentages(previous.versionId, versionId)], + stagedVersionOverride.deploymentId, + ) : { rollback: 'not-needed' as const }), }; } @@ -1690,6 +1697,7 @@ async function activateCloudflareVersionWithSecretsFile( return { ok: false, reason: 'uploader-changed', + beforeActivation: true, versionId, previousVersionId: previous.versionId, ...(stagedVersionOverride @@ -1698,6 +1706,7 @@ async function activateCloudflareVersionWithSecretsFile( previous.versionId, 'uploader verification failed', [stagedVersionPercentages(previous.versionId, versionId)], + stagedVersionOverride.deploymentId, ) : { rollback: 'not-needed' as const }), }; @@ -1705,15 +1714,45 @@ async function activateCloudflareVersionWithSecretsFile( // Readiness can take long enough for another deploy or rollback to finish. Never flatten that // newer operation using the stale `previous` snapshot captured before this upload began. - const ownerBeforeActivation = await readCurrentProductionVersion(options); - if (ownerBeforeActivation.kind === 'failed') { - return { - ok: false, - reason: 'status-failed', - status: ownerBeforeActivation.status, - versionId, - previousVersionId: previous.versionId, - }; + const previousTraffic = previous.versionId + ? [{ versionId: previous.versionId, percentage: 100 }] + : []; + const stagedTraffic = stagedVersionOverride + ? stagedVersionPercentages(previous.versionId, versionId) + : undefined; + let ownerBeforeActivation = await readCurrentProductionVersion(options); + let laggingStagingStatus = false; + if (stagedVersionOverride?.previousDeploymentId) { + const { previousDeploymentId } = stagedVersionOverride; + const isLaggingStagingStatus = (owner: CurrentProductionVersion) => + owner.kind === 'ok' && + owner.deploymentId === previousDeploymentId && + productionVersionPercentagesEqual(owner.versions, previousTraffic); + const statusDelays = options.versionHistoryRetryDelaysMs ?? STALE_VERSION_HISTORY_DELAYS_MS; + for ( + let attempt = 0; + attempt < statusDelays.length && isLaggingStagingStatus(ownerBeforeActivation); + attempt++ + ) { + if (attempt === 0) { + options.onProgress?.( + "Waiting for Cloudflare's deployment status to show the staged version...", + ); + } + await (options.sleep ?? delay)(statusDelays[attempt]); + if (!options.verifyUploader()) { + return { + ok: false, + reason: 'uploader-changed', + beforeActivation: true, + versionId, + previousVersionId: previous.versionId, + rollback: 'unsafe', + }; + } + ownerBeforeActivation = await readCurrentProductionVersion(options); + } + laggingStagingStatus = isLaggingStagingStatus(ownerBeforeActivation); } if (ownerBeforeActivation.kind === 'split') { return { @@ -1723,26 +1762,45 @@ async function activateCloudflareVersionWithSecretsFile( previousVersionId: previous.versionId, }; } - const expectedTrafficBeforeActivation = stagedVersionOverride - ? stagedVersionPercentages(previous.versionId, versionId) - : previous.versionId - ? [{ versionId: previous.versionId, percentage: 100 }] - : []; if ( + ownerBeforeActivation.kind === 'failed' || ownerBeforeActivation.versionId !== previous.versionId || + (stagedVersionOverride !== undefined && + ownerBeforeActivation.deploymentId !== stagedVersionOverride.deploymentId) || !productionVersionPercentagesEqual( ownerBeforeActivation.versions, - expectedTrafficBeforeActivation, + stagedTraffic ?? previousTraffic, ) ) { + const failure = + ownerBeforeActivation.kind === 'failed' + ? { reason: 'status-failed' as const, status: ownerBeforeActivation.status } + : { reason: 'deployment-changed' as const }; + const restore = + stagedVersionOverride && + stagedTraffic?.length && + (ownerBeforeActivation.kind === 'failed' || laggingStagingStatus) + ? await restorePreviousVersion( + options, + previous.versionId, + 'pre-activation status check failed', + [stagedTraffic], + stagedVersionOverride.deploymentId, + ) + : ownerBeforeActivation.kind === 'ok' + ? { + activeVersionId: ownerBeforeActivation.versionId, + rollback: 'not-needed' as const, + ...(stagedTraffic === undefined ? { triggerRepair: 'succeeded' as const } : {}), + } + : {}; return { ok: false, - reason: 'deployment-changed', + ...failure, + beforeActivation: true, versionId, previousVersionId: previous.versionId, - activeVersionId: ownerBeforeActivation.versionId, - rollback: 'not-needed', - triggerRepair: 'succeeded', + ...restore, }; } @@ -2838,6 +2896,7 @@ async function readCurrentProductionVersion( kind: 'ok', versionId: active?.versionId ?? null, versions, + deploymentId: typeof deployment.id === 'string' ? deployment.id : undefined, }; } catch { return { kind: 'failed', status: result.status }; @@ -2871,13 +2930,17 @@ function stagedVersionPercentages( : []; } +type ReadinessStagingResult = + | { ok: true; previousDeploymentId: string | undefined; deploymentId: string } + | Extract; + /** Stage the candidate at 0% beside the unchanged previous version so readiness can select it. */ async function stageCandidateForReadiness( options: CloudflareVersionActivationOptions, previousVersionId: string | null, versionId: string, message: string, -): Promise | null> { +): Promise { if (!options.verifyUploader()) { return { ok: false, @@ -2887,9 +2950,9 @@ async function stageCandidateForReadiness( rollback: 'not-needed', }; } - const ownerFailure = await verifyReadinessStagingOwner(options, previousVersionId, versionId); - if (ownerFailure) { - return ownerFailure; + const owner = await verifyReadinessStagingOwner(options, previousVersionId, versionId); + if (!owner.ok) { + return owner; } const staged = await deployVersionPercentages( options, @@ -2909,7 +2972,19 @@ async function stageCandidateForReadiness( rollback: 'not-needed', }; } - return null; + const deploymentId = isRecord(staged.data) ? staged.data.id : undefined; + if (typeof deploymentId !== 'string' || !deploymentId.trim()) { + return { + ok: false, + reason: 'status-failed', + beforeActivation: true, + diagnostic: 'Cloudflare did not return the 0% staging deployment ID.', + versionId, + previousVersionId, + rollback: 'unsafe', + }; + } + return { ...owner, deploymentId }; } async function verifyReadinessStagingOwner( @@ -2919,7 +2994,10 @@ async function verifyReadinessStagingOwner( >, previousVersionId: string | null, versionId: string, -): Promise | null> { +): Promise< + | { ok: true; previousDeploymentId: string | undefined } + | Extract +> { const owner = await readCurrentProductionVersion(options); if (owner.kind === 'failed') { return { @@ -2954,7 +3032,7 @@ async function verifyReadinessStagingOwner( rollback: 'not-needed', }; } - return null; + return { ok: true, previousDeploymentId: owner.deploymentId }; } async function probeReadiness( @@ -3219,6 +3297,7 @@ async function restorePreviousVersion( previousVersionId: string | null, cause: string, expectedOwnedTraffic: ReadonlyArray>, + expectedDeploymentId?: string, ): Promise { if (!previousVersionId) { return { rollback: 'unavailable' }; @@ -3231,6 +3310,7 @@ async function restorePreviousVersion( return { owns: owner.kind === 'ok' && + (expectedDeploymentId === undefined || owner.deploymentId === expectedDeploymentId) && expectedOwnedTraffic.some((expected) => productionVersionPercentagesEqual(owner.versions, expected), ), diff --git a/packages/deploy-cloudflare/test/unit/operations.test.ts b/packages/deploy-cloudflare/test/unit/operations.test.ts index 6054e3672..fbf05a268 100644 --- a/packages/deploy-cloudflare/test/unit/operations.test.ts +++ b/packages/deploy-cloudflare/test/unit/operations.test.ts @@ -8,7 +8,6 @@ import { activateCloudflareVersion, encodeCloudflareVersionMessage } from '../.. const current = '11111111-1111-4111-8111-111111111111'; const next = '22222222-2222-4222-8222-222222222222'; -const other = '33333333-3333-4333-8333-333333333333'; function setup( data: unknown, @@ -19,6 +18,7 @@ function setup( const calls: Array = []; let uploaded = false; let triggerFailed = false; + let deployment = 0; let versions = [{ version_id: current, percentage: 100 }]; const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { calls.push(operation); @@ -30,7 +30,7 @@ function setup( }); switch (operation.type) { case 'deployments.status': - return ok({ versions }); + return ok({ id: String(deployment), versions }); case 'versions.list': return ok([ { @@ -63,7 +63,7 @@ function setup( return { ...ok(), status: 1, errorCode: 10_000 }; } if (rollback === 'deployed-elsewhere') { - versions = [{ version_id: other, percentage: 100 }]; + deployment++; } return { ...ok(), status: 1, errorCode: 10_220 }; } @@ -79,7 +79,7 @@ function setup( version_id: versionId, percentage, })); - return ok(); + return ok({ id: String(++deployment) }); case 'triggers.deploy': if (failure === 'triggers' && !triggerFailed) { triggerFailed = true; @@ -207,7 +207,7 @@ it.each(recoveries)( }, ); -it('does not force a restore after someone else deploys', async () => { +it('does not force a restore after another deployment reuses the staged split', async () => { const { result, rollbacks } = await recover(recoveries[0], 'deployed-elsewhere'); expect(result).toMatchObject({ ok: false, reason: 'readiness-failed', rollback: 'unsafe' }); expect(result).not.toHaveProperty('restoredOlderSecrets'); diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 9768717d6..d39e58b27 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -234,6 +234,7 @@ function runner(overrides?: { let triggerCalls = 0; let statusCalls = 0; let activeVersionId: string | null = CURRENT; + let deploymentId = 'initial-deployment'; let deploymentVersions: Array = [{ version_id: CURRENT, percentage: 100 }]; let uploaded = false; return operationFixture((args: Array) => { @@ -246,7 +247,7 @@ function runner(overrides?: { } return overrides.status; } - return ok(JSON.stringify({ versions: deploymentVersions })); + return ok(JSON.stringify({ id: deploymentId, versions: deploymentVersions })); } if (args[0] === 'versions' && args[1] === 'upload') { uploaded = true; @@ -262,12 +263,14 @@ function runner(overrides?: { const result = deployCalls === 1 ? (overrides?.activate ?? ok()) : (overrides?.rollback ?? ok()); if (result.status === 0) { + deploymentId = `deployment-${deployCalls}`; deploymentVersions = args.flatMap((argument) => { const matched = argument.match(/^([^@]+)@(\d+(?:\.\d+)?)$/); return matched ? [{ version_id: matched[1], percentage: Number(matched[2]) }] : []; }); activeVersionId = deploymentVersions.find((version) => version.percentage === 100)?.version_id ?? null; + return { ...result, data: result.data ?? { id: deploymentId } }; } return result; } @@ -3863,6 +3866,322 @@ describe('Cloudflare version activation', () => { ); }); + describe('staged deployment status', () => { + const status = (id: string | undefined, ...versions: Array) => ({ + ...ok(), + data: { id, versions }, + }); + const beforeUpload = status('before-upload', { version_id: CURRENT, percentage: 100 }); + const previous = status('before-staging', { version_id: CURRENT, percentage: 100 }); + const concurrent = status('concurrent', { version_id: CONCURRENT, percentage: 100 }); + const staging = [`${CURRENT}@100`, `${NEXT}@0`]; + + function stagedActivation(...statusReads: Array) { + const base = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); + let staged = false; + let readBeforeUpload = false; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'deployments') { + if (!staged) { + const read = readBeforeUpload ? previous : beforeUpload; + readBeforeUpload = true; + return read; + } + const read = statusReads.shift(); + if (read) { + return read; + } + } + staged ||= args.includes(`${NEXT}@0`); + return base(args); + }); + const sleep = vi.fn(async (_milliseconds: number) => {}); + return { + runWrangler, + sleep, + options: { + runWrangler, + verifyUploader: () => true, + workerName: 'my-worker', + workersDevSubdomain: 'example', + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + versionHistoryRetryDelaysMs: [17, 29], + sleep, + }, + }; + } + + it('skips staging cleanup when a failed status read is followed by a different deployment ID', async () => { + const { options, runWrangler } = stagedActivation( + { ...ok(), status: 1 }, + status( + 'other-staging', + { version_id: CURRENT, percentage: 100 }, + { version_id: NEXT, percentage: 0 }, + ), + ); + + const result = await activateCloudflareVersion(options); + + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(result).toMatchObject({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + rollback: 'unsafe', + }); + }); + + it('stops when the staging write does not report its deployment ID', async () => { + const { options, runWrangler } = stagedActivation(); + + const result = await activateCloudflareVersion({ + ...options, + runWrangler: (operation, command) => { + const result = runWrangler(operation, command); + return operation.type === 'versions.deploy' ? ok() : result; + }, + }); + + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(result).toMatchObject({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + diagnostic: 'Cloudflare did not return the 0% staging deployment ID.', + rollback: 'unsafe', + }); + }); + + it('waits for Cloudflare to show its 0% staging deployment before activating', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous); + + await expect(activateCloudflareVersion(options)).resolves.toMatchObject({ + ok: true, + versionId: NEXT, + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${NEXT}@100`]]); + }); + + it.each([ + ['a different active version', concurrent, CONCURRENT], + [ + 'a different staged version', + status( + 'concurrent', + { version_id: CURRENT, percentage: 100 }, + { version_id: CONCURRENT, percentage: 0 }, + ), + CURRENT, + ], + ] as const)( + 'stops at %s during the wait without another traffic write', + async (_kind, read, activeVersionId) => { + const { options, runWrangler, sleep } = stagedActivation(previous, read); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId, + rollback: 'not-needed', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + expect(runWrangler.mock.calls.some(([args]) => args[0] === 'triggers')).toBe(false); + }, + ); + + it.each([ + ['a different deployment ID', 'concurrent'], + ['no deployment ID', undefined], + ] as const)('stops at the same active version with %s during the wait', async (_kind, id) => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + status(id, { version_id: CURRENT, percentage: 100 }), + status( + 'staged', + { version_id: CURRENT, percentage: 100 }, + { version_id: NEXT, percentage: 0 }, + ), + ); + + await expect(activateCloudflareVersion(options)).resolves.toMatchObject({ + ok: false, + reason: 'deployment-changed', + activeVersionId: CURRENT, + rollback: 'not-needed', + }); + expect(sleep).not.toHaveBeenCalledWith(29); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + + it('clears its staging deployment if the status only catches up during the final ownership check', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous, previous, previous); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId: CURRENT, + rollback: 'succeeded', + }); + expect(sleep.mock.calls).toEqual([[17], [29]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${CURRENT}@100`]]); + }); + + it.each([ + ['another deployment', concurrent, CONCURRENT], + ['the pre-staging deployment', previous, CURRENT], + ] as const)( + 'leaves production alone when the final ownership check sees %s', + async (_kind, read, activeVersionId) => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + previous, + previous, + read, + ); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId, + rollback: 'unsafe', + }); + expect(sleep.mock.calls).toEqual([[17], [29]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + }, + ); + + it('clears its staging deployment after a failed read if the ownership check confirms it', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous, { ...ok(), status: 1 }); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + status: 1, + versionId: NEXT, + previousVersionId: CURRENT, + activeVersionId: CURRENT, + rollback: 'succeeded', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging, [`${CURRENT}@100`]]); + }); + + it('stops at a split during the wait without writing traffic', async () => { + const { options, runWrangler, sleep } = stagedActivation( + previous, + status( + 'concurrent', + { version_id: CURRENT, percentage: 50 }, + { version_id: CONCURRENT, percentage: 50 }, + ), + ); + + await expect(activateCloudflareVersion(options)).resolves.toEqual({ + ok: false, + reason: 'traffic-split-unsupported', + versionId: NEXT, + previousVersionId: CURRENT, + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + + it('does not read or write through an uploader that changes during the wait', async () => { + const { options, runWrangler, sleep } = stagedActivation(previous); + let trusted = true; + sleep.mockImplementation(async () => { + trusted = false; + }); + + await expect( + activateCloudflareVersion({ ...options, verifyUploader: () => trusted }), + ).resolves.toMatchObject({ + ok: false, + reason: 'uploader-changed', + beforeActivation: true, + rollback: 'unsafe', + }); + expect(sleep.mock.calls).toEqual([[17]]); + expect(runWrangler.mock.invocationCallOrder.at(-1)).toBeLessThan( + sleep.mock.invocationCallOrder[0], + ); + expect(deployRequests(runWrangler)).toEqual([staging]); + }); + }); + + it.each([ + [ + 'adds beforeActivation when the final status read fails', + { ...ok(), status: 7 }, + { reason: 'status-failed', status: 7, beforeActivation: true }, + ], + [ + 'adds beforeActivation when the final status read reports a different deployment', + ok(JSON.stringify({ versions: [{ version_id: CONCURRENT, percentage: 100 }] })), + { + reason: 'deployment-changed', + activeVersionId: CONCURRENT, + rollback: 'not-needed', + triggerRepair: 'succeeded', + beforeActivation: true, + }, + ], + [ + 'reports the traffic split from the final status read', + ok( + JSON.stringify({ + versions: [ + { version_id: CURRENT, percentage: 50 }, + { version_id: CONCURRENT, percentage: 50 }, + ], + }), + ), + { reason: 'traffic-split-unsupported' }, + ], + ] as const)( + '%s after readiness succeeds on the path without a staging deployment', + async (_title, read, expected) => { + const base = runner(); + let statusReads = 0; + const runWrangler = operationFixture((args: Array) => { + if (args[0] === 'deployments' && ++statusReads === 2) { + return read; + } + return base(args); + }); + + await expect( + activateCloudflareVersion({ + runWrangler, + verifyUploader: () => true, + workerName: 'my-worker', + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + }), + ).resolves.toEqual({ + ok: false, + versionId: NEXT, + previousVersionId: CURRENT, + ...expected, + }); + expect(deployRequests(runWrangler)).toEqual([]); + }, + ); + it('does not stage over a production owner that changed after upload', async () => { let statusCalls = 0; const runWrangler = operationFixture(async (args: Array) => { @@ -3968,10 +4287,11 @@ describe('Cloudflare version activation', () => { it('does not restore failed readiness staging over a concurrent candidate', async () => { let deploymentVersions = [{ version_id: CURRENT, percentage: 100 }]; + let deploymentId = 'initial'; let deployCalls = 0; const runWrangler = operationFixture(async (args: Array) => { if (args[0] === 'deployments') { - return ok(JSON.stringify({ versions: deploymentVersions })); + return ok(JSON.stringify({ id: deploymentId, versions: deploymentVersions })); } if (args[0] === 'versions' && args[1] === 'list') { return ok(JSON.stringify([{ id: CURRENT, annotations: {} }])); @@ -3981,11 +4301,12 @@ describe('Cloudflare version activation', () => { } if (args[0] === 'versions' && args[1] === 'deploy') { deployCalls++; + deploymentId = 'staged'; deploymentVersions = [ { version_id: CURRENT, percentage: 100 }, { version_id: NEXT, percentage: 0 }, ]; - return ok(); + return { ...ok(), data: { id: deploymentId } }; } throw new Error(`Unexpected command: ${args.join(' ')}`); }); @@ -3998,6 +4319,7 @@ describe('Cloudflare version activation', () => { workersDevSubdomain: 'developer-platform-experience', message: encodeCloudflareVersionMessage([]), fetch: async () => { + deploymentId = 'concurrent'; deploymentVersions = [ { version_id: CURRENT, percentage: 100 }, { version_id: CONCURRENT, percentage: 0 }, diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 74188d610..a16253acd 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -553,6 +553,19 @@ export function formatCloudflareActivationError( : message; } +function formatStagingCleanup(result: Exclude): string { + switch (result.rollback) { + case 'succeeded': + return ' Void redeployed the previous version at 100% of traffic.'; + case 'failed': + return ' Void tried to redeploy the previous version at 100% of traffic, but Cloudflare did not confirm it.'; + case 'unsafe': + return " Void left the current deployment unchanged because it could not confirm it is Void's 0% staging deployment."; + default: + return ''; + } +} + function formatCloudflareActivationFailure( result: Exclude, ): string { @@ -562,6 +575,7 @@ function formatCloudflareActivationFailure( ? '' : ` Cloudflare error code: ${String(result.cloudflareErrorCode)}.`; const diagnostic = result.diagnostic ? `\n\n${result.diagnostic}` : ''; + const stagingCleanup = result.beforeActivation ? formatStagingCleanup(result) : ''; switch (result.reason) { case 'uploader-changed': if (result.rollback === 'succeeded') { @@ -574,18 +588,23 @@ function formatCloudflareActivationFailure( return 'deploy: the verified Wrangler uploader changed after version activation, and automatic traffic restoration failed. Inspect `void project status` immediately.'; } if (result.rollback === 'unsafe') { - return 'deploy: the verified Wrangler uploader changed after version activation. Void did not invoke the changed binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.'; + return result.beforeActivation + ? 'deploy: the verified Wrangler uploader changed before version activation. Void did not invoke the changed binary to remove its 0% staging deployment; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.' + : 'deploy: the verified Wrangler uploader changed after version activation. Void did not invoke the changed binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.'; } return 'deploy: the verified Wrangler uploader changed before version activation.'; case 'status-failed': if (result.versionId) { - if (result.rollback === 'not-needed') { - return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}. Inspect \`void project status\` before retrying.`; + if (result.beforeActivation || result.rollback === 'not-needed') { + return `deploy: Worker version ${result.versionId} was uploaded, but Cloudflare deployment status could not be verified before activation${status}.${stagingCleanup} Inspect \`void project status\` before retrying.${diagnostic}`; } return `deploy: Worker version ${result.versionId} was published, but current deployment status could not be verified${status}. Inspect \`void project status\` before retrying.`; } return `deploy: could not snapshot the current Cloudflare deployment${status}; no version was uploaded.`; case 'deployment-changed': + if (result.beforeActivation) { + return `deploy: Cloudflare deployment status did not show the expected deployment before activation.${stagingCleanup} Inspect \`void project status\` before retrying.`; + } return result.triggerRepair === 'succeeded' ? `deploy: another Cloudflare operation superseded this deployment. Void restored triggers for the active version ${result.activeVersionId ?? '(unknown)'}; retry from fresh deployment status.` : `deploy: another Cloudflare operation superseded this deployment, but its trigger state could not be verified. Inspect the active Worker version ${result.activeVersionId ?? '(unknown)'} immediately.`; @@ -612,7 +631,9 @@ function formatCloudflareActivationFailure( return [ 'deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.', 'Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout', - 'in Cloudflare, then retry; no version was uploaded.', + result.versionId + ? `in Cloudflare, then retry. Void uploaded Worker version ${result.versionId} and stopped before activating it.` + : 'in Cloudflare, then retry; no version was uploaded.', ].join('\n'); case 'upload-failed': return `deploy: Cloudflare Worker Version upload failed${status}; production traffic is unchanged.${cloudflareCode}${diagnostic}`; @@ -839,7 +860,10 @@ function formatCloudflareReadinessRestoration( case 'failed': return 'Automatic traffic restoration failed; inspect `void project status` immediately.'; case 'unsafe': - return 'Void did not invoke the changed Wrangler binary to restore traffic; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.'; + // Uploader verification stops cleanup before a status read, so activeVersionId is absent. + return result.activeVersionId === undefined + ? 'Void skipped staging cleanup because the verified Wrangler uploader changed. Inspect `void project status` and reinstall Wrangler from a trusted lockfile before retrying.' + : `${formatStagingCleanup(result).trim()} Inspect \`void project status\` before retrying.`; case 'unavailable': return 'No previous version was available to restore; inspect `void project status` immediately.'; default: diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index f43acc50f..bc42a84af 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -31,6 +31,7 @@ import { operationFixtureRequest, } from '../../../deploy-cloudflare/test/operation-fixture.ts'; import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts'; +import { createCfVersionRunner } from '../../src/cli/cf-version-runner.ts'; import { readCloudflareLink } from '../../src/cli/cloudflare-link.ts'; import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-validation.ts'; import { @@ -198,6 +199,63 @@ const cleanExit: DeployWranglerRunResult = { error: null, }; +it('does not change traffic when another Cloudflare deployment has the staged split', async () => { + const root = makeProject({ + 'wrangler.json': JSON.stringify({ name: 'site', workers_dev: true }), + }); + const live = '11111111-1111-4111-8111-111111111111'; + const candidate = '22222222-2222-4222-8222-222222222222'; + const stagedTraffic = [ + { version_id: live, percentage: 100 }, + { version_id: candidate, percentage: 0 }, + ]; + const writes: Array> = []; + const runWrangler = createCfVersionRunner({ + output: { directory: root, dispose: async () => {} }, + workerName: 'site', + verifyResources: async () => cleanExit, + runCf: (args) => { + const command = args.slice(1, 3).join(' '); + if (command === 'deployments list') { + return { + ...cleanExit, + stdout: JSON.stringify({ + deployments: [ + { + id: writes.length ? 'other-deployment' : 'live-deployment', + versions: writes.at(-1) ?? [{ version_id: live, percentage: 100 }], + }, + ], + }), + }; + } + if (command === 'versions create') { + return { ...cleanExit, stdout: JSON.stringify({ versionId: candidate }) }; + } + if (command === 'deployments create') { + const versions = JSON.parse(args[args.indexOf('--versions') + 1]) as typeof stagedTraffic; + writes.push(versions); + return { ...cleanExit, stdout: JSON.stringify({ id: 'void-staging', versions }) }; + } + throw new Error(`Unexpected cf command: ${command}`); + }, + }); + + const result = await activateCloudflareVersionPrimitive({ + runWrangler, + configPath: join(root, 'wrangler.json'), + workerName: 'site', + workersDevSubdomain: 'example', + preserveTriggers: true, + message: 'Staged deployment', + verifyUploader: () => true, + fetch: async () => Response.json({ ready: true }), + }); + + expect(writes).toEqual([stagedTraffic]); + expect(result).toMatchObject({ ok: false, reason: 'deployment-changed', beforeActivation: true }); +}); + // Most native deploy failures leave through exit(1), which skips the deploy_end that runDeploy // writes on a throw. These tests read the JSONL file back from a temp home folder. describe('Cloudflare deploy log end record', () => { @@ -517,6 +575,88 @@ describe('Cloudflare activation diagnostics', () => { }, ); + it.each([ + ['succeeded', ' Void redeployed the previous version at 100% of traffic.'], + [ + 'failed', + ' Void tried to redeploy the previous version at 100% of traffic, but Cloudflare did not confirm it.', + ], + ['not-needed', ''], + ] as const)('reports staging cleanup outcome %s', (rollback, details) => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + rollback, + }); + expect(message).toBe( + `deploy: Cloudflare deployment status did not show the expected deployment before activation.${details} Inspect \`void project status\` before retrying.`, + ); + }); + + it('reports an uploader change before activation when staging cleanup is unsafe', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'uploader-changed', + beforeActivation: true, + rollback: 'unsafe', + }); + expect(message).toBe( + 'deploy: the verified Wrangler uploader changed before version activation. Void did not invoke the changed binary to remove its 0% staging deployment; reinstall Wrangler from a trusted lockfile and inspect `void project status` immediately.', + ); + }); + + it('reports that the current deployment is unchanged when staging ownership is unconfirmed', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'deployment-changed', + beforeActivation: true, + activeVersionId: 'another-version', + rollback: 'unsafe', + }); + expect(message).toBe( + "deploy: Cloudflare deployment status did not show the expected deployment before activation. Void left the current deployment unchanged because it could not confirm it is Void's 0% staging deployment. Inspect `void project status` before retrying.", + ); + }); + + it('reports the uploaded version when the final deployment status read fails', () => { + const versionId = '22222222-2222-4222-8222-222222222222'; + const message = formatCloudflareActivationError({ + ok: false, + reason: 'status-failed', + beforeActivation: true, + versionId, + rollback: 'succeeded', + }); + expect(message).toBe( + `deploy: Worker version ${versionId} was uploaded, but Cloudflare deployment status could not be verified before activation. Void redeployed the previous version at 100% of traffic. Inspect \`void project status\` before retrying.`, + ); + }); + + it.each([ + [ + '22222222-2222-4222-8222-222222222222', + 'in Cloudflare, then retry. Void uploaded Worker version 22222222-2222-4222-8222-222222222222 and stopped before activating it.', + ], + [undefined, 'in Cloudflare, then retry; no version was uploaded.'], + ] as const)( + 'describes the upload state when the deployment status shows a traffic split (%s)', + (versionId, lastLine) => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'traffic-split-unsupported', + versionId, + }); + expect(message).toBe( + [ + 'deploy: the current Cloudflare deployment splits traffic across multiple Worker Versions.', + 'Void will not flatten an existing gradual rollout to 100%. Finish or cancel that rollout', + lastLine, + ].join('\n'), + ); + }, + ); + it('does not suggest an account subdomain when workers.dev is off', () => { const versionId = '22222222-2222-4222-8222-222222222222'; for (const reason of [ @@ -702,8 +842,21 @@ describe('Cloudflare activation diagnostics', () => { ok: false, reason: 'readiness-failed', rollback: 'unsafe', + activeVersionId: null, }), - ).toContain('did not invoke the changed Wrangler binary'); + ).toContain( + "could not confirm it is Void's 0% staging deployment. Inspect `void project status` before retrying.", + ); + }); + + it('recommends reinstalling Wrangler when uploader verification blocks readiness cleanup', () => { + const message = formatCloudflareActivationError({ + ok: false, + reason: 'readiness-failed', + rollback: 'unsafe', + }); + expect(message).toContain('the verified Wrangler uploader changed'); + expect(message).toContain('reinstall Wrangler from a trusted lockfile'); }); it.each(['readiness-failed', 'uploader-changed'] as const)(