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
158 changes: 119 additions & 39 deletions packages/deploy-cloudflare/src/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -167,6 +169,7 @@ type CurrentProductionVersion =
kind: 'ok';
versionId: string | null;
versions: ReadonlyArray<ProductionVersionPercentage>;
deploymentId?: string;
}
| { kind: 'failed'; status: number }
| { kind: 'split' };
Expand Down Expand Up @@ -877,7 +880,7 @@ export type CloudflareVersionActivationOptions = {
fetch?: typeof globalThis.fetch;
sleep?: (milliseconds: number) => Promise<void>;
/**
* 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<number>;
Expand Down Expand Up @@ -1557,7 +1560,7 @@ async function activateCloudflareVersionWithSecretsFile(
: undefined;
let readinessUrl = reportedPreviewUrl;
let readinessUsesCustomRoute = false;
let stagedVersionOverride = false;
let stagedVersionOverride: Extract<ReadinessStagingResult, { ok: true }> | undefined;
if (!readinessUrl) {
if (
!options.preserveTriggers &&
Expand All @@ -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 ||
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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 }),
};
}
Expand All @@ -1690,6 +1697,7 @@ async function activateCloudflareVersionWithSecretsFile(
return {
ok: false,
reason: 'uploader-changed',
beforeActivation: true,
versionId,
previousVersionId: previous.versionId,
...(stagedVersionOverride
Expand All @@ -1698,22 +1706,53 @@ async function activateCloudflareVersionWithSecretsFile(
previous.versionId,
'uploader verification failed',
[stagedVersionPercentages(previous.versionId, versionId)],
stagedVersionOverride.deploymentId,
)
: { rollback: 'not-needed' as const }),
};
}

// 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 {
Expand All @@ -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,
};
}

Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -2871,13 +2930,17 @@ function stagedVersionPercentages(
: [];
}

type ReadinessStagingResult =
| { ok: true; previousDeploymentId: string | undefined; deploymentId: string }
| Extract<CloudflareVersionActivation, { ok: false }>;

/** 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<Extract<CloudflareVersionActivation, { ok: false }> | null> {
): Promise<ReadinessStagingResult> {
if (!options.verifyUploader()) {
return {
ok: false,
Expand All @@ -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,
Expand All @@ -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(
Expand All @@ -2919,7 +2994,10 @@ async function verifyReadinessStagingOwner(
>,
previousVersionId: string | null,
versionId: string,
): Promise<Extract<CloudflareVersionActivation, { ok: false }> | null> {
): Promise<
| { ok: true; previousDeploymentId: string | undefined }
| Extract<CloudflareVersionActivation, { ok: false }>
> {
const owner = await readCurrentProductionVersion(options);
if (owner.kind === 'failed') {
return {
Expand Down Expand Up @@ -2954,7 +3032,7 @@ async function verifyReadinessStagingOwner(
rollback: 'not-needed',
};
}
return null;
return { ok: true, previousDeploymentId: owner.deploymentId };
}

async function probeReadiness(
Expand Down Expand Up @@ -3219,6 +3297,7 @@ async function restorePreviousVersion(
previousVersionId: string | null,
cause: string,
expectedOwnedTraffic: ReadonlyArray<ReadonlyArray<ProductionVersionPercentage>>,
expectedDeploymentId?: string,
): Promise<PreviousVersionRestore> {
if (!previousVersionId) {
return { rollback: 'unavailable' };
Expand All @@ -3231,6 +3310,7 @@ async function restorePreviousVersion(
return {
owns:
owner.kind === 'ok' &&
(expectedDeploymentId === undefined || owner.deploymentId === expectedDeploymentId) &&
expectedOwnedTraffic.some((expected) =>
productionVersionPercentagesEqual(owner.versions, expected),
),
Expand Down
10 changes: 5 additions & 5 deletions packages/deploy-cloudflare/test/unit/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,6 +18,7 @@ function setup(
const calls: Array<CloudflareOperation> = [];
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);
Expand All @@ -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([
{
Expand Down Expand Up @@ -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 };
}
Expand All @@ -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;
Expand Down Expand Up @@ -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');
Expand Down
Loading