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

main
ts 422 lines 13.6 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 waitUntilPresent,
26 } from "./internal.ts";
27
28 const COLLECTION = "destinations";
29
30 export type DestinationEndpoint = {
31 /** ASN of the remote IP prefix. */
32 asn?: string;
33 /** Cloud service provider of the remote IP prefix. */
34 csp?: string;
35 /** Server-reported endpoint state (`VALID`, `INVALID`). */
36 state?: string;
37 /** RFC3339 last-update timestamp. */
38 updateTime?: string;
39 };
40
41 export type DestinationStateTimeline = {
42 /** Ordered state/activation entries. */
43 states?: Array<{
44 state?: string;
45 effectiveTime?: string;
46 }>;
47 };
48
49 export type MulticloudDataTransferConfigsDestinationProps = {
50 /**
51 * Parent `MulticloudDataTransferConfig` resource name
52 * `projects/{project}/locations/{location}/multicloudDataTransferConfigs/{config}`.
53 * Immutable — changing it replaces the destination.
54 */
55 parent: string;
56 /**
57 * Destination id (the `{destination}` segment). If omitted, a unique
58 * name is generated from the stack, stage, and logical id. Immutable —
59 * changing it replaces the destination.
60 */
61 destinationId?: string;
62 /**
63 * IP prefix that represents the remote workload. Immutable — changing
64 * it replaces the destination.
65 */
66 ipPrefix: string;
67 /**
68 * Endpoints (ASN + CSP) configured for the prefix.
69 */
70 endpoints: DestinationEndpoint[];
71 /**
72 * Human-readable description.
73 */
74 description?: string;
75 /**
76 * User labels. Alchemy ownership labels are merged in automatically.
77 */
78 labels?: Record<string, string>;
79 };
80
81 export type MulticloudDataTransferConfigsDestination = Resource<
82 "GCP.NetworkConnectivity.MulticloudDataTransferConfigsDestination",
83 MulticloudDataTransferConfigsDestinationProps,
84 {
85 /** Full resource name `.../multicloudDataTransferConfigs/{config}/destinations/{destination}`. */
86 name: string;
87 /** Destination id (last path segment). */
88 destinationId: string;
89 /** Parent config resource name. */
90 parent: string;
91 /** Project id. */
92 project: string;
93 /** Location id. */
94 location: string;
95 /** Config id. */
96 multicloudDataTransferConfigId: string;
97 /** Remote IP prefix. */
98 ipPrefix: string | undefined;
99 /** Endpoints currently configured. */
100 endpoints: DestinationEndpoint[];
101 /** User-provided description. */
102 description: string | undefined;
103 /** Server-reported state timeline. */
104 stateTimeline: DestinationStateTimeline | undefined;
105 /** User labels (Alchemy ownership labels stripped). */
106 labels: Record<string, string>;
107 /** Google-generated unique id. */
108 uid: string | undefined;
109 /** Server etag. */
110 etag: string | undefined;
111 /** RFC3339 creation timestamp. */
112 createTime: string | undefined;
113 /** RFC3339 last-update timestamp. */
114 updateTime: string | undefined;
115 },
116 never,
117 Providers
118 >;
119
120 /**
121 * A Data Transfer Essentials `Destination` — an IP prefix plus ASN/CSP
122 * endpoints billed through a `MulticloudDataTransferConfig`.
123 *
124 * Changing `parent`, `destinationId`, or `ipPrefix` replaces the
125 * destination. Description, labels, and `endpoints` update in place.
126 *
127 * ### Creating a Destination
128 * **Example:** Prefix with one endpoint
129 * ```typescript
130 * const config = yield* GCP.NetworkConnectivity.MulticloudDataTransferConfig(
131 * "Dte",
132 * {},
133 * );
134 * const destination =
135 * yield* GCP.NetworkConnectivity.MulticloudDataTransferConfigsDestination(
136 * "OnPrem",
137 * {
138 * parent: config.name,
139 * ipPrefix: "203.0.113.0/24",
140 * endpoints: [{ asn: "64512", csp: "aws" }],
141 * labels: { env: "prod" },
142 * },
143 * );
144 * ```
145 *
146 * ### Updating a Destination
147 * **Example:** Description, labels, and endpoints
148 * ```typescript
149 * const destination =
150 * yield* GCP.NetworkConnectivity.MulticloudDataTransferConfigsDestination(
151 * "OnPrem",
152 * {
153 * parent: config.name,
154 * ipPrefix: "203.0.113.0/24",
155 * endpoints: [
156 * { asn: "64512", csp: "aws" },
157 * { asn: "64513", csp: "azure" },
158 * ],
159 * description: "on-prem v2",
160 * labels: { env: "prod", role: "dte" },
161 * },
162 * );
163 * ```
164 *
165 * @resource
166 * @category NetworkConnectivity
167 */
168 export const MulticloudDataTransferConfigsDestination =
169 Resource<MulticloudDataTransferConfigsDestination>(
170 "GCP.NetworkConnectivity.MulticloudDataTransferConfigsDestination",
171 );
172
173 const resourceNameOf = (parent: string, destinationId: string) =>
174 `${parent}/destinations/${destinationId}`;
175
176 const toEndpoint = (
177 endpoint: DestinationEndpoint | networkconnectivity.DestinationEndpoint,
178 ): DestinationEndpoint => ({
179 asn: endpoint.asn,
180 csp: endpoint.csp,
181 state: endpoint.state,
182 updateTime: endpoint.updateTime,
183 });
184
185 const desiredEndpoints = (endpoints: DestinationEndpoint[]) =>
186 endpoints.map((endpoint) => ({
187 asn: endpoint.asn,
188 csp: endpoint.csp,
189 }));
190
191 const endpointsKey = (endpoints: readonly DestinationEndpoint[] | undefined) =>
192 JSON.stringify(
193 [...(endpoints ?? [])]
194 .map((endpoint) => ({
195 asn: endpoint.asn ?? "",
196 csp: (endpoint.csp ?? "").toLowerCase(),
197 }))
198 .sort((left, right) =>
199 left.asn === right.asn
200 ? left.csp.localeCompare(right.csp)
201 : left.asn.localeCompare(right.asn),
202 ),
203 );
204
205 const configIdOf = (parent: string) => lastSegment(parent);
206
207 const toAttrs = (destination: networkconnectivity.Destination, project: string, region: string) => {
208 const name = destination.name ?? "";
209 const parsed = parseName(name, COLLECTION, region);
210 const parent = parentOfName(name, COLLECTION);
211 return {
212 name,
213 destinationId: parsed.id,
214 parent,
215 project: parsed.project || project,
216 location: parsed.location || region,
217 multicloudDataTransferConfigId: configIdOf(parent),
218 ipPrefix: destination.ipPrefix,
219 endpoints: (destination.endpoints ?? []).map(toEndpoint),
220 description: destination.description,
221 stateTimeline: destination.stateTimeline
222 ? {
223 states: (destination.stateTimeline.states ?? []).map((entry) => ({
224 state: entry.state,
225 effectiveTime: entry.effectiveTime,
226 })),
227 }
228 : undefined,
229 labels: userLabels(destination.labels),
230 uid: destination.uid,
231 etag: destination.etag,
232 createTime: destination.createTime,
233 updateTime: destination.updateTime,
234 };
235 };
236
237 const getByName = (name: string) =>
238 networkconnectivity
239 .getProjectsLocationsMulticloudDataTransferConfigsDestinations({ name })
240 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
241
242 export const MulticloudDataTransferConfigsDestinationProvider = () =>
243 Provider.succeed(MulticloudDataTransferConfigsDestination, {
244 stables: [
245 "name",
246 "destinationId",
247 "parent",
248 "project",
249 "location",
250 "multicloudDataTransferConfigId",
251 "ipPrefix",
252 "uid",
253 "createTime",
254 ],
255
256 diff: Effect.fn(function* ({ news, olds, output }) {
257 if (!isResolved(news)) return undefined;
258 const previousId = olds?.destinationId ?? output?.destinationId;
259 const nextId = news.destinationId ? rfc1035(news.destinationId, "destination") : previousId;
260 const previousParent = olds?.parent ?? output?.parent;
261 const previousPrefix = olds?.ipPrefix ?? output?.ipPrefix;
262 if (
263 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
264 (previousParent !== undefined && previousParent !== news.parent) ||
265 (previousPrefix !== undefined && previousPrefix !== news.ipPrefix)
266 ) {
267 return { action: "replace" as const };
268 }
269 return undefined;
270 }),
271
272 read: Effect.fn(function* ({ id, olds, output }) {
273 const env = yield* GcpEnvironment.current;
274 const destinationId = yield* toPhysicalId(
275 id,
276 olds?.destinationId,
277 output?.destinationId,
278 "destination",
279 );
280 const parent = olds?.parent ?? output?.parent;
281 const name =
282 output?.name ?? (parent !== undefined ? resourceNameOf(parent, destinationId) : undefined);
283 if (name === undefined) return undefined;
284 const existing = yield* getByName(name);
285 if (existing === undefined) return undefined;
286 const attrs = toAttrs(existing, env.project, env.region);
287 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
288 }),
289
290 list: () =>
291 Effect.gen(function* () {
292 const env = yield* GcpEnvironment.current;
293 const configs = yield* collectPages(
294 networkconnectivity.listProjectsLocationsMulticloudDataTransferConfigs.pages({
295 parent: `projects/${env.project}/locations/-`,
296 pageSize: 1000,
297 returnPartialSuccess: true,
298 }),
299 (page) => page.multicloudDataTransferConfigs,
300 );
301 const nested = yield* Effect.forEach(
302 configs.filter((config) => config.name),
303 (config) =>
304 collectPages(
305 networkconnectivity.listProjectsLocationsMulticloudDataTransferConfigsDestinations.pages(
306 {
307 parent: config.name!,
308 pageSize: 1000,
309 returnPartialSuccess: true,
310 },
311 ),
312 (page) => page.destinations,
313 ),
314 { concurrency: 4 },
315 );
316 return nested
317 .flat()
318 .filter((item) => hasAlchemyLabelKeys(item.labels))
319 .map((item) => toAttrs(item, env.project, env.region));
320 }),
321
322 reconcile: Effect.fn(function* ({ id, news, output }) {
323 const env = yield* GcpEnvironment.current;
324 const destinationId = yield* toPhysicalId(
325 id,
326 news.destinationId,
327 output?.destinationId,
328 "destination",
329 );
330 const name = resourceNameOf(news.parent, destinationId);
331 const desiredLabels = {
332 ...toLabels(news.labels),
333 ...(yield* createInternalLabels(id)),
334 };
335 const endpoints = desiredEndpoints(news.endpoints);
336
337 let current = yield* getByName(name);
338
339 if (current === undefined) {
340 const created = yield* networkconnectivity
341 .createProjectsLocationsMulticloudDataTransferConfigsDestinations({
342 parent: news.parent,
343 destinationId,
344 body: {
345 ipPrefix: news.ipPrefix,
346 endpoints,
347 description: news.description,
348 labels: desiredLabels,
349 },
350 })
351 .pipe(
352 Effect.retry({
353 while: (error) => error._tag === "Conflict",
354 times: 5,
355 schedule: Schedule.spaced("2 seconds"),
356 }),
357 Effect.catchTag("Conflict", () => Effect.undefined),
358 );
359 if (created !== undefined) {
360 yield* waitForOperation(created);
361 }
362 current = yield* waitUntilPresent(getByName(name), name);
363 }
364
365 if (current === undefined) {
366 return yield* new NetworkConnectivityNotResolved({ resourceName: name });
367 }
368
369 const observedLabels = tagRecord(current.labels);
370 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
371 const labelsChanged = upsert.length > 0 || removed.length > 0;
372 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
373 const endpointsChanged =
374 endpointsKey((current.endpoints ?? []).map(toEndpoint)) !== endpointsKey(news.endpoints);
375 const updateMask = changedFields([
376 ["labels", labelsChanged],
377 ["description", descriptionChanged],
378 ["endpoints", endpointsChanged],
379 ]);
380
381 if (updateMask.length > 0) {
382 const operation =
383 yield* networkconnectivity.patchProjectsLocationsMulticloudDataTransferConfigsDestinations(
384 {
385 name: current.name ?? name,
386 updateMask: updateMask.join(","),
387 body: {
388 name: current.name ?? name,
389 labels: desiredLabels,
390 description: news.description,
391 endpoints,
392 etag: current.etag,
393 },
394 },
395 );
396 yield* waitForOperation(operation);
397 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
398 }
399
400 return toAttrs(current, env.project, env.region);
401 }),
402
403 delete: Effect.fn(function* ({ output }) {
404 const operation = yield* networkconnectivity
405 .deleteProjectsLocationsMulticloudDataTransferConfigsDestinations({
406 name: output.name,
407 etag: output.etag,
408 })
409 .pipe(
410 Effect.retry({
411 while: (error) => error._tag === "Conflict",
412 times: 8,
413 schedule: Schedule.spaced("2 seconds"),
414 }),
415 Effect.catchTag("NotFound", () => Effect.undefined),
416 );
417 if (operation !== undefined) {
418 yield* waitForOperation(operation, { notFoundOk: true });
419 }
420 yield* waitUntilGone(getByName(output.name), output.name);
421 }),
422 });