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

main
ts 431 lines 15.1 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import { waitRegionOperation } from "./operations.ts";
14
15 export type RegionUrlMapProps = {
16 /**
17 * UrlMap name (RFC1035, 1-63 characters). If omitted, a unique name is
18 * generated from the stack, stage, and logical id. Changing it replaces
19 * the resource.
20 */
21 urlMapName?: string;
22 /**
23 * Region the URL map lives in (e.g. `us-central1`). Immutable —
24 * changing it replaces the resource. `US-CENTRAL1` is accepted and
25 * normalized to `us-central1`.
26 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
27 */
28 region?: string;
29 /**
30 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
31 * prefix so `list` / nuke can find resources (Compute RegionUrlMap has
32 * no labels field).
33 */
34 description?: string;
35 /**
36 * Default regional backend service URL used when no host rule matches.
37 * Mutually exclusive with `defaultUrlRedirect` and
38 * `defaultRouteAction.weightedBackendServices`.
39 */
40 defaultService?: string;
41 /**
42 * Redirect used when no host rule matches. Mutually exclusive with
43 * `defaultService`.
44 */
45 defaultUrlRedirect?: compute.HttpRedirectAction;
46 /**
47 * Advanced routing used when no host rule matches. Mutually exclusive
48 * with `defaultService` / `defaultUrlRedirect` when
49 * `weightedBackendServices` is set.
50 */
51 defaultRouteAction?: compute.HttpRouteAction;
52 /**
53 * Host-matching rules that select a named path matcher.
54 */
55 hostRules?: compute.HostRule[];
56 /**
57 * Named path matchers referenced by `hostRules`.
58 */
59 pathMatchers?: compute.PathMatcher[];
60 /**
61 * Optional header transformations applied after path-matcher headers.
62 */
63 headerAction?: compute.HttpHeaderAction;
64 /**
65 * UrlMap tests that must pass before an update is accepted (max 100).
66 */
67 tests?: compute.UrlMapTest[];
68 };
69
70 export type RegionUrlMap = Resource<
71 "GCP.Compute.RegionUrlMap",
72 RegionUrlMapProps,
73 {
74 /** UrlMap name. */
75 urlMapName: string;
76 /** Project id. */
77 project: string;
78 /** Region short name (`us-central1`). */
79 region: string;
80 /** User description with the Alchemy ownership prefix stripped. */
81 description: string | undefined;
82 /** Default regional backend service URL. */
83 defaultService: string | undefined;
84 /** Default redirect, if configured. */
85 defaultUrlRedirect: compute.HttpRedirectAction | undefined;
86 /** Default route action, if configured. */
87 defaultRouteAction: compute.HttpRouteAction | undefined;
88 /** Host-matching rules. */
89 hostRules: compute.HostRule[];
90 /** Named path matchers. */
91 pathMatchers: compute.PathMatcher[];
92 /** Header transformations, if configured. */
93 headerAction: compute.HttpHeaderAction | undefined;
94 /** UrlMap tests. */
95 tests: compute.UrlMapTest[];
96 /** Server-defined URL. */
97 selfLink: string | undefined;
98 /** Server-assigned numeric id. */
99 urlMapId: string | undefined;
100 /** Optimistic-locking fingerprint. */
101 fingerprint: string | undefined;
102 /** RFC3339 creation timestamp. */
103 creationTimestamp: string | undefined;
104 /** Resource kind. */
105 kind: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A regional Compute Engine URL map.
113 *
114 * Regional URL maps route hostnames and URL paths to a regional backend
115 * service or HTTP redirect. They back internal Application Load Balancers
116 * and regional external / internal Application Load Balancers. This
117 * resource maps to the `regionUrlMaps` collection (the global `urlMaps`
118 * collection is `GCP.Compute.UrlMap`). Compute RegionUrlMap has no labels
119 * field — Alchemy ownership is stored in the description so nuke can find
120 * leaked maps.
121 *
122 * One of `defaultService`, `defaultUrlRedirect`, or
123 * `defaultRouteAction.weightedBackendServices` is required.
124 *
125 * ### Creating a Regional URL Map
126 * **Example:** Generated name with a default HTTPS redirect
127 * ```typescript
128 * const map = yield* GCP.Compute.RegionUrlMap("web", {
129 * region: "us-central1",
130 * defaultUrlRedirect: {
131 * httpsRedirect: true,
132 * hostRedirect: "example.com",
133 * stripQuery: false,
134 * },
135 * });
136 * ```
137 *
138 * **Example:** Host rules and path matchers
139 * ```typescript
140 * const map = yield* GCP.Compute.RegionUrlMap("web", {
141 * description: "public https",
142 * defaultUrlRedirect: {
143 * httpsRedirect: true,
144 * stripQuery: false,
145 * },
146 * hostRules: [{ hosts: ["example.com"], pathMatcher: "all" }],
147 * pathMatchers: [
148 * {
149 * name: "all",
150 * defaultUrlRedirect: {
151 * httpsRedirect: true,
152 * hostRedirect: "www.example.com",
153 * stripQuery: false,
154 * },
155 * },
156 * ],
157 * });
158 * ```
159 *
160 * **Example:** Default regional backend service
161 * ```typescript
162 * const map = yield* GCP.Compute.RegionUrlMap("web", {
163 * defaultService: backend.selfLink,
164 * });
165 * ```
166 *
167 * @resource
168 * @category Compute
169 */
170 export const RegionUrlMap = Resource<RegionUrlMap>("GCP.Compute.RegionUrlMap");
171
172 export class RegionUrlMapNotResolved extends Data.TaggedError(
173 "GCP.Compute.RegionUrlMapNotResolved",
174 )<{
175 urlMapName: string;
176 region: string;
177 }> {}
178
179 const lastSegment = (value: string) => {
180 const trimmed = value.replace(/\/+$/, "");
181 const parts = trimmed.split("/");
182 return parts[parts.length - 1] || trimmed;
183 };
184
185 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
186 lastSegment(region ?? defaultRegion).toLowerCase();
187
188 const toName = (id: string, name: string | undefined, existing?: string) =>
189 Effect.gen(function* () {
190 if (name !== undefined) return name;
191 if (existing !== undefined) return existing;
192 const generated = yield* createPhysicalName({
193 id,
194 maxLength: 63,
195 lowercase: true,
196 });
197 return /^[a-z]/.test(generated) ? generated : `u${generated}`.slice(0, 63);
198 });
199
200 const encodeDescription = (
201 labels: Record<string, string>,
202 description: string | undefined,
203 ): string => {
204 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
205 return description ? `${marker}\n${description}` : marker;
206 };
207
208 const parseDescription = (
209 description: string | undefined,
210 ): {
211 labels: Record<string, string>;
212 description: string | undefined;
213 } => {
214 if (!description?.startsWith("[alchemy ")) {
215 return { labels: {}, description };
216 }
217 const end = description.indexOf("]");
218 if (end < 0) return { labels: {}, description };
219 const labels: Record<string, string> = {};
220 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
221 const eq = part.indexOf("=");
222 if (eq > 0) {
223 labels[part.slice(0, eq)] = part.slice(eq + 1);
224 }
225 }
226 const rest = description.slice(end + 1).replace(/^\n/, "");
227 return { labels, description: rest.length > 0 ? rest : undefined };
228 };
229
230 const hasOwnershipMarker = (description: string | undefined) =>
231 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
232
233 const toBody = (
234 urlMapName: string,
235 props: RegionUrlMapProps,
236 ownership: Record<string, string>,
237 fingerprint?: string,
238 ): compute.UrlMap => ({
239 name: urlMapName,
240 fingerprint,
241 description: encodeDescription(ownership, props.description),
242 defaultService: props.defaultService,
243 defaultUrlRedirect: props.defaultUrlRedirect,
244 defaultRouteAction: props.defaultRouteAction,
245 hostRules: props.hostRules,
246 pathMatchers: props.pathMatchers,
247 headerAction: props.headerAction,
248 tests: props.tests,
249 });
250
251 const toAttrs = (urlMap: compute.UrlMap, project: string) => {
252 const parsed = parseDescription(urlMap.description);
253 return {
254 urlMapName: urlMap.name ?? urlMap.id ?? "",
255 project,
256 region: lastSegment(urlMap.region ?? "").toLowerCase(),
257 description: parsed.description,
258 defaultService: urlMap.defaultService,
259 defaultUrlRedirect: urlMap.defaultUrlRedirect,
260 defaultRouteAction: urlMap.defaultRouteAction,
261 hostRules: urlMap.hostRules ?? [],
262 pathMatchers: urlMap.pathMatchers ?? [],
263 headerAction: urlMap.headerAction,
264 tests: urlMap.tests ?? [],
265 selfLink: urlMap.selfLink,
266 urlMapId: urlMap.id,
267 fingerprint: urlMap.fingerprint,
268 creationTimestamp: urlMap.creationTimestamp,
269 kind: urlMap.kind,
270 };
271 };
272
273 const isEmpty = (value: unknown): boolean =>
274 value === undefined || value === null || (Array.isArray(value) && value.length === 0);
275
276 const subsetEqual = (observed: unknown, desired: unknown): boolean => {
277 if (desired === undefined || desired === null) return isEmpty(observed);
278 if (Array.isArray(desired)) {
279 if (!Array.isArray(observed) || observed.length !== desired.length) {
280 return false;
281 }
282 return desired.every((item, index) => subsetEqual(observed[index], item));
283 }
284 if (typeof desired === "object") {
285 if (observed === undefined || observed === null || typeof observed !== "object") {
286 return false;
287 }
288 const current = observed as Record<string, unknown>;
289 for (const [key, value] of Object.entries(desired as Record<string, unknown>)) {
290 if (value === undefined) continue;
291 if (!subsetEqual(current[key], value)) return false;
292 }
293 return true;
294 }
295 return observed === desired;
296 };
297
298 const needsUpdate = (current: compute.UrlMap, desired: compute.UrlMap) =>
299 (current.description ?? "") !== (desired.description ?? "") ||
300 !subsetEqual(current.defaultService, desired.defaultService) ||
301 !subsetEqual(current.defaultUrlRedirect, desired.defaultUrlRedirect) ||
302 !subsetEqual(current.defaultRouteAction, desired.defaultRouteAction) ||
303 !subsetEqual(current.hostRules, desired.hostRules) ||
304 !subsetEqual(current.pathMatchers, desired.pathMatchers) ||
305 !subsetEqual(current.headerAction, desired.headerAction) ||
306 !subsetEqual(current.tests, desired.tests);
307
308 const getByName = (project: string, region: string, urlMap: string) =>
309 compute
310 .getRegionUrlMaps({ project, region, urlMap })
311 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
312
313 export const RegionUrlMapProvider = () =>
314 Provider.succeed(RegionUrlMap, {
315 stables: ["urlMapName", "project", "region", "urlMapId", "selfLink", "creationTimestamp"],
316
317 diff: Effect.fn(function* ({ news, olds, output }) {
318 if (!isResolved(news)) return undefined;
319 const env = yield* GcpEnvironment.current;
320 const previousName = olds?.urlMapName ?? output?.urlMapName;
321 const nextName = news.urlMapName ?? previousName;
322 const nameChanged =
323 previousName !== undefined && nextName !== undefined && previousName !== nextName;
324 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
325 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
326 const regionChanged = previousRegion !== nextRegion;
327 if (nameChanged || regionChanged) {
328 return { action: "replace" as const, deleteFirst: true };
329 }
330 return undefined;
331 }),
332
333 read: Effect.fn(function* ({ id, olds, output, previous }) {
334 const env = yield* GcpEnvironment.current;
335 const urlMapName = yield* toName(id, olds?.urlMapName, output?.urlMapName);
336 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
337 const existing = yield* getByName(env.project, region, urlMapName);
338 if (existing === undefined) return undefined;
339 const attrs = toAttrs(existing, env.project);
340 const { labels } = parseDescription(existing.description);
341 return (yield* hasAlchemyLabels(id, labels))
342 ? attrs
343 : unownedUnlessPrevious(attrs, previous, "urlMapName");
344 }),
345
346 list: () =>
347 Effect.gen(function* () {
348 const env = yield* GcpEnvironment.current;
349 const pages = yield* compute.aggregatedListUrlMaps
350 .pages({
351 project: env.project,
352 returnPartialSuccess: true,
353 maxResults: 500,
354 })
355 .pipe(Stream.runCollect);
356 return Array.from(pages).flatMap((page) =>
357 Object.values(page.items ?? {}).flatMap((scoped) =>
358 (scoped?.urlMaps ?? [])
359 .filter((urlMap) => (urlMap.region ?? "").length > 0)
360 .filter((urlMap) => hasOwnershipMarker(urlMap.description))
361 .map((urlMap) => toAttrs(urlMap, env.project)),
362 ),
363 );
364 }),
365
366 reconcile: Effect.fn(function* ({ id, news, output }) {
367 const env = yield* GcpEnvironment.current;
368 const urlMapName = yield* toName(id, news.urlMapName, output?.urlMapName);
369 const region = normalizeRegion(news.region ?? output?.region, env.region);
370 const ownership = yield* createInternalLabels(id);
371 const desired = toBody(urlMapName, news, ownership);
372
373 let current = yield* getByName(env.project, region, urlMapName);
374
375 if (current === undefined) {
376 yield* compute
377 .insertRegionUrlMaps({
378 project: env.project,
379 region,
380 body: desired,
381 })
382 .pipe(
383 Effect.flatMap((operation) =>
384 waitRegionOperation(env.project, region, operation, {
385 ignore: ["RESOURCE_ALREADY_EXISTS"],
386 }),
387 ),
388 Effect.catchTag("Conflict", () => Effect.undefined),
389 );
390 current = yield* getByName(env.project, region, urlMapName);
391 }
392
393 if (current === undefined) {
394 return yield* new RegionUrlMapNotResolved({ urlMapName, region });
395 }
396
397 if (needsUpdate(current, desired)) {
398 yield* compute
399 .updateRegionUrlMaps({
400 project: env.project,
401 region,
402 urlMap: urlMapName,
403 body: toBody(urlMapName, news, ownership, current.fingerprint),
404 })
405 .pipe(Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)));
406 current = yield* getByName(env.project, region, urlMapName);
407 if (current === undefined) {
408 return yield* new RegionUrlMapNotResolved({ urlMapName, region });
409 }
410 }
411
412 return toAttrs(current, env.project);
413 }),
414
415 delete: Effect.fn(function* ({ output }) {
416 const env = yield* GcpEnvironment.current;
417 const region = normalizeRegion(output.region, env.region);
418 const operation = yield* compute
419 .deleteRegionUrlMaps({
420 project: env.project,
421 region,
422 urlMap: output.urlMapName,
423 })
424 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
425 if (operation !== undefined) {
426 yield* waitRegionOperation(env.project, region, operation).pipe(
427 Effect.catchTag("NotFound", () => Effect.void),
428 );
429 }
430 }),
431 });