@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 310 lines 10.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 * as Data from "effect/Data";
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 type { Providers } from "../Providers.ts";
12 import { normalizeLocation, parentOf, parseResourceName, resourceName, toId } from "./names.ts";
13 import { waitForOperation } from "./operations.ts";
14 import {
15 createInternalLabels,
16 encodeDescription,
17 hasAlchemyLabels,
18 hasOwnershipMarker,
19 parseDescription,
20 sameStringList,
21 } from "./ownership.ts";
22
23 const COLLECTION = "urlLists";
24
25 export type UrlListProps = {
26 /**
27 * UrlList id (the `{urlList}` segment of
28 * `projects/{project}/locations/{location}/urlLists/{urlList}`). If
29 * omitted, a unique RFC1035 name is generated from the stack, stage,
30 * and logical id. Must match `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$`.
31 * Immutable — changing it replaces the list.
32 */
33 urlListId?: string;
34 /**
35 * Location (`us-central1`, `us-east1`, …). Immutable — changing it
36 * replaces the list. `US-CENTRAL1` is accepted and normalized to
37 * `us-central1`.
38 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
39 */
40 location?: string;
41 /**
42 * FQDNs, host patterns, URLs, and URL patterns in this list.
43 */
44 values: string[];
45 /**
46 * Human-readable description. UrlList has no labels field, so Alchemy
47 * ownership is stored in a `[alchemy …]` prefix and stripped from
48 * attributes.
49 */
50 description?: string;
51 };
52
53 export type UrlList = Resource<
54 "GCP.NetworkSecurity.UrlList",
55 UrlListProps,
56 {
57 /** Full resource name `projects/{project}/locations/{location}/urlLists/{urlList}`. */
58 name: string;
59 /** UrlList id (last path segment). */
60 urlListId: string;
61 /** Project id. */
62 project: string;
63 /** Location id (`us-central1`, …). */
64 location: string;
65 /** FQDNs and URLs currently configured. */
66 values: string[];
67 /** User description with the Alchemy ownership prefix stripped. */
68 description: string | undefined;
69 /** RFC3339 creation timestamp. */
70 createTime: string | undefined;
71 /** RFC3339 last-update timestamp. */
72 updateTime: string | undefined;
73 },
74 never,
75 Providers
76 >;
77
78 /**
79 * A reusable list of hosts, host patterns, URLs, and URL patterns used
80 * by Secure Web Proxy URL filtering.
81 *
82 * UrlList has no labels field, so Alchemy stamps ownership into the
83 * description for `list` / nuke. Changing `urlListId` or `location`
84 * replaces the list. `values` and `description` update in place.
85 *
86 * ### Creating a UrlList
87 * **Example:** Generated name
88 * ```typescript
89 * const blocked = yield* GCP.NetworkSecurity.UrlList("Blocked", {
90 * values: ["malware.example.com", "phishing.example.net"],
91 * });
92 * ```
93 *
94 * **Example:** Named list with a description
95 * ```typescript
96 * const blocked = yield* GCP.NetworkSecurity.UrlList("Blocked", {
97 * urlListId: "app-blocked-hosts",
98 * location: "us-central1",
99 * description: "denied destinations",
100 * values: ["malware.example.com"],
101 * });
102 * ```
103 *
104 * ### Updating a UrlList
105 * **Example:** Add values
106 * ```typescript
107 * const blocked = yield* GCP.NetworkSecurity.UrlList("Blocked", {
108 * urlListId: "app-blocked-hosts",
109 * location: "us-central1",
110 * description: "denied destinations v2",
111 * values: ["malware.example.com", "c2.example.net"],
112 * });
113 * ```
114 *
115 * @resource
116 * @category NetworkSecurity
117 */
118 export const UrlList = Resource<UrlList>("GCP.NetworkSecurity.UrlList");
119
120 export class UrlListNotResolved extends Data.TaggedError("GCP.NetworkSecurity.UrlListNotResolved")<{
121 resourceName: string;
122 }> {}
123
124 export class UrlListStillExists extends Data.TaggedError("GCP.NetworkSecurity.UrlListStillExists")<{
125 resourceName: string;
126 }> {}
127
128 const toAttrs = (list: networksecurity.UrlList, project: string, region: string) => {
129 const name = list.name ?? "";
130 const parsed = parseResourceName(name, COLLECTION);
131 const owned = parseDescription(list.description);
132 return {
133 name,
134 urlListId: parsed.id,
135 project: parsed.project || project,
136 location: parsed.location || region,
137 values: list.values ?? [],
138 description: owned.description,
139 createTime: list.createTime,
140 updateTime: list.updateTime,
141 };
142 };
143
144 const getByName = (name: string) =>
145 networksecurity
146 .getProjectsLocationsUrlLists({ name })
147 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
148
149 const waitUntilExists = (name: string) =>
150 getByName(name).pipe(
151 Effect.flatMap((list) =>
152 list ? Effect.succeed(list) : Effect.fail(new UrlListNotResolved({ resourceName: name })),
153 ),
154 Effect.retry({
155 while: (error) => error._tag === "GCP.NetworkSecurity.UrlListNotResolved",
156 times: 8,
157 schedule: Schedule.spaced("1 second"),
158 }),
159 );
160
161 const waitUntilGone = (name: string) =>
162 getByName(name).pipe(
163 Effect.flatMap((list) =>
164 list === undefined
165 ? Effect.void
166 : Effect.fail(new UrlListStillExists({ resourceName: name })),
167 ),
168 Effect.retry({
169 while: (error) => error._tag === "GCP.NetworkSecurity.UrlListStillExists",
170 times: 10,
171 schedule: Schedule.spaced("2 seconds"),
172 }),
173 );
174
175 const listOwned = (project: string, region: string) =>
176 networksecurity.listProjectsLocationsUrlLists
177 .pages({
178 parent: parentOf(project, "-"),
179 pageSize: 1000,
180 })
181 .pipe(
182 Stream.flatMap((page) => Stream.fromIterable(page.urlLists ?? [])),
183 Stream.filter((list) => hasOwnershipMarker(list.description)),
184 Stream.map((list) => toAttrs(list, project, region)),
185 Stream.runCollect,
186 Effect.map((chunk) => Array.from(chunk)),
187 Effect.catchTag("NotFound", () => Effect.succeed([])),
188 );
189
190 export const UrlListProvider = () =>
191 Provider.succeed(UrlList, {
192 stables: ["name", "urlListId", "project", "location", "createTime"],
193
194 diff: Effect.fn(function* ({ news, olds, output }) {
195 if (!isResolved(news)) return undefined;
196 const env = yield* GcpEnvironment.current;
197 const previousId = olds?.urlListId ?? output?.urlListId;
198 const nextId = news.urlListId ?? previousId;
199 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
200 const nextLocation = normalizeLocation(
201 news.location ?? olds?.location ?? output?.location,
202 env.region,
203 );
204 if (
205 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
206 previousLocation !== nextLocation
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 urlListId = yield* toId(id, olds?.urlListId, output?.urlListId, "urllist");
216 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
217 const name = output?.name ?? resourceName(env.project, location, COLLECTION, urlListId);
218 const existing = yield* getByName(name);
219 if (existing === undefined) return undefined;
220 const attrs = toAttrs(existing, env.project, env.region);
221 const { labels } = parseDescription(existing.description);
222 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
223 }),
224
225 list: () =>
226 Effect.gen(function* () {
227 const env = yield* GcpEnvironment.current;
228 return yield* listOwned(env.project, env.region);
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const env = yield* GcpEnvironment.current;
233 const urlListId = yield* toId(id, news.urlListId, output?.urlListId, "urllist");
234 const location = normalizeLocation(news.location ?? output?.location, env.region);
235 const name = resourceName(env.project, location, COLLECTION, urlListId);
236 const ownership = yield* createInternalLabels(id);
237 const desiredDescription = encodeDescription(ownership, news.description);
238 const desiredValues = news.values;
239
240 let current = yield* getByName(output?.name ?? name);
241
242 if (current === undefined) {
243 const created = yield* networksecurity
244 .createProjectsLocationsUrlLists({
245 parent: parentOf(env.project, location),
246 urlListId,
247 body: {
248 description: desiredDescription,
249 values: desiredValues,
250 },
251 })
252 .pipe(
253 Effect.retry({
254 while: (error) => error._tag === "Conflict",
255 times: 5,
256 schedule: Schedule.spaced("2 seconds"),
257 }),
258 Effect.catchTag("Conflict", () => Effect.undefined),
259 );
260 if (created !== undefined) {
261 yield* waitForOperation(created);
262 }
263 current = yield* waitUntilExists(name);
264 }
265
266 if (current === undefined) {
267 return yield* new UrlListNotResolved({ resourceName: name });
268 }
269
270 const descriptionChanged = (current.description ?? "") !== desiredDescription;
271 const valuesChanged = !sameStringList(current.values, desiredValues);
272
273 if (descriptionChanged || valuesChanged) {
274 const updateMask = [
275 descriptionChanged ? "description" : undefined,
276 valuesChanged ? "values" : undefined,
277 ].filter((field): field is string => field !== undefined);
278 const operation = yield* networksecurity.patchProjectsLocationsUrlLists({
279 name: current.name ?? name,
280 updateMask: updateMask.join(","),
281 body: {
282 name: current.name ?? name,
283 description: desiredDescription,
284 values: desiredValues,
285 },
286 });
287 yield* waitForOperation(operation);
288 current = yield* waitUntilExists(current.name ?? name);
289 }
290
291 return toAttrs(current, env.project, env.region);
292 }),
293
294 delete: Effect.fn(function* ({ output }) {
295 const operation = yield* networksecurity
296 .deleteProjectsLocationsUrlLists({ name: output.name })
297 .pipe(
298 Effect.retry({
299 while: (error) => error._tag === "Conflict",
300 times: 8,
301 schedule: Schedule.spaced("2 seconds"),
302 }),
303 Effect.catchTag("NotFound", () => Effect.undefined),
304 );
305 if (operation !== undefined) {
306 yield* waitForOperation(operation, { notFoundOk: true });
307 }
308 yield* waitUntilGone(output.name);
309 }),
310 });