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

main
ts 345 lines 11.3 KB
Raw
1 import * as artifactregistry from "@distilled.cloud/gcp/artifactregistry_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 { GcpEnvironment } from "../Environment.ts";
8 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 ResourceNotResolved,
12 encodeOwnership,
13 expandRepository,
14 fieldMask,
15 hasOwnershipMarker,
16 listAlchemyRepositories,
17 listChildResources,
18 listRules,
19 locationFromRepository,
20 missingGet,
21 normalizeLocation,
22 parseName,
23 parseOwnership,
24 replaceOnIdentity,
25 sameJson,
26 sameText,
27 toPhysicalId,
28 } from "./internal.ts";
29
30 const DEFAULT_OPERATION = "DOWNLOAD";
31 const OWNERSHIP_TRUE = "true";
32
33 export type RuleCondition = {
34 /** CEL expression that must match for the rule to apply. */
35 expression?: string;
36 /** Short title for the expression. */
37 title?: string;
38 /** Longer description of the expression. */
39 description?: string;
40 /** Source location used in error reporting. */
41 location?: string;
42 };
43
44 export type RepositoriesRuleProps = {
45 /**
46 * Parent repository. Full name
47 * `projects/{project}/locations/{location}/repositories/{repository}`
48 * or the repository id (combined with `location`). Immutable —
49 * changing it replaces the rule.
50 */
51 repository: string;
52 /**
53 * Region used when `repository` is a bare id.
54 * @default the repository's location, else the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
55 */
56 location?: string;
57 /**
58 * Rule id (the `{rule}` segment of `.../repositories/{repository}/rules/{rule}`).
59 * If omitted, a unique name is generated. Max 256 characters:
60 * alphanumeric plus `-._~:@+^`. Immutable — changing it replaces the
61 * rule.
62 */
63 ruleId?: string;
64 /**
65 * Action applied to matching downloads.
66 */
67 action: artifactregistry.GoogleDevtoolsArtifactregistryV1RuleActionEnum | (string & {});
68 /**
69 * Operation the rule applies to.
70 * @default "DOWNLOAD"
71 */
72 operation?: artifactregistry.GoogleDevtoolsArtifactregistryV1RuleOperationEnum | (string & {});
73 /**
74 * Package id this rule applies to. Empty or omitted applies to every
75 * package in the repository. Each repository may have one
76 * repository-level rule and one rule per package.
77 */
78 packageId?: string;
79 /**
80 * Optional CEL condition. Rules have no labels field, so Alchemy stamps
81 * ownership into `condition.title`.
82 */
83 condition?: RuleCondition;
84 };
85
86 export type RepositoriesRule = Resource<
87 "GCP.ArtifactRegistry.RepositoriesRule",
88 RepositoriesRuleProps,
89 {
90 /** Full resource name `projects/{project}/locations/{location}/repositories/{repository}/rules/{rule}`. */
91 name: string;
92 /** Rule id (last path segment). */
93 ruleId: string;
94 /** Parent repository resource name. */
95 repository: string;
96 /** Project id. */
97 project: string;
98 /** Location id (`us-central1`). */
99 location: string;
100 /** Action (`ALLOW` or `DENY`). */
101 action: string | undefined;
102 /** Operation (`DOWNLOAD`). */
103 operation: string | undefined;
104 /** Package id, if the rule is package-scoped. */
105 packageId: string | undefined;
106 /** User CEL condition with Alchemy ownership stripped from `title`. */
107 condition: RuleCondition | undefined;
108 },
109 never,
110 Providers
111 >;
112
113 /**
114 * An Artifact Registry download rule on a repository.
115 *
116 * Download rules are a Preview API. Each repository may have one
117 * repository-level rule and one rule per package. Changing `repository`,
118 * `location`, or `ruleId` replaces the rule. `action`, `operation`,
119 * `packageId`, and `condition` update in place.
120 *
121 * Rules have no labels field. Alchemy stamps ownership into
122 * `condition.title` so `list` / `pnpm nuke:gcp` can find them.
123 *
124 * ### Creating a RepositoriesRule
125 * **Example:** Deny all downloads
126 * ```typescript
127 * const rule = yield* GCP.ArtifactRegistry.RepositoriesRule("Deny", {
128 * repository: images.name,
129 * action: "DENY",
130 * });
131 * ```
132 *
133 * **Example:** Allow a package except old versions
134 * ```typescript
135 * const rule = yield* GCP.ArtifactRegistry.RepositoriesRule("AllowApp", {
136 * repository: images.name,
137 * action: "ALLOW",
138 * packageId: "app",
139 * condition: { expression: "pkg.version.id >= '1.0.0'" },
140 * });
141 * ```
142 *
143 * @resource
144 * @category ArtifactRegistry
145 */
146 export const RepositoriesRule = Resource<RepositoriesRule>("GCP.ArtifactRegistry.RepositoriesRule");
147
148 const normalizeOperation = (operation: string | undefined) => {
149 const value = (operation ?? DEFAULT_OPERATION).toUpperCase();
150 return value === "OPERATION_UNSPECIFIED" ? DEFAULT_OPERATION : value;
151 };
152
153 const normalizeAction = (action: string) => action.toUpperCase();
154
155 const resourceNameOf = (repository: string, ruleId: string) => `${repository}/rules/${ruleId}`;
156
157 const desiredCondition = (
158 news: RepositoriesRuleProps,
159 ownership: Record<string, string>,
160 ): artifactregistry.Expr => {
161 const expression =
162 news.condition?.expression && news.condition.expression.length > 0
163 ? news.condition.expression
164 : OWNERSHIP_TRUE;
165 return {
166 expression,
167 title: encodeOwnership(ownership, news.condition?.title),
168 description: news.condition?.description,
169 location: news.condition?.location,
170 };
171 };
172
173 const toUserCondition = (
174 condition: artifactregistry.Expr | undefined,
175 ): RuleCondition | undefined => {
176 if (condition === undefined) return undefined;
177 const ownership = parseOwnership(condition.title);
178 const title = ownership.text;
179 const expression = condition.expression;
180 const description = condition.description;
181 const location = condition.location;
182 const ownershipOnly =
183 expression === OWNERSHIP_TRUE &&
184 title === undefined &&
185 (description === undefined || description.length === 0) &&
186 (location === undefined || location.length === 0);
187 if (ownershipOnly) return undefined;
188 return {
189 expression,
190 title,
191 description,
192 location,
193 };
194 };
195
196 const toAttrs = (
197 rule: artifactregistry.GoogleDevtoolsArtifactregistryV1Rule,
198 project: string,
199 region: string,
200 ) => {
201 const name = rule.name ?? "";
202 const parsed = parseName(name, "rules", region);
203 return {
204 name,
205 ruleId: parsed.id,
206 repository: parsed.parent,
207 project: parsed.project || project,
208 location: parsed.location,
209 action: rule.action,
210 operation: normalizeOperation(rule.operation),
211 packageId: rule.packageId && rule.packageId.length > 0 ? rule.packageId : undefined,
212 condition: toUserCondition(rule.condition),
213 };
214 };
215
216 const getByName = missingGet(artifactregistry.getProjectsLocationsRepositoriesRules);
217
218 export const RepositoriesRuleProvider = () =>
219 Provider.succeed(RepositoriesRule, {
220 stables: ["name", "ruleId", "repository", "project", "location"],
221
222 diff: Effect.fn(function* ({ news, olds, output }) {
223 if (!isResolved(news)) return undefined;
224 const env = yield* GcpEnvironment.current;
225 const previousId = olds?.ruleId ?? output?.ruleId;
226 const nextId = news.ruleId ?? previousId;
227 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
228 const nextLocation = normalizeLocation(
229 news.location ?? locationFromRepository(news.repository, previousLocation),
230 env.region,
231 );
232 return replaceOnIdentity({
233 previousId,
234 nextId,
235 previousLocation,
236 nextLocation,
237 previousParent: olds?.repository ?? output?.repository,
238 nextParent: news.repository,
239 });
240 }),
241
242 read: Effect.fn(function* ({ id, olds, output }) {
243 const env = yield* GcpEnvironment.current;
244 const location = normalizeLocation(
245 olds?.location ??
246 output?.location ??
247 locationFromRepository(olds?.repository ?? output?.repository, env.region),
248 env.region,
249 );
250 const repository = expandRepository(
251 olds?.repository ?? output?.repository ?? "",
252 env.project,
253 location,
254 );
255 const ruleId = yield* toPhysicalId(id, olds?.ruleId, output?.ruleId, "rule");
256 const name = output?.name ?? resourceNameOf(repository, ruleId);
257 const existing = yield* getByName(name);
258 if (existing === undefined) return undefined;
259 const attrs = toAttrs(existing, env.project, env.region);
260 const { labels } = parseOwnership(existing.condition?.title);
261 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
262 }),
263
264 list: () =>
265 Effect.gen(function* () {
266 const env = yield* GcpEnvironment.current;
267 const repos = yield* listAlchemyRepositories(env.project);
268 const rules = yield* listChildResources(repos, listRules);
269 return rules
270 .filter((rule) => hasOwnershipMarker(rule.condition?.title))
271 .map((rule) => toAttrs(rule, env.project, env.region));
272 }),
273
274 reconcile: Effect.fn(function* ({ id, news, output }) {
275 const env = yield* GcpEnvironment.current;
276 const location = normalizeLocation(
277 news.location ?? output?.location ?? locationFromRepository(news.repository, env.region),
278 env.region,
279 );
280 const repository = expandRepository(news.repository, env.project, location);
281 const ruleId = yield* toPhysicalId(id, news.ruleId, output?.ruleId, "rule");
282 const name = resourceNameOf(repository, ruleId);
283 const ownership = yield* createInternalLabels(id);
284 const action = normalizeAction(news.action);
285 const operation = normalizeOperation(news.operation);
286 const packageId = news.packageId;
287 const condition = desiredCondition(news, ownership);
288
289 let current = yield* getByName(name);
290
291 if (current === undefined) {
292 const created = yield* artifactregistry
293 .createProjectsLocationsRepositoriesRules({
294 parent: repository,
295 ruleId,
296 body: {
297 action,
298 operation,
299 packageId,
300 condition,
301 },
302 })
303 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
304 current = created ?? undefined;
305 }
306
307 if (current === undefined) {
308 return yield* new ResourceNotResolved({ resourceName: name });
309 }
310
311 const observed = current.name ?? name;
312 const actionChanged = normalizeAction(current.action ?? "") !== action;
313 const operationChanged = normalizeOperation(current.operation) !== operation;
314 const packageChanged = !sameText(current.packageId, packageId);
315 const conditionChanged = !sameJson(current.condition, condition);
316 const updateMask = fieldMask([
317 actionChanged && "action",
318 operationChanged && "operation",
319 packageChanged && "packageId",
320 conditionChanged && "condition",
321 ]);
322
323 if (updateMask.length > 0) {
324 current = yield* artifactregistry.patchProjectsLocationsRepositoriesRules({
325 name: observed,
326 updateMask,
327 body: {
328 name: observed,
329 action,
330 operation,
331 packageId,
332 condition,
333 },
334 });
335 }
336
337 return toAttrs(current, env.project, env.region);
338 }),
339
340 delete: Effect.fn(function* ({ output }) {
341 yield* artifactregistry
342 .deleteProjectsLocationsRepositoriesRules({ name: output.name })
343 .pipe(Effect.catchTag("NotFound", () => Effect.void));
344 }),
345 });