The best way to control Claude Code, Codex and more from any computer or phone

main
ts 367 lines 13.1 KB
Raw
1 import * as pages from "@distilled.cloud/cloudflare/pages";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.Pages.Deployment" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Raised when a Pages deployment reaches a `failure`/`canceled` stage, or
18 * does not reach a successful `deploy` stage within the bounded wait.
19 */
20 export class DeploymentFailed extends Data.TaggedError("DeploymentFailed")<{
21 readonly projectName: string;
22 readonly deploymentId: string;
23 readonly stageName: string;
24 readonly stageStatus: string;
25 }> {}
26
27 export interface DeploymentProps {
28 /**
29 * Name of the Pages project to deploy to (e.g. `project.name`).
30 * Deployments are immutable and belong to exactly one project —
31 * changing the project triggers a replacement.
32 */
33 projectName: string;
34 /**
35 * The branch the deployment is attributed to. Deploying to the project's
36 * production branch produces a production deployment; any other branch
37 * produces a preview deployment. Deployments are immutable — changing
38 * the branch triggers a replacement (a new deployment).
39 * @default the project's production branch
40 */
41 branch?: string;
42 }
43
44 export interface DeploymentAttributes {
45 /**
46 * Cloudflare-assigned UUID of the deployment.
47 */
48 deploymentId: string;
49 /**
50 * Short (8-character) id of the deployment. Forms the deployment's
51 * preview URL (`<shortId>.<project>.pages.dev`).
52 */
53 shortId: string;
54 /**
55 * The Cloudflare account the project belongs to.
56 */
57 accountId: string;
58 /**
59 * Name of the Pages project the deployment belongs to.
60 */
61 projectName: string;
62 /**
63 * Whether this is a `production` or `preview` deployment, derived from
64 * the branch it was created on.
65 */
66 environment: string;
67 /**
68 * The live URL serving this specific deployment.
69 */
70 url: string;
71 /**
72 * The branch the deployment was created from.
73 */
74 branch: string;
75 /**
76 * Name of the deployment's latest pipeline stage (e.g. `deploy`).
77 */
78 latestStageName: string;
79 /**
80 * Status of the deployment's latest pipeline stage (e.g. `success`).
81 */
82 latestStageStatus: string;
83 /**
84 * When the deployment was created.
85 */
86 createdOn: string;
87 }
88
89 export type Deployment = Resource<TypeId, DeploymentProps, DeploymentAttributes, never, Providers>;
90
91 /**
92 * A direct-upload deployment on a Cloudflare Pages project.
93 *
94 * Creating the resource POSTs a new deployment to the project and waits
95 * (bounded) for it to reach a successful `deploy` stage. Deployments are
96 * immutable — every prop change triggers a replacement (a brand-new
97 * deployment that supersedes the previous one).
98 *
99 * The deployment is created with an **empty asset manifest**: the full
100 * direct-upload protocol (asset upload sessions driven by
101 * `wrangler pages deploy`) is not part of the public REST surface, so this
102 * resource cannot push file contents. It is useful for provisioning an
103 * initial/placeholder deployment on a direct-upload project (so the
104 * project's `*.pages.dev` subdomain starts serving) and for rolling the
105 * active deployment from IaC. For deploying real static sites prefer
106 * `Cloudflare.Website` (Workers Assets).
107 *
108 * Deleting the resource deletes the deployment (with `force`), except when
109 * it is the project's active production deployment — Cloudflare refuses to
110 * delete the live deployment, so delete tolerates that case and the
111 * deployment is cleaned up when the project itself is deleted.
112 * ### Creating a Deployment
113 * **Example:** Production deployment on a direct-upload project
114 * ```typescript
115 * const project = yield* Cloudflare.Pages.Project("site", {});
116 *
117 * const deployment = yield* Cloudflare.Pages.Deployment("site-deploy", {
118 * projectName: project.name,
119 * });
120 * // deployment.url === "https://<shortId>.<project>.pages.dev"
121 * // deployment.environment === "production"
122 * ```
123 *
124 * **Example:** Preview deployment from a non-production branch
125 * ```typescript
126 * const preview = yield* Cloudflare.Pages.Deployment("site-preview", {
127 * projectName: project.name,
128 * branch: "feature-x",
129 * });
130 * // preview.environment === "preview"
131 * ```
132 *
133 * @see https://developers.cloudflare.com/pages/
134 *
135 * @resource
136 * @product Pages
137 * @category Workers & Compute
138 */
139 export const Deployment = Resource<Deployment>(TypeId);
140
141 /**
142 * Returns true if the given value is a Deployment resource.
143 */
144 export const isDeployment = (value: unknown): value is Deployment =>
145 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
146
147 export const DeploymentProvider = () =>
148 Provider.succeed(Deployment, {
149 stables: [
150 "deploymentId",
151 "shortId",
152 "accountId",
153 "projectName",
154 "environment",
155 "url",
156 "branch",
157 "createdOn",
158 ],
159 diff: Effect.fn(function* ({ olds, news, output }) {
160 const { accountId } = yield* yield* CloudflareEnvironment;
161 if (!isResolved(news)) return undefined;
162 if ((output?.accountId ?? accountId) !== accountId) {
163 return { action: "replace" } as const;
164 }
165 // Deployments are immutable: a different project or branch means a
166 // brand-new deployment.
167 const oldProject =
168 output?.projectName ??
169 (typeof olds?.projectName === "string" ? olds.projectName : undefined);
170 if (oldProject !== undefined && oldProject !== news.projectName) {
171 return { action: "replace" } as const;
172 }
173 const oldBranch = olds?.branch;
174 if (oldBranch !== news.branch) {
175 return { action: "replace" } as const;
176 }
177 return undefined;
178 }),
179 read: Effect.fn(function* ({ output }) {
180 // Deployment ids are server-assigned and carry no deterministic
181 // identity, so there is no cold lookup — without persisted state the
182 // deployment is reported missing and reconcile creates a fresh one.
183 if (!output?.deploymentId) return undefined;
184 const observed = yield* getDeployment(
185 output.accountId,
186 output.projectName,
187 output.deploymentId,
188 );
189 return observed ? toAttributes(observed, output.accountId, output.projectName) : undefined;
190 }),
191 list: Effect.fn(function* () {
192 const { accountId } = yield* yield* CloudflareEnvironment;
193 // Deployments are sub-resources keyed by Pages project, with no
194 // account-wide deployment enumeration API. Enumerate every project
195 // (account-scoped) first, then fan out and list each project's
196 // deployments, paginating exhaustively.
197 const projects = yield* pages.listProjects.pages({ accountId }).pipe(
198 Stream.runCollect,
199 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.result ?? [])),
200 // Account without a Pages entitlement can't list projects → nothing.
201 Effect.catchTag("Forbidden", () => Effect.succeed([])),
202 );
203 const rows = yield* Effect.forEach(
204 projects,
205 (project) =>
206 pages.listProjectDeployments.pages({ accountId, projectName: project.name }).pipe(
207 Stream.runCollect,
208 Effect.map((chunk) =>
209 Array.from(chunk).flatMap((page) =>
210 (page.result ?? []).map((deployment) =>
211 toAttributes(deployment, accountId, project.name),
212 ),
213 ),
214 ),
215 ),
216 { concurrency: 10 },
217 );
218 return rows.flat();
219 }),
220 reconcile: Effect.fn(function* ({ news, output }) {
221 const { accountId } = yield* yield* CloudflareEnvironment;
222 // Inputs have been resolved to concrete strings by Plan.
223 const projectName = news.projectName as string;
224
225 // 1. Observe — `output.deploymentId` is a cache of the only handle we
226 // have on the deployment; a vanished deployment falls through to
227 // "missing" and we create a fresh one.
228 let observed = output?.deploymentId
229 ? yield* getDeployment(accountId, projectName, output.deploymentId)
230 : undefined;
231
232 // 2. Ensure — create the deployment when missing. Deployments are
233 // immutable, so there is no sync step beyond waiting for the
234 // pipeline to finish; an empty manifest means no assets to upload.
235 if (!observed) {
236 observed = yield* pages.createProjectDeployment({
237 accountId,
238 projectName,
239 branch: news.branch,
240 manifest: "{}",
241 });
242 }
243
244 // 3. Wait (bounded) for the deployment to reach a terminal stage and
245 // fail with a typed error if it didn't succeed.
246 observed = yield* awaitDeployment(accountId, projectName, observed);
247
248 // 4. Return fresh attributes.
249 return toAttributes(observed, accountId, projectName);
250 }),
251 delete: Effect.fn(function* ({ output }) {
252 // Idempotent: the deployment may already be gone (DeploymentNotFound)
253 // or the whole project deleted (ProjectNotFound) — both are success.
254 // The active production deployment cannot be deleted even with
255 // `force` (Cloudflare error 8000034) — it is removed when the project
256 // itself is deleted, so tolerate and move on.
257 yield* pages
258 .deleteProjectDeployment({
259 accountId: output.accountId,
260 projectName: output.projectName,
261 deploymentId: output.deploymentId,
262 force: true,
263 })
264 .pipe(
265 Effect.catchTags({
266 DeploymentNotFound: () => Effect.void,
267 ProjectNotFound: () => Effect.void,
268 ActiveProductionDeployment: () =>
269 Effect.logWarning(
270 `Pages deployment ${output.deploymentId} is the active production deployment of project ${output.projectName}; it will be deleted with the project.`,
271 ),
272 }),
273 );
274 }),
275 });
276
277 // ---------------------------------------------------------------------------
278 // Observation
279 // ---------------------------------------------------------------------------
280
281 type ObservedDeployment =
282 | pages.GetProjectDeploymentResponse
283 | pages.CreateProjectDeploymentResponse;
284
285 /**
286 * Read a deployment by id, mapping "gone" to `undefined` — either the
287 * deployment was deleted (`DeploymentNotFound`, code 8000009) or the whole
288 * project no longer exists (`ProjectNotFound`, code 8000007).
289 */
290 const getDeployment = (accountId: string, projectName: string, deploymentId: string) =>
291 pages.getProjectDeployment({ accountId, projectName, deploymentId }).pipe(
292 Effect.catchTags({
293 DeploymentNotFound: () => Effect.undefined,
294 ProjectNotFound: () => Effect.undefined,
295 }),
296 );
297
298 const isTerminalStage = (stage: ObservedDeployment["latestStage"]): boolean =>
299 (stage.name === "deploy" && stage.status === "success") ||
300 stage.status === "failure" ||
301 stage.status === "canceled";
302
303 /**
304 * Poll the deployment until its pipeline reaches a terminal stage —
305 * bounded so a stuck deployment fails fast instead of hanging the engine.
306 * Anything other than a successful `deploy` stage is a typed failure.
307 */
308 const awaitDeployment = (accountId: string, projectName: string, created: ObservedDeployment) =>
309 Effect.gen(function* () {
310 const observed: ObservedDeployment = isTerminalStage(created.latestStage)
311 ? created
312 : yield* pages
313 .getProjectDeployment({
314 accountId,
315 projectName,
316 deploymentId: created.id,
317 })
318 .pipe(
319 Effect.repeat({
320 schedule: Schedule.spaced("2 seconds"),
321 until: (d) => isTerminalStage(d.latestStage),
322 times: 25,
323 }),
324 );
325 if (observed.latestStage.status !== "success" || observed.latestStage.name !== "deploy") {
326 return yield* new DeploymentFailed({
327 projectName,
328 deploymentId: observed.id,
329 stageName: observed.latestStage.name,
330 stageStatus: observed.latestStage.status,
331 });
332 }
333 return observed;
334 });
335
336 /**
337 * Minimal structural shape `toAttributes` reads — satisfied by both the
338 * get/create deployment responses and a `listProjectDeployments` row.
339 */
340 type DeploymentAttributesSource = {
341 readonly id: string;
342 readonly shortId: string;
343 readonly environment: string;
344 readonly url: string;
345 readonly deploymentTrigger: {
346 readonly metadata: { readonly branch: string };
347 };
348 readonly latestStage: { readonly name: string; readonly status: string };
349 readonly createdOn: string;
350 };
351
352 const toAttributes = (
353 deployment: DeploymentAttributesSource,
354 accountId: string,
355 projectName: string,
356 ): DeploymentAttributes => ({
357 deploymentId: deployment.id,
358 shortId: deployment.shortId,
359 accountId,
360 projectName,
361 environment: deployment.environment,
362 url: deployment.url,
363 branch: deployment.deploymentTrigger.metadata.branch,
364 latestStageName: deployment.latestStage.name,
365 latestStageStatus: deployment.latestStage.status,
366 createdOn: deployment.createdOn,
367 });