@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, 04:45 UTC

main
ts 332 lines 11.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 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 DEFAULT_GLOBAL,
14 canonicalizeLink,
15 changedFields,
16 collectPages,
17 hasAlchemyLabelKeys,
18 linkKey,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 rfc1035,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilGone,
27 waitUntilReady,
28 } from "./internal.ts";
29
30 const COLLECTION = "interceptDeploymentGroups";
31
32 export type InterceptDeploymentGroupState =
33 | networksecurity.InterceptDeploymentGroupStateEnum
34 | (string & {});
35
36 export type InterceptDeploymentGroupNestedDeployment = {
37 /** Nested InterceptDeployment resource name. */
38 name: string | undefined;
39 /** Nested deployment state. */
40 state: string | undefined;
41 };
42
43 export type InterceptLocation = {
44 /** Cloud location (`us-central1-a`, `asia-south1`, …). */
45 location: string | undefined;
46 /** Association state in this location. */
47 state: string | undefined;
48 };
49
50 export type InterceptConnectedEndpointGroup = {
51 /** Connected InterceptEndpointGroup resource name. */
52 name: string | undefined;
53 };
54
55 export type InterceptDeploymentGroupProps = {
56 /**
57 * Deployment group id (the `{interceptDeploymentGroup}` segment of
58 * `projects/{project}/locations/global/interceptDeploymentGroups/{interceptDeploymentGroup}`).
59 * If omitted, a unique name is generated from the stack, stage, and
60 * logical id. Immutable — changing it replaces the group.
61 */
62 interceptDeploymentGroupId?: string;
63 /**
64 * Location. Intercept deployment groups are global. Immutable —
65 * changing it replaces the group.
66 * @default "global"
67 */
68 location?: string;
69 /**
70 * VPC network used by every child deployment, e.g.
71 * `projects/{project}/global/networks/{network}`. Immutable — changing
72 * it replaces the group.
73 */
74 network: string;
75 /**
76 * Human-readable description.
77 */
78 description?: string;
79 /**
80 * User labels. Alchemy ownership labels are merged in automatically.
81 */
82 labels?: Record<string, string>;
83 };
84
85 export type InterceptDeploymentGroup = Resource<
86 "GCP.NetworkSecurity.InterceptDeploymentGroup",
87 InterceptDeploymentGroupProps,
88 {
89 /** Full resource name `projects/{project}/locations/global/interceptDeploymentGroups/{interceptDeploymentGroup}`. */
90 name: string;
91 /** Deployment group id (last path segment). */
92 interceptDeploymentGroupId: string;
93 /** Project id. */
94 project: string;
95 /** Location id — always `"global"`. */
96 location: string;
97 /** VPC network resource name. */
98 network: string | undefined;
99 /** User-provided description. */
100 description: string | undefined;
101 /** User labels (Alchemy ownership labels stripped). */
102 labels: Record<string, string>;
103 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
104 state: string | undefined;
105 /** Whether reconciling is in progress. */
106 reconciling: boolean;
107 /** Nested zonal deployments. */
108 nestedDeployments: InterceptDeploymentGroupNestedDeployment[];
109 /** Locations where the group is present. */
110 locations: InterceptLocation[];
111 /** Connected intercept endpoint groups. */
112 connectedEndpointGroups: InterceptConnectedEndpointGroup[];
113 /** RFC3339 creation timestamp. */
114 createTime: string | undefined;
115 /** RFC3339 last-update timestamp. */
116 updateTime: string | undefined;
117 },
118 never,
119 Providers
120 >;
121
122 /**
123 * A global intercept deployment group — aggregates zonal intercept
124 * backends into a single intercept service that consumers attach via
125 * an endpoint group.
126 *
127 * Changing `interceptDeploymentGroupId`, `location`, or `network`
128 * replaces the group. Description and labels update in place.
129 *
130 * ### Creating an InterceptDeploymentGroup
131 * **Example:** Attach to a VPC
132 * ```typescript
133 * const group = yield* GCP.NetworkSecurity.InterceptDeploymentGroup("Inspect", {
134 * network: `projects/${vpc.project}/global/networks/${vpc.networkName}`,
135 * description: "prod intercept",
136 * labels: { env: "prod" },
137 * });
138 * ```
139 *
140 * @resource
141 * @category NetworkSecurity
142 */
143 export const InterceptDeploymentGroup = Resource<InterceptDeploymentGroup>(
144 "GCP.NetworkSecurity.InterceptDeploymentGroup",
145 );
146
147 const resourceName = (project: string, location: string, interceptDeploymentGroupId: string) =>
148 `projects/${project}/locations/${location}/interceptDeploymentGroups/${interceptDeploymentGroupId}`;
149
150 const toAttrs = (group: networksecurity.InterceptDeploymentGroup, project: string) => {
151 const name = group.name ?? "";
152 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
153 return {
154 name,
155 interceptDeploymentGroupId: parsed.id,
156 project: parsed.project || project,
157 location: parsed.location || DEFAULT_GLOBAL,
158 network: group.network ? canonicalizeLink(group.network) : undefined,
159 description: group.description,
160 labels: userLabels(group.labels),
161 state: group.state,
162 reconciling: group.reconciling === true,
163 nestedDeployments: (group.nestedDeployments ?? []).map((deployment) => ({
164 name: deployment.name,
165 state: deployment.state,
166 })),
167 locations: (group.locations ?? []).map((location) => ({
168 location: location.location,
169 state: location.state,
170 })),
171 connectedEndpointGroups: (group.connectedEndpointGroups ?? []).map((endpointGroup) => ({
172 name: endpointGroup.name,
173 })),
174 createTime: group.createTime,
175 updateTime: group.updateTime,
176 };
177 };
178
179 const getByName = (name: string) =>
180 networksecurity
181 .getProjectsLocationsInterceptDeploymentGroups({ name })
182 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
183
184 export const InterceptDeploymentGroupProvider = () =>
185 Provider.succeed(InterceptDeploymentGroup, {
186 stables: ["name", "interceptDeploymentGroupId", "project", "location", "network", "createTime"],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 const previousId = olds?.interceptDeploymentGroupId ?? output?.interceptDeploymentGroupId;
191 const nextId = news.interceptDeploymentGroupId
192 ? rfc1035(news.interceptDeploymentGroupId, "intercept-deployment-group")
193 : previousId;
194 const previousLocation = normalizeLocation(
195 olds?.location ?? output?.location,
196 DEFAULT_GLOBAL,
197 );
198 const nextLocation = normalizeLocation(
199 news.location ?? olds?.location ?? output?.location,
200 DEFAULT_GLOBAL,
201 );
202 const previousNetwork = linkKey(olds?.network ?? output?.network);
203 const nextNetwork = linkKey(news.network);
204 if (
205 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
206 previousLocation !== nextLocation ||
207 (previousNetwork.length > 0 && previousNetwork !== nextNetwork)
208 ) {
209 return { action: "replace" as const };
210 }
211 return undefined;
212 }),
213
214 read: Effect.fn(function* ({ id, olds, output }) {
215 const env = yield* GcpEnvironment.current;
216 const interceptDeploymentGroupId = yield* toPhysicalId(
217 id,
218 olds?.interceptDeploymentGroupId,
219 output?.interceptDeploymentGroupId,
220 "intercept-deployment-group",
221 );
222 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
223 const name = output?.name ?? resourceName(env.project, location, interceptDeploymentGroupId);
224 const existing = yield* getByName(name);
225 if (existing === undefined) return undefined;
226 const attrs = toAttrs(existing, env.project);
227 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
228 }),
229
230 list: () =>
231 Effect.gen(function* () {
232 const env = yield* GcpEnvironment.current;
233 const items = yield* collectPages(
234 networksecurity.listProjectsLocationsInterceptDeploymentGroups.pages({
235 parent: parentOf(env.project, "-"),
236 pageSize: 1000,
237 }),
238 (page) => page.interceptDeploymentGroups,
239 );
240 return items
241 .filter((item) => hasAlchemyLabelKeys(item.labels))
242 .map((item) => toAttrs(item, env.project));
243 }),
244
245 reconcile: Effect.fn(function* ({ id, news, output }) {
246 const env = yield* GcpEnvironment.current;
247 const interceptDeploymentGroupId = yield* toPhysicalId(
248 id,
249 news.interceptDeploymentGroupId,
250 output?.interceptDeploymentGroupId,
251 "intercept-deployment-group",
252 );
253 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
254 const name = resourceName(env.project, location, interceptDeploymentGroupId);
255 const desiredLabels = {
256 ...toLabels(news.labels),
257 ...(yield* createInternalLabels(id)),
258 };
259 const network = canonicalizeLink(news.network);
260
261 let current = yield* getByName(name);
262
263 if (current === undefined) {
264 const created = yield* networksecurity
265 .createProjectsLocationsInterceptDeploymentGroups({
266 parent: parentOf(env.project, location),
267 interceptDeploymentGroupId,
268 body: {
269 network,
270 description: news.description,
271 labels: desiredLabels,
272 },
273 })
274 .pipe(
275 Effect.retry({
276 while: (error) => error._tag === "Conflict",
277 times: 5,
278 schedule: Schedule.spaced("2 seconds"),
279 }),
280 Effect.catchTag("Conflict", () => Effect.undefined),
281 );
282 if (created !== undefined) {
283 yield* waitForOperation(created);
284 }
285 current = yield* waitUntilReady(getByName(name), name);
286 }
287
288 const observedLabels = tagRecord(current.labels);
289 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
290 const labelsChanged = upsert.length > 0 || removed.length > 0;
291 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
292 const updateMask = changedFields([
293 ["labels", labelsChanged],
294 ["description", descriptionChanged],
295 ]);
296
297 if (updateMask.length > 0) {
298 const operation = yield* networksecurity.patchProjectsLocationsInterceptDeploymentGroups({
299 name: current.name ?? name,
300 updateMask: updateMask.join(","),
301 body: {
302 name: current.name ?? name,
303 labels: desiredLabels,
304 description: news.description,
305 },
306 });
307 yield* waitForOperation(operation);
308 current = yield* waitUntilReady(getByName(current.name ?? name), current.name ?? name);
309 }
310
311 return toAttrs(current, env.project);
312 }),
313
314 delete: Effect.fn(function* ({ output }) {
315 const operation = yield* networksecurity
316 .deleteProjectsLocationsInterceptDeploymentGroups({
317 name: output.name,
318 })
319 .pipe(
320 Effect.retry({
321 while: (error) => error._tag === "Conflict",
322 times: 8,
323 schedule: Schedule.spaced("2 seconds"),
324 }),
325 Effect.catchTag("NotFound", () => Effect.undefined),
326 );
327 if (operation !== undefined) {
328 yield* waitForOperation(operation, { notFoundOk: true });
329 }
330 yield* waitUntilGone(getByName(output.name), output.name);
331 }),
332 });