@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 371 lines 12.6 KB
Raw
1 import * as acm from "@distilled.cloud/gcp/accesscontextmanager_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 { createInternalLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectPages,
12 encodeOwnership,
13 encodeOwnershipLine,
14 jsonEqual,
15 listOwnedPolicies,
16 MAX_DESCRIPTION_LENGTH,
17 MAX_TITLE_LENGTH,
18 ownedByAlchemy,
19 parseName,
20 parseOwnership,
21 policyNameOf,
22 replaceOnIdentity,
23 resourceNameOf,
24 toAcmId,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type ServicePerimeterConfig = acm.ServicePerimeterConfig;
31 export type ServicePerimeterType = acm.ServicePerimeterPerimeterTypeEnum;
32
33 export type AccessPoliciesServicePerimeterProps = {
34 /**
35 * Parent access policy (`accessPolicies/{policy}` or the policy id).
36 * Immutable — changing it replaces the perimeter.
37 */
38 policy: string;
39 /**
40 * Service perimeter id (the `{service_perimeter}` segment). If omitted,
41 * a unique name is generated from the stack, stage, and logical id.
42 * Must begin with a letter, then alphanumeric or `_`. Immutable —
43 * changing it replaces the perimeter.
44 */
45 servicePerimeterId?: string;
46 /**
47 * Human-readable title. Must be unique within the policy.
48 */
49 title?: string;
50 /**
51 * Description of the perimeter. Service perimeters have no labels, so
52 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
53 * from attributes.
54 */
55 description?: string;
56 /**
57 * Perimeter type. Immutable — changing it replaces the perimeter.
58 * @default "PERIMETER_TYPE_REGULAR"
59 */
60 perimeterType?: ServicePerimeterType | (string & {});
61 /**
62 * When true, `spec` is an explicit dry-run configuration instead of an
63 * implicit copy of `status`.
64 * @default false
65 */
66 useExplicitDryRunSpec?: boolean;
67 /**
68 * Enforced perimeter configuration (resources, restricted services,
69 * access levels, ingress/egress policies).
70 */
71 status?: ServicePerimeterConfig;
72 /**
73 * Proposed (dry-run) configuration. Only applied when
74 * `useExplicitDryRunSpec` is true.
75 */
76 spec?: ServicePerimeterConfig;
77 };
78
79 export type AccessPoliciesServicePerimeter = Resource<
80 "GCP.AccessContextManager.AccessPoliciesServicePerimeter",
81 AccessPoliciesServicePerimeterProps,
82 {
83 /** Resource name `accessPolicies/{policy}/servicePerimeters/{perimeter}`. */
84 name: string;
85 /** Service perimeter id (last path segment). */
86 servicePerimeterId: string;
87 /** Parent policy name `accessPolicies/{policy}`. */
88 policy: string;
89 /** User title with the Alchemy ownership prefix stripped. */
90 title: string | undefined;
91 /** User description with the Alchemy ownership prefix stripped. */
92 description: string | undefined;
93 /** Perimeter type. */
94 perimeterType: string | undefined;
95 /** Whether an explicit dry-run spec is in use. */
96 useExplicitDryRunSpec: boolean;
97 /** Enforced configuration. */
98 status: ServicePerimeterConfig | undefined;
99 /** Dry-run configuration. */
100 spec: ServicePerimeterConfig | undefined;
101 /** Server etag for optimistic concurrency. */
102 etag: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * An Access Context Manager service perimeter.
110 *
111 * A service perimeter groups Google Cloud resources that can freely
112 * exchange data with each other but not with the outside. Regular
113 * perimeters cannot overlap; bridges can share projects.
114 *
115 * Service perimeters have no labels. Alchemy stamps ownership into
116 * `description` so `list` / `pnpm nuke:gcp` can find them. `policy`,
117 * `servicePerimeterId`, and `perimeterType` are immutable. Title,
118 * description, `status`, `spec`, and `useExplicitDryRunSpec` update in
119 * place.
120 *
121 * ### Creating a Service Perimeter
122 * **Example:** Regular perimeter around Cloud Storage
123 * ```typescript
124 * const policy = yield* GCP.AccessContextManager.AccessPolicy("Corp", {
125 * scopes: ["projects/123456789"],
126 * });
127 * const perimeter = yield* GCP.AccessContextManager.AccessPoliciesServicePerimeter(
128 * "Storage",
129 * {
130 * policy: policy.name,
131 * title: "storage perimeter",
132 * status: {
133 * restrictedServices: ["storage.googleapis.com"],
134 * },
135 * },
136 * );
137 * ```
138 *
139 * ### Updating a Service Perimeter
140 * **Example:** Restrict BigQuery as well
141 * ```typescript
142 * const perimeter = yield* GCP.AccessContextManager.AccessPoliciesServicePerimeter(
143 * "Storage",
144 * {
145 * policy: policy.name,
146 * title: "data perimeter",
147 * status: {
148 * restrictedServices: [
149 * "storage.googleapis.com",
150 * "bigquery.googleapis.com",
151 * ],
152 * },
153 * },
154 * );
155 * ```
156 *
157 * @resource
158 * @category AccessContextManager
159 */
160 export const AccessPoliciesServicePerimeter = Resource<AccessPoliciesServicePerimeter>(
161 "GCP.AccessContextManager.AccessPoliciesServicePerimeter",
162 );
163
164 export class AccessPoliciesServicePerimeterNotResolved extends Data.TaggedError(
165 "GCP.AccessContextManager.AccessPoliciesServicePerimeterNotResolved",
166 )<{
167 resourceName: string;
168 }> {}
169
170 const DEFAULT_TYPE = "PERIMETER_TYPE_REGULAR";
171
172 const typeOf = (value: string | undefined) => value ?? DEFAULT_TYPE;
173
174 const toAttrs = (perimeter: acm.ServicePerimeter): AccessPoliciesServicePerimeter["Attributes"] => {
175 const name = perimeter.name ?? "";
176 const parsed = parseName(name, "servicePerimeters");
177 const title = parseOwnership(perimeter.title);
178 const description = parseOwnership(perimeter.description);
179 return {
180 name,
181 servicePerimeterId: parsed.id,
182 policy: parsed.parent,
183 title: title.text,
184 description: description.text,
185 perimeterType: perimeter.perimeterType,
186 useExplicitDryRunSpec: perimeter.useExplicitDryRunSpec === true,
187 status: perimeter.status,
188 spec: perimeter.spec,
189 etag: perimeter.etag,
190 };
191 };
192
193 const getByName = (name: string) =>
194 acm
195 .getAccessPoliciesServicePerimeters({ name })
196 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
197
198 const listPerimeters = (policy: string) =>
199 collectPages(
200 acm.listAccessPoliciesServicePerimeters.pages({
201 parent: policyNameOf(policy),
202 pageSize: 100,
203 }),
204 (page) => page.servicePerimeters,
205 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as acm.ServicePerimeter[])));
206
207 export const AccessPoliciesServicePerimeterProvider = () =>
208 Provider.succeed(AccessPoliciesServicePerimeter, {
209 stables: ["name", "servicePerimeterId", "policy", "perimeterType"],
210
211 diff: Effect.fn(function* ({ news, olds, output }) {
212 if (!isResolved(news)) return undefined;
213 const previousId = olds?.servicePerimeterId ?? output?.servicePerimeterId;
214 const idChanged =
215 previousId !== undefined &&
216 news.servicePerimeterId !== undefined &&
217 news.servicePerimeterId !== previousId;
218 const previousPolicy = olds?.policy ?? output?.policy;
219 const policyChanged =
220 previousPolicy !== undefined && policyNameOf(news.policy) !== policyNameOf(previousPolicy);
221 const previousType = typeOf(olds?.perimeterType ?? output?.perimeterType);
222 const nextType = typeOf(news.perimeterType ?? olds?.perimeterType ?? output?.perimeterType);
223 const typeChanged = previousType !== nextType;
224 return replaceOnIdentity(idChanged || policyChanged || typeChanged);
225 }),
226
227 read: Effect.fn(function* ({ id, olds, output }) {
228 const servicePerimeterId = yield* toAcmId(
229 id,
230 olds?.servicePerimeterId,
231 output?.servicePerimeterId,
232 );
233 const policy = olds?.policy ?? output?.policy;
234 if (policy === undefined) return undefined;
235 const name = output?.name ?? resourceNameOf(policy, "servicePerimeters", servicePerimeterId);
236 const existing = yield* getByName(name);
237 if (existing === undefined) return undefined;
238 const attrs = toAttrs(existing);
239 return (yield* ownedByAlchemy(id, existing.description ?? existing.title))
240 ? attrs
241 : Unowned(attrs);
242 }),
243
244 list: () =>
245 Effect.gen(function* () {
246 const policies = yield* listOwnedPolicies();
247 const perimeters = yield* Effect.forEach(
248 policies,
249 (policy) =>
250 policy.name
251 ? listPerimeters(policy.name)
252 : Effect.succeed([] as acm.ServicePerimeter[]),
253 { concurrency: 4 },
254 );
255 return perimeters
256 .flat()
257 .filter(
258 (perimeter) =>
259 parseOwnership(perimeter.description ?? perimeter.title).labels["alchemy-id"],
260 )
261 .map(toAttrs);
262 }),
263
264 reconcile: Effect.fn(function* ({ id, news, output }) {
265 const policy = policyNameOf(news.policy);
266 const servicePerimeterId = yield* toAcmId(
267 id,
268 news.servicePerimeterId,
269 output?.servicePerimeterId,
270 );
271 const name = resourceNameOf(policy, "servicePerimeters", servicePerimeterId);
272 const ownership = yield* createInternalLabels(id);
273 const desiredTitle = encodeOwnershipLine(
274 ownership,
275 news.title ?? servicePerimeterId,
276 MAX_TITLE_LENGTH,
277 );
278 const desiredDescription = encodeOwnership(
279 ownership,
280 news.description,
281 MAX_DESCRIPTION_LENGTH,
282 );
283 const desiredType = typeOf(news.perimeterType);
284 const desiredDryRun = news.useExplicitDryRunSpec === true;
285
286 let current = yield* getByName(output?.name ?? name);
287
288 if (current === undefined) {
289 const created = yield* acm
290 .createAccessPoliciesServicePerimeters({
291 parent: policy,
292 body: {
293 name,
294 title: desiredTitle,
295 description: desiredDescription,
296 perimeterType: desiredType,
297 useExplicitDryRunSpec: desiredDryRun ? true : undefined,
298 status: news.status,
299 spec: news.spec,
300 },
301 })
302 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
303 if (created !== undefined) {
304 // ALREADY_EXISTS (6): a concurrent create won the race.
305 yield* waitForOperation(created).pipe(
306 Effect.catchTag("GCP.OperationFailed", (error) =>
307 error.code === 6 ? Effect.void : Effect.fail(error),
308 ),
309 );
310 }
311 current = yield* waitUntilExists(getByName(name), name);
312 }
313
314 if (current === undefined) {
315 return yield* new AccessPoliciesServicePerimeterNotResolved({ resourceName: name });
316 }
317
318 const titleChanged = (current.title ?? "") !== desiredTitle;
319 const descriptionChanged = (current.description ?? "") !== desiredDescription;
320 const dryRunChanged = (current.useExplicitDryRunSpec === true) !== desiredDryRun;
321 const statusChanged = news.status !== undefined && !jsonEqual(current.status, news.status);
322 const specChanged = news.spec !== undefined && !jsonEqual(current.spec, news.spec);
323
324 const updateMask = [
325 titleChanged ? "title" : undefined,
326 descriptionChanged ? "description" : undefined,
327 dryRunChanged ? "use_explicit_dry_run_spec" : undefined,
328 statusChanged ? "status" : undefined,
329 specChanged ? "spec" : undefined,
330 ].filter((field): field is string => field !== undefined);
331
332 if (updateMask.length > 0) {
333 const operation = yield* acm.patchAccessPoliciesServicePerimeters({
334 name: current.name ?? name,
335 updateMask: updateMask.join(","),
336 body: {
337 name: current.name ?? name,
338 title: desiredTitle,
339 description: desiredDescription,
340 useExplicitDryRunSpec: desiredDryRun,
341 status: news.status,
342 spec: news.spec,
343 etag: current.etag,
344 },
345 });
346 yield* waitForOperation(operation);
347 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
348 }
349
350 if (current === undefined) {
351 return yield* new AccessPoliciesServicePerimeterNotResolved({ resourceName: name });
352 }
353
354 return toAttrs(current);
355 }),
356
357 delete: Effect.fn(function* ({ output }) {
358 const operation = yield* acm
359 .deleteAccessPoliciesServicePerimeters({ name: output.name })
360 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
361 if (operation !== undefined) {
362 // NOT_FOUND (5): already gone.
363 yield* waitForOperation(operation).pipe(
364 Effect.catchTag("GCP.OperationFailed", (error) =>
365 error.code === 5 ? Effect.void : Effect.fail(error),
366 ),
367 );
368 }
369 yield* waitUntilGone(getByName(output.name), output.name);
370 }),
371 });