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

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