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

main
ts 481 lines 14.6 KB
Raw
1 import * as firebaseapphosting from "@distilled.cloud/gcp/firebaseapphosting_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 expandParent,
14 fingerprint,
15 listAtNested,
16 listLabeledPages,
17 MAX_BACKEND_ID_LENGTH,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 stringMap,
23 toPhysicalId,
24 userLabels,
25 waitForDeleteOperation,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 } from "./internal.ts";
30
31 export type UserMetadata = {
32 /** Git user name. */
33 displayName?: string;
34 /** Git user email. */
35 email?: string;
36 /** URI of a profile image. */
37 imageUri?: string;
38 };
39
40 export type CodebaseSource = {
41 /**
42 * Branch to build from (latest commit). Mutually exclusive with
43 * `commit`.
44 */
45 branch?: string;
46 /**
47 * Commit SHA to build from. Mutually exclusive with `branch`.
48 */
49 commit?: string;
50 /**
51 * Developer Connect gitRepositoryLink resource name used for this
52 * build.
53 */
54 repository?: string;
55 };
56
57 export type ArchiveSource = {
58 /** Signed URL of an archive in a storage bucket. */
59 externalSignedUri?: string;
60 /**
61 * Cloud Storage URI of a `.zip` or `.tar.gz` archive
62 * (`gs://bucket/object`).
63 */
64 userStorageUri?: string;
65 /**
66 * Directory relative to the archive root used as the web app root.
67 */
68 rootDirectory?: string;
69 /** Optional message describing this uploaded source. */
70 description?: string;
71 };
72
73 export type ContainerSource = {
74 /**
75 * Artifact Registry container image URI used as the build source.
76 */
77 image?: string;
78 };
79
80 export type BuildSource = {
81 /** Git codebase at a branch or commit. */
82 codebase?: CodebaseSource;
83 /** Storage archive. */
84 archive?: ArchiveSource;
85 /** Artifact Registry container image. */
86 container?: ContainerSource;
87 };
88
89 export type RunConfig = {
90 /** Maximum Cloud Run instances per revision. */
91 maxInstances?: number;
92 /** Memory per instance in MiB (`128`–`32768`). */
93 memoryMib?: number;
94 /** Maximum concurrent requests per instance (`1`–`1000`). */
95 concurrency?: number;
96 /** Minimum Cloud Run instances. */
97 minInstances?: number;
98 /** CPUs per instance (`0.08`–`8`). */
99 cpu?: number;
100 };
101
102 export type EnvironmentVariable = {
103 /** Variable name. Must not start with `X_FIREBASE_`. */
104 variable?: string;
105 /** Plaintext value. */
106 value?: string;
107 /**
108 * Secret Manager version resource name. The Cloud Build and Cloud Run
109 * service accounts need `secretmanager.versions.access`.
110 */
111 secret?: string;
112 /**
113 * Where the variable is available (`BUILD`, `RUNTIME`). Unspecified
114 * means both.
115 */
116 availability?: Array<firebaseapphosting.EnvironmentVariableAvailabilityItemEnum | (string & {})>;
117 };
118
119 export type BuildConfig = {
120 /** Cloud Run service configuration for this build. */
121 runConfig?: RunConfig;
122 /**
123 * Environment variables supplied at create time. Immutable. Only
124 * valid for container or archive sources.
125 */
126 env?: EnvironmentVariable[];
127 };
128
129 export type BackendsBuildProps = {
130 /**
131 * Parent backend. Full name
132 * `projects/{project}/locations/{location}/backends/{backend}` or the
133 * backend id (combined with `location`). Immutable — changing it
134 * replaces the build.
135 */
136 backend: string;
137 /**
138 * Region used when `backend` is a bare id.
139 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
140 */
141 location?: string;
142 /**
143 * Build id (the `{buildId}` segment). If omitted, a unique RFC1035
144 * name is generated from the stack, stage, and logical id. Immutable
145 * — changing it replaces the build.
146 */
147 buildId?: string;
148 /**
149 * Source for the build. Immutable — changing it replaces the build.
150 */
151 source: BuildSource;
152 /**
153 * Additional Cloud Run / environment configuration. Immutable —
154 * changing it replaces the build.
155 */
156 config?: BuildConfig;
157 /**
158 * Human-readable name. 63 character limit.
159 */
160 displayName?: string;
161 /**
162 * User annotations (preserved by external tools).
163 */
164 annotations?: Record<string, string>;
165 /**
166 * User labels. Alchemy ownership labels are merged in automatically.
167 */
168 labels?: Record<string, string>;
169 };
170
171 export type BackendsBuild = Resource<
172 "GCP.FirebaseAppHosting.BackendsBuild",
173 BackendsBuildProps,
174 {
175 /** Full resource name. */
176 name: string;
177 /** Build id (last path segment). */
178 buildId: string;
179 /** Parent backend name. */
180 backend: string;
181 /** Project id. */
182 project: string;
183 /** Location id. */
184 location: string;
185 /** Build source. */
186 source: BuildSource | undefined;
187 /** Additional configuration. */
188 config: BuildConfig | undefined;
189 /** Human-readable name. */
190 displayName: string | undefined;
191 /** Environment name of the backend when this build was created. */
192 environment: string | undefined;
193 /** Artifact Registry image URI used by the Cloud Run revision. */
194 image: string | undefined;
195 /** Cloud Build logs URI. */
196 buildLogsUri: string | undefined;
197 /** Server-reported build state. */
198 state: string | undefined;
199 /** True while the build has an ongoing LRO. */
200 reconciling: boolean;
201 /** User annotations. */
202 annotations: Record<string, string>;
203 /** User labels (Alchemy ownership labels stripped). */
204 labels: Record<string, string>;
205 /** Server-generated resource uid. */
206 uid: string | undefined;
207 /** RFC3339 creation timestamp. */
208 createTime: string | undefined;
209 /** RFC3339 last-update timestamp. */
210 updateTime: string | undefined;
211 /** Server-computed etag. */
212 etag: string | undefined;
213 },
214 never,
215 Providers
216 >;
217
218 /**
219 * A Firebase App Hosting build of a backend from a git commit, storage
220 * archive, or container image.
221 *
222 * Builds have no update API. Changing `buildId`, `backend`,
223 * `location`, `source`, or `config` replaces the build.
224 *
225 * ### Creating a Build
226 * **Example:** Container image
227 * ```typescript
228 * const build = yield* GCP.FirebaseAppHosting.BackendsBuild("Hello", {
229 * backend: backend.name,
230 * source: {
231 * container: { image: "us-docker.pkg.dev/cloudrun/container/hello" },
232 * },
233 * labels: { env: "test" },
234 * });
235 * ```
236 *
237 * **Example:** Archive source with Cloud Run limits
238 * ```typescript
239 * const build = yield* GCP.FirebaseAppHosting.BackendsBuild("Archive", {
240 * backend: backend.name,
241 * source: { archive: { userStorageUri: "gs://bucket/app.tar.gz" } },
242 * config: { runConfig: { cpu: 1, memoryMib: 512, maxInstances: 4 } },
243 * });
244 * ```
245 *
246 * @resource
247 * @category FirebaseAppHosting
248 */
249 export const BackendsBuild = Resource<BackendsBuild>("GCP.FirebaseAppHosting.BackendsBuild");
250
251 const resourceName = (backend: string, buildId: string) => `${backend}/builds/${buildId}`;
252
253 const toCodebaseSource = (
254 value: firebaseapphosting.CodebaseSource | undefined,
255 ): CodebaseSource | undefined =>
256 value === undefined
257 ? undefined
258 : {
259 branch: value.branch,
260 commit: value.commit,
261 repository: value.repository,
262 };
263
264 const toArchiveSource = (
265 value: firebaseapphosting.ArchiveSource | undefined,
266 ): ArchiveSource | undefined =>
267 value === undefined
268 ? undefined
269 : {
270 externalSignedUri: value.externalSignedUri,
271 userStorageUri: value.userStorageUri,
272 rootDirectory: value.rootDirectory,
273 description: value.description,
274 };
275
276 const toContainerSource = (
277 value: firebaseapphosting.ContainerSource | undefined,
278 ): ContainerSource | undefined => (value === undefined ? undefined : { image: value.image });
279
280 const toSource = (value: firebaseapphosting.BuildSource | undefined): BuildSource | undefined =>
281 value === undefined
282 ? undefined
283 : {
284 codebase: toCodebaseSource(value.codebase),
285 archive: toArchiveSource(value.archive),
286 container: toContainerSource(value.container),
287 };
288
289 const toConfig = (value: firebaseapphosting.Config | undefined): BuildConfig | undefined =>
290 value === undefined
291 ? undefined
292 : {
293 runConfig: value.runConfig
294 ? {
295 maxInstances: value.runConfig.maxInstances,
296 memoryMib: value.runConfig.memoryMib,
297 concurrency: value.runConfig.concurrency,
298 minInstances: value.runConfig.minInstances,
299 cpu: value.runConfig.cpu,
300 }
301 : undefined,
302 env: value.env?.map((item) => ({
303 variable: item.variable,
304 value: item.value,
305 secret: item.secret,
306 availability: item.availability,
307 })),
308 };
309
310 const toAttrs = (item: firebaseapphosting.Build, project: string) => {
311 const name = item.name ?? "";
312 const parsed = parseName(name, "builds");
313 return {
314 name,
315 buildId: parsed.id,
316 backend: parsed.parent,
317 project: parsed.project || project,
318 location: parsed.location,
319 source: toSource(item.source),
320 config: toConfig(item.config),
321 displayName: item.displayName,
322 environment: item.environment,
323 image: item.image,
324 buildLogsUri: item.buildLogsUri,
325 state: item.state,
326 reconciling: item.reconciling === true,
327 annotations: stringMap(item.annotations),
328 labels: userLabels(item.labels),
329 uid: item.uid,
330 createTime: item.createTime,
331 updateTime: item.updateTime,
332 etag: item.etag,
333 };
334 };
335
336 const getByName = (name: string) =>
337 firebaseapphosting
338 .getProjectsLocationsBackendsBuilds({ name })
339 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
340
341 const listOwned = (project: string) =>
342 listAtNested(project, "backends/-", (parent) =>
343 listLabeledPages(
344 firebaseapphosting.listProjectsLocationsBackendsBuilds.pages({
345 parent,
346 pageSize: 1000,
347 }),
348 (page) => page.builds,
349 (item) => item.labels,
350 ),
351 );
352
353 export const BackendsBuildProvider = () =>
354 Provider.succeed(BackendsBuild, {
355 stables: ["name", "buildId", "backend", "project", "location", "uid", "createTime"],
356
357 diff: Effect.fn(function* ({ news, olds, output }) {
358 if (!isResolved(news)) return undefined;
359 const env = yield* GcpEnvironment.current;
360 const location = normalizeLocation(
361 news.location ?? olds?.location ?? output?.location,
362 env.region,
363 );
364 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
365 const previousParent =
366 (olds?.backend ?? output?.backend)
367 ? expandParent(
368 olds?.backend ?? output?.backend ?? "",
369 env.project,
370 previousLocation,
371 "backends",
372 )
373 : undefined;
374 const nextParent = expandParent(news.backend, env.project, location, "backends");
375 return replaceOnIdentity({
376 previousId: olds?.buildId ?? output?.buildId,
377 nextId: news.buildId ?? olds?.buildId ?? output?.buildId,
378 previousLocation,
379 nextLocation: location,
380 previousParent,
381 nextParent,
382 extra:
383 fingerprint(olds?.source ?? output?.source) !== fingerprint(news.source) ||
384 fingerprint(olds?.config ?? output?.config) !== fingerprint(news.config),
385 });
386 }),
387
388 read: Effect.fn(function* ({ id, olds, output }) {
389 const env = yield* GcpEnvironment.current;
390 const buildId = yield* toPhysicalId(
391 id,
392 olds?.buildId,
393 output?.buildId,
394 "build",
395 MAX_BACKEND_ID_LENGTH,
396 );
397 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
398 const backend =
399 output?.backend ??
400 (olds?.backend ? expandParent(olds.backend, env.project, location, "backends") : undefined);
401 const name = output?.name ?? (backend ? resourceName(backend, buildId) : undefined);
402 if (name === undefined) return undefined;
403 const existing = yield* getByName(name);
404 if (existing === undefined) return undefined;
405 const attrs = toAttrs(existing, env.project);
406 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
407 }),
408
409 list: () =>
410 Effect.gen(function* () {
411 const env = yield* GcpEnvironment.current;
412 const items = yield* listOwned(env.project);
413 return items.map((item) => toAttrs(item, env.project));
414 }),
415
416 reconcile: Effect.fn(function* ({ id, news, output }) {
417 const env = yield* GcpEnvironment.current;
418 const buildId = yield* toPhysicalId(
419 id,
420 news.buildId,
421 output?.buildId,
422 "build",
423 MAX_BACKEND_ID_LENGTH,
424 );
425 const location = normalizeLocation(news.location ?? output?.location, env.region);
426 const backend = expandParent(news.backend, env.project, location, "backends");
427 const name = resourceName(backend, buildId);
428 const desiredLabels = {
429 ...toLabels(news.labels),
430 ...(yield* createInternalLabels(id)),
431 };
432 const desiredAnnotations = news.annotations ?? {};
433
434 let current = yield* getByName(output?.name ?? name);
435
436 if (current === undefined) {
437 const created = yield* firebaseapphosting
438 .createProjectsLocationsBackendsBuilds({
439 parent: backend,
440 buildId,
441 body: {
442 source: news.source,
443 config: news.config,
444 displayName: news.displayName,
445 annotations: desiredAnnotations,
446 labels: desiredLabels,
447 },
448 })
449 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
450 if (created !== undefined) {
451 yield* waitForOperation(created);
452 }
453 current = yield* waitUntilExists(getByName(name), name);
454 }
455
456 if (current === undefined) {
457 return yield* new ResourceNotResolved({ resourceName: name });
458 }
459
460 return toAttrs(current, env.project);
461 }),
462
463 delete: Effect.fn(function* ({ output }) {
464 const operation = yield* firebaseapphosting
465 .deleteProjectsLocationsBackendsBuilds({
466 name: output.name,
467 })
468 .pipe(
469 Effect.retry({
470 while: (error) => error._tag === "Conflict",
471 times: 8,
472 schedule: Schedule.spaced("2 seconds"),
473 }),
474 Effect.catchTag("NotFound", () => Effect.undefined),
475 );
476 if (operation !== undefined) {
477 yield* waitForDeleteOperation(operation);
478 }
479 yield* waitUntilGone(getByName(output.name), output.name);
480 }),
481 });