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

main
ts 419 lines 14.6 KB
Raw
1 import * as networksecurity from "@distilled.cloud/gcp/networksecurity_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 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 { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import {
15 DEFAULT_LOCATION,
16 lastSegment,
17 normalizeLocation,
18 parentOf,
19 parseResourceName,
20 resourceName,
21 toId,
22 toNetworkResource,
23 userLabels,
24 } from "./names.ts";
25 import { waitForOperation } from "./operations.ts";
26
27 const COLLECTION = "mirroringDeploymentGroups";
28
29 export type MirroringLocation = {
30 /** Cloud location, e.g. `us-central1-a`. */
31 location: string | undefined;
32 /** Association state in this location (`ACTIVE`, `OUT_OF_SYNC`, …). */
33 state: string | undefined;
34 };
35
36 export type MirroringDeploymentGroupConnectedEndpointGroup = {
37 /** Connected endpoint group resource name. */
38 name: string | undefined;
39 };
40
41 export type MirroringDeploymentGroupNestedDeployment = {
42 /** Nested mirroring deployment resource name. */
43 name: string | undefined;
44 /** Most recent known state of the nested deployment. */
45 state: string | undefined;
46 };
47
48 export type MirroringDeploymentGroupProps = {
49 /**
50 * Deployment group id (the `{mirroringDeploymentGroup}` segment of
51 * `projects/{project}/locations/{location}/mirroringDeploymentGroups/{mirroringDeploymentGroup}`).
52 * If omitted, a unique RFC1035 name is generated from the stack, stage,
53 * and logical id. Immutable — changing it replaces the group.
54 */
55 mirroringDeploymentGroupId?: string;
56 /**
57 * Location of the group. Deployment groups are global — always
58 * `"global"`. Immutable — changing it replaces the group. `GLOBAL` is
59 * accepted and normalized to `global`.
60 * @default "global"
61 */
62 location?: string;
63 /**
64 * VPC used by every child deployment, as a name (`app-vpc`), resource
65 * path (`projects/{project}/global/networks/{network}`), or Compute
66 * self-link. Immutable — changing it replaces the group.
67 */
68 network: string;
69 /**
70 * Human-readable description of the deployment group.
71 */
72 description?: string;
73 /**
74 * User labels. Alchemy ownership labels are merged in automatically.
75 */
76 labels?: Record<string, string>;
77 };
78
79 export type MirroringDeploymentGroup = Resource<
80 "GCP.NetworkSecurity.MirroringDeploymentGroup",
81 MirroringDeploymentGroupProps,
82 {
83 /** Full resource name. */
84 name: string;
85 /** Deployment group id (last path segment). */
86 mirroringDeploymentGroupId: string;
87 /** Project id. */
88 project: string;
89 /** Location id. Always `"global"`. */
90 location: string;
91 /** VPC resource path used by child deployments. */
92 network: string | undefined;
93 /** VPC network id (last path segment). */
94 networkName: string | undefined;
95 /** User-provided description. */
96 description: string | undefined;
97 /** User labels (Alchemy ownership labels stripped). */
98 labels: Record<string, string>;
99 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
100 state: string | undefined;
101 /** Whether the API is still reconciling intended vs actual state. */
102 reconciling: boolean;
103 /** Locations where the group is present. */
104 locations: MirroringLocation[];
105 /** Endpoint groups connected to this group. */
106 connectedEndpointGroups: MirroringDeploymentGroupConnectedEndpointGroup[];
107 /** Nested mirroring deployments. */
108 nestedDeployments: MirroringDeploymentGroupNestedDeployment[];
109 /** RFC3339 creation timestamp. */
110 createTime: string | undefined;
111 /** RFC3339 last-update timestamp. */
112 updateTime: string | undefined;
113 },
114 never,
115 Providers
116 >;
117
118 /**
119 * A Network Security Integration mirroring deployment group — the global
120 * backend that aggregates zonal mirroring collectors.
121 *
122 * Changing `mirroringDeploymentGroupId`, `location`, or `network` replaces
123 * the group. Description and labels update in place.
124 *
125 * ### Creating a Deployment Group
126 * **Example:** Generated name
127 * ```typescript
128 * const group = yield* GCP.NetworkSecurity.MirroringDeploymentGroup("Collectors", {
129 * network: vpc.selfLink,
130 * });
131 * ```
132 *
133 * **Example:** Named group with labels
134 * ```typescript
135 * const group = yield* GCP.NetworkSecurity.MirroringDeploymentGroup("Collectors", {
136 * mirroringDeploymentGroupId: "app-collectors",
137 * network: "projects/my-project/global/networks/app-vpc",
138 * description: "prod mirroring backends",
139 * labels: { env: "prod" },
140 * });
141 * ```
142 *
143 * ### Updating a Deployment Group
144 * **Example:** Description and labels
145 * ```typescript
146 * const group = yield* GCP.NetworkSecurity.MirroringDeploymentGroup("Collectors", {
147 * mirroringDeploymentGroupId: "app-collectors",
148 * network: vpc.selfLink,
149 * description: "prod mirroring backends v2",
150 * labels: { env: "prod", role: "nsi" },
151 * });
152 * ```
153 *
154 * @resource
155 * @category NetworkSecurity
156 */
157 export const MirroringDeploymentGroup = Resource<MirroringDeploymentGroup>(
158 "GCP.NetworkSecurity.MirroringDeploymentGroup",
159 );
160
161 export class MirroringDeploymentGroupNotResolved extends Data.TaggedError(
162 "GCP.NetworkSecurity.MirroringDeploymentGroupNotResolved",
163 )<{
164 resourceName: string;
165 }> {}
166
167 export class MirroringDeploymentGroupFailed extends Data.TaggedError(
168 "GCP.NetworkSecurity.MirroringDeploymentGroupFailed",
169 )<{
170 resourceName: string;
171 state: string | undefined;
172 }> {}
173
174 export class MirroringDeploymentGroupStillExists extends Data.TaggedError(
175 "GCP.NetworkSecurity.MirroringDeploymentGroupStillExists",
176 )<{
177 resourceName: string;
178 }> {}
179
180 const isPendingState = (state: string | undefined) =>
181 state === "CREATING" || state === "DELETING" || state === "STATE_UNSPECIFIED";
182
183 const toLocations = (
184 locations: networksecurity.MirroringLocationList | undefined,
185 ): MirroringLocation[] =>
186 (locations ?? []).map((item) => ({
187 location: item.location,
188 state: item.state,
189 }));
190
191 const toConnected = (
192 groups: networksecurity.MirroringDeploymentGroupConnectedEndpointGroupList | undefined,
193 ): MirroringDeploymentGroupConnectedEndpointGroup[] =>
194 (groups ?? []).map((item) => ({ name: item.name }));
195
196 const toNested = (
197 deployments: networksecurity.MirroringDeploymentGroupDeploymentList | undefined,
198 ): MirroringDeploymentGroupNestedDeployment[] =>
199 (deployments ?? []).map((item) => ({
200 name: item.name,
201 state: item.state,
202 }));
203
204 const toAttrs = (group: networksecurity.MirroringDeploymentGroup, project: string) => {
205 const name = group.name ?? "";
206 const parsed = parseResourceName(name, COLLECTION);
207 return {
208 name,
209 mirroringDeploymentGroupId: parsed.id,
210 project: parsed.project || project,
211 location: parsed.location || DEFAULT_LOCATION,
212 network: group.network,
213 networkName: group.network ? lastSegment(group.network) : undefined,
214 description: group.description,
215 labels: userLabels(group.labels),
216 state: group.state,
217 reconciling: group.reconciling === true,
218 locations: toLocations(group.locations),
219 connectedEndpointGroups: toConnected(group.connectedEndpointGroups),
220 nestedDeployments: toNested(group.nestedDeployments),
221 createTime: group.createTime,
222 updateTime: group.updateTime,
223 };
224 };
225
226 const getByName = (name: string) =>
227 networksecurity
228 .getProjectsLocationsMirroringDeploymentGroups({ name })
229 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
230
231 const waitUntilReady = (name: string) =>
232 getByName(name).pipe(
233 Effect.filterOrFail(
234 (group): group is networksecurity.MirroringDeploymentGroup => group !== undefined,
235 () => new MirroringDeploymentGroupNotResolved({ resourceName: name }),
236 ),
237 Effect.filterOrFail(
238 (group) => group.state !== "DELETE_FAILED",
239 (group) => new MirroringDeploymentGroupFailed({ resourceName: name, state: group.state }),
240 ),
241 Effect.filterOrFail(
242 (group) => !isPendingState(group.state),
243 () => new MirroringDeploymentGroupNotResolved({ resourceName: name }),
244 ),
245 Effect.retry({
246 while: (error) => error._tag === "GCP.NetworkSecurity.MirroringDeploymentGroupNotResolved",
247 times: 10,
248 schedule: Schedule.spaced("2 seconds"),
249 }),
250 );
251
252 const waitUntilGone = (name: string) =>
253 getByName(name).pipe(
254 Effect.flatMap((group) =>
255 group === undefined
256 ? Effect.void
257 : Effect.fail(new MirroringDeploymentGroupStillExists({ resourceName: name })),
258 ),
259 Effect.retry({
260 while: (error) => error._tag === "GCP.NetworkSecurity.MirroringDeploymentGroupStillExists",
261 times: 10,
262 schedule: Schedule.spaced("2 seconds"),
263 }),
264 );
265
266 const listOwned = (project: string) =>
267 networksecurity.listProjectsLocationsMirroringDeploymentGroups
268 .pages({
269 parent: parentOf(project, "-"),
270 pageSize: 1000,
271 })
272 .pipe(
273 Stream.flatMap((page) => Stream.fromIterable(page.mirroringDeploymentGroups ?? [])),
274 Stream.filter((group) =>
275 Object.keys(group.labels ?? {}).some((key) => key.startsWith("alchemy-")),
276 ),
277 Stream.map((group) => toAttrs(group, project)),
278 Stream.runCollect,
279 Effect.map((chunk) => Array.from(chunk)),
280 Effect.catchTag("NotFound", () => Effect.succeed([])),
281 );
282
283 export const MirroringDeploymentGroupProvider = () =>
284 Provider.succeed(MirroringDeploymentGroup, {
285 stables: ["name", "mirroringDeploymentGroupId", "project", "location", "network", "createTime"],
286
287 diff: Effect.fn(function* ({ news, olds, output }) {
288 if (!isResolved(news)) return undefined;
289 const previousId = olds?.mirroringDeploymentGroupId ?? output?.mirroringDeploymentGroupId;
290 const nextId = news.mirroringDeploymentGroupId ?? previousId;
291 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
292 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
293 const previousNetwork = lastSegment(
294 olds?.network ?? output?.networkName ?? output?.network ?? "",
295 );
296 const nextNetwork = lastSegment(news.network);
297 const replace =
298 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
299 previousLocation !== nextLocation ||
300 (previousNetwork.length > 0 && previousNetwork !== nextNetwork);
301 if (!replace) return undefined;
302 return { action: "replace" as const };
303 }),
304
305 read: Effect.fn(function* ({ id, olds, output }) {
306 const env = yield* GcpEnvironment.current;
307 const mirroringDeploymentGroupId = yield* toId(
308 id,
309 olds?.mirroringDeploymentGroupId,
310 output?.mirroringDeploymentGroupId,
311 "mdg",
312 );
313 const location = normalizeLocation(olds?.location ?? output?.location);
314 const name =
315 output?.name ?? resourceName(env.project, location, COLLECTION, mirroringDeploymentGroupId);
316 const existing = yield* getByName(name);
317 if (existing === undefined) return undefined;
318 const attrs = toAttrs(existing, env.project);
319 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
320 }),
321
322 list: () =>
323 Effect.gen(function* () {
324 const env = yield* GcpEnvironment.current;
325 return yield* listOwned(env.project);
326 }),
327
328 reconcile: Effect.fn(function* ({ id, news, output }) {
329 const env = yield* GcpEnvironment.current;
330 const mirroringDeploymentGroupId = yield* toId(
331 id,
332 news.mirroringDeploymentGroupId,
333 output?.mirroringDeploymentGroupId,
334 "mdg",
335 );
336 const location = normalizeLocation(news.location ?? output?.location);
337 const name = resourceName(env.project, location, COLLECTION, mirroringDeploymentGroupId);
338 const network = toNetworkResource(env.project, news.network);
339 const desiredLabels = {
340 ...toLabels(news.labels),
341 ...(yield* createInternalLabels(id)),
342 };
343
344 let current = yield* getByName(name);
345
346 if (current === undefined) {
347 const created = yield* networksecurity
348 .createProjectsLocationsMirroringDeploymentGroups({
349 parent: parentOf(env.project, location),
350 mirroringDeploymentGroupId,
351 body: {
352 network,
353 description: news.description,
354 labels: desiredLabels,
355 },
356 })
357 .pipe(
358 Effect.retry({
359 while: (error) => error._tag === "Conflict",
360 times: 5,
361 schedule: Schedule.spaced("2 seconds"),
362 }),
363 Effect.catchTag("Conflict", () => Effect.undefined),
364 );
365 if (created !== undefined) {
366 yield* waitForOperation(created);
367 }
368 current = yield* waitUntilReady(name);
369 }
370
371 if (current === undefined) {
372 return yield* new MirroringDeploymentGroupNotResolved({ resourceName: name });
373 }
374
375 const observedLabels = tagRecord(current.labels);
376 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
377 const labelsChanged = upsert.length > 0 || removed.length > 0;
378 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
379
380 if (labelsChanged || descriptionChanged) {
381 const updateMask = [
382 labelsChanged ? "labels" : undefined,
383 descriptionChanged ? "description" : undefined,
384 ].filter((field): field is string => field !== undefined);
385 const operation = yield* networksecurity.patchProjectsLocationsMirroringDeploymentGroups({
386 name: current.name ?? name,
387 updateMask: updateMask.join(","),
388 body: {
389 name: current.name ?? name,
390 labels: desiredLabels,
391 description: news.description,
392 },
393 });
394 yield* waitForOperation(operation);
395 current = yield* waitUntilReady(current.name ?? name);
396 }
397
398 return toAttrs(current, env.project);
399 }),
400
401 delete: Effect.fn(function* ({ output }) {
402 const operation = yield* networksecurity
403 .deleteProjectsLocationsMirroringDeploymentGroups({
404 name: output.name,
405 })
406 .pipe(
407 Effect.retry({
408 while: (error) => error._tag === "Conflict",
409 times: 8,
410 schedule: Schedule.spaced("2 seconds"),
411 }),
412 Effect.catchTag("NotFound", () => Effect.undefined),
413 );
414 if (operation !== undefined) {
415 yield* waitForOperation(operation, { notFoundOk: true });
416 }
417 yield* waitUntilGone(output.name);
418 }),
419 });