diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 5146252b6..2e2b7f391 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -202,6 +202,20 @@ void project rollback [version] Void restores recorded triggers along with the code. Versions without a complete trigger snapshot keep current routes and schedules. Database recovery is separate: use [`void db restore`](../reference/cli/database.md#void-db-restore) to undo D1 migrations. +#### Clear a deployment with a candidate at 0% + +A failed deploy can leave the live version at 100% and a candidate at 0%. + +1. Pause other deploys and let any in progress finish. In the Cloudflare dashboard, select the account and Worker named in the error, then open **Deployments**. +2. Confirm **Active Deployment** still shows the exact versions and percentages Void reported. Continue only if the 0% version is unused, including by version overrides. +3. Select **Rollback** on the live version. [Cloudflare's split deployment rollback guide](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/#rolling-back-from-a-split-deployment) + +Retry when **Active Deployment** lists only the live version. If Void still reports the pair, wait and retry. + +Cloudflare can reject a rollback after a secret change (error `10220`). + +A newer inactive upload can still block a first link or a static deploy that inherits secrets after rollback. If Void reports a version-history or secret inheritance error, inspect the active and latest Worker versions in Cloudflare before retrying. + #### Scope and limitations Void deploys native apps, static sites, SPAs, supported SSGs, and Cloudflare builds from TanStack Start, React Router, SvelteKit, Nuxt, Analog, and Astro. The vinext adapters are experimental. diff --git a/packages/deploy-cloudflare/src/existing.ts b/packages/deploy-cloudflare/src/existing.ts index dae411a10..202d3fa41 100644 --- a/packages/deploy-cloudflare/src/existing.ts +++ b/packages/deploy-cloudflare/src/existing.ts @@ -9,6 +9,7 @@ import { isVoidSecretOnlyDraft, isWranglerSecretOnlyDraft, } from './secret-draft.ts'; +import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; export type ExistingCloudflareWorker = { versionId: string; @@ -24,6 +25,7 @@ type ExistingCloudflareWorkerOptions = { runWrangler: CloudflareCommandRunner; configPath: string; workerName: string; + accountId?: string; versionId?: string; }; @@ -97,7 +99,8 @@ async function readCloudflareWorker( typeof versions[0].version_id !== 'string' ) { throw new Error( - 'The existing Worker must have one deployed version receiving all traffic. Finish any gradual rollout before linking.', + cloudflareStagingPairGuidance(deployment, options)?.diagnostic ?? + 'The existing Worker must have one deployed version receiving all traffic. Finish any gradual rollout before linking.', ); } const versionId = versions[0].version_id; @@ -135,7 +138,8 @@ async function readCloudflareWorker( : await read({ type: 'deployments.status', ...target }); if (after === null || !isDeepStrictEqual(deployment.versions, after.versions)) { throw new Error( - 'Cloudflare production changed while linking. Retry from the current deployment.', + cloudflareStagingPairGuidance(after, options)?.diagnostic ?? + 'Cloudflare production changed while linking. Retry from the current deployment.', ); } return { diff --git a/packages/deploy-cloudflare/src/staging-guidance.ts b/packages/deploy-cloudflare/src/staging-guidance.ts new file mode 100644 index 000000000..3b42460fa --- /dev/null +++ b/packages/deploy-cloudflare/src/staging-guidance.ts @@ -0,0 +1,23 @@ +import { isRecord } from '@void/deploy-core'; +import { readConfigEntryString } from './config.ts'; + +export function cloudflareStagingPairGuidance( + deployment: Record | null | undefined, + { accountId, workerName }: { accountId?: string; workerName: string }, +): { diagnostic: string } | undefined { + const versions = deployment?.versions; + const entries: Array = Array.isArray(versions) && versions.length === 2 ? versions : []; + const liveEntry = entries.find((entry) => isRecord(entry) && entry.percentage === 100); + const candidateEntry = entries.find((entry) => isRecord(entry) && entry.percentage === 0); + const id = readConfigEntryString(deployment, 'id'); + const live = readConfigEntryString(liveEntry, 'version_id')?.trim(); + const candidate = readConfigEntryString(candidateEntry, 'version_id')?.trim(); + if (accountId && id?.trim() && live && candidate && live !== candidate) { + return { + diagnostic: `Cloudflare Worker "${workerName}" in account ${accountId} has ${live} at 100% and ${candidate} at 0%. A failed deploy can leave this pair. +Pause other deploys and let any in progress finish. Open this Worker's Deployments tab in the Cloudflare dashboard. +If Active Deployment still shows this exact pair and the 0% version is unused, including by version overrides, roll back to the live version. Retry once it's the only version listed. If Void still reports the pair, wait and retry. +https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/#rolling-back-from-a-split-deployment`, + }; + } +} diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 82d7c3b40..b71670a22 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -22,6 +22,7 @@ import { VOID_SECRET_DRAFT_MESSAGE, VOID_SECRET_DRAFT_SOURCE, } from './secret-draft.ts'; +import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; const DURABLE_MIGRATION_VERSION_ERROR = 10_211; const CLOUDFLARE_SECRET_CHANGED_ERROR = 10_220; @@ -117,7 +118,6 @@ export type CloudflareVersionActivation = | 'triggers-failed'; status?: number; cloudflareErrorCode?: number; - /** Bounded uploader error text with terminal escapes removed and common credential formats redacted. */ diagnostic?: string; /** Wrangler reached Cloudflare's Containers entitlement endpoint and received a 403. */ containersUnavailable?: boolean; @@ -822,6 +822,7 @@ function isCandidatePreviewUrl( } export type CloudflareVersionActivationOptions = { + accountId?: string; /** Human-readable deployment phases; the caller owns terminal rendering. */ onProgress?: (message: string) => void; /** Reuse an inspected Worker without republishing its domains or other triggers. */ @@ -1040,6 +1041,7 @@ async function activateCloudflareVersionWithSecretsFile( reason: 'deployment-changed', activeVersionId: owner.kind === 'ok' ? owner.versionId : null, rollback: 'not-needed', + ...cloudflareStagingPairGuidance(owner.deployment, options), }; } } @@ -1334,6 +1336,7 @@ async function activateCloudflareVersionWithSecretsFile( reason: 'deployment-changed', activeVersionId: owner.kind === 'ok' ? owner.versionId : null, rollback: 'not-needed', + ...cloudflareStagingPairGuidance(owner.deployment, options), }; } } @@ -1505,6 +1508,7 @@ async function activateCloudflareVersionWithSecretsFile( activeVersionId: ownerAfterWait.kind === 'ok' ? ownerAfterWait.versionId : null, rollback: 'not-needed', triggerRepair: 'succeeded', + ...cloudflareStagingPairGuidance(ownerAfterWait.deployment, options), }; } } @@ -1743,6 +1747,7 @@ async function activateCloudflareVersionWithSecretsFile( activeVersionId: ownerBeforeActivation.versionId, rollback: 'not-needed', triggerRepair: 'succeeded', + ...cloudflareStagingPairGuidance(ownerBeforeActivation.deployment, options), }; } @@ -2370,6 +2375,7 @@ async function bootstrapFirstDeployment( reason: 'deployment-changed', activeVersionId: current.kind === 'ok' ? current.versionId : null, rollback: 'not-needed', + ...cloudflareStagingPairGuidance(current.deployment, options), }; } } @@ -2788,7 +2794,7 @@ async function readCurrentProductionVersion( Parameters[0], 'configPath' | 'runWrangler' | 'workerName' >, -): Promise { +): Promise }> { const result = await options.runWrangler( { type: 'deployments.status', configPath: options.configPath, workerName: options.workerName }, { capture: true }, @@ -2838,6 +2844,7 @@ async function readCurrentProductionVersion( kind: 'ok', versionId: active?.versionId ?? null, versions, + deployment, }; } catch { return { kind: 'failed', status: result.status }; @@ -2915,7 +2922,7 @@ async function stageCandidateForReadiness( async function verifyReadinessStagingOwner( options: Pick< Parameters[0], - 'configPath' | 'runWrangler' | 'workerName' + 'accountId' | 'configPath' | 'runWrangler' | 'workerName' >, previousVersionId: string | null, versionId: string, @@ -2952,6 +2959,7 @@ async function verifyReadinessStagingOwner( previousVersionId, activeVersionId: owner.versionId, rollback: 'not-needed', + ...cloudflareStagingPairGuidance(owner.deployment, options), }; } return null; diff --git a/packages/deploy-cloudflare/test/unit/existing.test.ts b/packages/deploy-cloudflare/test/unit/existing.test.ts index d05924bdb..9e635af28 100644 --- a/packages/deploy-cloudflare/test/unit/existing.test.ts +++ b/packages/deploy-cloudflare/test/unit/existing.test.ts @@ -386,6 +386,94 @@ describe('existing Worker preservation', () => { expect(runWrangler.mock.calls[1][0]).toContain('original'); }); + describe('staging-pair guidance', () => { + const live = { version_id: 'original', percentage: 100 }; + const candidate = { version_id: 'staged', percentage: 0 }; + const pair = { id: 'deployment', versions: [candidate, live] }; + + function inspect(...deployments: Array) { + const runWrangler = operationFixture((args: Array) => ({ + status: 0, + stderr: '', + stdout: JSON.stringify( + args[0] === 'deployments' + ? deployments.shift() + : { + id: 'original', + resources: { + bindings: worker.bindings, + script: worker.script, + script_runtime: worker.runtime, + }, + }, + ), + })); + return readExistingCloudflareWorker({ + runWrangler, + accountId: 'test-account', + workerName: 'site', + configPath: '/app/wrangler.jsonc', + }); + } + + it('explains the staging pair on the first Worker status read', async () => { + await expect(inspect(pair)).rejects.toThrow( + 'Cloudflare Worker "site" in account test-account has original at 100% and staged at 0%', + ); + }); + + it('trims both IDs in the staging-pair guidance', async () => { + const padded = { + ...pair, + versions: [ + { ...live, version_id: ' original ' }, + { ...candidate, version_id: ' staged ' }, + ], + }; + await expect(inspect(padded)).rejects.toThrow( + 'Cloudflare Worker "site" in account test-account has original at 100% and staged at 0%', + ); + }); + + it('explains the staging pair when it appears during Worker inspection', async () => { + await expect(inspect({ versions: [live] }, pair)).rejects.toThrow( + 'Cloudflare Worker "site" in account test-account has original at 100% and staged at 0%', + ); + }); + + it.each([ + { + name: 'gradual rollout', + ...pair, + versions: [ + { ...live, percentage: 90 }, + { ...candidate, percentage: 10 }, + ], + }, + { name: 'missing deployment ID', versions: [live, candidate] }, + { + name: 'extra version', + ...pair, + versions: [live, candidate, { ...candidate, version_id: 'extra' }], + }, + { + name: 'duplicate version', + ...pair, + versions: [live, { ...candidate, version_id: live.version_id }], + }, + { + name: 'version IDs that match after trimming', + ...pair, + versions: [live, { ...candidate, version_id: ' original ' }], + }, + { name: 'string percentage', ...pair, versions: [live, { ...candidate, percentage: '0' }] }, + ])('keeps the generic refusal for $name', async ({ name: _name, ...deployment }) => { + await expect(inspect(deployment)).rejects.toThrow( + 'The existing Worker must have one deployed version receiving all traffic.', + ); + }); + }); + it('does not infer an active migration tag from an explicitly requested candidate', async () => { const runWrangler = operationFixture( (_args: Array, _options: { capture: boolean }) => ({ diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 9768717d6..50966c92e 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -25,6 +25,14 @@ import { apiSecretDraftVersion, voidSecretDraftVersion } from '../secret-draft-f const CURRENT = '11111111-1111-4111-8111-111111111111'; const NEXT = '22222222-2222-4222-8222-222222222222'; const CONCURRENT = '33333333-3333-4333-8333-333333333333'; +const STAGING_PAIR = { + id: 'staging-deployment', + versions: [ + { version_id: CURRENT, percentage: 100 }, + { version_id: CONCURRENT, percentage: 0 }, + ], +}; +const STAGING_GUIDANCE = 'Active Deployment still shows this exact pair'; function triggersWith(overrides: Partial = {}): CloudflareTriggerConfig { return { @@ -78,7 +86,7 @@ function sdkDraftActivation( async (operation: CloudflareOperation): Promise => { operations.push(operation); if (operation.type === 'deployments.status') { - return { ...ok(), data: { versions: traffic } }; + return { ...ok(), data: { id: 'production-deployment', versions: traffic } }; } if (operation.type === 'versions.list') { return { @@ -561,7 +569,10 @@ describe('Cloudflare version activation', () => { entered.resolve(); return release.promise; }); - const activation = activateCloudflareVersion(fixture.options); + const activation = activateCloudflareVersion({ + ...fixture.options, + accountId: 'test-account', + }); await entered.promise; fixture.changeOwner( kind === 'replacement' @@ -572,11 +583,15 @@ describe('Cloudflare version activation', () => { ], ); release.resolve(true); - expect(await activation).toMatchObject({ + const result = await activation; + expect(result).toMatchObject({ ok: false, reason: 'deployment-changed', rollback: 'not-needed', }); + if (kind === 'companion') { + expect(result).toHaveProperty('diagnostic', expect.stringContaining(STAGING_GUIDANCE)); + } expect(fixture.events).not.toContain('upload'); expect(fixture.events).not.toContain('publish'); expect(fixture.fetcher).not.toHaveBeenCalled(); @@ -1166,6 +1181,39 @@ describe('Cloudflare version activation', () => { runWrangler.mock.calls.some(([args]) => args[0] === 'versions' && args[1] === 'deploy'), ).toBe(false); }); + + it.each(['atomic publication', 'readiness staging', 'activation'] as const)( + 'explains the staging pair before %s', + async (gate) => { + const base = runner( + gate === 'readiness staging' ? { upload: ok(`Worker Version ID: ${NEXT}`) } : {}, + ); + let statuses = 0; + const runWrangler = operationFixture((args: Array) => + args[0] === 'deployments' && ++statuses === 2 + ? ok(JSON.stringify(STAGING_PAIR)) + : base(args), + ); + const result = await activateCloudflareVersion({ + runWrangler, + accountId: 'test-account', + workerName: 'my-worker', + verifyUploader: () => true, + atomic: gate === 'atomic publication', + workersDevSubdomain: 'example', + message: encodeCloudflareVersionMessage([]), + fetch: async () => Response.json({ ready: true }), + }); + expect(result).toMatchObject({ + ok: false, + reason: 'deployment-changed', + diagnostic: expect.stringContaining(STAGING_GUIDANCE), + }); + expect(deployRequests(runWrangler)).toEqual([]); + expect(runWrangler.mock.calls.some(([args]) => args[0] === 'deploy')).toBe(false); + }, + ); + it('pins active secrets for atomic publication when the active version is the latest', async () => { const base = runner({ bootstrap: ok(`Worker Version ID: ${NEXT}\nhttps://my-worker.example.workers.dev`), @@ -1761,19 +1809,30 @@ describe('Cloudflare version activation', () => { expect(candidateIds).toEqual([NEXT, CONCURRENT]); }); - it.each([{ phase: 'before' }, { phase: 'after' }] as const)( - 'stops without saving a candidate when a rollback lands during the version list wait ($phase upload)', - async ({ phase }) => { + it.each([ + { phase: 'before', change: 'rollback' }, + { phase: 'after', change: 'rollback' }, + { phase: 'before', change: 'staging pair' }, + { phase: 'after', change: 'staging pair' }, + ] as const)( + 'stops without saving a candidate when a $change appears during the version list wait ($phase upload)', + async ({ phase, change }) => { const base = runner(); let uploaded = false; - let rolledBack = false; + let ownerChanged = false; let reads = 0; const runWrangler = operationFixture((args: Array) => { if (args[0] === 'versions' && args[1] === 'upload') { uploaded = true; } - if (args[0] === 'deployments' && rolledBack) { - return ok(JSON.stringify({ versions: [{ version_id: CONCURRENT, percentage: 100 }] })); + if (args[0] === 'deployments' && ownerChanged) { + return ok( + JSON.stringify( + change === 'staging pair' + ? STAGING_PAIR + : { versions: [{ version_id: CONCURRENT, percentage: 100 }] }, + ), + ); } if (args[0] === 'versions' && args[1] === 'list' && uploaded === (phase === 'after')) { reads++; @@ -1793,13 +1852,13 @@ describe('Cloudflare version activation', () => { return base(args); }); const sleep = vi.fn(async (_milliseconds: number) => { - // Someone rolls production back to CONCURRENT while this deploy waits. - rolledBack = true; + ownerChanged = true; }); const recordVerifiedCandidate = vi.fn(); const fetch = vi.fn(async () => Response.json({ ready: true })); const result = await activateCloudflareVersion({ runWrangler, + accountId: 'test-account', workerName: 'my-worker', verifyUploader: () => true, verifyInheritedSecrets: true, @@ -1812,11 +1871,14 @@ describe('Cloudflare version activation', () => { expect(result).toMatchObject({ ok: false, reason: 'deployment-changed', - activeVersionId: CONCURRENT, + activeVersionId: change === 'staging pair' ? CURRENT : CONCURRENT, rollback: 'not-needed', }); + if (change === 'staging pair') { + expect(result).toHaveProperty('diagnostic', expect.stringContaining(STAGING_GUIDANCE)); + } expect(sleep.mock.calls).toEqual([[10]]); - // A receipt naming CURRENT as the parent would break the next deploy from CONCURRENT. + // The deployment must match the starting snapshot before Void records the candidate. expect(recordVerifiedCandidate).not.toHaveBeenCalled(); expect(runWrangler.mock.calls.some(([args]) => args[1] === 'upload')).toBe(phase === 'after'); expect(fetch).not.toHaveBeenCalled(); @@ -3817,13 +3879,17 @@ describe('Cloudflare version activation', () => { ).toBe(false); }); - it('probes a zero-percent Durable Object version through a production workers.dev URL', async () => { - const runWrangler = runner({ upload: ok(`Worker Version ID: ${NEXT}`) }); + it('probes and publishes a Durable Object candidate when only the first status read shows the split', async () => { + const runWrangler = runner({ + status: ok(JSON.stringify(STAGING_PAIR)), + upload: ok(`Worker Version ID: ${NEXT}`), + }); const fetcher = vi.fn(async () => Response.json({ ready: true })); await expect( activateCloudflareVersion({ runWrangler, + accountId: 'test-account', verifyUploader: () => true, workerName: 'my-worker', workersDevSubdomain: 'developer-platform-experience', diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index cf8220a92..aefd9ed97 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -8,7 +8,7 @@ import { parseDeployArgs } from './args.ts'; import { authSubcommands, parseAuthArgs } from './auth-args.ts'; import { buildSubcommands, parseBuildArgs } from './build-args.ts'; import { cloudflareSubcommands, parseCloudflareArgs } from './cloudflare-args.ts'; -import { formatCloudflareUserMessage } from './cloudflare-user-output.ts'; +import { formatCloudflareUserMessage, logCloudflareUserError } from './cloudflare-user-output.ts'; import { parseConnectArgs } from './connect-args.ts'; import { dbSubcommands, parseDbArgs } from './db-args.ts'; import { domainSubcommands, parseDomainArgs } from './domain-args.ts'; @@ -241,7 +241,7 @@ if (helpPath) { const { runDeploy } = await import('./deploy.ts'); await runDeploy(root, deployArgs).catch((err: unknown) => { - log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); + logCloudflareUserError(err instanceof Error ? err.message : String(err)); process.exit(1); }); } else if (command === 'connect') { diff --git a/packages/void/src/cli/cloudflare-link.ts b/packages/void/src/cli/cloudflare-link.ts index 3c609c589..dc98fb754 100644 --- a/packages/void/src/cli/cloudflare-link.ts +++ b/packages/void/src/cli/cloudflare-link.ts @@ -160,6 +160,7 @@ export async function prepareExistingCloudflareDeploy(options: { runWrangler: options.runWrangler, configPath: options.configPath, workerName: config.name, + accountId: options.accountId, }); const patch: LinkedWorkerPatch = { account_id: options.accountId, keep_vars: true }; // Native deploys may add version metadata only to their generated artifact. diff --git a/packages/void/src/cli/cloudflare-user-output.ts b/packages/void/src/cli/cloudflare-user-output.ts index 5bfb515da..4f907a847 100644 --- a/packages/void/src/cli/cloudflare-user-output.ts +++ b/packages/void/src/cli/cloudflare-user-output.ts @@ -1,3 +1,9 @@ +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { formatUrl, printNextStep } from './output.ts'; + +const ROLLBACK_GUIDE = + 'https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/#rolling-back-from-a-split-deployment'; + /** * Keep Void's public CLI vocabulary at the product level while preserving real * Cloudflare config filenames and environment variables that users may need to @@ -12,6 +18,7 @@ export function formatCloudflareUserMessage(message: string): string { }; let result = message + .replaceAll(/Cloudflare Worker "[^"\r\n]*(?:"|\.{3}$)/gm, protect) .replaceAll(/(?:[A-Za-z]:)?[^\s`"']*wrangler\.jsonc?/gi, protect) .replaceAll(/\bWRANGLER_[A-Z0-9_]+\b/g, protect) .replaceAll(/\.wrangler\b/gi, protect) @@ -32,3 +39,17 @@ export function formatCloudflareUserMessage(message: string): string { }); return result; } + +export function logCloudflareUserError(message: string): void { + const lines = formatCloudflareUserMessage(message).split('\n'); + const linkIndex = lines.indexOf(ROLLBACK_GUIDE); + if (linkIndex >= 0) { + const output = { columns: Infinity, write: process.stdout.write.bind(process.stdout) }; + log.error(lines.slice(0, linkIndex).join('\n'), { output: output as typeof process.stdout }); + printNextStep(formatUrl(ROLLBACK_GUIDE), { wrap: false }); + } + const details = lines.slice(linkIndex + 1).join('\n'); + if (linkIndex < 0 || details.trim()) { + log.error(linkIndex < 0 ? details : details.trimStart()); + } +} diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 74188d610..999e641c3 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -361,6 +361,7 @@ export function cloudflareCandidateActivationOptions(options: { const candidateReceipt = pinnedHandoffLink?.candidateReceipt; return { workerName, + accountId, configPath, preserveTriggers: existingWorker !== null, expectedPreviousVersionId: existingWorker?.versionId, @@ -586,6 +587,9 @@ function formatCloudflareActivationFailure( } return `deploy: could not snapshot the current Cloudflare deployment${status}; no version was uploaded.`; case 'deployment-changed': + if (result.diagnostic) { + return result.diagnostic; + } 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.`; diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 7a00f3130..7f2b9a024 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -12,7 +12,7 @@ import type { QueueDefinition } from '../queues/scan.ts'; import { buildEnv } from '../shared/untrusted-env.ts'; import type { PlatformClient } from './client.ts'; import type { DeploymentResponse, ProjectResponse } from './client.ts'; -import { formatCloudflareUserMessage } from './cloudflare-user-output.ts'; +import { formatCloudflareUserMessage, logCloudflareUserError } from './cloudflare-user-output.ts'; import { promptAndCreateProject, reportProjectCreationWarnings } from './create-project.ts'; import type { PrerenderSourceInputs, @@ -44,7 +44,7 @@ export const log: Record< 'error' | 'info' | 'message' | 'step' | 'warn', (message: string) => void > = { - error: (message: string) => clackLog.error(formatCloudflareUserMessage(message)), + error: logCloudflareUserError, info: (message: string) => clackLog.info(formatCloudflareUserMessage(message)), message: (message: string) => clackLog.message(formatCloudflareUserMessage(message)), step: (message: string) => clackLog.step(formatCloudflareUserMessage(message)), diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index f43acc50f..b61787c0f 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -25,7 +25,10 @@ import ignore from 'ignore'; import { toSlash } from 'pathslash'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { packageFixturePath } from '../../../../test/fixture-dir.ts'; -import { activateCloudflareVersion as activateCloudflareVersionPrimitive } from '../../../deploy-cloudflare/src/index.ts'; +import { + activateCloudflareVersion as activateCloudflareVersionPrimitive, + assertCloudflareDurableObjectLifecycleSupported, +} from '../../../deploy-cloudflare/src/index.ts'; import { operationFixture, operationFixtureRequest, @@ -296,6 +299,13 @@ describe('Cloudflare deploy log end record', () => { }); describe('Cloudflare activation diagnostics', () => { + it('returns the staging-pair diagnostic for a deployment change', () => { + const diagnostic = 'Open the Worker Deployments tab and check Active Deployment.'; + expect( + formatCloudflareActivationError({ ok: false, reason: 'deployment-changed', diagnostic }), + ).toBe(diagnostic); + }); + it.each(['worker', 'static'] as const)( 'flushes the %s upload diagnostic before exiting', async (kind) => { @@ -1729,6 +1739,112 @@ describe('existing Cloudflare site handoff', () => { expect(activateVersion).toHaveBeenCalledWith(expect.objectContaining({ atomic: true })); }); + it('guides an established Durable Object Worker through clearing a staging pair and retrying', async () => { + const root = site(); + const configPath = join(root, 'wrangler.jsonc'); + const config = { + ...parseRootWranglerConfig(configPath), + name: 'wrangler-canary', + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + workers_dev: true, + preview_urls: false, + routes: [], + }; + writeFileSync(configPath, JSON.stringify(config)); + vi.stubEnv('CLOUDFLARE_WORKERS_SUBDOMAIN', 'example'); + + const live = '11111111-1111-4111-8111-111111111111'; + const abandoned = '22222222-2222-4222-8222-222222222222'; + const next = '33333333-3333-4333-8333-333333333333'; + const liveOnly = [{ version_id: live, percentage: 100 }]; + let traffic = [...liveOnly, { version_id: abandoned, percentage: 0 }]; + let deploymentId = 'stuck-deployment'; + const versions = [live, abandoned].map((id, index) => ({ id, number: index + 1 })); + const publishes: Array> = []; + const runWrangler: DeployWranglerRun = (operation) => { + switch (operation.type) { + case 'auth.whoami': + return { ...cleanExit, data: { loggedIn: true, accounts: [] } }; + case 'deployments.status': + return { ...cleanExit, data: { id: deploymentId, versions: traffic } }; + case 'versions.list': + return { ...cleanExit, data: versions.slice() }; + case 'versions.view': + return { + ...cleanExit, + data: { + ...versions.find(({ id }) => id === operation.versionId), + resources: { + bindings: [{ name: 'ROOM', type: 'durable_object_namespace', class_name: 'Room' }], + script: { handlers: ['fetch'] }, + script_runtime: {}, + }, + }, + }; + case 'versions.upload': + versions.push({ id: next, number: 3 }); + return { ...cleanExit, data: { versionId: next } }; + case 'versions.deploy': + publishes.push( + operation.versions.map(({ versionId, percentage }) => `${versionId}@${percentage}`), + ); + traffic = operation.versions.map(({ versionId, percentage }) => ({ + version_id: versionId, + percentage, + })); + deploymentId = `publish-${publishes.length}`; + return cleanExit; + case 'triggers.deploy': + case 'triggers.clear-crons': + return cleanExit; + default: + throw new Error(`Unexpected Cloudflare operation: ${operation.type}`); + } + }; + const { deps, exitCalls } = harness({ + runWrangler, + runBuild: () => build(root), + assertDurableObjectLifecycle: (options) => + assertCloudflareDurableObjectLifecycleSupported({ + ...options, + readMigrationTag: async () => 'v1', + }), + activateVersion: (options) => + activateCloudflareVersionPrimitive({ + ...options, + fetch: async () => Response.json({ ready: true, versionId: next }), + }), + }); + const deploy = () => runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + const output = await captureDeployOutput(async () => { + await expect(deploy()).rejects.toBeInstanceOf(ExitError); + }); + const message = output.replaceAll(/\s+/g, ' '); + expect + .soft(message) + .toContain( + `Cloudflare Worker "wrangler-canary" in account personal has ${live} at 100% and ${abandoned} at 0%`, + ); + expect.soft(message).toContain('Pause other deploys'); + expect.soft(message).toContain('Active Deployment still shows this exact pair'); + expect.soft(message).toContain('version overrides'); + expect.soft(message).toContain('roll back to the live version'); + expect.soft(message).toContain('If Void still reports the pair, wait and retry.'); + expect + .soft(output) + .toContain( + 'https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/#rolling-back-from-a-split-deployment', + ); + expect(publishes).toEqual([]); + expect(versions.at(-1)?.id).toBe(abandoned); + + deploymentId = 'cleared-deployment'; + traffic = liveOnly; + expect(await captureDeployOutput(deploy)).toContain('Successfully deployed!'); + expect(exitCalls).toEqual([1]); + expect(publishes).toEqual([[`${live}@100`, `${next}@0`], [`${next}@100`]]); + }); + it('uses the project Cloudflare deploy mode on subsequent plain deploys', async () => { const root = site(); const configPath = join(root, 'wrangler.jsonc');