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

main
ts 582 lines 21 KB
Raw
1 import * as vpcaccess from "@distilled.cloud/gcp/vpcaccess_v1";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const DEFAULT_NETWORK = "default";
15 const DEFAULT_MACHINE_TYPE = "e2-micro";
16 const MAX_NAME_LENGTH = 25;
17
18 export type ConnectorSubnet = {
19 /**
20 * Subnet name (relative, not a full URL). For
21 * `.../regions/{region}/subnetworks/{subnetName}` pass `{subnetName}`.
22 */
23 name: string;
24 /**
25 * Project that owns the subnet. Defaults to the connector's project.
26 */
27 projectId?: string;
28 };
29
30 export type ConnectorProps = {
31 /**
32 * Connector id (the `{connector}` segment of
33 * `projects/{project}/locations/{location}/connectors/{connector}`).
34 * If omitted, a unique RFC1035 name is generated from the stack, stage,
35 * and logical id. Must be 1-25 characters and match
36 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Immutable — changing it replaces the
37 * connector.
38 */
39 connectorId?: string;
40 /**
41 * Region of the connector (`us-central1`, …). Immutable — changing it
42 * replaces the connector. `US-CENTRAL1` is accepted and normalized to
43 * `us-central1`.
44 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * VPC network name or URL to house the connector. Used with
49 * `ipCidrRange` to create an `aet-*` `/28` subnet. Ignored when
50 * `subnet` is set. Immutable — changing it replaces the connector.
51 * @default "default"
52 */
53 network?: string;
54 /**
55 * Unused `/28` CIDR (RFC 4632, e.g. `"10.8.0.0/28"`) used when the
56 * connector creates its own subnet in `network`. Required unless
57 * `subnet` is set. Immutable — changing it replaces the connector.
58 */
59 ipCidrRange?: string;
60 /**
61 * Existing subnet to house the connector (Shared VPC or a subnet you
62 * manage). Immutable — changing it replaces the connector. When set,
63 * `network` and `ipCidrRange` are not sent.
64 */
65 subnet?: ConnectorSubnet;
66 /**
67 * Machine type of the underlying VMs (`e2-micro`, `e2-standard-4`,
68 * `f1-micro`).
69 * @default "e2-micro"
70 */
71 machineType?: string;
72 /**
73 * Minimum instances in the connector's autoscaling group (2–9). Takes
74 * precedence over `minThroughput`. Prefer this over throughput.
75 */
76 minInstances?: number;
77 /**
78 * Maximum instances in the connector's autoscaling group (3–10). Takes
79 * precedence over `maxThroughput`. Prefer this over throughput.
80 */
81 maxInstances?: number;
82 /**
83 * Minimum throughput in Mbps for `e2-micro` (multiple of 100, 200–900).
84 * Discouraged — use `minInstances`.
85 */
86 minThroughput?: number;
87 /**
88 * Maximum throughput in Mbps for `e2-micro` (multiple of 100, 300–1000).
89 * Discouraged — use `maxInstances`.
90 */
91 maxThroughput?: number;
92 };
93
94 export type Connector = Resource<
95 "GCP.VpcAccess.Connector",
96 ConnectorProps,
97 {
98 /** Full resource name `projects/{project}/locations/{location}/connectors/{connector}`. */
99 name: string;
100 /** Connector id (last path segment). */
101 connectorId: string;
102 /** Project id. */
103 project: string;
104 /** Location id (`us-central1`). */
105 location: string;
106 /** VPC network name, if the connector created its own subnet. */
107 network: string | undefined;
108 /** `/28` CIDR used when the connector created its own subnet. */
109 ipCidrRange: string | undefined;
110 /** Existing subnet the connector is attached to, if any. */
111 subnet: ConnectorSubnet | undefined;
112 /** Machine type of the underlying VMs. */
113 machineType: string | undefined;
114 /** Minimum instances. */
115 minInstances: number | undefined;
116 /** Maximum instances. */
117 maxInstances: number | undefined;
118 /** Minimum throughput in Mbps. */
119 minThroughput: number | undefined;
120 /** Maximum throughput in Mbps. */
121 maxThroughput: number | undefined;
122 /** Server-reported state (`READY`, `CREATING`, …). */
123 state: string | undefined;
124 /** Projects currently using the connector. */
125 connectedProjects: ReadonlyArray<string>;
126 },
127 never,
128 Providers
129 >;
130
131 /**
132 * A Serverless VPC Access connector.
133 *
134 * Connectors let Cloud Run, Cloud Functions, and App Engine reach resources
135 * in a VPC. The API has no labels or description field — Alchemy treats
136 * existence at the computed name as ownership, and `list` returns every
137 * connector in the project so `pnpm nuke:gcp` can still clean leaks.
138 *
139 * `connectorId`, `location`, `network`, `ipCidrRange`, and `subnet` are
140 * immutable. `machineType` and min/max instances (or throughput) update
141 * in place.
142 *
143 * ### Creating a Connector
144 * **Example:** Generated name on the default VPC
145 * ```typescript
146 * const connector = yield* GCP.VpcAccess.Connector("Egress", {
147 * ipCidrRange: "10.8.0.0/28",
148 * minInstances: 2,
149 * maxInstances: 3,
150 * });
151 * ```
152 *
153 * **Example:** Explicit id, machine type, and scaling
154 * ```typescript
155 * const connector = yield* GCP.VpcAccess.Connector("Egress", {
156 * connectorId: "app-egress",
157 * location: "us-central1",
158 * network: "default",
159 * ipCidrRange: "10.8.0.0/28",
160 * machineType: "e2-micro",
161 * minInstances: 2,
162 * maxInstances: 4,
163 * });
164 * ```
165 *
166 * ### Existing subnet
167 * **Example:** Attach to a subnet you manage
168 * ```typescript
169 * const connector = yield* GCP.VpcAccess.Connector("Egress", {
170 * subnet: { name: subnet.subnetworkName },
171 * minInstances: 2,
172 * maxInstances: 3,
173 * });
174 * ```
175 *
176 * @resource
177 * @category VpcAccess
178 */
179 export const Connector = Resource<Connector>("GCP.VpcAccess.Connector");
180
181 export class ConnectorNotResolved extends Data.TaggedError("GCP.VpcAccess.ConnectorNotResolved")<{
182 resourceName: string;
183 }> {}
184
185 export class ConnectorRangeMissing extends Data.TaggedError("GCP.VpcAccess.ConnectorRangeMissing")<{
186 resourceName: string;
187 message: string;
188 }> {}
189
190 export class ConnectorFailed extends Data.TaggedError("GCP.VpcAccess.ConnectorFailed")<{
191 resourceName: string;
192 state: string | undefined;
193 }> {}
194
195 export class ConnectorNotReady extends Data.TaggedError("GCP.VpcAccess.ConnectorNotReady")<{
196 resourceName: string;
197 state: string | undefined;
198 }> {}
199
200 export class ConnectorStillExists extends Data.TaggedError("GCP.VpcAccess.ConnectorStillExists")<{
201 resourceName: string;
202 }> {}
203
204 const lastSegment = (value: string) => {
205 const trimmed = value.replace(/\/+$/, "");
206 const parts = trimmed.split("/");
207 return parts[parts.length - 1] || trimmed;
208 };
209
210 const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
211 lastSegment(location ?? defaultLocation).toLowerCase();
212
213 const linkKey = (value: string | undefined) =>
214 value === undefined || value === "" ? "" : lastSegment(value).toLowerCase();
215
216 const subnetKey = (subnet: ConnectorSubnet | undefined) => {
217 if (subnet === undefined) return "";
218 return `${linkKey(subnet.name)}:${(subnet.projectId ?? "").toLowerCase()}`;
219 };
220
221 const resourceName = (project: string, location: string, connectorId: string) =>
222 `projects/${project}/locations/${location}/connectors/${connectorId}`;
223
224 const parentOf = (project: string, location: string) => `projects/${project}/locations/${location}`;
225
226 const parseName = (name: string, defaultLocation: string) => {
227 const parts = name.split("/").filter((part) => part.length > 0);
228 const connectorsAt = parts.lastIndexOf("connectors");
229 const locationsAt = parts.lastIndexOf("locations");
230 const projectsAt = parts.lastIndexOf("projects");
231 return {
232 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
233 location:
234 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
235 connectorId:
236 connectorsAt >= 0 && parts[connectorsAt + 1] ? parts[connectorsAt + 1]! : lastSegment(name),
237 };
238 };
239
240 const toSubnet = (subnet: vpcaccess.Subnet | undefined): ConnectorSubnet | undefined => {
241 if (subnet === undefined) return undefined;
242 const name = subnet.name ? lastSegment(subnet.name) : undefined;
243 if (name === undefined || name.length === 0) {
244 return subnet.projectId ? { name: "", projectId: subnet.projectId } : undefined;
245 }
246 return subnet.projectId ? { name, projectId: subnet.projectId } : { name };
247 };
248
249 const rfc1035 = (name: string): string => {
250 let next = name
251 .toLowerCase()
252 .replace(/[^a-z0-9-]/g, "-")
253 .replace(/-+/g, "-")
254 .replace(/^-+|-+$/g, "");
255 if (!/^[a-z]/.test(next)) next = `c${next}`;
256 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
257 if (next.length === 0) return "connector";
258 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
259 return next.slice(0, MAX_NAME_LENGTH);
260 };
261
262 const toId = (id: string, connectorId: string | undefined, existing?: string) =>
263 Effect.gen(function* () {
264 if (connectorId !== undefined) return connectorId;
265 if (existing !== undefined) return existing;
266 return rfc1035(
267 yield* createPhysicalName({
268 id,
269 maxLength: MAX_NAME_LENGTH,
270 lowercase: true,
271 }),
272 );
273 });
274
275 const toAttrs = (connector: vpcaccess.Connector, project: string, region: string) => {
276 const name = connector.name ?? "";
277 const parsed = parseName(name, region);
278 const network = connector.network ? lastSegment(connector.network) : undefined;
279 return {
280 name,
281 connectorId: parsed.connectorId,
282 project: parsed.project || project,
283 location: parsed.location,
284 network,
285 ipCidrRange: connector.ipCidrRange,
286 subnet: toSubnet(connector.subnet),
287 machineType: connector.machineType,
288 minInstances: connector.minInstances,
289 maxInstances: connector.maxInstances,
290 minThroughput: connector.minThroughput,
291 maxThroughput: connector.maxThroughput,
292 state: connector.state,
293 connectedProjects: connector.connectedProjects ?? [],
294 };
295 };
296
297 const getByName = (name: string) =>
298 vpcaccess
299 .getProjectsLocationsConnectors({ name })
300 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
301
302 // Connector create/delete takes 2-5 minutes.
303 const waitForOperation = (operation: vpcaccess.Operation) =>
304 waitForGcpOperation(operation, (name) => vpcaccess.getProjectsLocationsOperations({ name }), {
305 budget: "10 minutes",
306 });
307
308 const waitUntilReady = (name: string) => {
309 const ready: Effect.Effect<
310 vpcaccess.Connector,
311 | ConnectorNotResolved
312 | ConnectorFailed
313 | ConnectorNotReady
314 | vpcaccess.GetProjectsLocationsConnectorsError,
315 vpcaccess.GcpOpContext
316 > = getByName(name).pipe(
317 Effect.filterOrFail(
318 (connector): connector is vpcaccess.Connector => connector !== undefined,
319 () => new ConnectorNotResolved({ resourceName: name }),
320 ),
321 Effect.filterOrFail(
322 (connector) => connector.state !== "ERROR",
323 (connector) => new ConnectorFailed({ resourceName: name, state: connector.state }),
324 ),
325 Effect.filterOrFail(
326 (connector) => connector.state === "READY" || connector.state === undefined,
327 (connector) => new ConnectorNotReady({ resourceName: name, state: connector.state }),
328 ),
329 );
330 return ready.pipe(
331 Effect.retry({
332 while: (error) =>
333 error._tag === "GCP.VpcAccess.ConnectorNotResolved" ||
334 error._tag === "GCP.VpcAccess.ConnectorNotReady",
335 times: 10,
336 schedule: Schedule.spaced("8 seconds"),
337 }),
338 );
339 };
340
341 const waitUntilGone = (name: string) =>
342 getByName(name).pipe(
343 Effect.flatMap((connector) =>
344 connector === undefined
345 ? Effect.void
346 : Effect.fail(new ConnectorStillExists({ resourceName: name })),
347 ),
348 Effect.retry({
349 while: (error) => error._tag === "GCP.VpcAccess.ConnectorStillExists",
350 times: 10,
351 schedule: Schedule.spaced("20 seconds"),
352 }),
353 );
354
355 // A location without the API answers NotFound: nothing lives there.
356 const listAt = (parent: string) =>
357 vpcaccess.listProjectsLocationsConnectors.pages({ parent, pageSize: 100 }).pipe(
358 Stream.flatMap((page) => Stream.fromIterable(page.connectors ?? [])),
359 Stream.runCollect,
360 Effect.map((chunk) => Array.from(chunk)),
361 Effect.catchTag("NotFound", () => Effect.succeed([] as vpcaccess.Connector[])),
362 );
363
364 const listLocations = (project: string) =>
365 vpcaccess.listProjectsLocations.pages({ name: `projects/${project}`, pageSize: 100 }).pipe(
366 Stream.flatMap((page) => Stream.fromIterable(page.locations ?? [])),
367 Stream.map((location) => location.name ?? ""),
368 Stream.filter((name) => name.length > 0),
369 Stream.runCollect,
370 Effect.map((chunk) => Array.from(chunk)),
371 );
372
373 const createBody = (news: ConnectorProps): vpcaccess.Connector => {
374 const body: vpcaccess.Connector = {};
375 if (news.subnet !== undefined) {
376 body.subnet = {
377 name: lastSegment(news.subnet.name),
378 projectId: news.subnet.projectId,
379 };
380 } else {
381 if (news.network !== undefined || news.ipCidrRange !== undefined) {
382 body.network = news.network ? lastSegment(news.network) : DEFAULT_NETWORK;
383 }
384 if (news.ipCidrRange !== undefined) {
385 body.ipCidrRange = news.ipCidrRange;
386 }
387 }
388 if (news.machineType !== undefined) {
389 body.machineType = news.machineType;
390 }
391 if (news.minInstances !== undefined) {
392 body.minInstances = news.minInstances;
393 }
394 if (news.maxInstances !== undefined) {
395 body.maxInstances = news.maxInstances;
396 }
397 if (news.minThroughput !== undefined) {
398 body.minThroughput = news.minThroughput;
399 }
400 if (news.maxThroughput !== undefined) {
401 body.maxThroughput = news.maxThroughput;
402 }
403 return body;
404 };
405
406 export const ConnectorProvider = () =>
407 Provider.succeed(Connector, {
408 stables: ["name", "connectorId", "project", "location", "network", "ipCidrRange", "subnet"],
409
410 diff: Effect.fn(function* ({ news, olds, output }) {
411 if (!isResolved(news)) return undefined;
412 const env = yield* GcpEnvironment.current;
413
414 const previousId = olds?.connectorId ?? output?.connectorId;
415 const nextId = news.connectorId ?? previousId;
416 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
417 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
418 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
419 const locationChanged = previousLocation !== nextLocation;
420
421 const previousNetwork = linkKey(olds?.network ?? output?.network);
422 const nextNetwork = news.network !== undefined ? linkKey(news.network) : previousNetwork;
423 const networkChanged = news.network !== undefined && nextNetwork !== previousNetwork;
424
425 const previousCidr = olds?.ipCidrRange ?? output?.ipCidrRange ?? "";
426 const cidrChanged = news.ipCidrRange !== undefined && news.ipCidrRange !== previousCidr;
427
428 const previousSubnet = subnetKey(olds?.subnet ?? output?.subnet);
429 const nextSubnet = news.subnet !== undefined ? subnetKey(news.subnet) : previousSubnet;
430 const subnetChanged = news.subnet !== undefined && nextSubnet !== previousSubnet;
431
432 if (!idChanged && !locationChanged && !networkChanged && !cidrChanged && !subnetChanged) {
433 return undefined;
434 }
435 return {
436 action: "replace" as const,
437 deleteFirst: !idChanged && !locationChanged,
438 };
439 }),
440
441 read: Effect.fn(function* ({ id, olds, output }) {
442 const env = yield* GcpEnvironment.current;
443 const connectorId = yield* toId(id, olds?.connectorId, output?.connectorId);
444 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
445 const name = output?.name ?? resourceName(env.project, location, connectorId);
446 const existing = yield* getByName(name);
447 if (existing === undefined) return undefined;
448 // Connectors have no labels or description. Existence at the computed
449 // name is ownership — the same approach Cloud KMS KeyRing uses.
450 return toAttrs(existing, env.project, env.region);
451 }),
452
453 list: () =>
454 Effect.gen(function* () {
455 const env = yield* GcpEnvironment.current;
456 const parents = yield* listLocations(env.project);
457 if (parents.length === 0) {
458 parents.push(parentOf(env.project, env.region));
459 }
460 const pages = yield* Effect.forEach(parents, (parent) => listAt(parent), {
461 concurrency: 4,
462 });
463 return pages.flat().map((connector) => toAttrs(connector, env.project, env.region));
464 }),
465
466 reconcile: Effect.fn(function* ({ id, news, output }) {
467 const env = yield* GcpEnvironment.current;
468 const connectorId = yield* toId(id, news.connectorId, output?.connectorId);
469 const location = normalizeLocation(news.location ?? output?.location, env.region);
470 const name = resourceName(env.project, location, connectorId);
471
472 if (news.subnet === undefined && news.ipCidrRange === undefined) {
473 return yield* new ConnectorRangeMissing({
474 resourceName: name,
475 message:
476 "VPC Access connectors require `ipCidrRange` (with optional `network`) or `subnet`.",
477 });
478 }
479
480 let current = yield* getByName(name);
481
482 if (current !== undefined && current.state === "DELETING") {
483 yield* waitUntilGone(name);
484 current = undefined;
485 }
486
487 if (current !== undefined && current.state === "ERROR") {
488 return yield* new ConnectorFailed({
489 resourceName: name,
490 state: current.state,
491 });
492 }
493
494 if (current === undefined) {
495 const created = yield* vpcaccess
496 .createProjectsLocationsConnectors({
497 parent: parentOf(env.project, location),
498 connectorId,
499 body: createBody(news),
500 })
501 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
502 if (created !== undefined) {
503 yield* waitForOperation(created);
504 } else {
505 const raced = yield* getByName(name);
506 if (raced === undefined) {
507 return yield* new ConnectorNotResolved({ resourceName: name });
508 }
509 }
510 current = yield* waitUntilReady(name);
511 } else if (current.state === "CREATING" || current.state === "UPDATING") {
512 current = yield* waitUntilReady(name);
513 }
514
515 if (current === undefined) {
516 return yield* new ConnectorNotResolved({ resourceName: name });
517 }
518
519 const desiredMachine = news.machineType ?? DEFAULT_MACHINE_TYPE;
520 const machineChanged =
521 news.machineType !== undefined &&
522 (current.machineType ?? DEFAULT_MACHINE_TYPE) !== desiredMachine;
523 const minChanged =
524 news.minInstances !== undefined && news.minInstances !== current.minInstances;
525 const maxChanged =
526 news.maxInstances !== undefined && news.maxInstances !== current.maxInstances;
527 const minThroughputChanged =
528 news.minThroughput !== undefined && news.minThroughput !== current.minThroughput;
529 const maxThroughputChanged =
530 news.maxThroughput !== undefined && news.maxThroughput !== current.maxThroughput;
531 const instancesChanged = minChanged || maxChanged;
532
533 if (machineChanged || instancesChanged || minThroughputChanged || maxThroughputChanged) {
534 const updateMask = [
535 machineChanged ? "machineType" : undefined,
536 instancesChanged ? "minInstances" : undefined,
537 instancesChanged ? "maxInstances" : undefined,
538 minThroughputChanged ? "minThroughput" : undefined,
539 maxThroughputChanged ? "maxThroughput" : undefined,
540 ].filter((field): field is string => field !== undefined);
541
542 const operation = yield* vpcaccess.patchProjectsLocationsConnectors({
543 name,
544 updateMask: updateMask.join(","),
545 body: {
546 name,
547 machineType: news.machineType ?? current.machineType,
548 minInstances: news.minInstances ?? current.minInstances,
549 maxInstances: news.maxInstances ?? current.maxInstances,
550 minThroughput: news.minThroughput ?? current.minThroughput,
551 maxThroughput: news.maxThroughput ?? current.maxThroughput,
552 },
553 });
554 yield* waitForOperation(operation);
555 current = yield* waitUntilReady(name);
556 }
557
558 return toAttrs(current, env.project, env.region);
559 }),
560
561 delete: Effect.fn(function* ({ output }) {
562 const operation = yield* vpcaccess
563 .deleteProjectsLocationsConnectors({ name: output.name })
564 .pipe(
565 Effect.catchTag("NotFound", () => Effect.undefined),
566 Effect.retry({
567 while: (error) => error._tag === "Conflict",
568 times: 8,
569 schedule: Schedule.spaced("8 seconds"),
570 }),
571 );
572 if (operation !== undefined) {
573 // NOT_FOUND (5): the connector was already gone.
574 yield* waitForOperation(operation).pipe(
575 Effect.catchTag("GCP.OperationFailed", (error) =>
576 error.code === 5 ? Effect.void : Effect.fail(error),
577 ),
578 );
579 }
580 yield* waitUntilGone(output.name);
581 }),
582 });