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

main
ts 445 lines 14.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 { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitRegionOperation } from "./operations.ts";
22
23 const MAX_NAME_LENGTH = 63;
24
25 export type TargetVpnGatewayProps = {
26 /**
27 * Gateway name. If omitted, a unique RFC1035 name is generated from
28 * the stack, stage, and logical id. Immutable — changing it replaces
29 * the gateway.
30 */
31 targetVpnGatewayName?: string;
32 /**
33 * Region the Classic VPN gateway lives in. Immutable — changing it
34 * replaces the gateway. `US-CENTRAL1` is accepted and normalized to
35 * `us-central1`.
36 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
37 */
38 region?: string;
39 /**
40 * VPC network this gateway is attached to. Accepts a name
41 * (`default`), a partial URL (`global/networks/default`), or a full
42 * resource URL. Immutable — changing it replaces the gateway.
43 */
44 network: string;
45 /**
46 * Optional description. Immutable — changing it replaces the
47 * gateway.
48 */
49 description?: string;
50 /**
51 * User labels. Alchemy ownership labels are merged in automatically
52 * and synced via `setLabels` (labels cannot be set on insert).
53 */
54 labels?: Record<string, string>;
55 };
56
57 export type TargetVpnGateway = Resource<
58 "GCP.Compute.TargetVpnGateway",
59 TargetVpnGatewayProps,
60 {
61 /** Gateway name. */
62 targetVpnGatewayName: string;
63 /** Project id. */
64 project: string;
65 /** Region short name (`us-central1`). */
66 region: string;
67 /** Network URL. */
68 network: string | undefined;
69 /** Server-assigned numeric id. */
70 targetVpnGatewayId: string | undefined;
71 /** Resource self-link. */
72 selfLink: string | undefined;
73 /** Description. */
74 description: string | undefined;
75 /** `CREATING`, `READY`, `FAILED`, or `DELETING`. */
76 status: string | undefined;
77 /** User labels (Alchemy ownership labels stripped). */
78 labels: Record<string, string>;
79 /** URLs of VpnTunnel resources attached to this gateway. */
80 tunnels: ReadonlyArray<string>;
81 /** URLs of ForwardingRule resources attached to this gateway. */
82 forwardingRules: ReadonlyArray<string>;
83 /** RFC3339 creation timestamp. */
84 creationTimestamp: string | undefined;
85 },
86 never,
87 Providers
88 >;
89
90 /**
91 * A regional Compute Engine Classic VPN gateway (`targetVpnGateway`).
92 *
93 * Classic VPN attaches a single gateway to a VPC in one region. Prefer
94 * HA VPN (`VpnGateway`) for new deployments. Labels are the only
95 * in-place update (`targetVpnGateways.setLabels`); name, region,
96 * network, and description replace the gateway.
97 *
98 * ### Creating a TargetVpnGateway
99 * **Example:** Generated name on a custom VPC
100 * ```typescript
101 * const network = yield* GCP.Compute.Network("Vpc", {
102 * autoCreateSubnetworks: false,
103 * });
104 * const gateway = yield* GCP.Compute.TargetVpnGateway("Gateway", {
105 * network: network.networkName,
106 * });
107 * ```
108 *
109 * **Example:** Named gateway with labels
110 * ```typescript
111 * const gateway = yield* GCP.Compute.TargetVpnGateway("Gateway", {
112 * targetVpnGatewayName: "app-classic-vpn",
113 * region: "us-central1",
114 * network: "default",
115 * description: "classic vpn",
116 * labels: { env: "prod" },
117 * });
118 * ```
119 *
120 * @resource
121 * @category Compute
122 */
123 export const TargetVpnGateway = Resource<TargetVpnGateway>("GCP.Compute.TargetVpnGateway");
124
125 export class TargetVpnGatewayNotResolved extends Data.TaggedError(
126 "GCP.Compute.TargetVpnGatewayNotResolved",
127 )<{
128 targetVpnGatewayName: string;
129 region: string;
130 }> {}
131
132 export class TargetVpnGatewayPending extends Data.TaggedError(
133 "GCP.Compute.TargetVpnGatewayPending",
134 )<{
135 targetVpnGatewayName: string;
136 status: string;
137 }> {}
138
139 export class TargetVpnGatewayOperationFailed extends Data.TaggedError(
140 "GCP.Compute.TargetVpnGatewayOperationFailed",
141 )<{
142 targetVpnGatewayName: string;
143 operation: string;
144 message: string;
145 }> {}
146
147 const userLabels = (
148 labels: Record<string, string | undefined> | null | undefined,
149 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
150
151 const lastSegment = (value: string) => {
152 const trimmed = value.replace(/\/+$/, "");
153 const parts = trimmed.split("/");
154 return parts[parts.length - 1] || trimmed;
155 };
156
157 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
158 lastSegment(region ?? defaultRegion).toLowerCase();
159
160 const resourceRefOf = (value: string | undefined) => {
161 if (!value) return "";
162 return lastSegment(value);
163 };
164
165 const networkUrl = (project: string, network: string) => {
166 if (network.includes("/")) {
167 return network.startsWith("projects/") || network.startsWith("http")
168 ? network
169 : `projects/${project}/${network.replace(/^\//, "")}`;
170 }
171 return `projects/${project}/global/networks/${network}`;
172 };
173
174 const toName = (id: string, name: string | undefined, existing?: string) =>
175 Effect.gen(function* () {
176 if (name !== undefined) return name;
177 if (existing !== undefined) return existing;
178 const generated = yield* createPhysicalName({
179 id,
180 maxLength: MAX_NAME_LENGTH,
181 lowercase: true,
182 });
183 const rfc = generated.replace(/^[^a-z]+/, "t").replace(/-+$/g, "");
184 return rfc.slice(0, MAX_NAME_LENGTH);
185 });
186
187 const toAttrs = (gateway: compute.TargetVpnGateway, project: string) => ({
188 targetVpnGatewayName: gateway.name ?? "",
189 project,
190 region: lastSegment(gateway.region ?? "").toLowerCase(),
191 network: gateway.network,
192 targetVpnGatewayId: gateway.id,
193 selfLink: gateway.selfLink,
194 description: gateway.description,
195 status: gateway.status,
196 labels: userLabels(gateway.labels),
197 tunnels: gateway.tunnels ?? [],
198 forwardingRules: gateway.forwardingRules ?? [],
199 creationTimestamp: gateway.creationTimestamp,
200 });
201
202 const getByName = (project: string, region: string, targetVpnGateway: string) =>
203 compute
204 .getTargetVpnGateways({ project, region, targetVpnGateway })
205 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
206
207 const requireGateway = (project: string, region: string, targetVpnGatewayName: string) =>
208 Effect.gen(function* () {
209 const gateway = yield* getByName(project, region, targetVpnGatewayName);
210 if (gateway === undefined) {
211 return yield* new TargetVpnGatewayNotResolved({
212 targetVpnGatewayName,
213 region,
214 });
215 }
216 if (gateway.status === "FAILED") {
217 return yield* new TargetVpnGatewayOperationFailed({
218 targetVpnGatewayName,
219 operation: "insert",
220 message: "target VPN gateway status is FAILED",
221 });
222 }
223 if (gateway.status !== undefined && gateway.status !== "READY") {
224 return yield* new TargetVpnGatewayPending({
225 targetVpnGatewayName,
226 status: gateway.status,
227 });
228 }
229 return gateway;
230 }).pipe(
231 Effect.retry({
232 while: (e) =>
233 e._tag === "GCP.Compute.TargetVpnGatewayNotResolved" ||
234 e._tag === "GCP.Compute.TargetVpnGatewayPending",
235 schedule: Schedule.spaced("1 second"),
236 times: 8,
237 }),
238 );
239
240 const waitUntilGone = (project: string, region: string, targetVpnGatewayName: string) =>
241 getByName(project, region, targetVpnGatewayName).pipe(
242 Effect.flatMap((gateway) =>
243 gateway === undefined
244 ? Effect.void
245 : Effect.fail(
246 new TargetVpnGatewayPending({
247 targetVpnGatewayName,
248 status: "EXISTS",
249 }),
250 ),
251 ),
252 Effect.retry({
253 while: (e) => e._tag === "GCP.Compute.TargetVpnGatewayPending",
254 times: 10,
255 schedule: Schedule.spaced("2 seconds"),
256 }),
257 );
258
259 export const TargetVpnGatewayProvider = () =>
260 Provider.succeed(TargetVpnGateway, {
261 nuke: {
262 dependsOn: ["GCP.Compute.Network"],
263 },
264 stables: [
265 "targetVpnGatewayName",
266 "project",
267 "region",
268 "network",
269 "targetVpnGatewayId",
270 "selfLink",
271 "creationTimestamp",
272 ],
273
274 diff: Effect.fn(function* ({ news, olds, output }) {
275 if (!isResolved(news)) return undefined;
276 const env = yield* GcpEnvironment.current;
277 const previousName = olds.targetVpnGatewayName ?? output?.targetVpnGatewayName;
278 const nextName = news.targetVpnGatewayName ?? previousName;
279 const nameChanged =
280 previousName !== undefined && nextName !== undefined && nextName !== previousName;
281
282 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
283 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
284 const regionChanged = previousRegion !== nextRegion;
285
286 const previousNetwork = resourceRefOf(olds.network ?? output?.network);
287 const nextNetwork = resourceRefOf(news.network);
288 const previousDescription = olds.description ?? output?.description ?? "";
289
290 const immutableChanged =
291 nextNetwork !== previousNetwork ||
292 (news.description !== undefined && (news.description ?? "") !== previousDescription);
293
294 if (nameChanged || regionChanged) {
295 return { action: "replace" as const, deleteFirst: false };
296 }
297 if (immutableChanged) {
298 return { action: "replace" as const, deleteFirst: true };
299 }
300 return undefined;
301 }),
302
303 read: Effect.fn(function* ({ id, olds, output, previous }) {
304 const env = yield* GcpEnvironment.current;
305 const targetVpnGatewayName = yield* toName(
306 id,
307 olds?.targetVpnGatewayName,
308 output?.targetVpnGatewayName,
309 );
310 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
311 const existing = yield* getByName(env.project, region, targetVpnGatewayName);
312 if (existing === undefined) return undefined;
313 const attrs = toAttrs(existing, env.project);
314 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
315 ? attrs
316 : unownedUnlessPrevious(attrs, previous, "targetVpnGatewayName");
317 }),
318
319 list: () =>
320 Effect.gen(function* () {
321 const env = yield* GcpEnvironment.current;
322 const pages = yield* compute.aggregatedListTargetVpnGateways
323 .pages({
324 project: env.project,
325 filter: "labels.alchemy-id:*",
326 returnPartialSuccess: true,
327 maxResults: 500,
328 })
329 .pipe(Stream.runCollect);
330 return Array.from(pages).flatMap((page) =>
331 Object.values(page.items ?? {}).flatMap((scoped) =>
332 (scoped?.targetVpnGateways ?? [])
333 .filter((gateway) =>
334 Object.keys(gateway.labels ?? {}).some((key) => key.startsWith("alchemy-")),
335 )
336 .map((gateway) => toAttrs(gateway, env.project)),
337 ),
338 );
339 }),
340
341 reconcile: Effect.fn(function* ({ id, news, output }) {
342 const env = yield* GcpEnvironment.current;
343 const targetVpnGatewayName = yield* toName(
344 id,
345 news.targetVpnGatewayName,
346 output?.targetVpnGatewayName,
347 );
348 const region = normalizeRegion(news.region ?? output?.region, env.region);
349 const desiredLabels = {
350 ...toLabels(news.labels),
351 ...(yield* createInternalLabels(id)),
352 };
353
354 let current = yield* getByName(env.project, region, targetVpnGatewayName);
355
356 if (current === undefined) {
357 const created = yield* compute
358 .insertTargetVpnGateways({
359 project: env.project,
360 region,
361 body: {
362 name: targetVpnGatewayName,
363 network: networkUrl(env.project, news.network),
364 description: news.description,
365 },
366 })
367 .pipe(
368 Effect.flatMap((operation) =>
369 waitRegionOperation(env.project, region, operation, {
370 ignore: ["RESOURCE_ALREADY_EXISTS"],
371 }).pipe(
372 Effect.flatMap(() => requireGateway(env.project, region, targetVpnGatewayName)),
373 ),
374 ),
375 Effect.catchTag("Conflict", () => getByName(env.project, region, targetVpnGatewayName)),
376 );
377 current = created ?? undefined;
378 }
379
380 if (current === undefined) {
381 return yield* new TargetVpnGatewayNotResolved({
382 targetVpnGatewayName,
383 region,
384 });
385 }
386
387 const resolved = current;
388 const observedLabels = tagRecord(resolved.labels);
389 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
390 if (upsert.length > 0 || removed.length > 0) {
391 yield* Effect.gen(function* () {
392 const latest = (yield* getByName(env.project, region, targetVpnGatewayName)) ?? resolved;
393 yield* compute
394 .setLabelsTargetVpnGateways({
395 project: env.project,
396 region,
397 resource: targetVpnGatewayName,
398 body: {
399 labels: desiredLabels,
400 labelFingerprint: latest.labelFingerprint,
401 },
402 })
403 .pipe(
404 Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)),
405 );
406 }).pipe(
407 Effect.retry({
408 while: (e) => e._tag === "Conflict",
409 times: 5,
410 schedule: Schedule.spaced("1 second"),
411 }),
412 );
413 current = (yield* getByName(env.project, region, targetVpnGatewayName)) ?? resolved;
414 }
415
416 return toAttrs(current ?? resolved, env.project);
417 }),
418
419 delete: Effect.fn(function* ({ output }) {
420 const env = yield* GcpEnvironment.current;
421 const project = output.project || env.project;
422 const region = normalizeRegion(output.region, env.region);
423 if (!output.targetVpnGatewayName) return;
424 yield* compute
425 .deleteTargetVpnGateways({
426 project,
427 region,
428 targetVpnGateway: output.targetVpnGatewayName,
429 })
430 .pipe(
431 Effect.flatMap((operation) =>
432 waitRegionOperation(project, region, operation, {
433 ignore: ["RESOURCE_NOT_FOUND"],
434 }),
435 ),
436 Effect.catchTag("NotFound", () => Effect.void),
437 Effect.retry({
438 while: (e) => e._tag === "Conflict",
439 times: 8,
440 schedule: Schedule.spaced("2 seconds"),
441 }),
442 );
443 yield* waitUntilGone(project, region, output.targetVpnGatewayName);
444 }),
445 });