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

main
ts 291 lines 10.2 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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 NetworksecurityNotResolved,
13 canonicalizeLink,
14 changedFields,
15 collectPages,
16 encodeOwnership,
17 hasOwnershipMarker,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 parseOwnership,
22 rfc1035,
23 toPhysicalId,
24 waitForOperation,
25 waitUntilGone,
26 waitUntilPresent,
27 } from "./internal.ts";
28
29 const COLLECTION = "gatewaySecurityPolicies";
30
31 export type GatewaySecurityPolicyProps = {
32 /**
33 * GatewaySecurityPolicy id (the `{gatewaySecurityPolicy}` segment of
34 * `projects/{project}/locations/{location}/gatewaySecurityPolicies/{gatewaySecurityPolicy}`).
35 * If omitted, a unique RFC1035 name is generated from the stack, stage,
36 * and logical id. Immutable — changing it replaces the policy.
37 */
38 gatewaySecurityPolicyId?: string;
39 /**
40 * Region of the policy (`us-central1`, …). Immutable — changing it
41 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
42 * `us-central1`.
43 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
44 */
45 location?: string;
46 /**
47 * Human-readable description. GatewaySecurityPolicy has no labels
48 * field, so Alchemy stamps ownership into a `[alchemy …]` prefix and
49 * strips it from attributes.
50 */
51 description?: string;
52 /**
53 * TlsInspectionPolicy resource name used by rules that enable TLS
54 * inspection.
55 */
56 tlsInspectionPolicy?: string;
57 };
58
59 export type GatewaySecurityPolicy = Resource<
60 "GCP.NetworkSecurity.GatewaySecurityPolicy",
61 GatewaySecurityPolicyProps,
62 {
63 /** Full resource name `projects/{project}/locations/{location}/gatewaySecurityPolicies/{gatewaySecurityPolicy}`. */
64 name: string;
65 /** GatewaySecurityPolicy id (last path segment). */
66 gatewaySecurityPolicyId: string;
67 /** Project id. */
68 project: string;
69 /** Location id (`us-central1`). */
70 location: string;
71 /** User description with the Alchemy ownership prefix stripped. */
72 description: string | undefined;
73 /** Attached TlsInspectionPolicy resource name, if any. */
74 tlsInspectionPolicy: string | undefined;
75 /** RFC3339 creation timestamp. */
76 createTime: string | undefined;
77 /** RFC3339 last-update timestamp. */
78 updateTime: string | undefined;
79 },
80 never,
81 Providers
82 >;
83
84 /**
85 * A Gateway Security Policy — a collection of
86 * GatewaySecurityPolicyRules used by Secure Web Proxy.
87 *
88 * The API has no labels field, so Alchemy stamps ownership into the
89 * description for `list` / nuke. Changing `gatewaySecurityPolicyId` or
90 * `location` replaces the policy. Description and `tlsInspectionPolicy`
91 * update in place.
92 *
93 * ### Creating a GatewaySecurityPolicy
94 * **Example:** Generated name
95 * ```typescript
96 * const policy = yield* GCP.NetworkSecurity.GatewaySecurityPolicy("Swp", {
97 * description: "secure web proxy",
98 * });
99 * ```
100 *
101 * **Example:** Named policy with TLS inspection
102 * ```typescript
103 * const policy = yield* GCP.NetworkSecurity.GatewaySecurityPolicy("Swp", {
104 * gatewaySecurityPolicyId: "app-swp",
105 * location: "us-central1",
106 * tlsInspectionPolicy: inspection.name,
107 * });
108 * ```
109 *
110 * @resource
111 * @category NetworkSecurity
112 */
113 export const GatewaySecurityPolicy = Resource<GatewaySecurityPolicy>(
114 "GCP.NetworkSecurity.GatewaySecurityPolicy",
115 );
116
117 const resourceName = (project: string, location: string, gatewaySecurityPolicyId: string) =>
118 `projects/${project}/locations/${location}/gatewaySecurityPolicies/${gatewaySecurityPolicyId}`;
119
120 const toAttrs = (
121 policy: networksecurity.GatewaySecurityPolicy,
122 project: string,
123 region: string,
124 ) => {
125 const name = policy.name ?? "";
126 const parsed = parseName(name, COLLECTION, region);
127 const ownership = parseOwnership(policy.description);
128 return {
129 name,
130 gatewaySecurityPolicyId: parsed.id,
131 project: parsed.project || project,
132 location: parsed.location || region,
133 description: ownership.text,
134 tlsInspectionPolicy: policy.tlsInspectionPolicy
135 ? canonicalizeLink(policy.tlsInspectionPolicy)
136 : undefined,
137 createTime: policy.createTime,
138 updateTime: policy.updateTime,
139 };
140 };
141
142 const getByName = (name: string) =>
143 networksecurity
144 .getProjectsLocationsGatewaySecurityPolicies({ name })
145 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
146
147 export const GatewaySecurityPolicyProvider = () =>
148 Provider.succeed(GatewaySecurityPolicy, {
149 stables: ["name", "gatewaySecurityPolicyId", "project", "location", "createTime"],
150
151 diff: Effect.fn(function* ({ news, olds, output }) {
152 if (!isResolved(news)) return undefined;
153 const env = yield* GcpEnvironment.current;
154 const previousId = olds?.gatewaySecurityPolicyId ?? output?.gatewaySecurityPolicyId;
155 const nextId = news.gatewaySecurityPolicyId
156 ? rfc1035(news.gatewaySecurityPolicyId, "gateway-security-policy")
157 : previousId;
158 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
159 const nextLocation = normalizeLocation(
160 news.location ?? olds?.location ?? output?.location,
161 env.region,
162 );
163 if (
164 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
165 previousLocation !== nextLocation
166 ) {
167 return { action: "replace" as const };
168 }
169 return undefined;
170 }),
171
172 read: Effect.fn(function* ({ id, olds, output }) {
173 const env = yield* GcpEnvironment.current;
174 const gatewaySecurityPolicyId = yield* toPhysicalId(
175 id,
176 olds?.gatewaySecurityPolicyId,
177 output?.gatewaySecurityPolicyId,
178 "gateway-security-policy",
179 );
180 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
181 const name = output?.name ?? resourceName(env.project, location, gatewaySecurityPolicyId);
182 const existing = yield* getByName(name);
183 if (existing === undefined) return undefined;
184 const attrs = toAttrs(existing, env.project, env.region);
185 const { labels } = parseOwnership(existing.description);
186 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
187 }),
188
189 list: () =>
190 Effect.gen(function* () {
191 const env = yield* GcpEnvironment.current;
192 const items = yield* collectPages(
193 networksecurity.listProjectsLocationsGatewaySecurityPolicies.pages({
194 parent: parentOf(env.project, "-"),
195 pageSize: 1000,
196 }),
197 (page) => page.gatewaySecurityPolicies,
198 );
199 return items
200 .filter((item) => hasOwnershipMarker(item.description))
201 .map((item) => toAttrs(item, env.project, env.region));
202 }),
203
204 reconcile: Effect.fn(function* ({ id, news, output }) {
205 const env = yield* GcpEnvironment.current;
206 const gatewaySecurityPolicyId = yield* toPhysicalId(
207 id,
208 news.gatewaySecurityPolicyId,
209 output?.gatewaySecurityPolicyId,
210 "gateway-security-policy",
211 );
212 const location = normalizeLocation(news.location ?? output?.location, env.region);
213 const name = resourceName(env.project, location, gatewaySecurityPolicyId);
214 const ownership = yield* createInternalLabels(id);
215 const desiredDescription = encodeOwnership(ownership, news.description);
216 const tlsInspectionPolicy = news.tlsInspectionPolicy
217 ? canonicalizeLink(news.tlsInspectionPolicy)
218 : undefined;
219
220 let current = yield* getByName(name);
221
222 if (current === undefined) {
223 const created = yield* networksecurity
224 .createProjectsLocationsGatewaySecurityPolicies({
225 parent: parentOf(env.project, location),
226 gatewaySecurityPolicyId,
227 body: {
228 description: desiredDescription,
229 tlsInspectionPolicy,
230 },
231 })
232 .pipe(
233 Effect.retry({
234 while: (error) => error._tag === "Conflict",
235 times: 5,
236 schedule: Schedule.spaced("2 seconds"),
237 }),
238 Effect.catchTag("Conflict", () => Effect.undefined),
239 );
240 if (created !== undefined) {
241 yield* waitForOperation(created);
242 }
243 current = yield* waitUntilPresent(getByName(name), name);
244 }
245
246 if (current === undefined) {
247 return yield* new NetworksecurityNotResolved({ resourceName: name });
248 }
249
250 const descriptionChanged = (current.description ?? "") !== desiredDescription;
251 const tlsChanged =
252 canonicalizeLink(current.tlsInspectionPolicy) !== (tlsInspectionPolicy ?? "");
253 const updateMask = changedFields([
254 ["description", descriptionChanged],
255 ["tlsInspectionPolicy", tlsChanged],
256 ]);
257
258 if (updateMask.length > 0) {
259 const operation = yield* networksecurity.patchProjectsLocationsGatewaySecurityPolicies({
260 name: current.name ?? name,
261 updateMask: updateMask.join(","),
262 body: {
263 name: current.name ?? name,
264 description: desiredDescription,
265 tlsInspectionPolicy,
266 },
267 });
268 yield* waitForOperation(operation);
269 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
270 }
271
272 return toAttrs(current, env.project, env.region);
273 }),
274
275 delete: Effect.fn(function* ({ output }) {
276 const operation = yield* networksecurity
277 .deleteProjectsLocationsGatewaySecurityPolicies({ name: output.name })
278 .pipe(
279 Effect.retry({
280 while: (error) => error._tag === "Conflict",
281 times: 8,
282 schedule: Schedule.spaced("2 seconds"),
283 }),
284 Effect.catchTag("NotFound", () => Effect.undefined),
285 );
286 if (operation !== undefined) {
287 yield* waitForOperation(operation, { notFoundOk: true });
288 }
289 yield* waitUntilGone(getByName(output.name), output.name);
290 }),
291 });