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

main
ts 373 lines 12.2 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import { unownedUnlessPrevious } 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 { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_LIEN_ORIGIN,
13 DEFAULT_LIEN_RESTRICTIONS,
14 LIEN_ORIGIN_MAX,
15 LIEN_REASON_MAX,
16 collectPages,
17 projectNumberOf,
18 projectParent,
19 sameStringList,
20 } from "./internal.ts";
21
22 export type LienProps = {
23 /**
24 * Resource this lien attaches to, e.g. `projects/{project}`. Defaults
25 * to the current project (numeric form). Immutable — changing it
26 * replaces the lien.
27 */
28 parent?: string;
29 /**
30 * Origin of the lien (max 200 characters). Programmatic identifier
31 * for the system that created it.
32 * @default "alchemy.effect"
33 */
34 origin?: string;
35 /**
36 * User-visible reason the restriction exists (max 200 characters).
37 * @default "Protected by a lien."
38 */
39 reason?: string;
40 /**
41 * IAM permissions this lien blocks. An empty list is rejected.
42 * @default ["resourcemanager.projects.delete"]
43 */
44 restrictions?: string[];
45 };
46
47 export type Lien = Resource<
48 "GCP.ResourceManager.Lien",
49 LienProps,
50 {
51 /** Resource name `liens/{lien_id}`. */
52 name: string;
53 /** Parent resource this lien is attached to. */
54 parent: string;
55 /** Origin identifier. */
56 origin: string;
57 /** Reason shown when a restricted operation is refused. */
58 reason: string | undefined;
59 /** Blocked IAM permissions. */
60 restrictions: string[];
61 /** RFC3339 creation timestamp. */
62 createTime: string | undefined;
63 /** Project id used to default `parent`. */
64 project: string;
65 },
66 never,
67 Providers
68 >;
69
70 /**
71 * A Cloud Resource Manager lien — an encumbrance that blocks selected
72 * operations on a project (most commonly project deletion).
73 *
74 * Liens have no update API, id, or labels: the lien on `parent` with the
75 * same origin, reason, and restrictions is the managed one, and `list` /
76 * `pnpm nuke:gcp` return liens whose `origin` is `alchemy.effect`. Changing `parent`,
77 * `origin`, `reason`, or `restrictions` replaces the lien (delete-first).
78 *
79 * ### Creating a Lien
80 * **Example:** Block deletion of the current project
81 * ```typescript
82 * const lien = yield* GCP.ResourceManager.Lien("Hold", {
83 * reason: "production API key",
84 * });
85 * ```
86 *
87 * **Example:** Explicit parent and restrictions
88 * ```typescript
89 * const lien = yield* GCP.ResourceManager.Lien("Hold", {
90 * parent: "projects/123456789",
91 * origin: "alchemy.effect",
92 * reason: "holds billing export",
93 * restrictions: ["resourcemanager.projects.delete"],
94 * });
95 * ```
96 *
97 * @resource
98 * @category ResourceManager
99 */
100 export const Lien = Resource<Lien>("GCP.ResourceManager.Lien");
101
102 export class LienNotResolved extends Data.TaggedError("GCP.ResourceManager.LienNotResolved")<{
103 resourceName: string;
104 }> {}
105
106 export class LienStillExists extends Data.TaggedError("GCP.ResourceManager.LienStillExists")<{
107 resourceName: string;
108 }> {}
109
110 const unique = (values: string[]) => [...new Set(values.filter((value) => value.length > 0))];
111
112 const parentAliases = (parent: string, project: string, projectNumber: string) => {
113 const normalized = projectParent(parent);
114 if (!normalized.startsWith("projects/")) return [normalized];
115 return unique([normalized, `projects/${project}`, `projects/${projectNumber}`]);
116 };
117
118 const sameParent = (left: string, right: string, project: string, projectNumber: string) => {
119 const aliases = new Set(parentAliases(left, project, projectNumber));
120 return parentAliases(right, project, projectNumber).some((alias) => aliases.has(alias));
121 };
122
123 const restrictionsOf = (values: readonly string[] | undefined) => {
124 const next = [...(values ?? DEFAULT_LIEN_RESTRICTIONS)].filter((value) => value.length > 0);
125 return next.length > 0 ? next : [...DEFAULT_LIEN_RESTRICTIONS];
126 };
127
128 const originOf = (origin: string | undefined) => {
129 const next = (origin ?? DEFAULT_LIEN_ORIGIN).trim();
130 return next.length > 0 ? next.slice(0, LIEN_ORIGIN_MAX) : DEFAULT_LIEN_ORIGIN;
131 };
132
133 const toAttrs = (lien: resourcemanager.Lien, project: string) => ({
134 name: lien.name ?? "",
135 parent: lien.parent ?? "",
136 origin: lien.origin ?? DEFAULT_LIEN_ORIGIN,
137 reason: lien.reason,
138 restrictions: lien.restrictions ?? [],
139 createTime: lien.createTime,
140 project,
141 });
142
143 const getByName = (name: string) =>
144 resourcemanager.getLiens({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
145
146 const listOnParent = (parent: string) =>
147 collectPages(
148 resourcemanager.listLiens.pages({
149 parent,
150 pageSize: 300,
151 }),
152 (page) => page.liens,
153 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as resourcemanager.Lien[])));
154
155 const listOnParents = (parents: string[]) =>
156 Effect.gen(function* () {
157 const pages = yield* Effect.forEach(parents, listOnParent, {
158 concurrency: 2,
159 });
160 const byName = new Map<string, resourcemanager.Lien>();
161 for (const lien of pages.flat()) {
162 if (lien.name) byName.set(lien.name, lien);
163 }
164 return [...byName.values()];
165 });
166
167 const matchesDesired = (
168 lien: resourcemanager.Lien,
169 parent: string,
170 origin: string,
171 reason: string,
172 restrictions: readonly string[],
173 project: string,
174 projectNumber: string,
175 ) =>
176 sameParent(lien.parent ?? "", parent, project, projectNumber) &&
177 (lien.origin ?? "") === origin &&
178 (lien.reason ?? "") === reason &&
179 sameStringList(lien.restrictions, restrictions);
180
181 const DEFAULT_REASON = "Protected by a lien.";
182
183 const reasonOf = (reason: string | undefined) =>
184 (reason ?? DEFAULT_REASON).slice(0, LIEN_REASON_MAX);
185
186 /**
187 * Liens have no user-chosen id or labels: a lien on the parent with the
188 * same origin, reason, and restrictions is the one this resource manages.
189 */
190 const findMatching = (
191 parent: string,
192 origin: string,
193 reason: string,
194 restrictions: readonly string[],
195 project: string,
196 projectNumber: string,
197 resourceName?: string,
198 ) =>
199 Effect.gen(function* () {
200 if (resourceName !== undefined && resourceName.length > 0) {
201 const byName = yield* getByName(resourceName);
202 if (byName !== undefined) return byName;
203 }
204 const liens = yield* listOnParents(parentAliases(parent, project, projectNumber));
205 return liens.find((lien) =>
206 matchesDesired(lien, parent, origin, reason, restrictions, project, projectNumber),
207 );
208 });
209
210 const waitUntilExists = (
211 parent: string,
212 origin: string,
213 reason: string,
214 restrictions: readonly string[],
215 project: string,
216 projectNumber: string,
217 ) =>
218 findMatching(parent, origin, reason, restrictions, project, projectNumber).pipe(
219 Effect.filterOrFail(
220 (lien): lien is resourcemanager.Lien => lien !== undefined,
221 () => new LienNotResolved({ resourceName: parent }),
222 ),
223 Effect.retry({
224 while: (error) => error._tag === "GCP.ResourceManager.LienNotResolved",
225 times: 8,
226 schedule: Schedule.spaced("1 second"),
227 }),
228 );
229
230 const waitUntilGone = (name: string) =>
231 getByName(name).pipe(
232 Effect.flatMap((lien) =>
233 lien === undefined ? Effect.void : Effect.fail(new LienStillExists({ resourceName: name })),
234 ),
235 Effect.retry({
236 while: (error) => error._tag === "GCP.ResourceManager.LienStillExists",
237 times: 10,
238 schedule: Schedule.spaced("1 second"),
239 }),
240 );
241
242 export const LienProvider = () =>
243 Provider.succeed(Lien, {
244 stables: ["name", "parent", "origin", "createTime", "project"],
245
246 diff: Effect.fn(function* ({ news, olds, output }) {
247 if (!isResolved(news)) return undefined;
248 const env = yield* GcpEnvironment.current;
249 const projectNumber = yield* projectNumberOf(env.project);
250 const previousParent = olds?.parent ?? output?.parent;
251 const nextParent = projectParent(news.parent ?? previousParent ?? env.project);
252 const parentChanged =
253 previousParent !== undefined &&
254 !sameParent(previousParent, nextParent, env.project, projectNumber);
255
256 const previousOrigin = originOf(olds?.origin ?? output?.origin);
257 const originChanged = news.origin !== undefined && originOf(news.origin) !== previousOrigin;
258
259 const previousRestrictions = restrictionsOf(olds?.restrictions ?? output?.restrictions);
260 const restrictionsChanged =
261 news.restrictions !== undefined && !sameStringList(news.restrictions, previousRestrictions);
262
263 const previousReason = olds?.reason ?? output?.reason;
264 const reasonChanged = news.reason !== undefined && news.reason !== previousReason;
265
266 if (!parentChanged && !originChanged && !restrictionsChanged && !reasonChanged) {
267 return undefined;
268 }
269 return { action: "replace" as const, deleteFirst: true };
270 }),
271
272 read: Effect.fn(function* ({ olds, output, previous }) {
273 const env = yield* GcpEnvironment.current;
274 const projectNumber = yield* projectNumberOf(env.project);
275 const parent = projectParent(output?.parent ?? olds?.parent ?? `projects/${projectNumber}`);
276 const existing = yield* findMatching(
277 parent,
278 originOf(olds?.origin ?? output?.origin),
279 reasonOf(olds?.reason ?? output?.reason),
280 restrictionsOf(olds?.restrictions ?? output?.restrictions),
281 env.project,
282 projectNumber,
283 output?.name,
284 );
285 if (existing === undefined) return undefined;
286 const attrs = toAttrs(existing, env.project);
287 // No labels field: without prior state it may not be ours.
288 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
289 }),
290
291 list: () =>
292 Effect.gen(function* () {
293 const env = yield* GcpEnvironment.current;
294 const projectNumber = yield* projectNumberOf(env.project);
295 const liens = yield* listOnParents(
296 parentAliases(`projects/${projectNumber}`, env.project, projectNumber),
297 );
298 // `origin` identifies the system that placed a lien.
299 return liens
300 .filter((lien) => lien.origin === DEFAULT_LIEN_ORIGIN)
301 .map((lien) => toAttrs(lien, env.project));
302 }),
303
304 reconcile: Effect.fn(function* ({ news, output }) {
305 const env = yield* GcpEnvironment.current;
306 const projectNumber = yield* projectNumberOf(env.project);
307 const parent = projectParent(news.parent ?? output?.parent ?? `projects/${projectNumber}`);
308 const origin = originOf(news.origin);
309 const restrictions = restrictionsOf(news.restrictions);
310 const reason = reasonOf(news.reason);
311
312 let current = yield* findMatching(
313 parent,
314 origin,
315 reason,
316 restrictions,
317 env.project,
318 projectNumber,
319 output?.name,
320 );
321
322 if (
323 current !== undefined &&
324 !matchesDesired(current, parent, origin, reason, restrictions, env.project, projectNumber)
325 ) {
326 if (current.name !== undefined) {
327 yield* resourcemanager
328 .deleteLiens({ name: current.name })
329 .pipe(Effect.catchTag("NotFound", () => Effect.void));
330 yield* waitUntilGone(current.name);
331 }
332 current = undefined;
333 }
334
335 if (current === undefined) {
336 const created = yield* resourcemanager
337 .createLiens({
338 body: {
339 parent,
340 origin,
341 reason,
342 restrictions,
343 },
344 })
345 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
346 if (created !== undefined && created.name !== undefined) {
347 current = created;
348 } else {
349 current = yield* waitUntilExists(
350 parent,
351 origin,
352 reason,
353 restrictions,
354 env.project,
355 projectNumber,
356 );
357 }
358 }
359
360 if (current === undefined || current.name === undefined) {
361 return yield* new LienNotResolved({ resourceName: parent });
362 }
363
364 return toAttrs(current, env.project);
365 }),
366
367 delete: Effect.fn(function* ({ output }) {
368 yield* resourcemanager
369 .deleteLiens({ name: output.name })
370 .pipe(Effect.catchTag("NotFound", () => Effect.void));
371 yield* waitUntilGone(output.name);
372 }),
373 });