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

main
ts 392 lines 13.1 KB
Raw
1 import * as networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 NetworkConnectivityNotResolved,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 lastSegment,
18 parentOfName,
19 parseName,
20 rfc1035,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilGone,
25 waitUntilReady,
26 } from "./internal.ts";
27
28 const COLLECTION = "gatewayAdvertisedRoutes";
29 const DEFAULT_PRIORITY = 100;
30
31 export type GatewayAdvertisedRouteRecipient =
32 | networkconnectivity.GatewayAdvertisedRouteRecipientEnum
33 | (string & {});
34
35 export type SpokesGatewayAdvertisedRouteProps = {
36 /**
37 * Parent gateway spoke resource name
38 * `projects/{project}/locations/{location}/spokes/{spoke}`. Immutable —
39 * changing it replaces the route.
40 */
41 parent: string;
42 /**
43 * Route id (the `{gateway_advertised_route}` segment). If omitted, a
44 * unique name is generated. Immutable — changing it replaces the
45 * route.
46 */
47 gatewayAdvertisedRouteId?: string;
48 /**
49 * Advertised CIDR (`"10.0.0.0/24"` or a single IP, interpreted as
50 * `/32` or `/128`). Immutable — changing it replaces the route.
51 */
52 ipRange: string;
53 /**
54 * Priority from `0` to `65335`. Defaults to `100`.
55 * @default 100
56 */
57 priority?: number;
58 /**
59 * Recipient of this advertised route.
60 */
61 recipient?: GatewayAdvertisedRouteRecipient;
62 /**
63 * Human-readable description. Immutable — changing it replaces the
64 * route (GCP rejects `description` in PATCH).
65 */
66 description?: string;
67 /**
68 * User labels. Alchemy ownership labels are merged in automatically.
69 * Immutable — changing them replaces the route.
70 */
71 labels?: Record<string, string>;
72 };
73
74 export type SpokesGatewayAdvertisedRoute = Resource<
75 "GCP.NetworkConnectivity.SpokesGatewayAdvertisedRoute",
76 SpokesGatewayAdvertisedRouteProps,
77 {
78 /** Full resource name `.../spokes/{spoke}/gatewayAdvertisedRoutes/{id}`. */
79 name: string;
80 /** Route id (last path segment). */
81 gatewayAdvertisedRouteId: string;
82 /** Parent gateway spoke resource name. */
83 parent: string;
84 /** Project id. */
85 project: string;
86 /** Location id. */
87 location: string;
88 /** Spoke id. */
89 spokeId: string;
90 /** Advertised CIDR. */
91 ipRange: string | undefined;
92 /** Advertised-route priority. */
93 priority: number | undefined;
94 /** Recipient of this advertised route. */
95 recipient: string | undefined;
96 /** User-provided description. */
97 description: string | undefined;
98 /** User labels (Alchemy ownership labels stripped). */
99 labels: Record<string, string>;
100 /** Server-generated UUID. */
101 uniqueId: string | undefined;
102 /** Server-reported lifecycle state. */
103 state: string | undefined;
104 /** RFC3339 creation timestamp. */
105 createTime: string | undefined;
106 /** RFC3339 last-update timestamp. */
107 updateTime: string | undefined;
108 },
109 never,
110 Providers
111 >;
112
113 /**
114 * A route a Network Connectivity Center gateway spoke advertises to a
115 * hub (or other recipient).
116 *
117 * Changing `parent`, `gatewayAdvertisedRouteId`, `ipRange`, `labels`, or
118 * `description` replaces the route (GCP does not allow updating labels or
119 * the description). `priority` and `recipient` update in place.
120 *
121 * ### Creating a GatewayAdvertisedRoute
122 * **Example:** Advertise a CIDR to the hub
123 * ```typescript
124 * const hub = yield* GCP.NetworkConnectivity.Hub("Mesh", {});
125 * const spoke = yield* GCP.NetworkConnectivity.Spoke("Gw", {
126 * location: "us-central1",
127 * hub: hub.name,
128 * gateway: {
129 * capacity: "CAPACITY_1_GBPS",
130 * ipRangeReservations: [{ ipRange: "10.200.0.0/23" }],
131 * },
132 * });
133 * const route = yield* GCP.NetworkConnectivity.SpokesGatewayAdvertisedRoute(
134 * "OnPrem",
135 * {
136 * parent: spoke.name,
137 * ipRange: "192.168.0.0/16",
138 * recipient: "ADVERTISE_TO_HUB",
139 * labels: { env: "prod" },
140 * },
141 * );
142 * ```
143 *
144 * ### Updating a GatewayAdvertisedRoute
145 * **Example:** Description and priority
146 * ```typescript
147 * const route = yield* GCP.NetworkConnectivity.SpokesGatewayAdvertisedRoute(
148 * "OnPrem",
149 * {
150 * parent: spoke.name,
151 * ipRange: "192.168.0.0/16",
152 * priority: 200,
153 * recipient: "ADVERTISE_TO_HUB",
154 * description: "on-prem v2",
155 * labels: { env: "prod" },
156 * },
157 * );
158 * ```
159 *
160 * @resource
161 * @category NetworkConnectivity
162 */
163 export const SpokesGatewayAdvertisedRoute = Resource<SpokesGatewayAdvertisedRoute>(
164 "GCP.NetworkConnectivity.SpokesGatewayAdvertisedRoute",
165 );
166
167 const resourceNameOf = (parent: string, gatewayAdvertisedRouteId: string) =>
168 `${parent}/gatewayAdvertisedRoutes/${gatewayAdvertisedRouteId}`;
169
170 const toAttrs = (
171 route: networkconnectivity.GatewayAdvertisedRoute,
172 project: string,
173 region: string,
174 ) => {
175 const name = route.name ?? "";
176 const parsed = parseName(name, COLLECTION, region);
177 const parent = parentOfName(name, COLLECTION);
178 return {
179 name,
180 gatewayAdvertisedRouteId: parsed.id,
181 parent,
182 project: parsed.project || project,
183 location: parsed.location || region,
184 spokeId: lastSegment(parent),
185 ipRange: route.ipRange,
186 priority: route.priority,
187 recipient: route.recipient,
188 description: route.description,
189 labels: userLabels(route.labels),
190 uniqueId: route.uniqueId,
191 state: route.state,
192 createTime: route.createTime,
193 updateTime: route.updateTime,
194 };
195 };
196
197 const getByName = (name: string) =>
198 networkconnectivity
199 .getProjectsLocationsSpokesGatewayAdvertisedRoutes({ name })
200 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
201
202 export const SpokesGatewayAdvertisedRouteProvider = () =>
203 Provider.succeed(SpokesGatewayAdvertisedRoute, {
204 stables: [
205 "name",
206 "gatewayAdvertisedRouteId",
207 "parent",
208 "project",
209 "location",
210 "spokeId",
211 "ipRange",
212 "uniqueId",
213 "createTime",
214 ],
215
216 diff: Effect.fn(function* ({ news, olds, output }) {
217 if (!isResolved(news)) return undefined;
218 const previousId = olds?.gatewayAdvertisedRouteId ?? output?.gatewayAdvertisedRouteId;
219 const nextId = news.gatewayAdvertisedRouteId
220 ? rfc1035(news.gatewayAdvertisedRouteId, "gateway-advertised-route")
221 : previousId;
222 const previousParent = olds?.parent ?? output?.parent;
223 const previousRange = olds?.ipRange ?? output?.ipRange;
224 const previousLabels = olds?.labels ?? output?.labels;
225 const previousDescription = olds?.description ?? output?.description;
226 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
227 const parentChanged = previousParent !== undefined && previousParent !== news.parent;
228 const rangeChanged = previousRange !== undefined && previousRange !== news.ipRange;
229 // `labels` is not mutable on GatewayAdvertisedRoute (PATCH rejects the
230 // path), so a labels change replaces the route.
231 const labels = diffLabels(toLabels(previousLabels), toLabels(news.labels));
232 const labelsChanged =
233 previousLabels !== undefined && (labels.upsert.length > 0 || labels.removed.length > 0);
234 // `description` is not mutable either.
235 const descriptionChanged =
236 (olds !== undefined || output !== undefined) &&
237 (previousDescription ?? "") !== (news.description ?? "");
238 if (idChanged || parentChanged || rangeChanged || labelsChanged || descriptionChanged) {
239 return {
240 action: "replace" as const,
241 // A route with a pinned id, or the same CIDR on the same spoke,
242 // collides with the old route; delete it first.
243 deleteFirst:
244 !parentChanged &&
245 (!rangeChanged || (news.gatewayAdvertisedRouteId !== undefined && !idChanged)),
246 };
247 }
248 return undefined;
249 }),
250
251 read: Effect.fn(function* ({ id, olds, output }) {
252 const env = yield* GcpEnvironment.current;
253 const gatewayAdvertisedRouteId = yield* toPhysicalId(
254 id,
255 olds?.gatewayAdvertisedRouteId,
256 output?.gatewayAdvertisedRouteId,
257 "gateway-advertised-route",
258 );
259 const parent = olds?.parent ?? output?.parent;
260 const name =
261 output?.name ??
262 (parent !== undefined ? resourceNameOf(parent, gatewayAdvertisedRouteId) : undefined);
263 if (name === undefined) return undefined;
264 const existing = yield* getByName(name);
265 if (existing === undefined) return undefined;
266 const attrs = toAttrs(existing, env.project, env.region);
267 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
268 }),
269
270 list: () =>
271 Effect.gen(function* () {
272 const env = yield* GcpEnvironment.current;
273 const spokes = yield* collectPages(
274 networkconnectivity.listProjectsLocationsSpokes.pages({
275 parent: `projects/${env.project}/locations/-`,
276 pageSize: 1000,
277 }),
278 (page) => page.spokes,
279 );
280 const nested = yield* Effect.forEach(
281 spokes.filter((spoke) => spoke.name),
282 (spoke) =>
283 collectPages(
284 networkconnectivity.listProjectsLocationsSpokesGatewayAdvertisedRoutes.pages({
285 parent: spoke.name!,
286 pageSize: 1000,
287 }),
288 (page) => page.gatewayAdvertisedRoutes,
289 ),
290 { concurrency: 4 },
291 );
292 return nested
293 .flat()
294 .filter((item) => hasAlchemyLabelKeys(item.labels))
295 .map((item) => toAttrs(item, env.project, env.region));
296 }),
297
298 reconcile: Effect.fn(function* ({ id, news, output }) {
299 const env = yield* GcpEnvironment.current;
300 const gatewayAdvertisedRouteId = yield* toPhysicalId(
301 id,
302 news.gatewayAdvertisedRouteId,
303 output?.gatewayAdvertisedRouteId,
304 "gateway-advertised-route",
305 );
306 const name = resourceNameOf(news.parent, gatewayAdvertisedRouteId);
307 const desiredLabels = {
308 ...toLabels(news.labels),
309 ...(yield* createInternalLabels(id)),
310 };
311 const priority = news.priority ?? DEFAULT_PRIORITY;
312
313 let current = yield* getByName(name);
314
315 if (current === undefined) {
316 const created = yield* networkconnectivity
317 .createProjectsLocationsSpokesGatewayAdvertisedRoutes({
318 parent: news.parent,
319 gatewayAdvertisedRouteId,
320 body: {
321 ipRange: news.ipRange,
322 priority,
323 recipient: news.recipient,
324 description: news.description,
325 labels: desiredLabels,
326 },
327 })
328 .pipe(
329 Effect.retry({
330 while: (error) => error._tag === "Conflict",
331 times: 5,
332 schedule: Schedule.spaced("2 seconds"),
333 }),
334 Effect.catchTag("Conflict", () => Effect.undefined),
335 );
336 if (created !== undefined) {
337 yield* waitForOperation(created);
338 }
339 current = yield* waitUntilReady(getByName(name), name);
340 }
341
342 if (current === undefined) {
343 return yield* new NetworkConnectivityNotResolved({ resourceName: name });
344 }
345
346 // Labels and description are create-only; `diff` replaces the route
347 // when they change.
348 const priorityChanged = (current.priority ?? DEFAULT_PRIORITY) !== priority;
349 const recipientChanged = (current.recipient ?? "") !== (news.recipient ?? "");
350 const updateMask = changedFields([
351 ["priority", priorityChanged],
352 ["recipient", recipientChanged],
353 ]);
354
355 if (updateMask.length > 0) {
356 const operation =
357 yield* networkconnectivity.patchProjectsLocationsSpokesGatewayAdvertisedRoutes({
358 name: current.name ?? name,
359 updateMask: updateMask.join(","),
360 body: {
361 name: current.name ?? name,
362 description: news.description,
363 priority,
364 recipient: news.recipient,
365 },
366 });
367 yield* waitForOperation(operation);
368 current = yield* waitUntilReady(getByName(current.name ?? name), current.name ?? name);
369 }
370
371 return toAttrs(current, env.project, env.region);
372 }),
373
374 delete: Effect.fn(function* ({ output }) {
375 const operation = yield* networkconnectivity
376 .deleteProjectsLocationsSpokesGatewayAdvertisedRoutes({
377 name: output.name,
378 })
379 .pipe(
380 Effect.retry({
381 while: (error) => error._tag === "Conflict",
382 times: 8,
383 schedule: Schedule.spaced("2 seconds"),
384 }),
385 Effect.catchTag("NotFound", () => Effect.undefined),
386 );
387 if (operation !== undefined) {
388 yield* waitForOperation(operation, { notFoundOk: true });
389 }
390 yield* waitUntilGone(getByName(output.name), output.name);
391 }),
392 });