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

main
ts 469 lines 16.5 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 { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitForDeleteOperation, waitForOperation } from "./internal.ts";
22
23 const DEFAULT_FORMAT = "DOCKER";
24 const DEFAULT_MODE = "STANDARD_REPOSITORY";
25 const MAX_NAME_LENGTH = 63;
26
27 export type RepositoryProps = {
28 /**
29 * Repository id (the `{repository}` segment of
30 * `projects/{project}/locations/{location}/repositories/{repository}`).
31 * If omitted, a unique name is generated from the stack, stage, and
32 * logical id. Must be 2-63 characters, start with a letter, and match
33 * `[a-z]([a-z0-9-]*[a-z0-9])?`. Immutable — changing it replaces the
34 * repository.
35 */
36 repositoryId?: string;
37 /**
38 * Artifact Registry location (`us-central1`, `us`, `europe`, …).
39 * Immutable — changing it replaces the repository. `US-CENTRAL1` is
40 * accepted and normalized to `us-central1`.
41 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
42 */
43 location?: string;
44 /**
45 * Package format (`DOCKER`, `MAVEN`, `NPM`, `PYTHON`, `APT`, `YUM`,
46 * `GO`, `GENERIC`, `KFP`, `RUBY`, `GOOGET`). Immutable — changing it
47 * replaces the repository.
48 * @default "DOCKER"
49 */
50 format?: artifactregistry.RepositoryFormatEnum | (string & {});
51 /**
52 * Repository mode. Immutable — changing it replaces the repository.
53 * @default "STANDARD_REPOSITORY"
54 */
55 mode?: artifactregistry.RepositoryModeEnum | (string & {});
56 /**
57 * User-provided description of the repository.
58 */
59 description?: string;
60 /**
61 * User labels. Alchemy ownership labels are merged in automatically.
62 */
63 labels?: Record<string, string>;
64 /**
65 * Cloud KMS key used to encrypt repository contents, as
66 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`. Immutable —
67 * changing it replaces the repository.
68 */
69 kmsKeyName?: string;
70 /**
71 * Docker repository config. Only applied when `format` is `DOCKER`.
72 */
73 dockerConfig?: {
74 /**
75 * Prevent tags from being modified, moved, or deleted. Tags can still
76 * be created.
77 */
78 immutableTags?: boolean;
79 };
80 /**
81 * Maven repository config. Only applied when `format` is `MAVEN`.
82 * Immutable — changing it replaces the repository.
83 */
84 mavenConfig?: {
85 /** Allow republishing the same snapshot versions. */
86 allowSnapshotOverwrites?: boolean;
87 /** Versions the registry will accept (`RELEASE`, `SNAPSHOT`). */
88 versionPolicy?: artifactregistry.MavenRepositoryConfigVersionPolicyEnum | (string & {});
89 };
90 /**
91 * Cleanup policies keyed by user-provided policy id.
92 */
93 cleanupPolicies?: artifactregistry.CleanupPolicyMap;
94 /**
95 * If true, the cleanup pipeline is prevented from deleting versions.
96 * @default false
97 */
98 cleanupPolicyDryRun?: boolean;
99 };
100
101 export type Repository = Resource<
102 "GCP.ArtifactRegistry.Repository",
103 RepositoryProps,
104 {
105 /** Full resource name `projects/{project}/locations/{location}/repositories/{repository}`. */
106 name: string;
107 /** Repository id (last path segment). */
108 repositoryId: string;
109 /** Project id. */
110 project: string;
111 /** Location id (`us-central1`, `us`, …). */
112 location: string;
113 /** Package format (`DOCKER`, `NPM`, …). */
114 format: string;
115 /** Repository mode (`STANDARD_REPOSITORY`, …). */
116 mode: string;
117 /** User-provided description. */
118 description: string | undefined;
119 /** User labels (Alchemy ownership labels stripped). */
120 labels: Record<string, string>;
121 /** Registry endpoint, e.g. `us-central1-docker.pkg.dev/proj/repo`. */
122 registryUri: string | undefined;
123 /** KMS key used for encryption, if any. */
124 kmsKeyName: string | undefined;
125 /** Whether Docker tags are immutable. */
126 immutableTags: boolean;
127 /** Whether cleanup policies run in dry-run mode. */
128 cleanupPolicyDryRun: boolean;
129 /** Server-reported size of stored artifacts, in bytes. */
130 sizeBytes: string | undefined;
131 /** RFC3339 creation timestamp. */
132 createTime: string | undefined;
133 /** RFC3339 last-update timestamp. */
134 updateTime: string | undefined;
135 },
136 never,
137 Providers
138 >;
139
140 /**
141 * An Artifact Registry repository for Docker images, language packages, or
142 * generic artifacts.
143 *
144 * Changing `repositoryId`, `location`, `format`, `mode`, `kmsKeyName`, or
145 * Maven version policy replaces the repository.
146 *
147 * ### Creating a Repository
148 * **Example:** Generated name
149 * ```typescript
150 * const images = yield* GCP.ArtifactRegistry.Repository("Images", {});
151 * ```
152 *
153 * **Example:** Explicit id, format, and labels
154 * ```typescript
155 * const images = yield* GCP.ArtifactRegistry.Repository("Images", {
156 * repositoryId: "app-images",
157 * location: "us-central1",
158 * format: "DOCKER",
159 * description: "container images",
160 * labels: { env: "prod" },
161 * dockerConfig: { immutableTags: true },
162 * });
163 * ```
164 *
165 * @resource
166 * @category ArtifactRegistry
167 */
168 export const Repository = Resource<Repository>("GCP.ArtifactRegistry.Repository");
169
170 export class RepositoryNotResolved extends Data.TaggedError(
171 "GCP.ArtifactRegistry.RepositoryNotResolved",
172 )<{
173 resourceName: string;
174 }> {}
175
176 export class RepositoryStillExists extends Data.TaggedError(
177 "GCP.ArtifactRegistry.RepositoryStillExists",
178 )<{
179 resourceName: string;
180 }> {}
181
182 const lastSegment = (value: string) => {
183 const trimmed = value.replace(/\/+$/, "");
184 const parts = trimmed.split("/");
185 return parts[parts.length - 1] || trimmed;
186 };
187
188 const normalizeLocation = (location: string | undefined, fallback: string) =>
189 lastSegment(location ?? fallback).toLowerCase();
190
191 const normalizeFormat = (format: string | undefined) => (format ?? DEFAULT_FORMAT).toUpperCase();
192
193 const normalizeMode = (mode: string | undefined) => {
194 const value = (mode ?? DEFAULT_MODE).toUpperCase();
195 return value === "MODE_UNSPECIFIED" ? DEFAULT_MODE : value;
196 };
197
198 const resourceName = (project: string, location: string, repositoryId: string) =>
199 `projects/${project}/locations/${location}/repositories/${repositoryId}`;
200
201 const parseName = (name: string, fallbackLocation: string) => {
202 const parts = name.split("/").filter((part) => part.length > 0);
203 const repositoriesAt = parts.lastIndexOf("repositories");
204 const locationsAt = parts.lastIndexOf("locations");
205 const projectsAt = parts.lastIndexOf("projects");
206 return {
207 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
208 location:
209 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
210 repositoryId:
211 repositoriesAt >= 0 && parts[repositoriesAt + 1]
212 ? parts[repositoriesAt + 1]!
213 : lastSegment(name),
214 };
215 };
216
217 const userLabels = (
218 labels: Record<string, string | undefined> | null | undefined,
219 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
220
221 const toId = (id: string, repositoryId: string | undefined, existing?: string) =>
222 Effect.gen(function* () {
223 return (
224 repositoryId ??
225 existing ??
226 (yield* createPhysicalName({
227 id,
228 maxLength: MAX_NAME_LENGTH,
229 lowercase: true,
230 }))
231 );
232 });
233
234 const toAttrs = (repo: artifactregistry.Repository, project: string, region: string) => {
235 const name = repo.name ?? "";
236 const parsed = parseName(name, region);
237 return {
238 name,
239 repositoryId: parsed.repositoryId,
240 project: parsed.project || project,
241 location: parsed.location,
242 format: normalizeFormat(repo.format),
243 mode: normalizeMode(repo.mode),
244 description: repo.description,
245 labels: userLabels(repo.labels),
246 registryUri: repo.registryUri,
247 kmsKeyName: repo.kmsKeyName,
248 immutableTags: repo.dockerConfig?.immutableTags === true,
249 cleanupPolicyDryRun: repo.cleanupPolicyDryRun === true,
250 sizeBytes: repo.sizeBytes,
251 createTime: repo.createTime,
252 updateTime: repo.updateTime,
253 };
254 };
255
256 const getByName = (name: string) =>
257 artifactregistry
258 .getProjectsLocationsRepositories({ name })
259 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
260
261 const mavenKey = (config: RepositoryProps["mavenConfig"] | undefined) =>
262 `${config?.allowSnapshotOverwrites === true}:${(
263 config?.versionPolicy ?? "VERSION_POLICY_UNSPECIFIED"
264 ).toUpperCase()}`;
265
266 const cleanupPoliciesJson = (policies: artifactregistry.CleanupPolicyMap | undefined) =>
267 JSON.stringify(policies ?? {});
268
269 const waitUntilExists = (name: string) =>
270 getByName(name).pipe(
271 Effect.filterOrFail(
272 (repo): repo is artifactregistry.Repository => repo !== undefined,
273 () => new RepositoryNotResolved({ resourceName: name }),
274 ),
275 Effect.retry({
276 while: (error) => error._tag === "GCP.ArtifactRegistry.RepositoryNotResolved",
277 times: 8,
278 schedule: Schedule.spaced("1 second"),
279 }),
280 );
281
282 const waitUntilGone = (name: string) =>
283 getByName(name).pipe(
284 Effect.filterOrFail(
285 (repo) => repo === undefined,
286 () => new RepositoryStillExists({ resourceName: name }),
287 ),
288 Effect.asVoid,
289 Effect.retry({
290 while: (error) => error._tag === "GCP.ArtifactRegistry.RepositoryStillExists",
291 times: 10,
292 schedule: Schedule.spaced("1 second"),
293 }),
294 );
295
296 export const RepositoryProvider = () =>
297 Provider.succeed(Repository, {
298 stables: [
299 "name",
300 "repositoryId",
301 "project",
302 "location",
303 "format",
304 "mode",
305 "kmsKeyName",
306 "createTime",
307 ],
308
309 diff: Effect.fn(function* ({ news, olds, output }) {
310 if (!isResolved(news)) return undefined;
311 const env = yield* GcpEnvironment.current;
312
313 const previousId = olds?.repositoryId ?? output?.repositoryId;
314 const nextId = news.repositoryId ?? previousId;
315 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
316 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
317 const previousFormat = normalizeFormat(olds?.format ?? output?.format);
318 const nextFormat = normalizeFormat(news.format ?? output?.format);
319 const previousMode = normalizeMode(olds?.mode ?? output?.mode);
320 const nextMode = normalizeMode(news.mode ?? output?.mode);
321 const previousKms = olds?.kmsKeyName ?? output?.kmsKeyName ?? "";
322 const nextKms = news.kmsKeyName ?? previousKms;
323 const mavenChanged = mavenKey(news.mavenConfig) !== mavenKey(olds?.mavenConfig);
324
325 const replace =
326 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
327 previousLocation !== nextLocation ||
328 previousFormat !== nextFormat ||
329 previousMode !== nextMode ||
330 previousKms !== nextKms ||
331 mavenChanged;
332
333 if (!replace) return undefined;
334 return {
335 action: "replace" as const,
336 deleteFirst:
337 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
338 };
339 }),
340
341 read: Effect.fn(function* ({ id, olds, output }) {
342 const env = yield* GcpEnvironment.current;
343 const repositoryId = yield* toId(id, olds?.repositoryId, output?.repositoryId);
344 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
345 const name = output?.name ?? resourceName(env.project, location, repositoryId);
346 const existing = yield* getByName(name);
347 if (existing === undefined) return undefined;
348 const attrs = toAttrs(existing, env.project, env.region);
349 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
350 }),
351
352 list: () =>
353 Effect.gen(function* () {
354 const env = yield* GcpEnvironment.current;
355 const pages = yield* artifactregistry.listProjectsLocationsRepositories
356 .pages({
357 parent: `projects/${env.project}/locations/-`,
358 pageSize: 1000,
359 })
360 .pipe(Stream.runCollect);
361 return Array.from(pages).flatMap((page) =>
362 (page.repositories ?? [])
363 .filter((repo) =>
364 Object.keys(repo.labels ?? {}).some((key) => key.startsWith("alchemy-")),
365 )
366 .map((repo) => toAttrs(repo, env.project, env.region)),
367 );
368 }),
369
370 reconcile: Effect.fn(function* ({ id, news, output }) {
371 const env = yield* GcpEnvironment.current;
372 const repositoryId = yield* toId(id, news.repositoryId, output?.repositoryId);
373 const location = normalizeLocation(news.location ?? output?.location, env.region);
374 const format = normalizeFormat(news.format);
375 const mode = normalizeMode(news.mode);
376 const name = resourceName(env.project, location, repositoryId);
377 const desiredLabels = {
378 ...toLabels(news.labels),
379 ...(yield* createInternalLabels(id)),
380 };
381 const desiredImmutableTags = news.dockerConfig?.immutableTags === true;
382 const desiredCleanupDryRun = news.cleanupPolicyDryRun === true;
383 const desiredMaven = format === "MAVEN" ? news.mavenConfig : undefined;
384 const desiredDocker =
385 format === "DOCKER" ? { immutableTags: desiredImmutableTags } : undefined;
386
387 let current = yield* getByName(name);
388
389 if (current === undefined) {
390 const created = yield* artifactregistry
391 .createProjectsLocationsRepositories({
392 parent: `projects/${env.project}/locations/${location}`,
393 repositoryId,
394 body: {
395 format,
396 mode,
397 description: news.description,
398 labels: desiredLabels,
399 kmsKeyName: news.kmsKeyName,
400 dockerConfig: desiredDocker,
401 mavenConfig: desiredMaven,
402 cleanupPolicies: news.cleanupPolicies,
403 cleanupPolicyDryRun: desiredCleanupDryRun,
404 },
405 })
406 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
407 if (created !== undefined) {
408 yield* waitForOperation(created);
409 }
410 current = yield* waitUntilExists(name);
411 }
412
413 if (current === undefined) {
414 return yield* new RepositoryNotResolved({ resourceName: name });
415 }
416
417 const observedLabels = tagRecord(current.labels);
418 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
419 const labelsChanged = upsert.length > 0 || removed.length > 0;
420 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
421 const dockerChanged =
422 format === "DOCKER" &&
423 (current.dockerConfig?.immutableTags === true) !== desiredImmutableTags;
424 const cleanupDryRunChanged = (current.cleanupPolicyDryRun === true) !== desiredCleanupDryRun;
425 const cleanupPoliciesChanged =
426 cleanupPoliciesJson(current.cleanupPolicies) !== cleanupPoliciesJson(news.cleanupPolicies);
427
428 if (
429 labelsChanged ||
430 descriptionChanged ||
431 dockerChanged ||
432 cleanupDryRunChanged ||
433 cleanupPoliciesChanged
434 ) {
435 const updateMask = [
436 labelsChanged ? "labels" : undefined,
437 descriptionChanged ? "description" : undefined,
438 dockerChanged ? "dockerConfig" : undefined,
439 cleanupDryRunChanged ? "cleanupPolicyDryRun" : undefined,
440 cleanupPoliciesChanged ? "cleanupPolicies" : undefined,
441 ].filter((field): field is string => field !== undefined);
442
443 current = yield* artifactregistry.patchProjectsLocationsRepositories({
444 name,
445 updateMask: updateMask.join(","),
446 body: {
447 name,
448 labels: desiredLabels,
449 description: news.description,
450 dockerConfig: desiredDocker,
451 cleanupPolicyDryRun: desiredCleanupDryRun,
452 cleanupPolicies: news.cleanupPolicies ?? {},
453 },
454 });
455 }
456
457 return toAttrs(current, env.project, env.region);
458 }),
459
460 delete: Effect.fn(function* ({ output }) {
461 const operation = yield* artifactregistry
462 .deleteProjectsLocationsRepositories({ name: output.name })
463 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
464 if (operation !== undefined) {
465 yield* waitForDeleteOperation(operation);
466 }
467 yield* waitUntilGone(output.name);
468 }),
469 });