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

main
ts 368 lines 12.3 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 { 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 { waitGlobalOperation } from "./operations.ts";
15
16 export type GlobalPublicDelegatedPrefixProps = {
17 /**
18 * Prefix name (RFC1035, 1-63 chars). If omitted, a unique name is
19 * generated from the stack, stage, and logical id. Changing it replaces
20 * the prefix.
21 */
22 prefixName?: string;
23 /**
24 * Optional description. Public delegated prefixes have no labels field —
25 * Alchemy ownership is stored in a `[alchemy …]` prefix for `list` /
26 * nuke.
27 */
28 description?: string;
29 /**
30 * Parent Public Advertised Prefix or Public Delegated Prefix URL.
31 * Immutable — changing it replaces the prefix.
32 */
33 parentPrefix: string;
34 /**
35 * IP range in CIDR format allocated from the parent. Immutable —
36 * changing it replaces the prefix.
37 */
38 ipCidrRange: string;
39 /**
40 * IPv6 allocation mode (`DELEGATION`,
41 * `EXTERNAL_IPV6_FORWARDING_RULE_CREATION`, …). Immutable — changing
42 * it replaces the prefix.
43 */
44 mode?: compute.PublicDelegatedPrefixModeEnum | (string & {});
45 /**
46 * Allocatable prefix length for IPv6 prefixes that are not in
47 * `DELEGATION` mode.
48 */
49 allocatablePrefixLength?: number;
50 /**
51 * Whether this prefix is a live-migration prefix.
52 */
53 isLiveMigration?: boolean;
54 };
55
56 export type GlobalPublicDelegatedPrefix = Resource<
57 "GCP.Compute.GlobalPublicDelegatedPrefix",
58 GlobalPublicDelegatedPrefixProps,
59 {
60 /** Prefix name. */
61 prefixName: string;
62 /** Project id. */
63 project: string;
64 /** User description with the Alchemy ownership prefix stripped. */
65 description: string | undefined;
66 /** Parent prefix URL. */
67 parentPrefix: string | undefined;
68 /** Allocated CIDR. */
69 ipCidrRange: string | undefined;
70 /** Allocation mode. */
71 mode: string | undefined;
72 /** Allocatable prefix length. */
73 allocatablePrefixLength: number | undefined;
74 /** Live-migration flag. */
75 isLiveMigration: boolean | undefined;
76 /** Server-reported status. */
77 status: string | undefined;
78 /** IPv6 access type inherited from the parent. */
79 ipv6AccessType: string | undefined;
80 /** Server-assigned numeric id. */
81 prefixId: string | undefined;
82 /** Server-defined URL. */
83 selfLink: string | undefined;
84 /** RFC3339 creation timestamp. */
85 creationTimestamp: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * A global Compute Engine public delegated prefix (BYOIP).
93 *
94 * Delegates a CIDR from a Public Advertised Prefix so addresses and
95 * sub-prefixes can be created. Creating one requires a parent advertised
96 * prefix (Bring Your Own IP). Name, parent, CIDR, and mode replace the
97 * resource; description updates in place via patch. Compute has no labels
98 * field, so Alchemy stamps ownership into the description.
99 *
100 * ### Creating a Global Public Delegated Prefix
101 * **Example:** Delegate a /24 from a PAP
102 * ```typescript
103 * const prefix = yield* GCP.Compute.GlobalPublicDelegatedPrefix("byoip", {
104 * parentPrefix:
105 * "projects/my-project/global/publicAdvertisedPrefixes/edge",
106 * ipCidrRange: "203.0.113.0/24",
107 * });
108 * ```
109 *
110 * @resource
111 * @category Compute
112 */
113 export const GlobalPublicDelegatedPrefix = Resource<GlobalPublicDelegatedPrefix>(
114 "GCP.Compute.GlobalPublicDelegatedPrefix",
115 );
116
117 export class GlobalPublicDelegatedPrefixNotResolved extends Data.TaggedError(
118 "GCP.Compute.GlobalPublicDelegatedPrefixNotResolved",
119 )<{
120 prefixName: string;
121 }> {}
122
123 const rfc1035 = (name: string): string => {
124 let next = name
125 .toLowerCase()
126 .replace(/[^a-z0-9-]/g, "-")
127 .replace(/-+/g, "-")
128 .replace(/^-+/, "")
129 .replace(/-+$/, "");
130 if (!/^[a-z]/.test(next)) {
131 next = `p${next}`;
132 }
133 next = next.slice(0, 63).replace(/-+$/, "");
134 return next.length > 0 ? next : "publicdelegatedprefix";
135 };
136
137 const lastSegment = (value: string | undefined): string => {
138 if (value === undefined || value.length === 0) return "";
139 const parts = value.replace(/\/+$/, "").split("/");
140 return parts[parts.length - 1] || value;
141 };
142
143 const toName = (id: string, name: string | undefined, existing?: string) =>
144 Effect.gen(function* () {
145 if (name !== undefined) return name;
146 if (existing !== undefined) return existing;
147 return rfc1035(
148 yield* createPhysicalName({
149 id,
150 maxLength: 63,
151 lowercase: true,
152 }),
153 );
154 });
155
156 const encodeDescription = (
157 labels: Record<string, string>,
158 description: string | undefined,
159 ): string => {
160 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
161 return description ? `${marker}\n${description}` : marker;
162 };
163
164 const parseDescription = (
165 description: string | undefined,
166 ): {
167 labels: Record<string, string>;
168 description: string | undefined;
169 } => {
170 if (!description?.startsWith("[alchemy ")) {
171 return { labels: {}, description };
172 }
173 const end = description.indexOf("]");
174 if (end < 0) return { labels: {}, description };
175 const labels: Record<string, string> = {};
176 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
177 const eq = part.indexOf("=");
178 if (eq > 0) {
179 labels[part.slice(0, eq)] = part.slice(eq + 1);
180 }
181 }
182 const rest = description.slice(end + 1).replace(/^\n/, "");
183 return { labels, description: rest.length > 0 ? rest : undefined };
184 };
185
186 const toAttrs = (
187 prefix: compute.PublicDelegatedPrefix,
188 project: string,
189 ): GlobalPublicDelegatedPrefix["Attributes"] => {
190 const parsed = parseDescription(prefix.description);
191 return {
192 prefixName: prefix.name ?? prefix.id ?? "",
193 project,
194 description: parsed.description,
195 parentPrefix: prefix.parentPrefix,
196 ipCidrRange: prefix.ipCidrRange,
197 mode: prefix.mode,
198 allocatablePrefixLength: prefix.allocatablePrefixLength,
199 isLiveMigration: prefix.isLiveMigration,
200 status: prefix.status,
201 ipv6AccessType: prefix.ipv6AccessType,
202 prefixId: prefix.id,
203 selfLink: prefix.selfLink,
204 creationTimestamp: prefix.creationTimestamp,
205 };
206 };
207
208 const getByName = (project: string, publicDelegatedPrefix: string) =>
209 compute
210 .getGlobalPublicDelegatedPrefixes({ project, publicDelegatedPrefix })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 const awaitResource = (project: string, prefixName: string) =>
214 getByName(project, prefixName).pipe(
215 Effect.repeat({
216 schedule: Schedule.spaced("1 second"),
217 until: (item) => item !== undefined,
218 times: 8,
219 }),
220 );
221
222 export const GlobalPublicDelegatedPrefixProvider = () =>
223 Provider.succeed(GlobalPublicDelegatedPrefix, {
224 stables: [
225 "prefixName",
226 "project",
227 "parentPrefix",
228 "ipCidrRange",
229 "mode",
230 "prefixId",
231 "selfLink",
232 "creationTimestamp",
233 ],
234
235 diff: Effect.fn(function* ({ news, olds, output }) {
236 if (!isResolved(news)) return undefined;
237 const previousName = olds?.prefixName ?? output?.prefixName;
238 const nextName = news.prefixName;
239 const previousParent = lastSegment(olds?.parentPrefix ?? output?.parentPrefix);
240 const nextParent = lastSegment(news.parentPrefix);
241 const previousRange = olds?.ipCidrRange ?? output?.ipCidrRange ?? "";
242 const nextRange = news.ipCidrRange;
243 const previousMode = olds?.mode ?? output?.mode ?? "";
244 const nextMode = news.mode ?? previousMode;
245 if (
246 (previousName !== undefined && nextName !== undefined && previousName !== nextName) ||
247 (nextParent.length > 0 && previousParent.length > 0 && previousParent !== nextParent) ||
248 (nextRange.length > 0 && previousRange.length > 0 && previousRange !== nextRange) ||
249 (news.mode !== undefined && previousMode !== nextMode)
250 ) {
251 return {
252 action: "replace" as const,
253 deleteFirst:
254 previousName !== undefined && nextName !== undefined && previousName === nextName,
255 };
256 }
257 return undefined;
258 }),
259
260 read: Effect.fn(function* ({ id, olds, output }) {
261 const env = yield* GcpEnvironment.current;
262 const prefixName = yield* toName(id, olds?.prefixName, output?.prefixName);
263 const existing = yield* getByName(env.project, prefixName);
264 if (existing === undefined) return undefined;
265 const attrs = toAttrs(existing, env.project);
266 const { labels } = parseDescription(existing.description);
267 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
268 }),
269
270 list: () =>
271 Effect.gen(function* () {
272 const env = yield* GcpEnvironment.current;
273 return yield* compute.listGlobalPublicDelegatedPrefixes
274 .items({ project: env.project, maxResults: 500 })
275 .pipe(
276 Stream.filter((prefix) => {
277 const { labels } = parseDescription(prefix.description);
278 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
279 }),
280 Stream.map((prefix) => toAttrs(prefix, env.project)),
281 Stream.runCollect,
282 Effect.map((chunk) => Array.from(chunk)),
283 );
284 }),
285
286 reconcile: Effect.fn(function* ({ id, news, output }) {
287 const env = yield* GcpEnvironment.current;
288 const prefixName = yield* toName(id, news.prefixName, output?.prefixName);
289 const ownership = yield* createInternalLabels(id);
290 const description = encodeDescription(ownership, news.description);
291
292 let current = yield* getByName(env.project, prefixName);
293
294 if (current === undefined) {
295 yield* compute
296 .insertGlobalPublicDelegatedPrefixes({
297 project: env.project,
298 body: {
299 name: prefixName,
300 description,
301 parentPrefix: news.parentPrefix,
302 ipCidrRange: news.ipCidrRange,
303 mode: news.mode,
304 allocatablePrefixLength: news.allocatablePrefixLength,
305 isLiveMigration: news.isLiveMigration,
306 },
307 })
308 .pipe(
309 Effect.flatMap((operation) =>
310 waitGlobalOperation(env.project, operation, {
311 ignore: ["RESOURCE_ALREADY_EXISTS"],
312 }),
313 ),
314 Effect.catchTag("Conflict", () => Effect.undefined),
315 );
316 current = yield* awaitResource(env.project, prefixName);
317 }
318
319 if (current === undefined) {
320 return yield* new GlobalPublicDelegatedPrefixNotResolved({
321 prefixName,
322 });
323 }
324
325 if ((current.description ?? "") !== description) {
326 yield* compute
327 .patchGlobalPublicDelegatedPrefixes({
328 project: env.project,
329 publicDelegatedPrefix: prefixName,
330 body: {
331 description,
332 fingerprint: current.fingerprint,
333 },
334 })
335 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
336 current = yield* getByName(env.project, prefixName);
337 if (current === undefined) {
338 return yield* new GlobalPublicDelegatedPrefixNotResolved({
339 prefixName,
340 });
341 }
342 }
343
344 return toAttrs(current, env.project);
345 }),
346
347 delete: Effect.fn(function* ({ output }) {
348 const env = yield* GcpEnvironment.current;
349 const operation = yield* compute
350 .deleteGlobalPublicDelegatedPrefixes({
351 project: env.project,
352 publicDelegatedPrefix: output.prefixName,
353 })
354 .pipe(
355 Effect.retry({
356 while: (error) => error._tag === "Conflict",
357 schedule: Schedule.spaced("2 seconds"),
358 times: 8,
359 }),
360 Effect.catchTag("NotFound", () => Effect.undefined),
361 );
362 if (operation !== undefined) {
363 yield* waitGlobalOperation(env.project, operation).pipe(
364 Effect.catchTag("NotFound", () => Effect.void),
365 );
366 }
367 }),
368 });