@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 330 lines 11.5 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_ZONE,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 rfc1035,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilGone,
25 waitUntilPresent,
26 } from "./internal.ts";
27
28 const COLLECTION = "firewallEndpoints";
29
30 export type FirewallEndpointState = networksecurity.FirewallEndpointStateEnum | (string & {});
31
32 export type FirewallEndpointAssociationRef = {
33 /** Association resource name. */
34 name: string | undefined;
35 };
36
37 export type FirewallEndpointProps = {
38 /**
39 * FirewallEndpoint id (the `{firewallEndpoint}` segment of
40 * `projects/{project}/locations/{location}/firewallEndpoints/{firewallEndpoint}`).
41 * If omitted, a unique name is generated from the stack, stage, and
42 * logical id. Immutable — changing it replaces the endpoint.
43 */
44 firewallEndpointId?: string;
45 /**
46 * Zone of the endpoint (`us-central1-a`, …). Immutable — changing it
47 * replaces the endpoint. `US-CENTRAL1-A` is accepted and normalized to
48 * `us-central1-a`.
49 * @default "us-central1-a"
50 */
51 location?: string;
52 /**
53 * Project billed for the endpoint. Required for organization-scoped
54 * endpoints; omit for project-scoped endpoints. Immutable — changing
55 * it replaces the endpoint.
56 */
57 billingProjectId?: string;
58 /**
59 * Human-readable description (max 2048 characters).
60 */
61 description?: string;
62 /**
63 * Enable jumbo frames on the endpoint. Immutable — changing it
64 * replaces the endpoint.
65 * @default false
66 */
67 jumboFramesEnabled?: boolean;
68 /**
69 * User labels. Alchemy ownership labels are merged in automatically.
70 */
71 labels?: Record<string, string>;
72 };
73
74 export type FirewallEndpoint = Resource<
75 "GCP.NetworkSecurity.FirewallEndpoint",
76 FirewallEndpointProps,
77 {
78 /** Full resource name `projects/{project}/locations/{location}/firewallEndpoints/{firewallEndpoint}`. */
79 name: string;
80 /** FirewallEndpoint id (last path segment). */
81 firewallEndpointId: string;
82 /** Project id. */
83 project: string;
84 /** Zone id (`us-central1-a`). */
85 location: string;
86 /** Project billed for the endpoint, if set. */
87 billingProjectId: string | undefined;
88 /** User-provided description. */
89 description: string | undefined;
90 /** Whether jumbo frames are enabled. */
91 jumboFramesEnabled: boolean;
92 /** User labels (Alchemy ownership labels stripped). */
93 labels: Record<string, string>;
94 /** Server-reported lifecycle state (`ACTIVE`, `CREATING`, …). */
95 state: string | undefined;
96 /** Whether reconciling is in progress. */
97 reconciling: boolean;
98 /** Associated FirewallEndpointAssociation names. */
99 associations: FirewallEndpointAssociationRef[];
100 /** Associated VPC network names (deprecated projection). */
101 associatedNetworks: string[];
102 /** RFC3339 creation timestamp. */
103 createTime: string | undefined;
104 /** RFC3339 last-update timestamp. */
105 updateTime: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A project-scoped Cloud NGFW firewall endpoint. Endpoints terminate
113 * inspected traffic in a zone; associate them with a VPC via
114 * FirewallEndpointAssociation.
115 *
116 * Changing `firewallEndpointId`, `location`, `billingProjectId`, or
117 * jumbo-frame settings replaces the endpoint. Description and labels
118 * update in place. Provisioning is asynchronous and can take several
119 * minutes.
120 *
121 * ### Creating a FirewallEndpoint
122 * **Example:** Generated name
123 * ```typescript
124 * const endpoint = yield* GCP.NetworkSecurity.FirewallEndpoint("Ngfw", {
125 * location: "us-central1-a",
126 * });
127 * ```
128 *
129 * **Example:** Named endpoint with labels
130 * ```typescript
131 * const endpoint = yield* GCP.NetworkSecurity.FirewallEndpoint("Ngfw", {
132 * firewallEndpointId: "app-ngfw",
133 * location: "us-central1-a",
134 * description: "prod inspection",
135 * labels: { env: "prod" },
136 * });
137 * ```
138 *
139 * @resource
140 * @category NetworkSecurity
141 */
142 export const FirewallEndpoint = Resource<FirewallEndpoint>("GCP.NetworkSecurity.FirewallEndpoint");
143
144 const resourceName = (project: string, location: string, firewallEndpointId: string) =>
145 `projects/${project}/locations/${location}/firewallEndpoints/${firewallEndpointId}`;
146
147 const toAttrs = (endpoint: networksecurity.FirewallEndpoint, project: string) => {
148 const name = endpoint.name ?? "";
149 const parsed = parseName(name, COLLECTION, DEFAULT_ZONE);
150 return {
151 name,
152 firewallEndpointId: parsed.id,
153 project: parsed.project || project,
154 location: parsed.location || DEFAULT_ZONE,
155 billingProjectId: endpoint.billingProjectId,
156 description: endpoint.description,
157 jumboFramesEnabled: endpoint.endpointSettings?.jumboFramesEnabled === true,
158 labels: userLabels(endpoint.labels),
159 state: endpoint.state,
160 reconciling: endpoint.reconciling === true,
161 associations: (endpoint.associations ?? []).map((association) => ({
162 name: association.name,
163 })),
164 associatedNetworks: endpoint.associatedNetworks ?? [],
165 createTime: endpoint.createTime,
166 updateTime: endpoint.updateTime,
167 };
168 };
169
170 const getByName = (name: string) =>
171 networksecurity
172 .getProjectsLocationsFirewallEndpoints({ name })
173 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
174
175 export const FirewallEndpointProvider = () =>
176 Provider.succeed(FirewallEndpoint, {
177 stables: [
178 "name",
179 "firewallEndpointId",
180 "project",
181 "location",
182 "billingProjectId",
183 "jumboFramesEnabled",
184 "createTime",
185 ],
186
187 diff: Effect.fn(function* ({ news, olds, output }) {
188 if (!isResolved(news)) return undefined;
189 const previousId = olds?.firewallEndpointId ?? output?.firewallEndpointId;
190 const nextId = news.firewallEndpointId
191 ? rfc1035(news.firewallEndpointId, "firewall-endpoint")
192 : previousId;
193 const previousLocation = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
194 const nextLocation = normalizeLocation(
195 news.location ?? olds?.location ?? output?.location,
196 DEFAULT_ZONE,
197 );
198 const previousBilling = olds?.billingProjectId ?? output?.billingProjectId ?? "";
199 const nextBilling = news.billingProjectId ?? previousBilling;
200 const previousJumbo = olds?.jumboFramesEnabled ?? output?.jumboFramesEnabled ?? false;
201 const nextJumbo = news.jumboFramesEnabled ?? previousJumbo;
202 if (
203 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
204 previousLocation !== nextLocation ||
205 previousBilling !== nextBilling ||
206 previousJumbo !== nextJumbo
207 ) {
208 return { action: "replace" as const };
209 }
210 return undefined;
211 }),
212
213 read: Effect.fn(function* ({ id, olds, output }) {
214 const env = yield* GcpEnvironment.current;
215 const firewallEndpointId = yield* toPhysicalId(
216 id,
217 olds?.firewallEndpointId,
218 output?.firewallEndpointId,
219 "firewall-endpoint",
220 );
221 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_ZONE);
222 const name = output?.name ?? resourceName(env.project, location, firewallEndpointId);
223 const existing = yield* getByName(name);
224 if (existing === undefined) return undefined;
225 const attrs = toAttrs(existing, env.project);
226 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
227 }),
228
229 list: () =>
230 Effect.gen(function* () {
231 const env = yield* GcpEnvironment.current;
232 const items = yield* collectPages(
233 networksecurity.listProjectsLocationsFirewallEndpoints.pages({
234 parent: parentOf(env.project, "-"),
235 pageSize: 1000,
236 }),
237 (page) => page.firewallEndpoints,
238 );
239 return items
240 .filter((item) => hasAlchemyLabelKeys(item.labels))
241 .map((item) => toAttrs(item, env.project));
242 }),
243
244 reconcile: Effect.fn(function* ({ id, news, output }) {
245 const env = yield* GcpEnvironment.current;
246 const firewallEndpointId = yield* toPhysicalId(
247 id,
248 news.firewallEndpointId,
249 output?.firewallEndpointId,
250 "firewall-endpoint",
251 );
252 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_ZONE);
253 const name = resourceName(env.project, location, firewallEndpointId);
254 const desiredLabels = {
255 ...toLabels(news.labels),
256 ...(yield* createInternalLabels(id)),
257 };
258 const jumboFramesEnabled = news.jumboFramesEnabled === true;
259
260 let current = yield* getByName(name);
261
262 if (current === undefined) {
263 const created = yield* networksecurity
264 .createProjectsLocationsFirewallEndpoints({
265 parent: parentOf(env.project, location),
266 firewallEndpointId,
267 body: {
268 billingProjectId: news.billingProjectId,
269 description: news.description,
270 labels: desiredLabels,
271 endpointSettings: { jumboFramesEnabled },
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* waitUntilPresent(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.patchProjectsLocationsFirewallEndpoints({
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* waitUntilPresent(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 .deleteProjectsLocationsFirewallEndpoints({ name: output.name })
317 .pipe(
318 Effect.retry({
319 while: (error) => error._tag === "Conflict",
320 times: 8,
321 schedule: Schedule.spaced("2 seconds"),
322 }),
323 Effect.catchTag("NotFound", () => Effect.undefined),
324 );
325 if (operation !== undefined) {
326 yield* waitForOperation(operation, { notFoundOk: true });
327 }
328 yield* waitUntilGone(getByName(output.name), output.name);
329 }),
330 });