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

main
ts 412 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 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 normalizeZone,
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 OrganizationsFirewallEndpointState =
28 | networksecurity.FirewallEndpointStateEnum
29 | (string & {});
30
31 export type OrganizationsFirewallEndpointSettings = {
32 /**
33 * Whether jumbo frames are enabled. Immutable — changing it replaces
34 * the endpoint.
35 * @default false
36 */
37 jumboFramesEnabled?: boolean;
38 };
39
40 export type OrganizationsFirewallEndpointAssociation = {
41 /** FirewallEndpointAssociation resource name. */
42 name: string | undefined;
43 /** VPC network `projects/{project}/global/networks/{name}`. */
44 network: string | undefined;
45 };
46
47 export type OrganizationsFirewallEndpointProps = {
48 /**
49 * Firewall endpoint id. If omitted, a unique RFC1035 name is generated
50 * from the stack, stage, and logical id. Immutable — changing it
51 * replaces the endpoint.
52 */
53 firewallEndpointId?: string;
54 /**
55 * Organization id or `organizations/{organization}`. If omitted,
56 * Alchemy uses `GOOGLE_ORGANIZATION_ID` or the project's Resource
57 * Manager parent. Immutable — changing it replaces the endpoint.
58 */
59 organization?: string;
60 /**
61 * Zone (`us-central1-a`, …). Firewall endpoints are zonal. Immutable —
62 * changing it replaces the endpoint.
63 * @default "us-central1-a"
64 */
65 location?: string;
66 /**
67 * Project billed for the endpoint. Required for organization-scoped
68 * endpoints. Defaults to the stack project.
69 */
70 billingProjectId?: string;
71 /**
72 * Endpoint settings. `jumboFramesEnabled` is immutable.
73 */
74 endpointSettings?: OrganizationsFirewallEndpointSettings;
75 /**
76 * Human-readable description (max 2048 characters).
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 OrganizationsFirewallEndpoint = Resource<
86 "GCP.NetworkSecurity.OrganizationsFirewallEndpoint",
87 OrganizationsFirewallEndpointProps,
88 {
89 /** Full resource name `organizations/{organization}/locations/{location}/firewallEndpoints/{firewallEndpoint}`. */
90 name: string;
91 /** Firewall endpoint id (last path segment). */
92 firewallEndpointId: string;
93 /** Organization id. */
94 organization: string;
95 /** Zone id. */
96 location: string;
97 /** Project billed for the endpoint. */
98 billingProjectId: string | undefined;
99 /** Whether jumbo frames are enabled. */
100 jumboFramesEnabled: boolean;
101 /** User-provided description. */
102 description: string | undefined;
103 /** User labels (Alchemy ownership labels stripped). */
104 labels: Record<string, string>;
105 /** Server-reported lifecycle state. */
106 state: string | undefined;
107 /** Whether the endpoint is reconciling. */
108 reconciling: boolean;
109 /** Associated FirewallEndpointAssociations. */
110 associations: OrganizationsFirewallEndpointAssociation[];
111 /** Associated VPC networks. */
112 associatedNetworks: string[];
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 * An organization-scoped Cloud NGFW firewall endpoint.
124 *
125 * Endpoints are zonal and bill to `billingProjectId`. Changing
126 * `firewallEndpointId`, `organization`, `location`, `billingProjectId`,
127 * or jumbo-frame settings replaces the endpoint. Description and labels
128 * update in place. Provisioning is slow — tests skip when `FAST` is set.
129 *
130 * ### Creating a Firewall Endpoint
131 * **Example:** Generated name
132 * ```typescript
133 * const endpoint = yield* GCP.NetworkSecurity.OrganizationsFirewallEndpoint(
134 * "Ngfw",
135 * { location: "us-central1-a" },
136 * );
137 * ```
138 *
139 * **Example:** Named endpoint
140 * ```typescript
141 * const endpoint = yield* GCP.NetworkSecurity.OrganizationsFirewallEndpoint(
142 * "Ngfw",
143 * {
144 * firewallEndpointId: "app-ngfw",
145 * organization: "123456789",
146 * location: "us-central1-a",
147 * billingProjectId: "my-project",
148 * description: "prod NGFW",
149 * labels: { env: "prod" },
150 * },
151 * );
152 * ```
153 *
154 * @resource
155 * @category NetworkSecurity
156 */
157 export const OrganizationsFirewallEndpoint = Resource<OrganizationsFirewallEndpoint>(
158 "GCP.NetworkSecurity.OrganizationsFirewallEndpoint",
159 );
160
161 const resourceName = (organization: string, location: string, firewallEndpointId: string) =>
162 `organizations/${organization}/locations/${location}/firewallEndpoints/${firewallEndpointId}`;
163
164 const jumboOf = (settings: OrganizationsFirewallEndpointSettings | undefined) =>
165 settings?.jumboFramesEnabled === true;
166
167 const toAttrs = (endpoint: networksecurity.FirewallEndpoint) => {
168 const name = endpoint.name ?? "";
169 const parsed = parseResourceName(name);
170 return {
171 name,
172 firewallEndpointId: parsed.id,
173 organization: parsed.parentId,
174 location: parsed.location,
175 billingProjectId: endpoint.billingProjectId,
176 jumboFramesEnabled: endpoint.endpointSettings?.jumboFramesEnabled === true,
177 description: endpoint.description,
178 labels: userLabels(endpoint.labels),
179 state: endpoint.state,
180 reconciling: endpoint.reconciling === true,
181 associations: (endpoint.associations ?? []).map((association) => ({
182 name: association.name,
183 network: association.network,
184 })),
185 associatedNetworks: endpoint.associatedNetworks ?? [],
186 createTime: endpoint.createTime,
187 updateTime: endpoint.updateTime,
188 };
189 };
190
191 const getByName = (name: string) =>
192 networksecurity
193 .getOrganizationsLocationsFirewallEndpoints({ name })
194 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 const isPendingState = (state: string | undefined) =>
197 state === "CREATING" || state === "DELETING" || state === "STATE_UNSPECIFIED";
198
199 const waitUntilReady = (name: string) =>
200 getByName(name).pipe(
201 Effect.filterOrFail(
202 (endpoint): endpoint is networksecurity.FirewallEndpoint => endpoint !== undefined,
203 () => new ResourceNotResolved({ resourceName: name }),
204 ),
205 Effect.filterOrFail(
206 (endpoint) => !isPendingState(endpoint.state),
207 () => new ResourceNotResolved({ resourceName: name }),
208 ),
209 Effect.retry({
210 while: (error) => error._tag === "GCP.NetworkSecurity.ResourceNotResolved",
211 times: 10,
212 schedule: Schedule.spaced("5 seconds"),
213 }),
214 );
215
216 const listOwned = (organization: string) =>
217 networksecurity.listOrganizationsLocationsFirewallEndpoints
218 .pages({
219 parent: organizationParent(organization, "-"),
220 pageSize: 1000,
221 })
222 .pipe(
223 Stream.flatMap((page) => Stream.fromIterable(page.firewallEndpoints ?? [])),
224 Stream.filter((endpoint) =>
225 Object.keys(endpoint.labels ?? {}).some((key) => key.startsWith("alchemy-")),
226 ),
227 Stream.map(toAttrs),
228 Stream.runCollect,
229 Effect.map((chunk) => Array.from(chunk)),
230 Effect.catchTag("NotFound", () => Effect.succeed([])),
231 );
232
233 export const OrganizationsFirewallEndpointProvider = () =>
234 Provider.succeed(OrganizationsFirewallEndpoint, {
235 stables: [
236 "name",
237 "firewallEndpointId",
238 "organization",
239 "location",
240 "billingProjectId",
241 "jumboFramesEnabled",
242 "createTime",
243 ],
244
245 diff: Effect.fn(function* ({ news, olds, output }) {
246 if (!isResolved(news)) return undefined;
247 const previousId = olds?.firewallEndpointId ?? output?.firewallEndpointId;
248 const nextId = news.firewallEndpointId ?? previousId;
249 const previousOrg = olds?.organization ?? output?.organization;
250 const nextOrg = news.organization ?? previousOrg;
251 const previousLocation = normalizeZone(olds?.location ?? output?.location);
252 const nextLocation = normalizeZone(news.location ?? olds?.location ?? output?.location);
253 const previousBilling = olds?.billingProjectId ?? output?.billingProjectId;
254 const nextBilling = news.billingProjectId ?? previousBilling;
255 const previousJumbo = jumboOf(olds?.endpointSettings);
256 const nextJumbo =
257 news.endpointSettings !== undefined
258 ? jumboOf(news.endpointSettings)
259 : (output?.jumboFramesEnabled ?? previousJumbo);
260 const replace =
261 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
262 (previousOrg !== undefined && nextOrg !== undefined && nextOrg !== previousOrg) ||
263 previousLocation !== nextLocation ||
264 (previousBilling !== undefined &&
265 nextBilling !== undefined &&
266 previousBilling !== nextBilling) ||
267 previousJumbo !== nextJumbo;
268 if (!replace) return undefined;
269 return {
270 action: "replace" as const,
271 deleteFirst:
272 previousLocation === nextLocation &&
273 previousOrg === nextOrg &&
274 previousId !== undefined &&
275 nextId === previousId,
276 };
277 }),
278
279 read: Effect.fn(function* ({ id, olds, output }) {
280 const firewallEndpointId = yield* toPhysicalId(
281 id,
282 olds?.firewallEndpointId,
283 output?.firewallEndpointId,
284 "fwep",
285 );
286 const organization = yield* resolveOrganization(
287 olds?.organization ?? output?.organization,
288 output?.organization,
289 ).pipe(
290 Effect.catchTag("GCP.NetworkSecurity.OrganizationRequired", () =>
291 Effect.succeed(output?.organization ?? ""),
292 ),
293 );
294 const location = normalizeZone(olds?.location ?? output?.location);
295 const name =
296 output?.name ??
297 (organization.length > 0 ? resourceName(organization, location, firewallEndpointId) : "");
298 if (name.length === 0) return undefined;
299 const existing = yield* getByName(name);
300 if (existing === undefined) return undefined;
301 const attrs = toAttrs(existing);
302 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
303 }),
304
305 list: () =>
306 Effect.gen(function* () {
307 const env = yield* GcpEnvironment.current;
308 const orgs = yield* listOrganizations(env.project);
309 const listed: OrganizationsFirewallEndpoint["Attributes"][] = [];
310 for (const organization of orgs) {
311 listed.push(...(yield* listOwned(organization)));
312 }
313 return listed;
314 }),
315
316 reconcile: Effect.fn(function* ({ id, news, output }) {
317 const env = yield* GcpEnvironment.current;
318 const firewallEndpointId = yield* toPhysicalId(
319 id,
320 news.firewallEndpointId,
321 output?.firewallEndpointId,
322 "fwep",
323 );
324 const organization = yield* resolveOrganization(
325 news.organization ?? output?.organization,
326 output?.organization,
327 );
328 const location = normalizeZone(news.location ?? output?.location);
329 const name = resourceName(organization, location, firewallEndpointId);
330 const billingProjectId = news.billingProjectId ?? env.project;
331 const jumboFramesEnabled = jumboOf(news.endpointSettings);
332 const desiredLabels = {
333 ...toLabels(news.labels),
334 ...(yield* createInternalLabels(id)),
335 };
336
337 let current = yield* getByName(name);
338
339 if (current === undefined) {
340 const created = yield* networksecurity
341 .createOrganizationsLocationsFirewallEndpoints({
342 parent: organizationParent(organization, location),
343 firewallEndpointId,
344 body: {
345 billingProjectId,
346 description: news.description,
347 labels: desiredLabels,
348 endpointSettings: { jumboFramesEnabled },
349 },
350 })
351 .pipe(
352 Effect.retry({
353 while: (error) => error._tag === "Conflict",
354 times: 5,
355 schedule: Schedule.spaced("2 seconds"),
356 }),
357 Effect.catchTag("Conflict", () => Effect.undefined),
358 );
359 if (created !== undefined) {
360 yield* waitForOperation(created);
361 }
362 current = yield* waitUntilReady(name);
363 }
364
365 if (current === undefined) {
366 return yield* new ResourceNotResolved({ resourceName: name });
367 }
368
369 const observedLabels = tagRecord(current.labels);
370 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
371 const labelsChanged = upsert.length > 0 || removed.length > 0;
372 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
373
374 if (labelsChanged || descriptionChanged) {
375 const updateMask = [
376 labelsChanged ? "labels" : undefined,
377 descriptionChanged ? "description" : undefined,
378 ].filter((field): field is string => field !== undefined);
379
380 const operation = yield* networksecurity.patchOrganizationsLocationsFirewallEndpoints({
381 name: current.name ?? name,
382 updateMask: updateMask.join(","),
383 body: {
384 name: current.name ?? name,
385 labels: desiredLabels,
386 description: news.description,
387 },
388 });
389 yield* waitForOperation(operation);
390 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
391 }
392
393 return toAttrs(current);
394 }),
395
396 delete: Effect.fn(function* ({ output }) {
397 const operation = yield* networksecurity
398 .deleteOrganizationsLocationsFirewallEndpoints({ name: output.name })
399 .pipe(
400 Effect.retry({
401 while: (error) => error._tag === "Conflict",
402 times: 8,
403 schedule: Schedule.spaced("2 seconds"),
404 }),
405 Effect.catchTag("NotFound", () => Effect.undefined),
406 );
407 if (operation !== undefined) {
408 yield* waitForOperation(operation, { notFoundOk: true });
409 }
410 yield* waitUntilGone(getByName(output.name), output.name);
411 }),
412 });