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

main
ts 365 lines 12.6 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
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 { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeDescription,
15 hasOwnershipMarker,
16 lastSegment,
17 normalizeRegion,
18 parseDescription,
19 runRegionOp,
20 toPhysicalName,
21 } from "./internal.ts";
22
23 export type PublicDelegatedPrefixMode = compute.PublicDelegatedPrefixModeEnum | (string & {});
24
25 export type PublicDelegatedPrefixProps = {
26 /**
27 * Prefix name (RFC1035, 1-63 characters). If omitted, a unique name is
28 * generated from the stack, stage, and logical id. Changing it replaces
29 * the prefix.
30 */
31 prefixName?: string;
32 /**
33 * Region the prefix lives in. Immutable — changing it replaces the
34 * prefix. `US-CENTRAL1` is accepted and normalized to `us-central1`.
35 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
36 */
37 region?: string;
38 /**
39 * Parent public advertised prefix or public delegated prefix URL.
40 * Immutable — changing it replaces the prefix.
41 */
42 parentPrefix: string;
43 /**
44 * IP address range in CIDR format delegated from the parent. Immutable
45 * — changing it replaces the prefix.
46 */
47 ipCidrRange: string;
48 /**
49 * IPv6-only mode (`DELEGATION`, `EXTERNAL_IPV6_FORWARDING_RULE_CREATION`,
50 * `EXTERNAL_IPV6_SUBNETWORK_CREATION`, or
51 * `INTERNAL_IPV6_SUBNETWORK_CREATION`). Immutable.
52 */
53 mode?: PublicDelegatedPrefixMode;
54 /**
55 * Allocatable prefix length supported by this PDP. Optional; cannot be
56 * set for prefixes in `DELEGATION` mode or for IPv4 prefixes.
57 */
58 allocatablePrefixLength?: number;
59 /**
60 * If true, the prefix is a live-migration prefix. Immutable.
61 */
62 isLiveMigration?: boolean;
63 /**
64 * Optional description. Public delegated prefixes have no labels field,
65 * so Alchemy ownership is stored in a `[alchemy …]` prefix for `list` /
66 * nuke.
67 */
68 description?: string;
69 };
70
71 export type PublicDelegatedPrefix = Resource<
72 "GCP.Compute.PublicDelegatedPrefix",
73 PublicDelegatedPrefixProps,
74 {
75 /** Prefix name. */
76 prefixName: string;
77 /** Project id. */
78 project: string;
79 /** Region short name (`us-central1`). */
80 region: string;
81 /** Parent prefix URL. */
82 parentPrefix: string | undefined;
83 /** Delegated CIDR range. */
84 ipCidrRange: string;
85 /** IPv6 mode, if set. */
86 mode: string | undefined;
87 /** Allocatable prefix length. */
88 allocatablePrefixLength: number | undefined;
89 /** Whether this is a live-migration prefix. */
90 isLiveMigration: boolean;
91 /** User description with the Alchemy ownership prefix stripped. */
92 description: string | undefined;
93 /** Provisioning status. */
94 status: string | undefined;
95 /** Child sub-prefixes. */
96 publicDelegatedSubPrefixs: compute.PublicDelegatedPrefixPublicDelegatedSubPrefix[];
97 /** IPv6 access type inherited from the parent. */
98 ipv6AccessType: string | undefined;
99 /** Whether enhanced IPv4 allocations are enabled. */
100 enableEnhancedIpv4Allocation: boolean | undefined;
101 /** BYOIP API version. */
102 byoipApiVersion: string | undefined;
103 /** Optimistic-locking fingerprint. */
104 fingerprint: string | undefined;
105 /** Server-defined URL. */
106 selfLink: string | undefined;
107 /** Server-assigned numeric id. */
108 prefixId: 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 regional public delegated prefix (BYOIP).
120 *
121 * A public delegated prefix is an IP block carved from a public advertised
122 * prefix and scoped to one region (or global). Creating one requires a
123 * parent advertised prefix. Name, region, parent, CIDR, and mode are
124 * immutable. Description and sub-prefixes update in place via
125 * `publicDelegatedPrefixes.patch`.
126 *
127 * ### Creating a Public Delegated Prefix
128 * **Example:** Regional IPv4 sub-prefix
129 * ```typescript
130 * const pap = yield* GCP.Compute.PublicAdvertisedPrefix("Byoip", {
131 * ipCidrRange: "203.0.113.0/24",
132 * pdpScope: "REGIONAL",
133 * });
134 * const pdp = yield* GCP.Compute.PublicDelegatedPrefix("Delegate", {
135 * parentPrefix: pap.selfLink,
136 * ipCidrRange: "203.0.113.0/26",
137 * description: "us-central1 block",
138 * });
139 * ```
140 *
141 * **Example:** Explicit name
142 * ```typescript
143 * const pdp = yield* GCP.Compute.PublicDelegatedPrefix("Delegate", {
144 * prefixName: "lab-pdp",
145 * region: "us-central1",
146 * parentPrefix: pap.selfLink,
147 * ipCidrRange: "203.0.113.0/26",
148 * });
149 * ```
150 *
151 * @resource
152 * @category Compute
153 */
154 export const PublicDelegatedPrefix = Resource<PublicDelegatedPrefix>(
155 "GCP.Compute.PublicDelegatedPrefix",
156 );
157
158 export class PublicDelegatedPrefixNotResolved extends Data.TaggedError(
159 "GCP.Compute.PublicDelegatedPrefixNotResolved",
160 )<{
161 prefixName: string;
162 region: string;
163 }> {}
164
165 const toAttrs = (
166 prefix: compute.PublicDelegatedPrefix,
167 project: string,
168 ): PublicDelegatedPrefix["Attributes"] => {
169 const parsed = parseDescription(prefix.description);
170 return {
171 prefixName: prefix.name ?? lastSegment(prefix.selfLink),
172 project,
173 region: lastSegment(prefix.region).toLowerCase(),
174 parentPrefix: prefix.parentPrefix,
175 ipCidrRange: prefix.ipCidrRange ?? "",
176 mode: prefix.mode,
177 allocatablePrefixLength: prefix.allocatablePrefixLength,
178 isLiveMigration: prefix.isLiveMigration === true,
179 description: parsed.description,
180 status: prefix.status,
181 publicDelegatedSubPrefixs: prefix.publicDelegatedSubPrefixs ?? [],
182 ipv6AccessType: prefix.ipv6AccessType,
183 enableEnhancedIpv4Allocation: prefix.enableEnhancedIpv4Allocation,
184 byoipApiVersion: prefix.byoipApiVersion,
185 fingerprint: prefix.fingerprint,
186 selfLink: prefix.selfLink,
187 prefixId: prefix.id,
188 creationTimestamp: prefix.creationTimestamp,
189 kind: prefix.kind,
190 };
191 };
192
193 const getByName = (project: string, region: string, name: string) =>
194 compute
195 .getPublicDelegatedPrefixes({
196 project,
197 region,
198 publicDelegatedPrefix: name,
199 })
200 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
201
202 const awaitResource = (project: string, region: string, prefixName: string) =>
203 getByName(project, region, prefixName).pipe(
204 Effect.flatMap((prefix) =>
205 prefix !== undefined
206 ? Effect.succeed(prefix)
207 : Effect.fail(new PublicDelegatedPrefixNotResolved({ prefixName, region })),
208 ),
209 Effect.retry({
210 while: (error) => error._tag === "GCP.Compute.PublicDelegatedPrefixNotResolved",
211 times: 8,
212 schedule: Schedule.spaced("1 second"),
213 }),
214 );
215
216 export const PublicDelegatedPrefixProvider = () =>
217 Provider.succeed(PublicDelegatedPrefix, {
218 stables: [
219 "prefixName",
220 "project",
221 "region",
222 "ipCidrRange",
223 "prefixId",
224 "selfLink",
225 "creationTimestamp",
226 ],
227
228 diff: Effect.fn(function* ({ news, olds, output }) {
229 if (!isResolved(news)) return undefined;
230 const env = yield* GcpEnvironment.current;
231 const previousName = olds?.prefixName ?? output?.prefixName;
232 const nextName = news.prefixName ?? previousName;
233 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
234 const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region);
235 const nameChanged =
236 previousName !== undefined && nextName !== undefined && previousName !== nextName;
237 const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion;
238 const parentChanged =
239 lastSegment(olds?.parentPrefix ?? output?.parentPrefix) !==
240 lastSegment(news.parentPrefix) &&
241 (olds?.parentPrefix ?? output?.parentPrefix) !== undefined;
242 const cidrChanged =
243 (olds?.ipCidrRange ?? output?.ipCidrRange) !== undefined &&
244 news.ipCidrRange !== (olds?.ipCidrRange ?? output?.ipCidrRange);
245 const modeChanged =
246 news.mode !== undefined &&
247 (olds?.mode ?? output?.mode) !== undefined &&
248 news.mode !== (olds?.mode ?? output?.mode);
249 if (nameChanged || regionChanged || parentChanged || cidrChanged || modeChanged) {
250 return {
251 action: "replace" as const,
252 deleteFirst: !nameChanged || nextName === undefined || nextName === previousName,
253 };
254 }
255 return undefined;
256 }),
257
258 read: Effect.fn(function* ({ id, olds, output }) {
259 const env = yield* GcpEnvironment.current;
260 const prefixName = yield* toPhysicalName(id, olds?.prefixName, output?.prefixName, "prefix");
261 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
262 const existing = yield* getByName(env.project, region, prefixName);
263 if (existing === undefined) return undefined;
264 const attrs = toAttrs(existing, env.project);
265 const { labels } = parseDescription(existing.description);
266 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
267 }),
268
269 list: () =>
270 Effect.gen(function* () {
271 const env = yield* GcpEnvironment.current;
272 const pages = yield* compute.aggregatedListPublicDelegatedPrefixes
273 .pages({
274 project: env.project,
275 maxResults: 500,
276 returnPartialSuccess: true,
277 })
278 .pipe(
279 Stream.runCollect,
280 Effect.catchTag("NotFound", () => Effect.succeed([] as never[])),
281 );
282 return Array.from(pages as readonly compute.PublicDelegatedPrefixAggregatedList[]).flatMap(
283 (page) =>
284 Object.entries(page.items ?? {}).flatMap(([scope, scoped]) => {
285 if (!scope.startsWith("regions/")) return [];
286 return (scoped?.publicDelegatedPrefixes ?? [])
287 .filter((item) => hasOwnershipMarker(item.description))
288 .map((item) => toAttrs(item, env.project));
289 }),
290 );
291 }),
292
293 reconcile: Effect.fn(function* ({ id, news, output }) {
294 const env = yield* GcpEnvironment.current;
295 const prefixName = yield* toPhysicalName(id, news.prefixName, output?.prefixName, "prefix");
296 const region = normalizeRegion(news.region ?? output?.region, env.region);
297 const ownership = yield* createInternalLabels(id);
298 const desiredDescription = encodeDescription(ownership, news.description);
299
300 let current = yield* getByName(env.project, region, prefixName);
301
302 if (current === undefined) {
303 yield* runRegionOp(
304 env.project,
305 region,
306 compute.insertPublicDelegatedPrefixes({
307 project: env.project,
308 region,
309 body: {
310 name: prefixName,
311 description: desiredDescription,
312 parentPrefix: news.parentPrefix,
313 ipCidrRange: news.ipCidrRange,
314 mode: news.mode,
315 allocatablePrefixLength: news.allocatablePrefixLength,
316 isLiveMigration: news.isLiveMigration,
317 },
318 }),
319 { ignoreAlreadyExists: true },
320 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
321 current = yield* awaitResource(env.project, region, prefixName);
322 }
323
324 if (current === undefined) {
325 return yield* new PublicDelegatedPrefixNotResolved({
326 prefixName,
327 region,
328 });
329 }
330
331 if ((current.description ?? "") !== desiredDescription) {
332 yield* runRegionOp(
333 env.project,
334 region,
335 compute.patchPublicDelegatedPrefixes({
336 project: env.project,
337 region,
338 publicDelegatedPrefix: prefixName,
339 body: {
340 description: desiredDescription,
341 fingerprint: current.fingerprint,
342 },
343 }),
344 );
345 current = (yield* getByName(env.project, region, prefixName)) ?? current;
346 }
347
348 return toAttrs(current, env.project);
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 const env = yield* GcpEnvironment.current;
353 const region = normalizeRegion(output.region, env.region);
354 yield* runRegionOp(
355 env.project,
356 region,
357 compute.deletePublicDelegatedPrefixes({
358 project: env.project,
359 region,
360 publicDelegatedPrefix: output.prefixName,
361 }),
362 { ignoreNotFound: true },
363 ).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
364 }),
365 });