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

main
ts 359 lines 12.9 KB
Raw
1 import * as ecrpublic from "@distilled.cloud/aws/ecr-public";
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 Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { AccountID } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { Region } from "../Region.ts";
14
15 export class ECRPublicRepositoryUnexpectedResponse extends Data.TaggedError(
16 "ECRPublicRepositoryUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 // Amazon ECR Public is a single global registry hosted only in us-east-1. Every
23 // control-plane call must target that region regardless of the ambient stack
24 // region, so we pin it on every distilled operation.
25 const US_EAST_1 = "us-east-1";
26 const pin = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
27 effect.pipe(Effect.provideService(Region, Effect.succeed(US_EAST_1)));
28
29 export type RepositoryName = string;
30 export type RepositoryArn = `arn:aws:ecr-public::${AccountID}:repository/${RepositoryName}`;
31
32 /**
33 * Catalog display metadata shown on the public.ecr.aws gallery page for a
34 * repository. All fields are optional and free-form.
35 */
36 export interface PublicRepositoryCatalogData {
37 /** Short description of the contents of the repository. */
38 description?: string;
39 /** CPU architectures the images support (e.g. `["x86-64", "ARM 64"]`). */
40 architectures?: string[];
41 /** Operating systems the images support (e.g. `["Linux"]`). */
42 operatingSystems?: string[];
43 /** Detailed "about" markdown shown on the gallery page. */
44 aboutText?: string;
45 /** Usage instructions markdown shown on the gallery page. */
46 usageText?: string;
47 }
48
49 export interface PublicRepositoryProps {
50 /**
51 * Name of the public repository. If omitted, a unique name is generated.
52 * Must be lowercase.
53 */
54 repositoryName?: string;
55 /**
56 * Catalog display metadata for the public gallery page.
57 */
58 catalogData?: PublicRepositoryCatalogData;
59 /**
60 * Repository permission policy JSON granting push/pull access to other
61 * principals. Omit for a private-push, public-pull repository.
62 */
63 policyText?: string;
64 /**
65 * User-defined tags to apply to the repository.
66 */
67 tags?: Record<string, string>;
68 }
69
70 export interface PublicRepository extends Resource<
71 "AWS.ECRPublic.Repository",
72 PublicRepositoryProps,
73 {
74 /** The name of the public repository. */
75 repositoryName: RepositoryName;
76 /** The ARN of the public repository. */
77 repositoryArn: RepositoryArn;
78 /** The public pull URI, e.g. `public.ecr.aws/<alias>/<name>`. */
79 repositoryUri: string;
80 /** The AWS account ID of the registry. */
81 registryId: string;
82 /** The JSON repository permissions policy, if any. */
83 policyText?: string;
84 /** The tags attached to the repository. */
85 tags: Record<string, string>;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * An Amazon ECR Public repository on the public.ecr.aws registry. Images pushed
93 * here are pullable by anyone. ECR Public is a global service hosted only in
94 * `us-east-1`; this resource pins every control-plane call there regardless of
95 * the stack region.
96 *
97 * ### Creating Public Repositories
98 * **Example:** Basic Public Repository
99 * ```typescript
100 * const repo = yield* PublicRepository("MyPublicRepo", {});
101 * ```
102 *
103 * **Example:** With Catalog Metadata
104 * ```typescript
105 * const repo = yield* PublicRepository("MyPublicRepo", {
106 * catalogData: {
107 * description: "My awesome container image",
108 * architectures: ["x86-64", "ARM 64"],
109 * operatingSystems: ["Linux"],
110 * aboutText: "# About\nThis image does X.",
111 * usageText: "docker pull public.ecr.aws/...",
112 * },
113 * });
114 * ```
115 *
116 * ### Access Policies
117 * **Example:** Grant Cross-Account Push
118 * ```typescript
119 * const repo = yield* PublicRepository("MyPublicRepo", {
120 * policyText: JSON.stringify({
121 * Version: "2012-10-17",
122 * Statement: [
123 * {
124 * Sid: "AllowPush",
125 * Effect: "Allow",
126 * Principal: { AWS: "arn:aws:iam::123456789012:root" },
127 * Action: ["ecr-public:BatchCheckLayerAvailability", "ecr-public:PutImage"],
128 * },
129 * ],
130 * }),
131 * });
132 * ```
133 *
134 * @resource
135 */
136 export const PublicRepository = Resource<PublicRepository>("AWS.ECRPublic.Repository");
137
138 const toCatalogInput = (
139 catalogData: PublicRepositoryCatalogData | undefined,
140 ): ecrpublic.RepositoryCatalogDataInput | undefined =>
141 catalogData
142 ? {
143 description: catalogData.description,
144 architectures: catalogData.architectures,
145 operatingSystems: catalogData.operatingSystems,
146 aboutText: catalogData.aboutText,
147 usageText: catalogData.usageText,
148 }
149 : undefined;
150
151 const toTagRecord = (tags: ecrpublic.Tag[] | undefined): Record<string, string> =>
152 Object.fromEntries(
153 (tags ?? [])
154 .filter(
155 (t): t is { Key: string; Value: string } =>
156 typeof t.Key === "string" && typeof t.Value === "string",
157 )
158 .map((t) => [t.Key, t.Value]),
159 );
160
161 export const PublicRepositoryProvider = () =>
162 Provider.effect(
163 PublicRepository,
164 Effect.gen(function* () {
165 const toRepositoryName = (id: string, props: { repositoryName?: string } = {}) =>
166 props.repositoryName
167 ? Effect.succeed(props.repositoryName)
168 : createPhysicalName({ id, maxLength: 205, lowercase: true });
169
170 const observe = (repositoryName: string) =>
171 pin(
172 ecrpublic.describeRepositories({
173 repositoryNames: [repositoryName],
174 }),
175 ).pipe(
176 Effect.map((r) => r.repositories?.[0]),
177 Effect.catchTag("RepositoryNotFoundException", () => Effect.undefined),
178 );
179
180 const readPolicy = (repositoryName: string) =>
181 pin(ecrpublic.getRepositoryPolicy({ repositoryName })).pipe(
182 Effect.map((r) => r.policyText),
183 Effect.catchTag("RepositoryPolicyNotFoundException", () => Effect.undefined),
184 );
185
186 const syncPolicy = Effect.fn(function* (repositoryName: string, desired: string | undefined) {
187 const observed = yield* readPolicy(repositoryName);
188 if (desired) {
189 if (observed !== desired) {
190 yield* pin(
191 ecrpublic.setRepositoryPolicy({
192 repositoryName,
193 policyText: desired,
194 }),
195 );
196 }
197 } else if (observed !== undefined) {
198 yield* pin(ecrpublic.deleteRepositoryPolicy({ repositoryName })).pipe(
199 Effect.catchTag("RepositoryPolicyNotFoundException", () => Effect.void),
200 );
201 }
202 });
203
204 const syncTags = Effect.fn(function* (
205 repositoryArn: string,
206 desiredTags: Record<string, string>,
207 ) {
208 const listed = yield* pin(ecrpublic.listTagsForResource({ resourceArn: repositoryArn }));
209 const observedTags = toTagRecord(listed.tags);
210 const { removed, upsert } = diffTags(observedTags, desiredTags);
211 if (upsert.length > 0) {
212 yield* pin(ecrpublic.tagResource({ resourceArn: repositoryArn, tags: upsert }));
213 }
214 if (removed.length > 0) {
215 yield* pin(
216 ecrpublic.untagResource({
217 resourceArn: repositoryArn,
218 tagKeys: removed,
219 }),
220 );
221 }
222 });
223
224 return {
225 stables: ["repositoryArn", "repositoryName", "repositoryUri", "registryId"],
226 diff: Effect.fn(function* ({ id, olds, news }) {
227 if (!isResolved(news)) return;
228 if (
229 (yield* toRepositoryName(id, olds ?? {})) !== (yield* toRepositoryName(id, news ?? {}))
230 ) {
231 return { action: "replace" } as const;
232 }
233 }),
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const repositoryName =
236 output?.repositoryName ?? (yield* toRepositoryName(id, olds ?? {}));
237 const repository = yield* observe(repositoryName);
238 if (!repository?.repositoryArn || !repository.repositoryUri) {
239 return undefined;
240 }
241 const listed = yield* pin(
242 ecrpublic.listTagsForResource({
243 resourceArn: repository.repositoryArn,
244 }),
245 );
246 const attrs = {
247 repositoryName,
248 repositoryArn: repository.repositoryArn as RepositoryArn,
249 repositoryUri: repository.repositoryUri,
250 registryId: repository.registryId!,
251 policyText: yield* readPolicy(repositoryName),
252 tags: toTagRecord(listed.tags),
253 };
254 return (yield* hasAlchemyTags(id, toTagRecord(listed.tags))) ? attrs : Unowned(attrs);
255 }),
256 reconcile: Effect.fn(function* ({ id, news, session }) {
257 const repositoryName = yield* toRepositoryName(id, news);
258 const internalTags = yield* createInternalTags(id);
259 const desiredTags = { ...internalTags, ...news.tags };
260
261 // Observe — cloud state is authoritative.
262 let repository = yield* observe(repositoryName);
263
264 // Ensure — create if missing. Tolerate the AlreadyExists race.
265 if (!repository?.repositoryArn || !repository.repositoryUri) {
266 const created = yield* pin(
267 ecrpublic.createRepository({
268 repositoryName,
269 catalogData: toCatalogInput(news.catalogData),
270 tags: Object.entries(desiredTags).map(([Key, Value]) => ({
271 Key,
272 Value,
273 })),
274 }),
275 ).pipe(
276 Effect.map((r) => r.repository),
277 Effect.catchTag("RepositoryAlreadyExistsException", () => observe(repositoryName)),
278 );
279 repository = created;
280 if (!repository?.repositoryArn || !repository.repositoryUri) {
281 return yield* new ECRPublicRepositoryUnexpectedResponse({
282 message: `Failed to create or read public repository ${repositoryName}`,
283 });
284 }
285 } else if (news.catalogData) {
286 // Sync catalog data on updates (create already set it).
287 yield* pin(
288 ecrpublic.putRepositoryCatalogData({
289 repositoryName,
290 catalogData: toCatalogInput(news.catalogData)!,
291 }),
292 );
293 }
294
295 const repositoryArn = repository.repositoryArn as RepositoryArn;
296
297 yield* syncPolicy(repositoryName, news.policyText);
298 yield* syncTags(repositoryArn, desiredTags);
299
300 yield* session.note(repositoryArn);
301 return {
302 repositoryName,
303 repositoryArn,
304 repositoryUri: repository.repositoryUri,
305 registryId: repository.registryId!,
306 policyText: news.policyText,
307 tags: desiredTags,
308 };
309 }),
310 // Enumerate every public repository in the account. `describeRepositories`
311 // is paginated (items under `repositories`).
312 list: () =>
313 Effect.gen(function* () {
314 const repositories = yield* pin(
315 ecrpublic.describeRepositories.pages({}).pipe(
316 Stream.runCollect,
317 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.repositories ?? [])),
318 ),
319 );
320 return yield* Effect.forEach(
321 repositories.filter(
322 (
323 r,
324 ): r is ecrpublic.Repository & {
325 repositoryName: string;
326 repositoryArn: string;
327 repositoryUri: string;
328 } => r.repositoryName != null && r.repositoryArn != null && r.repositoryUri != null,
329 ),
330 (repository) =>
331 Effect.gen(function* () {
332 const listed = yield* pin(
333 ecrpublic.listTagsForResource({
334 resourceArn: repository.repositoryArn,
335 }),
336 );
337 return {
338 repositoryName: repository.repositoryName,
339 repositoryArn: repository.repositoryArn as RepositoryArn,
340 repositoryUri: repository.repositoryUri,
341 registryId: repository.registryId!,
342 policyText: yield* readPolicy(repository.repositoryName),
343 tags: toTagRecord(listed.tags),
344 };
345 }),
346 { concurrency: 10 },
347 );
348 }),
349 delete: Effect.fn(function* ({ output }) {
350 yield* pin(
351 ecrpublic.deleteRepository({
352 repositoryName: output.repositoryName,
353 force: true,
354 }),
355 ).pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.void));
356 }),
357 };
358 }),
359 );