@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 421 lines 14.3 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 toResourcePath,
23 userLabels,
24 } from "./names.ts";
25 import { waitForOperation } from "./operations.ts";
26
27 const COLLECTION = "interceptEndpointGroups";
28
29 export type InterceptEndpointGroupAssociationDetail = {
30 /** Connected association resource name. */
31 name: string | undefined;
32 /** Associated VPC network. */
33 network: string | undefined;
34 /** Most recent known association state. */
35 state: string | undefined;
36 };
37
38 export type InterceptEndpointGroupConnectedDeploymentGroup = {
39 /** Connected deployment group resource name. */
40 name: string | undefined;
41 /** Locations where the deployment group is present. */
42 locations: Array<{
43 location: string | undefined;
44 state: string | undefined;
45 }>;
46 };
47
48 export type InterceptEndpointGroupProps = {
49 /**
50 * Endpoint group id (the `{interceptEndpointGroup}` segment of
51 * `projects/{project}/locations/{location}/interceptEndpointGroups/{interceptEndpointGroup}`).
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 interceptEndpointGroupId?: string;
56 /**
57 * Location of the group. Endpoint 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 * Deployment group this endpoint group is connected to, as a full
65 * resource name. Immutable — changing it replaces the group.
66 */
67 interceptDeploymentGroup: string;
68 /**
69 * Human-readable description of the endpoint group.
70 */
71 description?: string;
72 /**
73 * User labels. Alchemy ownership labels are merged in automatically.
74 */
75 labels?: Record<string, string>;
76 };
77
78 export type InterceptEndpointGroup = Resource<
79 "GCP.NetworkSecurity.InterceptEndpointGroup",
80 InterceptEndpointGroupProps,
81 {
82 /** Full resource name. */
83 name: string;
84 /** Endpoint group id (last path segment). */
85 interceptEndpointGroupId: string;
86 /** Project id. */
87 project: string;
88 /** Location id. Always `"global"`. */
89 location: string;
90 /** Connected deployment group resource name. */
91 interceptDeploymentGroup: string | undefined;
92 /** User-provided description. */
93 description: string | undefined;
94 /** User labels (Alchemy ownership labels stripped). */
95 labels: Record<string, string>;
96 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
97 state: string | undefined;
98 /** Whether the API is still reconciling intended vs actual state. */
99 reconciling: boolean;
100 /** Associations attached to this group. */
101 associations: InterceptEndpointGroupAssociationDetail[];
102 /** Connected deployment group details. */
103 connectedDeploymentGroup: InterceptEndpointGroupConnectedDeploymentGroup | 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 Network Security Integration intercept endpoint group — the consumer
115 * frontend for an intercept deployment group.
116 *
117 * Changing `interceptEndpointGroupId`, `location`, or
118 * `interceptDeploymentGroup` replaces the group. Description and labels
119 * update in place.
120 *
121 * ### Creating an Endpoint Group
122 * **Example:** Generated name
123 * ```typescript
124 * const endpoints = yield* GCP.NetworkSecurity.InterceptEndpointGroup("Front", {
125 * interceptDeploymentGroup: group.name,
126 * });
127 * ```
128 *
129 * **Example:** Named group with labels
130 * ```typescript
131 * const endpoints = yield* GCP.NetworkSecurity.InterceptEndpointGroup("Front", {
132 * interceptEndpointGroupId: "app-intercept-eg",
133 * interceptDeploymentGroup: group.name,
134 * description: "prod intercept frontend",
135 * labels: { env: "prod" },
136 * });
137 * ```
138 *
139 * ### Updating an Endpoint Group
140 * **Example:** Description and labels
141 * ```typescript
142 * const endpoints = yield* GCP.NetworkSecurity.InterceptEndpointGroup("Front", {
143 * interceptEndpointGroupId: "app-intercept-eg",
144 * interceptDeploymentGroup: group.name,
145 * description: "prod intercept frontend v2",
146 * labels: { env: "prod", role: "nsi" },
147 * });
148 * ```
149 *
150 * @resource
151 * @category NetworkSecurity
152 */
153 export const InterceptEndpointGroup = Resource<InterceptEndpointGroup>(
154 "GCP.NetworkSecurity.InterceptEndpointGroup",
155 );
156
157 export class InterceptEndpointGroupNotResolved extends Data.TaggedError(
158 "GCP.NetworkSecurity.InterceptEndpointGroupNotResolved",
159 )<{
160 resourceName: string;
161 }> {}
162
163 export class InterceptEndpointGroupFailed extends Data.TaggedError(
164 "GCP.NetworkSecurity.InterceptEndpointGroupFailed",
165 )<{
166 resourceName: string;
167 state: string | undefined;
168 }> {}
169
170 export class InterceptEndpointGroupStillExists extends Data.TaggedError(
171 "GCP.NetworkSecurity.InterceptEndpointGroupStillExists",
172 )<{
173 resourceName: string;
174 }> {}
175
176 const isPendingState = (state: string | undefined) =>
177 state === "CREATING" || state === "DELETING" || state === "STATE_UNSPECIFIED";
178
179 const toAssociations = (
180 associations: networksecurity.InterceptEndpointGroupAssociationDetailsList | undefined,
181 ): InterceptEndpointGroupAssociationDetail[] =>
182 (associations ?? []).map((item) => ({
183 name: item.name,
184 network: item.network,
185 state: item.state,
186 }));
187
188 const toConnected = (
189 group: networksecurity.InterceptEndpointGroupConnectedDeploymentGroup | undefined,
190 ): InterceptEndpointGroupConnectedDeploymentGroup | undefined =>
191 group === undefined
192 ? undefined
193 : {
194 name: group.name,
195 locations: (group.locations ?? []).map((location) => ({
196 location: location.location,
197 state: location.state,
198 })),
199 };
200
201 const toAttrs = (group: networksecurity.InterceptEndpointGroup, project: string) => {
202 const name = group.name ?? "";
203 const parsed = parseResourceName(name, COLLECTION);
204 return {
205 name,
206 interceptEndpointGroupId: parsed.id,
207 project: parsed.project || project,
208 location: parsed.location || DEFAULT_LOCATION,
209 interceptDeploymentGroup: group.interceptDeploymentGroup,
210 description: group.description,
211 labels: userLabels(group.labels),
212 state: group.state,
213 reconciling: group.reconciling === true,
214 associations: toAssociations(group.associations),
215 connectedDeploymentGroup: toConnected(group.connectedDeploymentGroup),
216 createTime: group.createTime,
217 updateTime: group.updateTime,
218 };
219 };
220
221 const getByName = (name: string) =>
222 networksecurity
223 .getProjectsLocationsInterceptEndpointGroups({ name })
224 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
225
226 const waitUntilReady = (name: string) =>
227 getByName(name).pipe(
228 Effect.filterOrFail(
229 (group): group is networksecurity.InterceptEndpointGroup => group !== undefined,
230 () => new InterceptEndpointGroupNotResolved({ resourceName: name }),
231 ),
232 Effect.filterOrFail(
233 (group) => group.state !== "DELETE_FAILED",
234 (group) => new InterceptEndpointGroupFailed({ resourceName: name, state: group.state }),
235 ),
236 Effect.filterOrFail(
237 (group) => !isPendingState(group.state),
238 () => new InterceptEndpointGroupNotResolved({ resourceName: name }),
239 ),
240 Effect.retry({
241 while: (error) => error._tag === "GCP.NetworkSecurity.InterceptEndpointGroupNotResolved",
242 times: 10,
243 schedule: Schedule.spaced("2 seconds"),
244 }),
245 );
246
247 const waitUntilGone = (name: string) =>
248 getByName(name).pipe(
249 Effect.flatMap((group) =>
250 group === undefined
251 ? Effect.void
252 : Effect.fail(new InterceptEndpointGroupStillExists({ resourceName: name })),
253 ),
254 Effect.retry({
255 while: (error) => error._tag === "GCP.NetworkSecurity.InterceptEndpointGroupStillExists",
256 times: 10,
257 schedule: Schedule.spaced("2 seconds"),
258 }),
259 );
260
261 const listOwned = (project: string) =>
262 networksecurity.listProjectsLocationsInterceptEndpointGroups
263 .pages({
264 parent: parentOf(project, "-"),
265 pageSize: 1000,
266 })
267 .pipe(
268 Stream.flatMap((page) => Stream.fromIterable(page.interceptEndpointGroups ?? [])),
269 Stream.filter((group) =>
270 Object.keys(group.labels ?? {}).some((key) => key.startsWith("alchemy-")),
271 ),
272 Stream.map((group) => toAttrs(group, project)),
273 Stream.runCollect,
274 Effect.map((chunk) => Array.from(chunk)),
275 Effect.catchTag("NotFound", () => Effect.succeed([])),
276 );
277
278 export const InterceptEndpointGroupProvider = () =>
279 Provider.succeed(InterceptEndpointGroup, {
280 stables: [
281 "name",
282 "interceptEndpointGroupId",
283 "project",
284 "location",
285 "interceptDeploymentGroup",
286 "createTime",
287 ],
288
289 diff: Effect.fn(function* ({ news, olds, output }) {
290 if (!isResolved(news)) return undefined;
291 const previousId = olds?.interceptEndpointGroupId ?? output?.interceptEndpointGroupId;
292 const nextId = news.interceptEndpointGroupId ?? previousId;
293 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
294 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
295 const previousGroup = lastSegment(
296 olds?.interceptDeploymentGroup ?? output?.interceptDeploymentGroup ?? "",
297 );
298 const nextGroup = lastSegment(news.interceptDeploymentGroup);
299 const replace =
300 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
301 previousLocation !== nextLocation ||
302 (previousGroup.length > 0 && previousGroup !== nextGroup);
303 if (!replace) return undefined;
304 return { action: "replace" as const };
305 }),
306
307 read: Effect.fn(function* ({ id, olds, output }) {
308 const env = yield* GcpEnvironment.current;
309 const interceptEndpointGroupId = yield* toId(
310 id,
311 olds?.interceptEndpointGroupId,
312 output?.interceptEndpointGroupId,
313 "ieg",
314 );
315 const location = normalizeLocation(olds?.location ?? output?.location);
316 const name =
317 output?.name ?? resourceName(env.project, location, COLLECTION, interceptEndpointGroupId);
318 const existing = yield* getByName(name);
319 if (existing === undefined) return undefined;
320 const attrs = toAttrs(existing, env.project);
321 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
322 }),
323
324 list: () =>
325 Effect.gen(function* () {
326 const env = yield* GcpEnvironment.current;
327 return yield* listOwned(env.project);
328 }),
329
330 reconcile: Effect.fn(function* ({ id, news, output }) {
331 const env = yield* GcpEnvironment.current;
332 const interceptEndpointGroupId = yield* toId(
333 id,
334 news.interceptEndpointGroupId,
335 output?.interceptEndpointGroupId,
336 "ieg",
337 );
338 const location = normalizeLocation(news.location ?? output?.location);
339 const name = resourceName(env.project, location, COLLECTION, interceptEndpointGroupId);
340 const interceptDeploymentGroup = toResourcePath(news.interceptDeploymentGroup);
341 const desiredLabels = {
342 ...toLabels(news.labels),
343 ...(yield* createInternalLabels(id)),
344 };
345
346 let current = yield* getByName(name);
347
348 if (current === undefined) {
349 const created = yield* networksecurity
350 .createProjectsLocationsInterceptEndpointGroups({
351 parent: parentOf(env.project, location),
352 interceptEndpointGroupId,
353 body: {
354 interceptDeploymentGroup,
355 description: news.description,
356 labels: desiredLabels,
357 },
358 })
359 .pipe(
360 Effect.retry({
361 while: (error) => error._tag === "Conflict",
362 times: 5,
363 schedule: Schedule.spaced("2 seconds"),
364 }),
365 Effect.catchTag("Conflict", () => Effect.undefined),
366 );
367 if (created !== undefined) {
368 yield* waitForOperation(created);
369 }
370 current = yield* waitUntilReady(name);
371 }
372
373 if (current === undefined) {
374 return yield* new InterceptEndpointGroupNotResolved({ resourceName: name });
375 }
376
377 const observedLabels = tagRecord(current.labels);
378 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
379 const labelsChanged = upsert.length > 0 || removed.length > 0;
380 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
381
382 if (labelsChanged || descriptionChanged) {
383 const updateMask = [
384 labelsChanged ? "labels" : undefined,
385 descriptionChanged ? "description" : undefined,
386 ].filter((field): field is string => field !== undefined);
387 const operation = yield* networksecurity.patchProjectsLocationsInterceptEndpointGroups({
388 name: current.name ?? name,
389 updateMask: updateMask.join(","),
390 body: {
391 name: current.name ?? name,
392 labels: desiredLabels,
393 description: news.description,
394 },
395 });
396 yield* waitForOperation(operation);
397 current = yield* waitUntilReady(current.name ?? name);
398 }
399
400 return toAttrs(current, env.project);
401 }),
402
403 delete: Effect.fn(function* ({ output }) {
404 const operation = yield* networksecurity
405 .deleteProjectsLocationsInterceptEndpointGroups({
406 name: output.name,
407 })
408 .pipe(
409 Effect.retry({
410 while: (error) => error._tag === "Conflict",
411 times: 8,
412 schedule: Schedule.spaced("2 seconds"),
413 }),
414 Effect.catchTag("NotFound", () => Effect.undefined),
415 );
416 if (operation !== undefined) {
417 yield* waitForOperation(operation, { notFoundOk: true });
418 }
419 yield* waitUntilGone(output.name);
420 }),
421 });