@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 535 lines 18.6 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 DEFAULT_ADDRESS_TYPE = "EXTERNAL";
24 const DEFAULT_IP_VERSION = "IPV4";
25 const DEFAULT_NETWORK_TIER = "PREMIUM";
26 const MAX_NAME_LENGTH = 63;
27
28 export type AddressProps = {
29 /**
30 * Name of the address. If omitted, a unique RFC1035 name is generated
31 * from the stack, stage, and logical id. Immutable — changing it
32 * replaces the address.
33 */
34 addressName?: string;
35 /**
36 * Region to reserve the address in. Immutable — changing it replaces
37 * the address. `US-CENTRAL1` is accepted and normalized to `us-central1`.
38 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
39 */
40 region?: string;
41 /**
42 * Optional description. Immutable — changing it replaces the address.
43 */
44 description?: string;
45 /**
46 * Specific IP to reserve. If omitted, GCP assigns one. Immutable —
47 * changing it replaces the address.
48 */
49 address?: string;
50 /**
51 * `EXTERNAL` or `INTERNAL`. Immutable — changing it replaces the
52 * address.
53 * @default "EXTERNAL"
54 */
55 addressType?: compute.AddressAddressTypeEnum | (string & {});
56 /**
57 * `IPV4` or `IPV6`. Immutable — changing it replaces the address.
58 * @default "IPV4"
59 */
60 ipVersion?: compute.AddressIpVersionEnum | (string & {});
61 /**
62 * Prefix length when the resource is an IP range. Immutable — changing
63 * it replaces the address.
64 */
65 prefixLength?: number;
66 /**
67 * Purpose of an internal address (`GCE_ENDPOINT`, `DNS_RESOLVER`,
68 * `VPC_PEERING`, `NAT_AUTO`, `IPSEC_INTERCONNECT`,
69 * `SHARED_LOADBALANCER_VIP`, `PRIVATE_SERVICE_CONNECT`, `SERVERLESS`).
70 * Immutable — changing it replaces the address.
71 */
72 purpose?: compute.AddressPurposeEnum | (string & {});
73 /**
74 * Network URL for internal addresses (`VPC_PEERING` /
75 * `IPSEC_INTERCONNECT`). Immutable — changing it replaces the address.
76 */
77 network?: string;
78 /**
79 * Subnetwork URL for internal `GCE_ENDPOINT` / `DNS_RESOLVER`
80 * addresses. Immutable — changing it replaces the address.
81 */
82 subnetwork?: string;
83 /**
84 * Networking tier (`PREMIUM` or `STANDARD`). Internal addresses are
85 * always Premium. Immutable — changing it replaces the address.
86 * @default "PREMIUM"
87 */
88 networkTier?: compute.AddressNetworkTierEnum | (string & {});
89 /**
90 * Endpoint type for reserved IPv6 addresses (`VM` or `NETLB`).
91 * Immutable — changing it replaces the address.
92 */
93 ipv6EndpointType?: compute.AddressIpv6EndpointTypeEnum | (string & {});
94 /**
95 * Public delegated prefix used to draw a BYOIP address. Immutable —
96 * changing it replaces the address.
97 */
98 ipCollection?: string;
99 /**
100 * User labels. Alchemy ownership labels are merged in automatically
101 * and synced via `setLabels` (labels cannot be set on insert).
102 */
103 labels?: Record<string, string>;
104 };
105
106 export type Address = Resource<
107 "GCP.Compute.Address",
108 AddressProps,
109 {
110 /** Address name. */
111 addressName: string;
112 /** Project id. */
113 project: string;
114 /** Region short name (`us-central1`). */
115 region: string;
116 /** Reserved IP address or start of the range. */
117 address: string | undefined;
118 /** Server-assigned numeric id. */
119 addressId: string | undefined;
120 /** Resource self-link. */
121 selfLink: string | undefined;
122 /** `RESERVING`, `RESERVED`, or `IN_USE`. */
123 status: string | undefined;
124 /** `EXTERNAL` or `INTERNAL`. */
125 addressType: string | undefined;
126 /** `IPV4` or `IPV6`. */
127 ipVersion: string | undefined;
128 /** Prefix length of an IP range, if any. */
129 prefixLength: number | undefined;
130 /** Purpose of an internal address, if any. */
131 purpose: string | undefined;
132 /** Network URL for internal addresses, if any. */
133 network: string | undefined;
134 /** Subnetwork URL, if any. */
135 subnetwork: string | undefined;
136 /** Networking tier. */
137 networkTier: string | undefined;
138 /** IPv6 endpoint type, if any. */
139 ipv6EndpointType: string | undefined;
140 /** BYOIP public delegated prefix, if any. */
141 ipCollection: string | undefined;
142 /** Description. */
143 description: string | undefined;
144 /** User labels (Alchemy ownership labels stripped). */
145 labels: Record<string, string>;
146 /** RFC3339 creation timestamp. */
147 creationTimestamp: string | undefined;
148 /** Self-links of resources using this address. */
149 users: ReadonlyArray<string>;
150 },
151 never,
152 Providers
153 >;
154
155 /**
156 * A regional Compute Engine static IP address.
157 *
158 * Reserves a regional internal or external IP. Labels are the only
159 * in-place update (`addresses.setLabels`); name, region, IP, type,
160 * version, purpose, network, subnetwork, prefix length, and description
161 * replace the address.
162 *
163 * ### Creating an Address
164 * **Example:** Generated name
165 * ```typescript
166 * const ip = yield* GCP.Compute.Address("Ingress", {});
167 * ```
168 *
169 * **Example:** Named address with labels
170 * ```typescript
171 * const ip = yield* GCP.Compute.Address("Ingress", {
172 * addressName: "app-ingress",
173 * region: "us-central1",
174 * addressType: "EXTERNAL",
175 * networkTier: "PREMIUM",
176 * labels: { env: "prod" },
177 * });
178 * ```
179 *
180 * ### Internal Addresses
181 * **Example:** Regional internal IP in a subnetwork
182 * ```typescript
183 * const ip = yield* GCP.Compute.Address("ServiceIp", {
184 * region: "us-central1",
185 * addressType: "INTERNAL",
186 * subnetwork:
187 * "projects/my-project/regions/us-central1/subnetworks/default",
188 * purpose: "GCE_ENDPOINT",
189 * });
190 * ```
191 *
192 * @resource
193 * @category Compute
194 */
195 export const Address = Resource<Address>("GCP.Compute.Address");
196
197 export class AddressNotResolved extends Data.TaggedError("GCP.Compute.AddressNotResolved")<{
198 addressName: string;
199 region: string;
200 }> {}
201
202 export class AddressPending extends Data.TaggedError("GCP.Compute.AddressPending")<{
203 addressName: string;
204 status: string;
205 }> {}
206
207 const userLabels = (
208 labels: Record<string, string | undefined> | null | undefined,
209 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
210
211 const lastSegment = (value: string) => {
212 const trimmed = value.replace(/\/+$/, "");
213 const parts = trimmed.split("/");
214 return parts[parts.length - 1] || trimmed;
215 };
216
217 const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
218 lastSegment(region ?? defaultRegion).toLowerCase();
219
220 const resourceRefOf = (value: string | undefined) => {
221 if (!value) return "";
222 return lastSegment(value);
223 };
224
225 const addressTypeOf = (value: string | undefined) =>
226 value && value !== "UNSPECIFIED_TYPE" ? value : DEFAULT_ADDRESS_TYPE;
227
228 const ipVersionOf = (value: string | undefined) =>
229 value && value !== "UNSPECIFIED_VERSION" ? value : DEFAULT_IP_VERSION;
230
231 const networkTierOf = (value: string | undefined) => value ?? DEFAULT_NETWORK_TIER;
232
233 const toName = (id: string, name: string | undefined, existing?: string) =>
234 Effect.gen(function* () {
235 if (name !== undefined) return name;
236 if (existing !== undefined) return existing;
237 const generated = yield* createPhysicalName({
238 id,
239 maxLength: MAX_NAME_LENGTH,
240 lowercase: true,
241 });
242 return /^[a-z]/.test(generated) ? generated : `a${generated}`.slice(0, MAX_NAME_LENGTH);
243 });
244
245 const toAttrs = (address: compute.Address, project: string) => ({
246 addressName: address.name ?? "",
247 project,
248 region: lastSegment(address.region ?? "").toLowerCase(),
249 address: address.address,
250 addressId: address.id,
251 selfLink: address.selfLink,
252 status: address.status,
253 addressType: address.addressType,
254 ipVersion: address.ipVersion,
255 prefixLength: address.prefixLength,
256 purpose: address.purpose,
257 network: address.network,
258 subnetwork: address.subnetwork,
259 networkTier: address.networkTier,
260 ipv6EndpointType: address.ipv6EndpointType,
261 ipCollection: address.ipCollection,
262 description: address.description,
263 labels: userLabels(address.labels),
264 creationTimestamp: address.creationTimestamp,
265 users: address.users ?? [],
266 });
267
268 const getByName = (project: string, region: string, address: string) =>
269 compute
270 .getAddresses({ project, region, address })
271 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
272
273 const waitUntilReady = (project: string, region: string, addressName: string) =>
274 getByName(project, region, addressName).pipe(
275 Effect.flatMap((address) => {
276 if (address === undefined || address.status === "RESERVING") {
277 return Effect.fail(
278 new AddressPending({
279 addressName,
280 status: address?.status ?? "MISSING",
281 }),
282 );
283 }
284 return Effect.succeed(address);
285 }),
286 Effect.retry({
287 while: (e) => e._tag === "GCP.Compute.AddressPending",
288 times: 10,
289 schedule: Schedule.spaced("1 second"),
290 }),
291 );
292
293 const requireAddress = (project: string, region: string, addressName: string) =>
294 getByName(project, region, addressName).pipe(
295 Effect.flatMap((address) =>
296 address
297 ? Effect.succeed(address)
298 : Effect.fail(new AddressNotResolved({ addressName, region })),
299 ),
300 Effect.retry({
301 while: (e) => e._tag === "GCP.Compute.AddressNotResolved",
302 schedule: Schedule.spaced("1 second"),
303 times: 8,
304 }),
305 );
306
307 const waitUntilGone = (project: string, region: string, addressName: string) =>
308 getByName(project, region, addressName).pipe(
309 Effect.flatMap((address) =>
310 address === undefined
311 ? Effect.void
312 : Effect.fail(
313 new AddressPending({
314 addressName,
315 status: address.status ?? "EXISTS",
316 }),
317 ),
318 ),
319 Effect.retry({
320 while: (e) => e._tag === "GCP.Compute.AddressPending",
321 times: 10,
322 schedule: Schedule.spaced("2 seconds"),
323 }),
324 );
325
326 export const AddressProvider = () =>
327 Provider.succeed(Address, {
328 stables: [
329 "addressName",
330 "project",
331 "region",
332 "address",
333 "addressId",
334 "selfLink",
335 "addressType",
336 "ipVersion",
337 "prefixLength",
338 "purpose",
339 "network",
340 "subnetwork",
341 "networkTier",
342 "creationTimestamp",
343 ],
344
345 diff: Effect.fn(function* ({ news, olds, output }) {
346 if (!isResolved(news)) return undefined;
347 const env = yield* GcpEnvironment.current;
348 const previousName = olds.addressName ?? output?.addressName;
349 const nextName = news.addressName ?? previousName;
350 const nameChanged =
351 previousName !== undefined && nextName !== undefined && nextName !== previousName;
352
353 const previousRegion = normalizeRegion(olds.region ?? output?.region, env.region);
354 const nextRegion = normalizeRegion(news.region ?? output?.region, env.region);
355 const regionChanged = previousRegion !== nextRegion;
356
357 const previousType = addressTypeOf(olds.addressType ?? output?.addressType);
358 const previousVersion = ipVersionOf(olds.ipVersion ?? output?.ipVersion);
359 const previousTier = networkTierOf(olds.networkTier ?? output?.networkTier);
360 const previousNetwork = resourceRefOf(olds.network ?? output?.network);
361 const previousSubnetwork = resourceRefOf(olds.subnetwork ?? output?.subnetwork);
362 const previousPurpose = olds.purpose ?? output?.purpose ?? "";
363 const previousDescription = olds.description ?? output?.description ?? "";
364 const previousPrefix = olds.prefixLength ?? output?.prefixLength;
365 const previousIpv6 = olds.ipv6EndpointType ?? output?.ipv6EndpointType ?? "";
366 const previousCollection = resourceRefOf(olds.ipCollection ?? output?.ipCollection);
367
368 const immutableChanged =
369 (news.description !== undefined && (news.description ?? "") !== previousDescription) ||
370 (news.address !== undefined &&
371 output?.address !== undefined &&
372 news.address !== output.address) ||
373 (news.addressType !== undefined && addressTypeOf(news.addressType) !== previousType) ||
374 (news.ipVersion !== undefined && ipVersionOf(news.ipVersion) !== previousVersion) ||
375 (news.prefixLength !== undefined && news.prefixLength !== previousPrefix) ||
376 (news.purpose !== undefined && (news.purpose ?? "") !== previousPurpose) ||
377 (news.network !== undefined && resourceRefOf(news.network) !== previousNetwork) ||
378 (news.subnetwork !== undefined && resourceRefOf(news.subnetwork) !== previousSubnetwork) ||
379 (news.networkTier !== undefined && networkTierOf(news.networkTier) !== previousTier) ||
380 (news.ipv6EndpointType !== undefined && (news.ipv6EndpointType ?? "") !== previousIpv6) ||
381 (news.ipCollection !== undefined &&
382 resourceRefOf(news.ipCollection) !== previousCollection);
383
384 if (nameChanged || regionChanged) {
385 return { action: "replace" as const, deleteFirst: false };
386 }
387 if (immutableChanged) {
388 return { action: "replace" as const, deleteFirst: true };
389 }
390 return undefined;
391 }),
392
393 read: Effect.fn(function* ({ id, olds, output, previous }) {
394 const env = yield* GcpEnvironment.current;
395 const addressName = yield* toName(id, olds?.addressName, output?.addressName);
396 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
397 const existing = yield* getByName(env.project, region, addressName);
398 if (existing === undefined) return undefined;
399 const attrs = toAttrs(existing, env.project);
400 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
401 ? attrs
402 : unownedUnlessPrevious(attrs, previous, "addressName");
403 }),
404
405 list: () =>
406 Effect.gen(function* () {
407 const env = yield* GcpEnvironment.current;
408 const pages = yield* compute.aggregatedListAddresses
409 .pages({
410 project: env.project,
411 filter: "labels.alchemy-id:*",
412 returnPartialSuccess: true,
413 maxResults: 500,
414 })
415 .pipe(Stream.runCollect);
416 return Array.from(pages).flatMap((page) =>
417 Object.values(page.items ?? {}).flatMap((scoped) =>
418 (scoped?.addresses ?? [])
419 .filter((item) => item.region !== undefined)
420 .filter((item) =>
421 Object.keys(item.labels ?? {}).some((key) => key.startsWith("alchemy-")),
422 )
423 .map((item) => toAttrs(item, env.project)),
424 ),
425 );
426 }),
427
428 reconcile: Effect.fn(function* ({ id, news, output }) {
429 const env = yield* GcpEnvironment.current;
430 const addressName = yield* toName(id, news.addressName, output?.addressName);
431 const region = normalizeRegion(news.region ?? output?.region, env.region);
432 const desiredLabels = {
433 ...toLabels(news.labels),
434 ...(yield* createInternalLabels(id)),
435 };
436
437 let current = yield* getByName(env.project, region, addressName);
438
439 if (current === undefined) {
440 const created = yield* compute
441 .insertAddresses({
442 project: env.project,
443 region,
444 body: {
445 name: addressName,
446 description: news.description,
447 address: news.address,
448 addressType: news.addressType,
449 ipVersion: news.ipVersion,
450 prefixLength: news.prefixLength,
451 purpose: news.purpose,
452 network: news.network,
453 subnetwork: news.subnetwork,
454 networkTier: news.networkTier,
455 ipv6EndpointType: news.ipv6EndpointType,
456 ipCollection: news.ipCollection,
457 },
458 })
459 .pipe(
460 Effect.flatMap((operation) =>
461 waitRegionOperation(env.project, region, operation, {
462 ignore: ["RESOURCE_ALREADY_EXISTS"],
463 }).pipe(Effect.flatMap(() => requireAddress(env.project, region, addressName))),
464 ),
465 Effect.catchTag("Conflict", () => getByName(env.project, region, addressName)),
466 );
467 current = created ?? undefined;
468 }
469
470 if (current === undefined) {
471 return yield* new AddressNotResolved({ addressName, region });
472 }
473
474 if (current.status === "RESERVING") {
475 current = yield* waitUntilReady(env.project, region, addressName);
476 }
477
478 const resolved = current;
479 const observedLabels = tagRecord(resolved.labels);
480 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
481 if (upsert.length > 0 || removed.length > 0) {
482 yield* Effect.gen(function* () {
483 const latest = (yield* getByName(env.project, region, addressName)) ?? resolved;
484 yield* compute
485 .setLabelsAddresses({
486 project: env.project,
487 region,
488 resource: addressName,
489 body: {
490 labels: desiredLabels,
491 labelFingerprint: latest.labelFingerprint,
492 },
493 })
494 .pipe(
495 Effect.flatMap((operation) => waitRegionOperation(env.project, region, operation)),
496 );
497 }).pipe(
498 Effect.retry({
499 while: (e) => e._tag === "Conflict",
500 times: 5,
501 schedule: Schedule.spaced("1 second"),
502 }),
503 );
504 current = (yield* getByName(env.project, region, addressName)) ?? resolved;
505 }
506
507 return toAttrs(current ?? resolved, env.project);
508 }),
509
510 delete: Effect.fn(function* ({ output }) {
511 const env = yield* GcpEnvironment.current;
512 const project = output.project || env.project;
513 const region = normalizeRegion(output.region, env.region);
514 yield* compute
515 .deleteAddresses({
516 project,
517 region,
518 address: output.addressName,
519 })
520 .pipe(
521 Effect.flatMap((operation) =>
522 waitRegionOperation(project, region, operation, {
523 ignore: ["RESOURCE_NOT_FOUND"],
524 }),
525 ),
526 Effect.catchTag("NotFound", () => Effect.void),
527 Effect.retry({
528 while: (e) => e._tag === "Conflict",
529 times: 8,
530 schedule: Schedule.spaced("2 seconds"),
531 }),
532 );
533 yield* waitUntilGone(project, region, output.addressName);
534 }),
535 });