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

main
ts 382 lines 13.4 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 listOrganizations,
15 normalizeLocation,
16 organizationParent,
17 parseResourceName,
18 ResourceNotResolved,
19 resolveOrganization,
20 toPhysicalId,
21 userLabels,
22 waitForOperation,
23 waitUntilExists,
24 waitUntilGone,
25 } from "./operations.ts";
26
27 export type OrganizationsSecurityProfileGroupProps = {
28 /**
29 * Security profile group id. If omitted, a unique RFC1035 name is
30 * generated from the stack, stage, and logical id. Immutable —
31 * changing it replaces the group.
32 */
33 securityProfileGroupId?: string;
34 /**
35 * Organization id or `organizations/{organization}`. If omitted,
36 * Alchemy uses `GOOGLE_ORGANIZATION_ID` or the project's Resource
37 * Manager parent. Immutable — changing it replaces the group.
38 */
39 organization?: string;
40 /**
41 * Location. Profile groups live in `global`. Immutable — changing it
42 * replaces the group.
43 * @default "global"
44 */
45 location?: string;
46 /**
47 * Threat-prevention SecurityProfile resource name.
48 */
49 threatPreventionProfile?: string;
50 /**
51 * URL-filtering SecurityProfile resource name.
52 */
53 urlFilteringProfile?: string;
54 /**
55 * Custom-mirroring SecurityProfile resource name.
56 */
57 customMirroringProfile?: string;
58 /**
59 * Custom-intercept SecurityProfile resource name.
60 */
61 customInterceptProfile?: string;
62 /**
63 * Human-readable description (max 2048 characters).
64 */
65 description?: string;
66 /**
67 * User labels. Alchemy ownership labels are merged in automatically.
68 */
69 labels?: Record<string, string>;
70 };
71
72 export type OrganizationsSecurityProfileGroup = Resource<
73 "GCP.NetworkSecurity.OrganizationsSecurityProfileGroup",
74 OrganizationsSecurityProfileGroupProps,
75 {
76 /** Full resource name `organizations/{organization}/locations/{location}/securityProfileGroups/{securityProfileGroup}`. */
77 name: string;
78 /** Security profile group id (last path segment). */
79 securityProfileGroupId: string;
80 /** Organization id. */
81 organization: string;
82 /** Location id. */
83 location: string;
84 /** Threat-prevention profile name, if set. */
85 threatPreventionProfile: string | undefined;
86 /** URL-filtering profile name, if set. */
87 urlFilteringProfile: string | undefined;
88 /** Custom-mirroring profile name, if set. */
89 customMirroringProfile: string | undefined;
90 /** Custom-intercept profile name, if set. */
91 customInterceptProfile: string | undefined;
92 /** User-provided description. */
93 description: string | undefined;
94 /** User labels (Alchemy ownership labels stripped). */
95 labels: Record<string, string>;
96 /** Data-path identifier. */
97 dataPathId: string | undefined;
98 /** Server-computed checksum. */
99 etag: string | undefined;
100 /** RFC3339 creation timestamp. */
101 createTime: string | undefined;
102 /** RFC3339 last-update timestamp. */
103 updateTime: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * An organization-scoped group of Network Security profiles.
111 *
112 * Changing `securityProfileGroupId`, `organization`, or `location`
113 * replaces the group. Profile references, description, and labels update
114 * in place.
115 *
116 * ### Creating a Security Profile Group
117 * **Example:** Empty group
118 * ```typescript
119 * const group = yield* GCP.NetworkSecurity.OrganizationsSecurityProfileGroup(
120 * "Profiles",
121 * {},
122 * );
123 * ```
124 *
125 * **Example:** Attach a threat-prevention profile
126 * ```typescript
127 * const group = yield* GCP.NetworkSecurity.OrganizationsSecurityProfileGroup(
128 * "Profiles",
129 * {
130 * threatPreventionProfile: profile.name,
131 * labels: { env: "prod" },
132 * },
133 * );
134 * ```
135 *
136 * @resource
137 * @category NetworkSecurity
138 */
139 export const OrganizationsSecurityProfileGroup = Resource<OrganizationsSecurityProfileGroup>(
140 "GCP.NetworkSecurity.OrganizationsSecurityProfileGroup",
141 );
142
143 const resourceName = (organization: string, location: string, securityProfileGroupId: string) =>
144 `organizations/${organization}/locations/${location}/securityProfileGroups/${securityProfileGroupId}`;
145
146 const toAttrs = (group: networksecurity.SecurityProfileGroup) => {
147 const name = group.name ?? "";
148 const parsed = parseResourceName(name);
149 return {
150 name,
151 securityProfileGroupId: parsed.id,
152 organization: parsed.parentId,
153 location: parsed.location,
154 threatPreventionProfile: group.threatPreventionProfile,
155 urlFilteringProfile: group.urlFilteringProfile,
156 customMirroringProfile: group.customMirroringProfile,
157 customInterceptProfile: group.customInterceptProfile,
158 description: group.description,
159 labels: userLabels(group.labels),
160 dataPathId: group.dataPathId,
161 etag: group.etag,
162 createTime: group.createTime,
163 updateTime: group.updateTime,
164 };
165 };
166
167 const getByName = (name: string) =>
168 networksecurity
169 .getOrganizationsLocationsSecurityProfileGroups({ name })
170 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
171
172 const listOwned = (organization: string) =>
173 networksecurity.listOrganizationsLocationsSecurityProfileGroups
174 .pages({
175 parent: organizationParent(organization, "-"),
176 pageSize: 1000,
177 })
178 .pipe(
179 Stream.flatMap((page) => Stream.fromIterable(page.securityProfileGroups ?? [])),
180 Stream.filter((group) =>
181 Object.keys(group.labels ?? {}).some((key) => key.startsWith("alchemy-")),
182 ),
183 Stream.map(toAttrs),
184 Stream.runCollect,
185 Effect.map((chunk) => Array.from(chunk)),
186 Effect.catchTag("NotFound", () => Effect.succeed([])),
187 );
188
189 export const OrganizationsSecurityProfileGroupProvider = () =>
190 Provider.succeed(OrganizationsSecurityProfileGroup, {
191 stables: [
192 "name",
193 "securityProfileGroupId",
194 "organization",
195 "location",
196 "dataPathId",
197 "createTime",
198 ],
199
200 diff: Effect.fn(function* ({ news, olds, output }) {
201 if (!isResolved(news)) return undefined;
202 const previousId = olds?.securityProfileGroupId ?? output?.securityProfileGroupId;
203 const nextId = news.securityProfileGroupId ?? previousId;
204 const previousOrg = olds?.organization ?? output?.organization;
205 const nextOrg = news.organization ?? previousOrg;
206 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
207 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
208 const replace =
209 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
210 (previousOrg !== undefined && nextOrg !== undefined && nextOrg !== previousOrg) ||
211 previousLocation !== nextLocation;
212 if (!replace) return undefined;
213 return {
214 action: "replace" as const,
215 deleteFirst:
216 previousLocation === nextLocation &&
217 previousOrg === nextOrg &&
218 previousId !== undefined &&
219 nextId === previousId,
220 };
221 }),
222
223 read: Effect.fn(function* ({ id, olds, output }) {
224 const securityProfileGroupId = yield* toPhysicalId(
225 id,
226 olds?.securityProfileGroupId,
227 output?.securityProfileGroupId,
228 "secprofilegroup",
229 );
230 const organization = yield* resolveOrganization(
231 olds?.organization ?? output?.organization,
232 output?.organization,
233 ).pipe(
234 Effect.catchTag("GCP.NetworkSecurity.OrganizationRequired", () =>
235 Effect.succeed(output?.organization ?? ""),
236 ),
237 );
238 const location = normalizeLocation(olds?.location ?? output?.location);
239 const name =
240 output?.name ??
241 (organization.length > 0
242 ? resourceName(organization, location, securityProfileGroupId)
243 : "");
244 if (name.length === 0) return undefined;
245 const existing = yield* getByName(name);
246 if (existing === undefined) return undefined;
247 const attrs = toAttrs(existing);
248 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
249 }),
250
251 list: () =>
252 Effect.gen(function* () {
253 const env = yield* GcpEnvironment.current;
254 const orgs = yield* listOrganizations(env.project);
255 const listed: OrganizationsSecurityProfileGroup["Attributes"][] = [];
256 for (const organization of orgs) {
257 listed.push(...(yield* listOwned(organization)));
258 }
259 return listed;
260 }),
261
262 reconcile: Effect.fn(function* ({ id, news, output }) {
263 const securityProfileGroupId = yield* toPhysicalId(
264 id,
265 news.securityProfileGroupId,
266 output?.securityProfileGroupId,
267 "secprofilegroup",
268 );
269 const organization = yield* resolveOrganization(
270 news.organization ?? output?.organization,
271 output?.organization,
272 );
273 const location = normalizeLocation(news.location ?? output?.location);
274 const name = resourceName(organization, location, securityProfileGroupId);
275 const desiredLabels = {
276 ...toLabels(news.labels),
277 ...(yield* createInternalLabels(id)),
278 };
279
280 let current = yield* getByName(name);
281
282 if (current === undefined) {
283 const created = yield* networksecurity
284 .createOrganizationsLocationsSecurityProfileGroups({
285 parent: organizationParent(organization, location),
286 securityProfileGroupId,
287 body: {
288 description: news.description,
289 labels: desiredLabels,
290 threatPreventionProfile: news.threatPreventionProfile,
291 urlFilteringProfile: news.urlFilteringProfile,
292 customMirroringProfile: news.customMirroringProfile,
293 customInterceptProfile: news.customInterceptProfile,
294 },
295 })
296 .pipe(
297 Effect.retry({
298 while: (error) => error._tag === "Conflict",
299 times: 5,
300 schedule: Schedule.spaced("2 seconds"),
301 }),
302 Effect.catchTag("Conflict", () => Effect.undefined),
303 );
304 if (created !== undefined) {
305 yield* waitForOperation(created);
306 }
307 current = yield* waitUntilExists(getByName(name), name);
308 }
309
310 if (current === undefined) {
311 return yield* new ResourceNotResolved({ resourceName: name });
312 }
313
314 const observedLabels = tagRecord(current.labels);
315 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
316 const labelsChanged = upsert.length > 0 || removed.length > 0;
317 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
318 const threatChanged =
319 (current.threatPreventionProfile ?? "") !== (news.threatPreventionProfile ?? "");
320 const urlChanged = (current.urlFilteringProfile ?? "") !== (news.urlFilteringProfile ?? "");
321 const mirrorChanged =
322 (current.customMirroringProfile ?? "") !== (news.customMirroringProfile ?? "");
323 const interceptChanged =
324 (current.customInterceptProfile ?? "") !== (news.customInterceptProfile ?? "");
325
326 if (
327 labelsChanged ||
328 descriptionChanged ||
329 threatChanged ||
330 urlChanged ||
331 mirrorChanged ||
332 interceptChanged
333 ) {
334 const updateMask = [
335 labelsChanged ? "labels" : undefined,
336 descriptionChanged ? "description" : undefined,
337 threatChanged ? "threatPreventionProfile" : undefined,
338 urlChanged ? "urlFilteringProfile" : undefined,
339 mirrorChanged ? "customMirroringProfile" : undefined,
340 interceptChanged ? "customInterceptProfile" : undefined,
341 ].filter((field): field is string => field !== undefined);
342
343 const operation = yield* networksecurity.patchOrganizationsLocationsSecurityProfileGroups({
344 name: current.name ?? name,
345 updateMask: updateMask.join(","),
346 body: {
347 name: current.name ?? name,
348 labels: desiredLabels,
349 description: news.description,
350 threatPreventionProfile: news.threatPreventionProfile,
351 urlFilteringProfile: news.urlFilteringProfile,
352 customMirroringProfile: news.customMirroringProfile,
353 customInterceptProfile: news.customInterceptProfile,
354 },
355 });
356 yield* waitForOperation(operation);
357 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
358 }
359
360 return toAttrs(current);
361 }),
362
363 delete: Effect.fn(function* ({ output }) {
364 const operation = yield* networksecurity
365 .deleteOrganizationsLocationsSecurityProfileGroups({
366 name: output.name,
367 etag: output.etag,
368 })
369 .pipe(
370 Effect.retry({
371 while: (error) => error._tag === "Conflict",
372 times: 8,
373 schedule: Schedule.spaced("2 seconds"),
374 }),
375 Effect.catchTag("NotFound", () => Effect.undefined),
376 );
377 if (operation !== undefined) {
378 yield* waitForOperation(operation, { notFoundOk: true });
379 }
380 yield* waitUntilGone(getByName(output.name), output.name);
381 }),
382 });