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

main
ts 377 lines 12.1 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, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 expandParent,
14 fieldMask,
15 fingerprint,
16 listAtNested,
17 listLabeledPages,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sameBool,
23 sameText,
24 stringMap,
25 toDomainId,
26 userLabels,
27 waitForDeleteOperation,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 export type Redirect = {
34 /**
35 * Redirect destination URI. URIs without a scheme are assumed to be
36 * HTTPS. Prepended to the original request path.
37 */
38 uri?: string;
39 /**
40 * HTTP 3xx status used in the redirect response.
41 * @default "302"
42 */
43 status?: string;
44 };
45
46 export type ServingBehavior = {
47 /** Redirect behavior. When set, the domain does not serve live content. */
48 redirect?: Redirect;
49 };
50
51 export type BackendsDomainProps = {
52 /**
53 * Parent backend. Full name
54 * `projects/{project}/locations/{location}/backends/{backend}` or the
55 * backend id (combined with `location`). Immutable — changing it
56 * replaces the domain.
57 */
58 backend: string;
59 /**
60 * Region used when `backend` is a bare id.
61 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
62 */
63 location?: string;
64 /**
65 * Domain id — a valid domain name (for example `www.example.com`).
66 * If omitted, a unique `{id}.example.com` name is generated.
67 * Immutable — changing it replaces the domain.
68 */
69 domainId?: string;
70 /**
71 * Serving behavior. When set, the domain serves something other than
72 * the backend's live content (typically a redirect).
73 */
74 serve?: ServingBehavior;
75 /**
76 * Human-readable name. 63 character limit.
77 */
78 displayName?: string;
79 /**
80 * When true, the domain is disabled.
81 * @default false
82 */
83 disabled?: boolean;
84 /**
85 * User annotations (preserved by external tools).
86 */
87 annotations?: Record<string, string>;
88 /**
89 * User labels. Alchemy ownership labels are merged in automatically.
90 */
91 labels?: Record<string, string>;
92 };
93
94 export type BackendsDomain = Resource<
95 "GCP.FirebaseAppHosting.BackendsDomain",
96 BackendsDomainProps,
97 {
98 /** Full resource name. */
99 name: string;
100 /** Domain id (last path segment, a domain name). */
101 domainId: string;
102 /** Parent backend name. */
103 backend: string;
104 /** Project id. */
105 project: string;
106 /** Location id. */
107 location: string;
108 /** Serving behavior. */
109 serve: ServingBehavior | undefined;
110 /** Human-readable name. */
111 displayName: string | undefined;
112 /** Whether the domain is disabled. */
113 disabled: boolean;
114 /** Domain type (`DEFAULT` or `CUSTOM`). */
115 type: string | undefined;
116 /** Custom-domain linkage status. */
117 customDomainStatus: firebaseapphosting.CustomDomainStatus | undefined;
118 /** True while the domain has an ongoing LRO. */
119 reconciling: boolean;
120 /** User annotations. */
121 annotations: Record<string, string>;
122 /** User labels (Alchemy ownership labels stripped). */
123 labels: Record<string, string>;
124 /** Server-generated resource uid. */
125 uid: string | undefined;
126 /** RFC3339 creation timestamp. */
127 createTime: string | undefined;
128 /** RFC3339 last-update timestamp. */
129 updateTime: string | undefined;
130 /** Server-computed etag. */
131 etag: string | undefined;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * A domain name linked to a Firebase App Hosting backend. Default
139 * domains are created with the backend; this resource manages custom
140 * domains.
141 *
142 * Changing `domainId`, `backend`, or `location` replaces the domain.
143 * Serving behavior, display name, disabled, labels, and annotations
144 * update in place.
145 *
146 * ### Creating a Domain
147 * **Example:** Custom domain
148 * ```typescript
149 * const domain = yield* GCP.FirebaseAppHosting.BackendsDomain("Www", {
150 * backend: backend.name,
151 * domainId: "www.example.com",
152 * labels: { env: "test" },
153 * });
154 * ```
155 *
156 * **Example:** Redirect
157 * ```typescript
158 * const domain = yield* GCP.FirebaseAppHosting.BackendsDomain("Apex", {
159 * backend: backend.name,
160 * domainId: "example.com",
161 * serve: { redirect: { uri: "https://www.example.com", status: "301" } },
162 * });
163 * ```
164 *
165 * ### Updating a Domain
166 * **Example:** Disable and relabel
167 * ```typescript
168 * const domain = yield* GCP.FirebaseAppHosting.BackendsDomain("Www", {
169 * domainId: "www.example.com",
170 * backend: backend.name,
171 * disabled: true,
172 * labels: { env: "prod" },
173 * });
174 * ```
175 *
176 * @resource
177 * @category FirebaseAppHosting
178 */
179 export const BackendsDomain = Resource<BackendsDomain>("GCP.FirebaseAppHosting.BackendsDomain");
180
181 const resourceName = (backend: string, domainId: string) => `${backend}/domains/${domainId}`;
182
183 const toServe = (
184 value: firebaseapphosting.ServingBehavior | undefined,
185 ): ServingBehavior | undefined =>
186 value === undefined
187 ? undefined
188 : {
189 redirect: value.redirect
190 ? { uri: value.redirect.uri, status: value.redirect.status }
191 : undefined,
192 };
193
194 const toAttrs = (item: firebaseapphosting.Domain, project: string) => {
195 const name = item.name ?? "";
196 const parsed = parseName(name, "domains");
197 return {
198 name,
199 domainId: parsed.id,
200 backend: parsed.parent,
201 project: parsed.project || project,
202 location: parsed.location,
203 serve: toServe(item.serve),
204 displayName: item.displayName,
205 disabled: item.disabled === true,
206 type: item.type,
207 customDomainStatus: item.customDomainStatus,
208 reconciling: item.reconciling === true,
209 annotations: stringMap(item.annotations),
210 labels: userLabels(item.labels),
211 uid: item.uid,
212 createTime: item.createTime,
213 updateTime: item.updateTime,
214 etag: item.etag,
215 };
216 };
217
218 const getByName = (name: string) =>
219 firebaseapphosting
220 .getProjectsLocationsBackendsDomains({ name })
221 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
222
223 const listOwned = (project: string) =>
224 listAtNested(project, "backends/-", (parent) =>
225 listLabeledPages(
226 firebaseapphosting.listProjectsLocationsBackendsDomains.pages({
227 parent,
228 pageSize: 1000,
229 }),
230 (page) => page.domains,
231 (item) => item.labels,
232 ),
233 );
234
235 export const BackendsDomainProvider = () =>
236 Provider.succeed(BackendsDomain, {
237 stables: ["name", "domainId", "backend", "project", "location", "uid", "createTime"],
238
239 diff: Effect.fn(function* ({ news, olds, output }) {
240 if (!isResolved(news)) return undefined;
241 const env = yield* GcpEnvironment.current;
242 const location = normalizeLocation(
243 news.location ?? olds?.location ?? output?.location,
244 env.region,
245 );
246 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
247 const previousParent =
248 (olds?.backend ?? output?.backend)
249 ? expandParent(
250 olds?.backend ?? output?.backend ?? "",
251 env.project,
252 previousLocation,
253 "backends",
254 )
255 : undefined;
256 const nextParent = expandParent(news.backend, env.project, location, "backends");
257 return replaceOnIdentity({
258 previousId: olds?.domainId ?? output?.domainId,
259 nextId: news.domainId ?? olds?.domainId ?? output?.domainId,
260 previousLocation,
261 nextLocation: location,
262 previousParent,
263 nextParent,
264 });
265 }),
266
267 read: Effect.fn(function* ({ id, olds, output }) {
268 const env = yield* GcpEnvironment.current;
269 const domainId = yield* toDomainId(id, olds?.domainId, output?.domainId);
270 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
271 const backend =
272 output?.backend ??
273 (olds?.backend ? expandParent(olds.backend, env.project, location, "backends") : undefined);
274 const name = output?.name ?? (backend ? resourceName(backend, domainId) : undefined);
275 if (name === undefined) return undefined;
276 const existing = yield* getByName(name);
277 if (existing === undefined) return undefined;
278 const attrs = toAttrs(existing, env.project);
279 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
280 }),
281
282 list: () =>
283 Effect.gen(function* () {
284 const env = yield* GcpEnvironment.current;
285 const items = yield* listOwned(env.project);
286 return items.map((item) => toAttrs(item, env.project));
287 }),
288
289 reconcile: Effect.fn(function* ({ id, news, output }) {
290 const env = yield* GcpEnvironment.current;
291 const domainId = yield* toDomainId(id, news.domainId, output?.domainId);
292 const location = normalizeLocation(news.location ?? output?.location, env.region);
293 const backend = expandParent(news.backend, env.project, location, "backends");
294 const name = resourceName(backend, domainId);
295 const desiredLabels = {
296 ...toLabels(news.labels),
297 ...(yield* createInternalLabels(id)),
298 };
299 const desiredAnnotations = news.annotations ?? {};
300 const desiredDisabled = news.disabled === true;
301
302 let current = yield* getByName(output?.name ?? name);
303
304 if (current === undefined) {
305 const created = yield* firebaseapphosting
306 .createProjectsLocationsBackendsDomains({
307 parent: backend,
308 domainId,
309 body: {
310 serve: news.serve,
311 displayName: news.displayName,
312 disabled: desiredDisabled,
313 annotations: desiredAnnotations,
314 labels: desiredLabels,
315 },
316 })
317 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
318 if (created !== undefined) {
319 yield* waitForOperation(created);
320 }
321 current = yield* waitUntilExists(getByName(name), name);
322 }
323
324 if (current === undefined) {
325 return yield* new ResourceNotResolved({ resourceName: name });
326 }
327
328 const observedLabels = tagRecord(current.labels);
329 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
330 const mask = fieldMask([
331 (upsert.length > 0 || removed.length > 0) && "labels",
332 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
333 "annotations",
334 !sameText(current.displayName, news.displayName) && "displayName",
335 !sameBool(current.disabled, desiredDisabled) && "disabled",
336 fingerprint(toServe(current.serve)) !== fingerprint(news.serve) && "serve",
337 ]);
338
339 if (mask.length > 0) {
340 const operation = yield* firebaseapphosting.patchProjectsLocationsBackendsDomains({
341 name: current.name ?? name,
342 updateMask: mask,
343 body: {
344 etag: current.etag,
345 serve: news.serve,
346 displayName: news.displayName,
347 disabled: desiredDisabled,
348 annotations: desiredAnnotations,
349 labels: desiredLabels,
350 },
351 });
352 yield* waitForOperation(operation);
353 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
354 }
355
356 return toAttrs(current, env.project);
357 }),
358
359 delete: Effect.fn(function* ({ output }) {
360 const operation = yield* firebaseapphosting
361 .deleteProjectsLocationsBackendsDomains({
362 name: output.name,
363 })
364 .pipe(
365 Effect.retry({
366 while: (error) => error._tag === "Conflict",
367 times: 8,
368 schedule: Schedule.spaced("2 seconds"),
369 }),
370 Effect.catchTag("NotFound", () => Effect.undefined),
371 );
372 if (operation !== undefined) {
373 yield* waitForDeleteOperation(operation);
374 }
375 yield* waitUntilGone(getByName(output.name), output.name);
376 }),
377 });