diff --git a/packages/alchemy/src/Cloudflare/Workers/Worker.ts b/packages/alchemy/src/Cloudflare/Workers/Worker.ts index 4fe71b9203a..e31e7994d74 100644 --- a/packages/alchemy/src/Cloudflare/Workers/Worker.ts +++ b/packages/alchemy/src/Cloudflare/Workers/Worker.ts @@ -325,6 +325,88 @@ export interface WorkerRouteConfig { zone?: ZoneReference; } +/** + * Versioning configuration for a Worker deploy — controls Worker + * [versions and gradual deployments](https://developers.cloudflare.com/workers/configuration/versions-and-deployments/). + * + * Two modes, selected by {@link parent}: + * + * - **Version worker** (`parent` set): instead of creating its own script, + * this Worker uploads an immutable *version* to the referenced parent + * Worker's script. With `traffic: 0` (the default) the parent's live + * deployment is untouched and the version is reachable only at its + * preview URL (`-..workers.dev`) — + * the PR-preview use case. With `traffic > 0` the version becomes a + * canary taking that percentage of the parent's traffic. + * - **Gradual rollout** (`parent` omitted): when this Worker deploys + * itself, the newly uploaded version receives {@link traffic} percent + * and the currently-live version keeps the remainder, instead of the + * default 100% cutover. + */ +export interface WorkerVersionOptions { + /** + * The Worker that owns the script this version is uploaded to. Accepts a + * Worker reference — typically `yield* Cloudflare.Worker.ref(id, { stage, + * stack })` for a Worker deployed in another stage/stack, or a + * locally-declared Worker — or a literal script name as an escape hatch. + * + * When set, this resource does not create a script of its own: it + * uploads a version (code + bindings + compatibility settings) to the + * parent's script. Script-level settings apply immediately to *all* + * versions of the parent, so they cannot be set on a version worker — + * `name`, `assets`, `namespace`, `crons`, `domain`, `routes`, `tags`, + * `logpush`, `observability`, `placement`, `limits`, and `subdomain` are + * rejected, as are locally-hosted Durable Object or Workflow classes + * (their migrations would mutate the parent). + * + * Changing the parent replaces the resource (a version belongs to + * exactly one script). + */ + parent?: string | Worker; + /** + * Percentage of traffic (0–100) the newly uploaded version receives; the + * currently-live version keeps the remainder. Cloudflare deployments + * split between at most two versions, so one canary can be active per + * script at a time. + * + * With {@link parent} set, defaults to `0`: the version is + * preview-URL-only and the parent's live deployment is untouched. + * Without `parent`, defaults to `100` (today's full cutover); `0` means + * "upload the version without deploying it" (the equivalent of + * `wrangler versions upload`). + * + * Note that a subsequent full deploy of the parent (or of this Worker + * itself, at the default 100) resets traffic to 100% of its own new + * version. + */ + traffic?: number; + /** + * Preview-URL alias for the uploaded version. Aliased preview URLs + * (`-..workers.dev`) are stable — each upload + * with the same alias re-points the URL at the new version — which is + * what makes them useful as shareable PR-preview links and lets + * `Worker.URL` resolve before the version exists. + * + * For a version worker ({@link parent} set) an alias is derived + * automatically from the stack, stage, and logical id, so every version + * worker gets a stable preview URL out of the box; set this to override + * it. Must start with a lowercase letter, contain only lowercase + * letters, digits, and dashes, and `-` must fit in + * 63 characters (a DNS label). + */ + alias?: string; + /** + * Human-readable annotation attached to the uploaded version, shown in + * the Cloudflare dashboard and `wrangler versions list`. + */ + message?: string; + /** + * Machine-readable tag annotation attached to the uploaded version + * (e.g. a git commit SHA or PR number). + */ + tag?: string; +} + export interface WorkerProps< Bindings extends WorkerBindingProps = any, Assets extends WorkerAssetsConfig | undefined = @@ -357,6 +439,14 @@ export interface WorkerProps< * @see https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/ */ namespace?: string | DispatchNamespace; + /** + * Worker versions & gradual deployments. Set `version.parent` to upload + * this Worker as a preview/canary *version* of another Worker's script + * instead of creating its own; set `version.traffic` below 100 to + * gradually roll out a deploy of this Worker's own script. See + * {@link WorkerVersionOptions}. + */ + version?: WorkerVersionOptions; /** * Whether to enable a workers.dev URL for this worker * @default true @@ -672,6 +762,36 @@ export type Worker = Resource< domains: string[]; routes: { id: string; pattern: string; zoneId: string }[]; crons: string[]; + /** + * The parent script name this Worker uploads versions to, when this + * resource is a version worker (`version.parent` set). `undefined` for + * a Worker that owns its own script — including one deploying with a + * gradual rollout. This is the discriminator `read`/`delete` use to + * avoid treating the parent's script as this resource's own. + */ + versionOf?: string | undefined; + /** + * The id of the version uploaded by the most recent deploy. Only set + * when versioning is in play: always for a version worker + * (`version.parent`), and for a self-owned Worker when a gradual + * rollout (`version.traffic` < 100) deployed via the versions API. + */ + versionId?: string | undefined; + /** + * The preview-URL alias attached to the uploaded version — the + * user-provided `version.alias`, or the auto-derived stable alias for + * a version worker. The aliased preview URL + * (`-..workers.dev`) is stable across + * deploys and is the version worker's primary `url`. + */ + versionAlias?: string | undefined; + /** + * The id of the deployment created by the most recent deploy, when the + * deploy created one through the deployments API (a version with + * `traffic > 0`). Preview-only versions (`traffic: 0`) have no + * deployment. + */ + deploymentId?: string | undefined; hash?: { assets: string | undefined; bundle: string | undefined; @@ -1062,6 +1182,65 @@ export const isSelfUrl = (value: unknown): value is URLEffect => * } * ``` * + * @section Versions & Gradual Deployments + * The `version` prop maps Cloudflare's + * [versions and gradual deployments](https://developers.cloudflare.com/workers/configuration/versions-and-deployments/) + * onto Alchemy stages. A Worker with `version.parent` set uploads an + * immutable *version* to the parent Worker's script instead of creating its + * own — by default with no traffic, reachable only at its preview URL + * (`worker.url`), which is the PR-preview workflow. Give it `traffic` to + * run it as a canary, or use `version.traffic` on a normal Worker to roll + * out its own deploys gradually. + * + * A version worker's `url` is its *aliased* preview URL + * (`-..workers.dev`) — the alias is derived from + * the stack, stage, and logical id (override with `version.alias`), so the + * URL is stable across deploys and always points at the latest uploaded + * version. The per-version URL (`-...`) is also returned + * in `domains`. Because the aliased URL is known before the version + * exists, `Worker.URL` works on version workers and resolves to it. + * + * A version carries code, bindings, and compatibility settings. Script-level + * settings (routes, domains, crons, tags, observability, …) belong to the + * parent and are rejected on version workers, as are locally-hosted Durable + * Object or Workflow classes. Preview URLs require the parent's workers.dev + * subdomain to be enabled (the default). + * + * @example PR preview: a version of another stage's Worker + * ```typescript + * // The staging stage deploys the real Worker; a PR stage uploads its + * // code as a zero-traffic version of staging's script and gets back a + * // stable preview URL. + * const parent = yield* Cloudflare.Worker.ref("MyWorker", { + * stage: "staging", + * }); + * const preview = yield* Cloudflare.Worker("MyWorker", { + * main: "./src/worker.ts", + * version: { parent, message: `PR #${process.env.PR_NUMBER}` }, + * }); + * // preview.url -> https://-..workers.dev + * // (stable across deploys; re-points at each newly uploaded version) + * ``` + * + * @example Canary: send 10% of the parent's traffic to a version + * ```typescript + * const parent = yield* Cloudflare.Worker.ref("MyWorker", { stage: "prod" }); + * yield* Cloudflare.Worker("MyWorker", { + * main: "./src/worker.ts", + * version: { parent, traffic: 10 }, + * }); + * ``` + * + * @example Gradual rollout of a Worker's own deploy + * ```typescript + * // The new version takes 25% of traffic; the previously-live version + * // keeps 75%. Bump traffic (or remove the prop) and re-deploy to promote. + * yield* Cloudflare.Worker("MyWorker", { + * main: "./src/worker.ts", + * version: { traffic: 25 }, + * }); + * ``` + * * @section The Worker's own URL * `Worker.URL` injects the URL a Worker is served at as a binding on that * same Worker — the first custom `domain` if one is configured, otherwise diff --git a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts index 57913ab195a..97d3cbc80b9 100644 --- a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts +++ b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts @@ -130,6 +130,61 @@ export const resolveNamespaceName = ( return (namespace as { name?: string }).name; }; +/** + * A Worker's `version` configuration is invalid — a prop that can't be + * combined with `version.parent` (script-level settings belong to the + * parent), a locally-hosted Durable Object / Workflow class on a version + * worker, an out-of-range `traffic`, or a gradual rollout that requires + * changes the versions API can't carry (assets, DO migrations). + */ +export class WorkerVersionConfigError extends Data.TaggedError( + "WorkerVersionConfigError", +)<{ + message: string; +}> {} + +/** + * Resolve the parent script *name* from a resolved `version.parent` prop or + * persisted props. The engine resolves a passed {@link Worker} (or + * `Worker.ref(...)`) to its Attributes object — possibly stables-only during + * planning, but `workerName` is always a stable — so the value is either the + * script name string, that attributes object, or `undefined`. + * + * @internal + */ +export const resolveVersionParentName = ( + version: WorkerProps["version"], +): string | undefined => { + const parent = version?.parent; + if (parent == null) return undefined; + if (typeof parent === "string") return parent; + const workerName = (parent as { workerName?: unknown }).workerName; + return typeof workerName === "string" ? workerName : undefined; +}; + +/** + * The traffic percentage a *self-owned* Worker's new version should receive, + * or `undefined` for the default full cutover. Only a `version` prop without + * a `parent` participates — version workers handle traffic separately. + * + * @internal + */ +const getSelfRolloutTraffic = (news: WorkerProps): number | undefined => { + if (!news.version || news.version.parent != null) return undefined; + const traffic = news.version.traffic; + return traffic === undefined || traffic >= 100 ? undefined : traffic; +}; + +const validateTraffic = (traffic: number | undefined) => + traffic !== undefined && + (!Number.isFinite(traffic) || traffic < 0 || traffic > 100) + ? Effect.fail( + new WorkerVersionConfigError({ + message: `version.traffic must be a percentage between 0 and 100, got ${traffic}`, + }), + ) + : Effect.void; + // Workers for Platforms "user workers" live inside a dispatch namespace and // use a parallel family of script endpoints (`/workers/dispatch/namespaces/ // :namespace/scripts/...`). The request/response shapes are identical to the @@ -186,7 +241,8 @@ const getScriptSettings = ( const isBindingTargetNotFound = ( e: | Effect.Error> - | Effect.Error>, + | Effect.Error> + | Effect.Error>, ): boolean => e._tag === "SecretsStoreBindingNotFound" || e._tag === "KVNamespaceNotFound" || @@ -450,6 +506,19 @@ const resolveWorkerMetadataHash = ({ subdomain: props.subdomain, tags: props.tags, url: props.url, + // Reduce `version.parent` to the parent's script name: the resolved + // parent is a full attributes object whose *other* fields (hash, url, + // ...) change on every parent deploy, which would spuriously re-version + // this Worker even though nothing about the version itself changed. + version: props.version + ? { + parent: resolveVersionParentName(props.version), + traffic: props.version.traffic, + alias: props.version.alias, + message: props.version.message, + tag: props.version.tag, + } + : undefined, }).pipe(Effect.flatMap((metadata) => sha256Object({ metadata }))); export const WorkerProvider = () => @@ -1461,6 +1530,446 @@ export const LiveWorkerProvider = () => return { directory, config, hash, skip: hash === output?.hash?.assets }; }; + /** + * Append the standard Alchemy runtime bindings plus the user's `env` + * entries (routed by shape: `Redacted` → secret_text, string → + * plain_text, everything else → json) to a metadata binding list. + * Shared between the full script upload and the version upload. + */ + const appendAlchemyAndEnvBindings = ( + metadataBindings: WorkerBinding[], + news: WorkerProps, + accountId: string, + ) => { + metadataBindings.push( + { + type: "plain_text", + name: "ALCHEMY_PHASE", + text: "runtime", + }, + { + type: "plain_text", + name: "ALCHEMY_STACK_NAME", + text: stack.name, + }, + { + type: "plain_text", + name: "ALCHEMY_STAGE", + text: stack.stage, + }, + { + type: "plain_text", + name: "ALCHEMY_CLOUDFLARE_ACCOUNT_ID", + text: accountId, + }, + ); + // Add environment variables as metadata bindings + if (news.env) { + for (const [key, value] of Object.entries(news.env)) { + if (value === undefined) continue; + if (metadataBindings.some((b) => b.name === key)) continue; + if (Redacted.isRedacted(value)) { + const unredacted = Redacted.value(value); + metadataBindings.push({ + type: "secret_text", + name: key, + text: + typeof unredacted === "string" + ? unredacted + : JSON.stringify(unredacted), + }); + } else if (typeof value === "string") { + metadataBindings.push({ + type: "plain_text", + name: key, + text: value, + }); + } else { + metadataBindings.push({ + type: "json", + name: key, + json: value, + }); + } + } + } + }; + + /** + * Create a deployment routing `traffic`% to `versionId`, with the + * remainder staying on the currently-live version (the + * highest-percentage version of the script's latest deployment). + * `traffic >= 100` — or a script with no other live version to split + * against — deploys the new version at 100%. + */ + const deployVersionTraffic = Effect.fn(function* (params: { + accountId: string; + scriptName: string; + versionId: string; + traffic: number; + message: string | undefined; + }) { + const { accountId, scriptName, versionId, traffic } = params; + const split = yield* Effect.gen(function* () { + if (traffic >= 100) { + return [{ versionId, percentage: 100 }]; + } + const { deployments } = yield* workers.listScriptDeployments({ + accountId, + scriptName, + }); + // Deployments are returned newest-first; the live version is the + // highest-percentage version of the most recent deployment. + const stable = deployments[0]?.versions + .filter((v) => v.versionId !== versionId) + .sort((a, b) => b.percentage - a.percentage)[0]; + if (!stable) { + // Nothing to split against (first deployment of this script). + return [{ versionId, percentage: 100 }]; + } + return [ + { versionId, percentage: traffic }, + { versionId: stable.versionId, percentage: 100 - traffic }, + ]; + }); + const deployment = yield* workers.createScriptDeployment({ + accountId, + scriptName, + strategy: "percentage", + versions: split, + annotations: params.message + ? { workersMessage: params.message } + : undefined, + }); + return deployment.id; + }); + + /** + * Resolve the preview-URL alias for a version worker: the + * user-provided `version.alias` (validated against Cloudflare's + * naming rules), or an alias derived from the stack, stage, and + * logical id — stable across deploys, so the aliased preview URL + * (`-