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

main
ts 333 lines 12.1 KB
Raw
1 import * as codeartifact from "@distilled.cloud/aws/codeartifact";
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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export interface RepositoryProps {
13 /**
14 * Name of the domain that contains the repository. Pass a `Domain`'s
15 * `domainName` attribute. Changing the domain replaces the repository.
16 */
17 domain: string;
18 /**
19 * AWS account ID that owns the domain, if it differs from the caller's
20 * account (cross-account domains).
21 */
22 domainOwner?: string;
23 /**
24 * Name of the repository (2-100 chars). If omitted a deterministic physical
25 * name is generated. Changing the name replaces the repository.
26 */
27 repositoryName?: string;
28 /**
29 * Human-readable description of the repository.
30 */
31 description?: string;
32 /**
33 * Names of other repositories in the same domain to configure as upstream
34 * sources. Requests fall through to upstreams (and then any external
35 * connection) on a cache miss.
36 */
37 upstreams?: string[];
38 /**
39 * A single external connection (e.g. `public:npmjs`, `public:pypi`,
40 * `public:maven-central`) to a public package registry. AWS allows at most
41 * one external connection per repository.
42 */
43 externalConnection?: string;
44 /**
45 * User-defined tags.
46 */
47 tags?: Record<string, string>;
48 }
49
50 export interface Repository extends Resource<
51 "AWS.CodeArtifact.Repository",
52 RepositoryProps,
53 {
54 /** Physical name of the repository. */
55 repositoryName: string;
56 /** ARN of the repository. */
57 repositoryArn: string;
58 /** Name of the domain containing the repository. */
59 domainName: string;
60 /** AWS account ID that owns the containing domain. */
61 domainOwner: string;
62 /** AWS account that manages the repository resource. */
63 administratorAccount: string;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * An AWS CodeArtifact repository — a package store inside a
71 * {@link Domain}. Repositories host packages (npm, PyPI, Maven, NuGet, etc.)
72 * and can chain to upstream repositories and a single external connection to a
73 * public registry.
74 *
75 * ### Creating a Repository
76 * **Example:** Basic Repository
77 * ```typescript
78 * const domain = yield* CodeArtifact.Domain("packages", {});
79 * const repo = yield* CodeArtifact.Repository("npm-store", {
80 * domain: domain.domainName,
81 * });
82 * ```
83 *
84 * **Example:** Repository with an external connection to npmjs
85 * ```typescript
86 * const repo = yield* CodeArtifact.Repository("npm-store", {
87 * domain: domain.domainName,
88 * description: "Proxy of the public npm registry",
89 * externalConnection: "public:npmjs",
90 * });
91 * ```
92 *
93 * **Example:** Repository with an upstream
94 * ```typescript
95 * const shared = yield* CodeArtifact.Repository("shared", {
96 * domain: domain.domainName,
97 * });
98 * const app = yield* CodeArtifact.Repository("app", {
99 * domain: domain.domainName,
100 * upstreams: [shared.repositoryName],
101 * });
102 * ```
103 *
104 * @resource
105 */
106 export const Repository = Resource<Repository>("AWS.CodeArtifact.Repository");
107
108 /** Convert a CodeArtifact wire tag list into a plain record. */
109 const toTagRecord = (
110 tags: ReadonlyArray<{ key?: string; value?: string }> | undefined,
111 ): Record<string, string> =>
112 Object.fromEntries(
113 (tags ?? [])
114 .filter(
115 (tag): tag is { key: string; value: string } =>
116 typeof tag.key === "string" && typeof tag.value === "string",
117 )
118 .map((tag) => [tag.key, tag.value]),
119 );
120
121 const upstreamNames = (
122 upstreams: ReadonlyArray<{ repositoryName?: string }> | undefined,
123 ): string[] =>
124 (upstreams ?? []).map((u) => u.repositoryName).filter((n): n is string => typeof n === "string");
125
126 const externalConnectionNames = (
127 connections: ReadonlyArray<{ externalConnectionName?: string }> | undefined,
128 ): string[] =>
129 (connections ?? [])
130 .map((c) => c.externalConnectionName)
131 .filter((n): n is string => typeof n === "string");
132
133 const sameSet = (a: readonly string[], b: readonly string[]): boolean =>
134 a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
135
136 export const RepositoryProvider = () =>
137 Provider.effect(
138 Repository,
139 Effect.gen(function* () {
140 const toName = (id: string, props: Partial<RepositoryProps>) =>
141 props.repositoryName
142 ? Effect.succeed(props.repositoryName)
143 : createPhysicalName({ id, maxLength: 100 });
144
145 const getRepository = Effect.fn(function* (
146 domain: string,
147 domainOwner: string | undefined,
148 name: string,
149 ) {
150 const response = yield* codeartifact
151 .describeRepository({ domain, domainOwner, repository: name })
152 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
153 return response?.repository;
154 });
155
156 const toAttrs = (
157 repository: codeartifact.RepositoryDescription,
158 name: string,
159 domain: string,
160 ) => ({
161 repositoryName: repository.name ?? name,
162 repositoryArn: repository.arn!,
163 domainName: repository.domainName ?? domain,
164 domainOwner: repository.domainOwner ?? "",
165 administratorAccount: repository.administratorAccount ?? "",
166 });
167
168 const syncTags = Effect.fn(function* (arn: string, desiredTags: Record<string, string>) {
169 const observed = yield* codeartifact
170 .listTagsForResource({ resourceArn: arn })
171 .pipe(Effect.orElseSucceed(() => undefined));
172 const { removed, upsert } = diffTags(toTagRecord(observed?.tags), desiredTags);
173 if (upsert.length > 0) {
174 yield* codeartifact.tagResource({
175 resourceArn: arn,
176 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
177 });
178 }
179 if (removed.length > 0) {
180 yield* codeartifact.untagResource({
181 resourceArn: arn,
182 tagKeys: removed,
183 });
184 }
185 });
186
187 return {
188 stables: ["repositoryName", "repositoryArn", "domainName"],
189
190 diff: Effect.fn(function* ({ id, olds, news }) {
191 if (!isResolved(news)) return undefined;
192 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
193 return { action: "replace" } as const;
194 }
195 // The containing domain is immutable — replace on change.
196 if (
197 (news?.domain ?? undefined) !== (olds?.domain ?? undefined) ||
198 (news?.domainOwner ?? undefined) !== (olds?.domainOwner ?? undefined)
199 ) {
200 return { action: "replace" } as const;
201 }
202 }),
203
204 read: Effect.fn(function* ({ id, olds, output }) {
205 const name = output?.repositoryName ?? (yield* toName(id, olds ?? {}));
206 const domain = output?.domainName ?? olds?.domain;
207 if (domain === undefined) return undefined;
208 const repository = yield* getRepository(domain, olds?.domainOwner, name);
209 if (repository?.arn === undefined) return undefined;
210 const attrs = toAttrs(repository, name, domain);
211 const tags = yield* codeartifact
212 .listTagsForResource({ resourceArn: attrs.repositoryArn })
213 .pipe(
214 Effect.map((res) => toTagRecord(res.tags)),
215 Effect.orElseSucceed(() => ({})),
216 );
217 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output, session }) {
221 const name = output?.repositoryName ?? (yield* toName(id, news));
222 const domain = news.domain;
223 const domainOwner = news.domainOwner;
224 const internalTags = yield* createInternalTags(id);
225 const desiredTags = { ...internalTags, ...news.tags };
226 const desiredUpstreams = news.upstreams ?? [];
227
228 // 1. Observe — cloud state is authoritative.
229 let observed = yield* getRepository(domain, domainOwner, name);
230
231 // 2. Ensure — create if missing. Tolerate a concurrent-create race.
232 if (observed?.arn === undefined) {
233 observed = yield* codeartifact
234 .createRepository({
235 domain,
236 domainOwner,
237 repository: name,
238 description: news.description,
239 upstreams: desiredUpstreams.map((repositoryName) => ({
240 repositoryName,
241 })),
242 tags: Object.entries(desiredTags).map(([key, value]) => ({
243 key,
244 value,
245 })),
246 })
247 .pipe(
248 Effect.map((res) => res.repository),
249 Effect.catchTag("ConflictException", () =>
250 getRepository(domain, domainOwner, name),
251 ),
252 );
253 if (observed?.arn === undefined) {
254 observed = yield* getRepository(domain, domainOwner, name);
255 }
256 } else {
257 // 3a. Sync description + upstreams via updateRepository if they drift.
258 const descChanged =
259 (news.description ?? undefined) !== (observed.description ?? undefined);
260 const upstreamsChanged = !sameSet(desiredUpstreams, upstreamNames(observed.upstreams));
261 if (descChanged || upstreamsChanged) {
262 observed = yield* codeartifact
263 .updateRepository({
264 domain,
265 domainOwner,
266 repository: name,
267 description: news.description,
268 upstreams: desiredUpstreams.map((repositoryName) => ({
269 repositoryName,
270 })),
271 })
272 .pipe(Effect.map((res) => res.repository ?? observed));
273 }
274 }
275
276 // 3b. Sync the external connection — AWS allows at most one.
277 const desiredConn = news.externalConnection;
278 const currentConns = externalConnectionNames(observed!.externalConnections);
279 for (const conn of currentConns) {
280 if (conn !== desiredConn) {
281 yield* codeartifact.disassociateExternalConnection({
282 domain,
283 domainOwner,
284 repository: name,
285 externalConnection: conn,
286 });
287 }
288 }
289 if (desiredConn !== undefined && !currentConns.includes(desiredConn)) {
290 observed = yield* codeartifact
291 .associateExternalConnection({
292 domain,
293 domainOwner,
294 repository: name,
295 externalConnection: desiredConn,
296 })
297 .pipe(Effect.map((res) => res.repository ?? observed));
298 }
299
300 // 3c. Sync tags — diff against OBSERVED cloud tags.
301 yield* syncTags(observed!.arn!, desiredTags);
302
303 // 4. Return fresh attributes.
304 yield* session.note(name);
305 return toAttrs(observed!, name, domain);
306 }),
307
308 delete: Effect.fn(function* ({ output, olds }) {
309 yield* codeartifact
310 .deleteRepository({
311 domain: output.domainName,
312 domainOwner: output.domainOwner || olds?.domainOwner,
313 repository: output.repositoryName,
314 })
315 .pipe(
316 // Deleting a downstream repository propagates eventually — a
317 // shared upstream deleted right after can transiently fail with
318 // "being used as an upstream repository".
319 Effect.retry({
320 while: (e): boolean => e._tag === "ConflictException",
321 schedule: Schedule.spaced("2 seconds"),
322 times: 10,
323 }),
324 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
325 );
326 }),
327
328 // Repositories are scoped to a domain; there is no global enumeration
329 // without knowing the domain, so list() returns an empty set.
330 list: () => Effect.succeed([]),
331 };
332 }),
333 );