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

main
ts 358 lines 12.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 Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 normalizeLocation,
15 parseResourceName,
16 projectParent,
17 ResourceNotResolved,
18 sameStringList,
19 sortedStrings,
20 toPhysicalId,
21 userLabels,
22 waitForOperation,
23 waitUntilExists,
24 waitUntilGone,
25 } from "./operations.ts";
26
27 const DEFAULT_TYPE = "IPV4" satisfies networksecurity.AddressGroupTypeEnum;
28 const DEFAULT_CAPACITY = 100;
29
30 export type AddressGroupType = networksecurity.AddressGroupTypeEnum | (string & {});
31
32 export type AddressGroupPurpose = networksecurity.AddressGroupPurposeItemEnum | (string & {});
33
34 export type AddressGroupProps = {
35 /**
36 * Address group id (the `{addressGroup}` segment of
37 * `projects/{project}/locations/{location}/addressGroups/{addressGroup}`).
38 * If omitted, a unique RFC1035 name is generated from the stack, stage,
39 * and logical id. Must be 1-63 characters and match
40 * `[a-z]([a-z0-9-]*[a-z0-9])?`. Immutable — changing it replaces the
41 * group.
42 */
43 addressGroupId?: string;
44 /**
45 * Location (`global`, `us-central1`, …). Immutable — changing it
46 * replaces the group. `US-CENTRAL1` is accepted and normalized to
47 * `us-central1`.
48 * @default "global"
49 */
50 location?: string;
51 /**
52 * Address type. Immutable — changing it replaces the group.
53 * @default "IPV4"
54 */
55 type?: AddressGroupType;
56 /**
57 * Maximum number of items. Immutable — changing it replaces the group.
58 * @default 100
59 */
60 capacity?: number;
61 /**
62 * IP addresses or CIDR ranges stored in the group.
63 */
64 items?: string[];
65 /**
66 * Supported purposes (`DEFAULT`, `CLOUD_ARMOR`). Immutable — changing
67 * them replaces the group.
68 */
69 purpose?: AddressGroupPurpose[];
70 /**
71 * Human-readable description.
72 */
73 description?: string;
74 /**
75 * User labels. Alchemy ownership labels are merged in automatically.
76 */
77 labels?: Record<string, string>;
78 };
79
80 export type AddressGroup = Resource<
81 "GCP.NetworkSecurity.AddressGroup",
82 AddressGroupProps,
83 {
84 /** Full resource name `projects/{project}/locations/{location}/addressGroups/{addressGroup}`. */
85 name: string;
86 /** Address group id (last path segment). */
87 addressGroupId: string;
88 /** Project id. */
89 project: string;
90 /** Location id (`global`, `us-central1`, …). */
91 location: string;
92 /** Address type (`IPV4` or `IPV6`). */
93 type: string;
94 /** Maximum number of items. */
95 capacity: number;
96 /** IP addresses or CIDR ranges. */
97 items: string[];
98 /** Supported purposes. */
99 purpose: string[];
100 /** User-provided description. */
101 description: string | undefined;
102 /** User labels (Alchemy ownership labels stripped). */
103 labels: Record<string, string>;
104 /** Server-defined URL for this resource. */
105 selfLink: string | undefined;
106 /** RFC3339 creation timestamp. */
107 createTime: string | undefined;
108 /** RFC3339 last-update timestamp. */
109 updateTime: string | undefined;
110 },
111 never,
112 Providers
113 >;
114
115 /**
116 * A Network Security address group — a named collection of IP addresses
117 * or CIDR ranges used by firewall policies and Cloud Armor.
118 *
119 * Changing `addressGroupId`, `location`, `type`, `capacity`, or `purpose`
120 * replaces the group. Description, labels, and items update in place.
121 *
122 * ### Creating an Address Group
123 * **Example:** Generated name
124 * ```typescript
125 * const group = yield* GCP.NetworkSecurity.AddressGroup("Allowlist", {
126 * items: ["10.0.0.1"],
127 * });
128 * ```
129 *
130 * **Example:** Named group with labels
131 * ```typescript
132 * const group = yield* GCP.NetworkSecurity.AddressGroup("Allowlist", {
133 * addressGroupId: "app-allowlist",
134 * type: "IPV4",
135 * capacity: 100,
136 * items: ["10.0.0.0/24"],
137 * description: "prod allowlist",
138 * labels: { env: "prod" },
139 * });
140 * ```
141 *
142 * ### Updating an Address Group
143 * **Example:** Change items and description
144 * ```typescript
145 * const group = yield* GCP.NetworkSecurity.AddressGroup("Allowlist", {
146 * addressGroupId: "app-allowlist",
147 * items: ["10.0.0.0/24", "10.1.0.1"],
148 * description: "prod allowlist v2",
149 * labels: { env: "prod", role: "allowlist" },
150 * });
151 * ```
152 *
153 * @resource
154 * @category NetworkSecurity
155 */
156 export const AddressGroup = Resource<AddressGroup>("GCP.NetworkSecurity.AddressGroup");
157
158 const resourceName = (project: string, location: string, addressGroupId: string) =>
159 `projects/${project}/locations/${location}/addressGroups/${addressGroupId}`;
160
161 const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase();
162
163 const capacityOf = (value: number | undefined) => value ?? DEFAULT_CAPACITY;
164
165 const toAttrs = (group: networksecurity.AddressGroup, project: string) => {
166 const name = group.name ?? "";
167 const parsed = parseResourceName(name);
168 return {
169 name,
170 addressGroupId: parsed.id,
171 project: parsed.parentId || project,
172 location: parsed.location,
173 type: group.type ?? DEFAULT_TYPE,
174 capacity: group.capacity ?? DEFAULT_CAPACITY,
175 items: group.items ?? [],
176 purpose: (group.purpose ?? []) as string[],
177 description: group.description,
178 labels: userLabels(group.labels),
179 selfLink: group.selfLink,
180 createTime: group.createTime,
181 updateTime: group.updateTime,
182 };
183 };
184
185 const getByName = (name: string) =>
186 networksecurity
187 .getProjectsLocationsAddressGroups({ name })
188 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
189
190 const listOwned = (project: string) =>
191 networksecurity.listProjectsLocationsAddressGroups
192 .pages({
193 parent: projectParent(project, "-"),
194 pageSize: 1000,
195 })
196 .pipe(
197 Stream.flatMap((page) => Stream.fromIterable(page.addressGroups ?? [])),
198 Stream.filter((group) =>
199 Object.keys(group.labels ?? {}).some((key) => key.startsWith("alchemy-")),
200 ),
201 Stream.map((group) => toAttrs(group, project)),
202 Stream.runCollect,
203 Effect.map((chunk) => Array.from(chunk)),
204 Effect.catchTag("NotFound", () => Effect.succeed([])),
205 );
206
207 export const AddressGroupProvider = () =>
208 Provider.succeed(AddressGroup, {
209 stables: ["name", "addressGroupId", "project", "location", "type", "capacity", "createTime"],
210
211 diff: Effect.fn(function* ({ news, olds, output }) {
212 if (!isResolved(news)) return undefined;
213 const previousId = olds?.addressGroupId ?? output?.addressGroupId;
214 const nextId = news.addressGroupId ?? previousId;
215 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
216 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
217 const previousType = typeOf(olds?.type ?? output?.type);
218 const nextType = typeOf(news.type ?? olds?.type ?? output?.type);
219 const previousCapacity = capacityOf(olds?.capacity ?? output?.capacity);
220 const nextCapacity = capacityOf(news.capacity ?? olds?.capacity ?? output?.capacity);
221 const previousPurpose = sortedStrings(olds?.purpose ?? output?.purpose);
222 const nextPurpose = sortedStrings(news.purpose ?? olds?.purpose ?? output?.purpose);
223 const replace =
224 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
225 previousLocation !== nextLocation ||
226 previousType !== nextType ||
227 previousCapacity !== nextCapacity ||
228 JSON.stringify(previousPurpose) !== JSON.stringify(nextPurpose);
229 if (!replace) return undefined;
230 return {
231 action: "replace" as const,
232 deleteFirst:
233 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
234 };
235 }),
236
237 read: Effect.fn(function* ({ id, olds, output }) {
238 const env = yield* GcpEnvironment.current;
239 const addressGroupId = yield* toPhysicalId(
240 id,
241 olds?.addressGroupId,
242 output?.addressGroupId,
243 "addressgroup",
244 );
245 const location = normalizeLocation(olds?.location ?? output?.location);
246 const name = output?.name ?? resourceName(env.project, location, addressGroupId);
247 const existing = yield* getByName(name);
248 if (existing === undefined) return undefined;
249 const attrs = toAttrs(existing, env.project);
250 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
251 }),
252
253 list: () =>
254 Effect.gen(function* () {
255 const env = yield* GcpEnvironment.current;
256 return yield* listOwned(env.project);
257 }),
258
259 reconcile: Effect.fn(function* ({ id, news, output }) {
260 const env = yield* GcpEnvironment.current;
261 const addressGroupId = yield* toPhysicalId(
262 id,
263 news.addressGroupId,
264 output?.addressGroupId,
265 "addressgroup",
266 );
267 const location = normalizeLocation(news.location ?? output?.location);
268 const name = resourceName(env.project, location, addressGroupId);
269 const type = typeOf(news.type);
270 const capacity = capacityOf(news.capacity);
271 const items = news.items ?? [];
272 const purpose = news.purpose;
273 const desiredLabels = {
274 ...toLabels(news.labels),
275 ...(yield* createInternalLabels(id)),
276 };
277
278 let current = yield* getByName(name);
279
280 if (current === undefined) {
281 const created = yield* networksecurity
282 .createProjectsLocationsAddressGroups({
283 parent: projectParent(env.project, location),
284 addressGroupId,
285 body: {
286 type,
287 capacity,
288 items,
289 purpose,
290 description: news.description,
291 labels: desiredLabels,
292 },
293 })
294 .pipe(
295 Effect.retry({
296 while: (error) => error._tag === "Conflict",
297 times: 5,
298 schedule: Schedule.spaced("2 seconds"),
299 }),
300 Effect.catchTag("Conflict", () => Effect.undefined),
301 );
302 if (created !== undefined) {
303 yield* waitForOperation(created);
304 }
305 current = yield* waitUntilExists(getByName(name), name);
306 }
307
308 if (current === undefined) {
309 return yield* new ResourceNotResolved({ resourceName: name });
310 }
311
312 const observedLabels = tagRecord(current.labels);
313 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
314 const labelsChanged = upsert.length > 0 || removed.length > 0;
315 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
316 const itemsChanged = !sameStringList(current.items, items);
317
318 if (labelsChanged || descriptionChanged || itemsChanged) {
319 const updateMask = [
320 labelsChanged ? "labels" : undefined,
321 descriptionChanged ? "description" : undefined,
322 itemsChanged ? "items" : undefined,
323 ].filter((field): field is string => field !== undefined);
324
325 const operation = yield* networksecurity.patchProjectsLocationsAddressGroups({
326 name: current.name ?? name,
327 updateMask: updateMask.join(","),
328 body: {
329 name: current.name ?? name,
330 labels: desiredLabels,
331 description: news.description,
332 items,
333 },
334 });
335 yield* waitForOperation(operation);
336 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
337 }
338
339 return toAttrs(current, env.project);
340 }),
341
342 delete: Effect.fn(function* ({ output }) {
343 const operation = yield* networksecurity
344 .deleteProjectsLocationsAddressGroups({ name: output.name })
345 .pipe(
346 Effect.retry({
347 while: (error) => error._tag === "Conflict",
348 times: 8,
349 schedule: Schedule.spaced("2 seconds"),
350 }),
351 Effect.catchTag("NotFound", () => Effect.undefined),
352 );
353 if (operation !== undefined) {
354 yield* waitForOperation(operation, { notFoundOk: true });
355 }
356 yield* waitUntilGone(getByName(output.name), output.name);
357 }),
358 });