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

main
ts 435 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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { ignoredCodes } from "./internal.ts";
15 import { waitRegionOperation } from "./operations.ts";
16
17 const MAX_NAME_LENGTH = 63;
18
19 export type NetworkEdgeSecurityServiceProps = {
20 /**
21 * Service name (RFC1035, 1-63 characters). If omitted, a unique name is
22 * generated from the stack, stage, and logical id. Immutable — changing
23 * it replaces the service.
24 */
25 networkEdgeSecurityServiceName?: string;
26 /**
27 * Region the service lives in. Immutable — changing it replaces the
28 * service. `US-CENTRAL1` is accepted and normalized to `us-central1`.
29 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
30 */
31 region?: string;
32 /**
33 * Optional description. Network edge security services have no labels
34 * field, so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
35 * `alchemy-id`) is stored in a `[alchemy …]` prefix for `list` / nuke.
36 * Updated in place via `patch`.
37 */
38 description?: string;
39 /**
40 * Cloud Armor network security policy URL attached to this service.
41 * Updated in place via `patch`.
42 */
43 securityPolicy?: string;
44 };
45
46 export type NetworkEdgeSecurityService = Resource<
47 "GCP.Compute.NetworkEdgeSecurityService",
48 NetworkEdgeSecurityServiceProps,
49 {
50 /** Service name. */
51 networkEdgeSecurityServiceName: string;
52 /** Project id. */
53 project: string;
54 /** Region short name (`us-central1`). */
55 region: string;
56 /** User description with the Alchemy ownership prefix stripped. */
57 description: string | undefined;
58 /** Attached Cloud Armor network security policy URL. */
59 securityPolicy: string | undefined;
60 /** Optimistic-locking fingerprint. */
61 fingerprint: string | undefined;
62 /** Server-assigned numeric id. */
63 networkEdgeSecurityServiceId: string | undefined;
64 /** Resource self-link. */
65 selfLink: string | undefined;
66 /** Self-link including the numeric id. */
67 selfLinkWithId: string | undefined;
68 /** RFC3339 creation timestamp. */
69 creationTimestamp: string | undefined;
70 /** Resource kind. */
71 kind: string | undefined;
72 },
73 never,
74 Providers
75 >;
76
77 /**
78 * A regional Compute Engine network edge security service.
79 *
80 * Network edge security services attach a Cloud Armor network (L3/L4)
81 * security policy to a region. Name and region are immutable. Description
82 * and `securityPolicy` update in place via
83 * `networkEdgeSecurityServices.patch`. Compute NetworkEdgeSecurityService
84 * has no labels field — Alchemy stamps ownership into the description so
85 * nuke can find leaked services.
86 *
87 * ### Creating a Network Edge Security Service
88 * **Example:** Generated name
89 * ```typescript
90 * const ness = yield* GCP.Compute.NetworkEdgeSecurityService("EdgeArmor", {
91 * region: "us-central1",
92 * description: "regional network armor",
93 * });
94 * ```
95 *
96 * **Example:** Attach a network security policy
97 * ```typescript
98 * const ness = yield* GCP.Compute.NetworkEdgeSecurityService("EdgeArmor", {
99 * networkEdgeSecurityServiceName: "app-ness",
100 * securityPolicy: policy.selfLink,
101 * });
102 * ```
103 *
104 * @resource
105 * @category Compute
106 */
107 export const NetworkEdgeSecurityService = Resource<NetworkEdgeSecurityService>(
108 "GCP.Compute.NetworkEdgeSecurityService",
109 );
110
111 export class NetworkEdgeSecurityServiceNotResolved extends Data.TaggedError(
112 "GCP.Compute.NetworkEdgeSecurityServiceNotResolved",
113 )<{
114 networkEdgeSecurityServiceName: string;
115 region: string;
116 }> {}
117
118 export class NetworkEdgeSecurityServiceStillExists extends Data.TaggedError(
119 "GCP.Compute.NetworkEdgeSecurityServiceStillExists",
120 )<{
121 networkEdgeSecurityServiceName: string;
122 }> {}
123
124 const lastSegment = (value: string | undefined): string => {
125 if (value === undefined || value.length === 0) return "";
126 const trimmed = value.replace(/\/+$/, "");
127 const parts = trimmed.split("/");
128 return parts[parts.length - 1] || trimmed;
129 };
130
131 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
132 lastSegment(region ?? defaultRegion).toLowerCase();
133
134 const rfc1035 = (name: string): string => {
135 let next = name
136 .toLowerCase()
137 .replace(/[^a-z0-9-]/g, "-")
138 .replace(/-+/g, "-")
139 .replace(/^-+/, "")
140 .replace(/-+$/, "");
141 if (!/^[a-z]/.test(next)) next = `e${next}`;
142 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
143 return next.length > 0 ? next : "ness";
144 };
145
146 const toName = (id: string, name: string | undefined, existing?: string) =>
147 Effect.gen(function* () {
148 if (name !== undefined) return name;
149 if (existing !== undefined) return existing;
150 return rfc1035(
151 yield* createPhysicalName({
152 id,
153 maxLength: MAX_NAME_LENGTH,
154 lowercase: true,
155 }),
156 );
157 });
158
159 const encodeDescription = (
160 labels: Record<string, string>,
161 description: string | undefined,
162 ): string => {
163 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
164 return description ? `${marker}\n${description}` : marker;
165 };
166
167 const parseDescription = (
168 description: string | undefined,
169 ): {
170 labels: Record<string, string>;
171 description: string | undefined;
172 } => {
173 if (!description?.startsWith("[alchemy ")) {
174 return { labels: {}, description };
175 }
176 const end = description.indexOf("]");
177 if (end < 0) return { labels: {}, description };
178 const labels: Record<string, string> = {};
179 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
180 const eq = part.indexOf("=");
181 if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1);
182 }
183 const rest = description.slice(end + 1).replace(/^\n/, "");
184 return { labels, description: rest.length > 0 ? rest : undefined };
185 };
186
187 const hasOwnershipMarker = (description: string | undefined) =>
188 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
189
190 const toAttrs = (
191 service: compute.NetworkEdgeSecurityService,
192 project: string,
193 ): NetworkEdgeSecurityService["Attributes"] => {
194 const parsed = parseDescription(service.description);
195 return {
196 networkEdgeSecurityServiceName: service.name ?? "",
197 project,
198 region: lastSegment(service.region).toLowerCase(),
199 description: parsed.description,
200 securityPolicy: service.securityPolicy,
201 fingerprint: service.fingerprint,
202 networkEdgeSecurityServiceId: service.id,
203 selfLink: service.selfLink,
204 selfLinkWithId: service.selfLinkWithId,
205 creationTimestamp: service.creationTimestamp,
206 kind: service.kind,
207 };
208 };
209
210 const getByName = (project: string, region: string, networkEdgeSecurityService: string) =>
211 compute
212 .getNetworkEdgeSecurityServices({
213 project,
214 region,
215 networkEdgeSecurityService,
216 })
217 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
218
219 const awaitResource = (project: string, region: string, networkEdgeSecurityServiceName: string) =>
220 getByName(project, region, networkEdgeSecurityServiceName).pipe(
221 Effect.flatMap((service) =>
222 service !== undefined
223 ? Effect.succeed(service)
224 : Effect.fail(
225 new NetworkEdgeSecurityServiceNotResolved({
226 networkEdgeSecurityServiceName,
227 region,
228 }),
229 ),
230 ),
231 Effect.retry({
232 while: (error) => error._tag === "GCP.Compute.NetworkEdgeSecurityServiceNotResolved",
233 times: 8,
234 schedule: Schedule.spaced("1 second"),
235 }),
236 );
237
238 const waitUntilGone = (project: string, region: string, networkEdgeSecurityServiceName: string) =>
239 getByName(project, region, networkEdgeSecurityServiceName).pipe(
240 Effect.flatMap((service) =>
241 service === undefined
242 ? Effect.void
243 : Effect.fail(
244 new NetworkEdgeSecurityServiceStillExists({
245 networkEdgeSecurityServiceName,
246 }),
247 ),
248 ),
249 Effect.retry({
250 while: (error) => error._tag === "GCP.Compute.NetworkEdgeSecurityServiceStillExists",
251 times: 10,
252 schedule: Schedule.spaced("2 seconds"),
253 }),
254 Effect.catchTag("GCP.Compute.NetworkEdgeSecurityServiceStillExists", () => Effect.void),
255 );
256
257 const runOp = <E extends { readonly _tag: string }, R>(
258 project: string,
259 region: string,
260 networkEdgeSecurityServiceName: string,
261 start: Effect.Effect<compute.Operation, E, R>,
262 options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean },
263 ) =>
264 start.pipe(
265 Effect.flatMap((operation) =>
266 waitRegionOperation(project, region, operation, {
267 ignore: ignoredCodes(options),
268 }),
269 ),
270 Effect.retry({
271 while: (error) => error._tag === "Conflict",
272 times: 5,
273 schedule: Schedule.spaced("1 second"),
274 }),
275 );
276
277 export const NetworkEdgeSecurityServiceProvider = () =>
278 Provider.succeed(NetworkEdgeSecurityService, {
279 stables: [
280 "networkEdgeSecurityServiceName",
281 "project",
282 "region",
283 "networkEdgeSecurityServiceId",
284 "selfLink",
285 "selfLinkWithId",
286 "creationTimestamp",
287 ],
288
289 diff: Effect.fn(function* ({ news, olds, output }) {
290 if (!isResolved(news)) return undefined;
291 const env = yield* GcpEnvironment.current;
292 const previousName =
293 olds?.networkEdgeSecurityServiceName ?? output?.networkEdgeSecurityServiceName;
294 const nextName = news.networkEdgeSecurityServiceName ?? previousName;
295 const nameChanged =
296 previousName !== undefined && nextName !== undefined && previousName !== nextName;
297 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
298 const nextRegion = normalizeRegion(news.region ?? previousRegion, env.region);
299 if (nameChanged) {
300 return { action: "replace" as const, deleteFirst: false };
301 }
302 if (previousRegion !== nextRegion) {
303 return { action: "replace" as const, deleteFirst: true };
304 }
305 return undefined;
306 }),
307
308 read: Effect.fn(function* ({ id, olds, output, previous }) {
309 const env = yield* GcpEnvironment.current;
310 const networkEdgeSecurityServiceName = yield* toName(
311 id,
312 olds?.networkEdgeSecurityServiceName,
313 output?.networkEdgeSecurityServiceName,
314 );
315 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
316 const existing = yield* getByName(env.project, region, networkEdgeSecurityServiceName);
317 if (existing === undefined) return undefined;
318 const attrs = toAttrs(existing, env.project);
319 const { labels } = parseDescription(existing.description);
320 return (yield* hasAlchemyLabels(id, labels))
321 ? attrs
322 : unownedUnlessPrevious(attrs, previous, "networkEdgeSecurityServiceName");
323 }),
324
325 list: () =>
326 Effect.gen(function* () {
327 const env = yield* GcpEnvironment.current;
328 const pages = yield* compute.aggregatedListNetworkEdgeSecurityServices
329 .pages({
330 project: env.project,
331 returnPartialSuccess: true,
332 maxResults: 500,
333 })
334 .pipe(Stream.runCollect);
335 return Array.from(pages).flatMap((page) =>
336 Object.values(page.items ?? {}).flatMap((scoped) =>
337 (scoped?.networkEdgeSecurityServices ?? [])
338 .filter((item) => hasOwnershipMarker(item.description))
339 .map((item) => toAttrs(item, env.project)),
340 ),
341 );
342 }),
343
344 reconcile: Effect.fn(function* ({ id, news, output }) {
345 const env = yield* GcpEnvironment.current;
346 const networkEdgeSecurityServiceName = yield* toName(
347 id,
348 news.networkEdgeSecurityServiceName,
349 output?.networkEdgeSecurityServiceName,
350 );
351 const region = normalizeRegion(news.region ?? output?.region, env.region);
352 const ownership = yield* createInternalLabels(id);
353 const desiredDescription = encodeDescription(ownership, news.description);
354
355 let current = yield* getByName(env.project, region, networkEdgeSecurityServiceName);
356
357 if (current === undefined) {
358 yield* compute
359 .insertNetworkEdgeSecurityServices({
360 project: env.project,
361 region,
362 body: {
363 name: networkEdgeSecurityServiceName,
364 description: desiredDescription,
365 securityPolicy: news.securityPolicy,
366 },
367 })
368 .pipe(
369 Effect.flatMap((operation) =>
370 waitRegionOperation(env.project, region, operation, {
371 ignore: ["RESOURCE_ALREADY_EXISTS"],
372 }),
373 ),
374 Effect.catchTag("Conflict", () => Effect.void),
375 );
376 current = yield* awaitResource(env.project, region, networkEdgeSecurityServiceName);
377 }
378
379 const needsPatch =
380 (current.description ?? "") !== desiredDescription ||
381 (news.securityPolicy !== undefined &&
382 lastSegment(current.securityPolicy) !== lastSegment(news.securityPolicy));
383
384 if (needsPatch) {
385 const latest =
386 (yield* getByName(env.project, region, networkEdgeSecurityServiceName)) ?? current;
387 yield* runOp(
388 env.project,
389 region,
390 networkEdgeSecurityServiceName,
391 compute.patchNetworkEdgeSecurityServices({
392 project: env.project,
393 region,
394 networkEdgeSecurityService: networkEdgeSecurityServiceName,
395 body: {
396 fingerprint: latest.fingerprint,
397 description: desiredDescription,
398 securityPolicy: news.securityPolicy ?? current.securityPolicy,
399 },
400 }),
401 );
402 current =
403 (yield* getByName(env.project, region, networkEdgeSecurityServiceName)) ?? current;
404 }
405
406 return toAttrs(current, env.project);
407 }),
408
409 delete: Effect.fn(function* ({ output }) {
410 if (!output.networkEdgeSecurityServiceName) return;
411 const env = yield* GcpEnvironment.current;
412 const project = output.project || env.project;
413 const region = normalizeRegion(output.region, env.region);
414 yield* compute
415 .deleteNetworkEdgeSecurityServices({
416 project,
417 region,
418 networkEdgeSecurityService: output.networkEdgeSecurityServiceName,
419 })
420 .pipe(
421 Effect.flatMap((operation) =>
422 waitRegionOperation(project, region, operation, {
423 ignore: ["RESOURCE_NOT_FOUND"],
424 }),
425 ),
426 Effect.catchTag("NotFound", () => Effect.void),
427 Effect.retry({
428 while: (error) => error._tag === "Conflict",
429 times: 8,
430 schedule: Schedule.spaced("2 seconds"),
431 }),
432 );
433 yield* waitUntilGone(project, region, output.networkEdgeSecurityServiceName);
434 }),
435 });