The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ecr from "@distilled.cloud/aws/ecr"; |
| 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 { PolicyDocument } from "../IAM/Policy.ts"; |
| 13 | import { normalizePolicyDocument, stringifyPolicyDocument } from "../IAM/Policy.ts"; |
| 14 | import { canonicalJson, tagListRecord } from "../internal/Observe.ts"; |
| 15 | import type { Providers } from "../Providers.ts"; |
| 16 | import type { RegionID } from "../Region.ts"; |
| 17 | |
| 18 | export class ECRRepositoryUnexpectedResponse extends Data.TaggedError( |
| 19 | "ECRRepositoryUnexpectedResponse", |
| 20 | )<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export type RepositoryName = string; |
| 26 | export type RepositoryArn = `arn:aws:ecr:${RegionID}:${AccountID}:repository/${RepositoryName}`; |
| 27 | export type RepositoryUri = `${AccountID}.dkr.ecr.${RegionID}.amazonaws.com/${RepositoryName}`; |
| 28 | |
| 29 | export interface RepositoryProps { |
| 30 | /** |
| 31 | * Name of the repository. If omitted, a unique name is generated. |
| 32 | */ |
| 33 | repositoryName?: string; |
| 34 | /** |
| 35 | * Image tag mutability setting. |
| 36 | * @default "MUTABLE" |
| 37 | */ |
| 38 | imageTagMutability?: ecr.ImageTagMutability; |
| 39 | /** |
| 40 | * Whether enhanced image scanning should run on push. |
| 41 | */ |
| 42 | scanOnPush?: boolean; |
| 43 | /** |
| 44 | * Optional lifecycle policy document JSON. |
| 45 | */ |
| 46 | lifecyclePolicyText?: string; |
| 47 | /** |
| 48 | * Repository permission policy controlling access from other AWS |
| 49 | * principals — either a structured IAM {@link PolicyDocument} or a raw |
| 50 | * JSON string (escape hatch / adoption of an existing policy). Omitting |
| 51 | * the prop removes any repository policy. |
| 52 | */ |
| 53 | policy?: PolicyDocument | string; |
| 54 | /** |
| 55 | * User-defined tags to apply to the repository. |
| 56 | */ |
| 57 | tags?: Record<string, string>; |
| 58 | } |
| 59 | |
| 60 | export interface Repository extends Resource< |
| 61 | "AWS.ECR.Repository", |
| 62 | RepositoryProps, |
| 63 | { |
| 64 | /** The name of the repository. */ |
| 65 | repositoryName: RepositoryName; |
| 66 | /** The ARN of the repository. */ |
| 67 | repositoryArn: RepositoryArn; |
| 68 | /** The URI used to push/pull images, e.g. `<account>.dkr.ecr.<region>.amazonaws.com/<name>`. */ |
| 69 | repositoryUri: RepositoryUri; |
| 70 | /** The AWS account ID of the registry. */ |
| 71 | registryId: string; |
| 72 | /** Whether image tags are `MUTABLE` or `IMMUTABLE`. */ |
| 73 | imageTagMutability: ecr.ImageTagMutability; |
| 74 | /** Whether repository images are scanned when they are pushed. */ |
| 75 | scanOnPush: boolean; |
| 76 | /** The JSON lifecycle policy applied to the repository, if any. */ |
| 77 | lifecyclePolicyText?: string; |
| 78 | /** The JSON repository permissions policy, if any. */ |
| 79 | policy?: string; |
| 80 | /** The tags attached to the repository. */ |
| 81 | tags: Record<string, string>; |
| 82 | }, |
| 83 | never, |
| 84 | Providers |
| 85 | > {} |
| 86 | |
| 87 | /** |
| 88 | * An Amazon ECR repository for container images. |
| 89 | * ### Creating Repositories |
| 90 | * **Example:** Task Image Repository |
| 91 | * ```typescript |
| 92 | * const repo = yield* Repository("TaskRepository", { |
| 93 | * scanOnPush: true, |
| 94 | * }); |
| 95 | * ``` |
| 96 | * |
| 97 | * ### Repository Policies |
| 98 | * **Example:** Grant Lambda Pull Access |
| 99 | * ```typescript |
| 100 | * const repo = yield* Repository("LambdaImages", { |
| 101 | * policy: { |
| 102 | * Version: "2012-10-17", |
| 103 | * Statement: [ |
| 104 | * { |
| 105 | * Sid: "LambdaECRImageRetrieval", |
| 106 | * Effect: "Allow", |
| 107 | * Principal: { Service: "lambda.amazonaws.com" }, |
| 108 | * Action: ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"], |
| 109 | * }, |
| 110 | * ], |
| 111 | * }, |
| 112 | * }); |
| 113 | * ``` |
| 114 | * |
| 115 | * @resource |
| 116 | */ |
| 117 | export const Repository = Resource<Repository>("AWS.ECR.Repository"); |
| 118 | |
| 119 | export const RepositoryProvider = () => |
| 120 | Provider.effect( |
| 121 | Repository, |
| 122 | Effect.gen(function* () { |
| 123 | const toRepositoryName = (id: string, props: { repositoryName?: string } = {}) => |
| 124 | props.repositoryName |
| 125 | ? Effect.succeed(props.repositoryName) |
| 126 | : createPhysicalName({ |
| 127 | id, |
| 128 | maxLength: 256, |
| 129 | lowercase: true, |
| 130 | }); |
| 131 | |
| 132 | const toPolicyText = (policy: PolicyDocument | string | undefined) => |
| 133 | policy === undefined |
| 134 | ? undefined |
| 135 | : typeof policy === "string" |
| 136 | ? policy |
| 137 | : stringifyPolicyDocument(policy); |
| 138 | |
| 139 | const readPolicy = (repositoryName: string) => |
| 140 | ecr.getRepositoryPolicy({ repositoryName }).pipe( |
| 141 | Effect.map((response) => response.policyText), |
| 142 | Effect.catchTag( |
| 143 | ["RepositoryPolicyNotFoundException", "RepositoryNotFoundException"], |
| 144 | () => Effect.undefined, |
| 145 | ), |
| 146 | ); |
| 147 | |
| 148 | // The lifecycle policy is managed only when declared, so it is only |
| 149 | // observed then (canonical JSON — ECR may reformat the document). |
| 150 | const readLifecyclePolicy = (repositoryName: string, declared: string | undefined) => |
| 151 | declared === undefined |
| 152 | ? Effect.undefined |
| 153 | : ecr.getLifecyclePolicy({ repositoryName }).pipe( |
| 154 | Effect.map((res) => canonicalJson(res.lifecyclePolicyText)), |
| 155 | Effect.catchTag( |
| 156 | ["LifecyclePolicyNotFoundException", "RepositoryNotFoundException"], |
| 157 | () => Effect.undefined, |
| 158 | ), |
| 159 | ); |
| 160 | |
| 161 | // Sync the repository policy — compare the OBSERVED policy against the |
| 162 | // desired one via `normalizePolicyDocument` (key order / whitespace |
| 163 | // insensitive) so a re-deploy of an equivalent document is a no-op. |
| 164 | const syncPolicy = Effect.fn(function* (repositoryName: string, desired: string | undefined) { |
| 165 | const observed = yield* readPolicy(repositoryName); |
| 166 | if (desired !== undefined) { |
| 167 | if ( |
| 168 | observed === undefined || |
| 169 | normalizePolicyDocument(observed) !== normalizePolicyDocument(desired) |
| 170 | ) { |
| 171 | yield* ecr.setRepositoryPolicy({ |
| 172 | repositoryName, |
| 173 | policyText: desired, |
| 174 | }); |
| 175 | } |
| 176 | } else if (observed !== undefined) { |
| 177 | yield* ecr |
| 178 | .deleteRepositoryPolicy({ repositoryName }) |
| 179 | .pipe(Effect.catchTag("RepositoryPolicyNotFoundException", () => Effect.void)); |
| 180 | } |
| 181 | }); |
| 182 | |
| 183 | return { |
| 184 | stables: ["repositoryArn", "repositoryName", "repositoryUri", "registryId"], |
| 185 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 186 | if (!isResolved(news)) return; |
| 187 | if ( |
| 188 | (yield* toRepositoryName(id, olds ?? {})) !== (yield* toRepositoryName(id, news ?? {})) |
| 189 | ) { |
| 190 | return { action: "replace" } as const; |
| 191 | } |
| 192 | }), |
| 193 | read: Effect.fn(function* ({ id, olds, output }) { |
| 194 | const repositoryName = |
| 195 | output?.repositoryName ?? (yield* toRepositoryName(id, olds ?? {})); |
| 196 | const described = yield* ecr |
| 197 | .describeRepositories({ |
| 198 | repositoryNames: [repositoryName], |
| 199 | }) |
| 200 | .pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.undefined)); |
| 201 | const repository = described?.repositories?.[0]; |
| 202 | if (!repository?.repositoryArn || !repository.repositoryUri) { |
| 203 | return undefined; |
| 204 | } |
| 205 | const listedTags = yield* ecr.listTagsForResource({ |
| 206 | resourceArn: repository.repositoryArn, |
| 207 | }); |
| 208 | const attrs = { |
| 209 | repositoryName, |
| 210 | repositoryArn: repository.repositoryArn as RepositoryArn, |
| 211 | repositoryUri: repository.repositoryUri as RepositoryUri, |
| 212 | registryId: repository.registryId!, |
| 213 | imageTagMutability: |
| 214 | repository.imageTagMutability ?? output?.imageTagMutability ?? "MUTABLE", |
| 215 | scanOnPush: |
| 216 | repository.imageScanningConfiguration?.scanOnPush ?? output?.scanOnPush ?? false, |
| 217 | lifecyclePolicyText: yield* readLifecyclePolicy( |
| 218 | repositoryName, |
| 219 | olds?.lifecyclePolicyText, |
| 220 | ), |
| 221 | policy: yield* readPolicy(repositoryName), |
| 222 | tags: tagListRecord(listedTags.tags), |
| 223 | }; |
| 224 | return (yield* hasAlchemyTags(id, listedTags.tags ?? [])) ? attrs : Unowned(attrs); |
| 225 | }), |
| 226 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 227 | // Prefer the deployed name: regenerating would target a different |
| 228 | // repository if the generator's output for this id ever drifts. |
| 229 | const repositoryName = output?.repositoryName ?? (yield* toRepositoryName(id, news)); |
| 230 | const internalTags = yield* createInternalTags(id); |
| 231 | const desiredTags = { ...internalTags, ...news.tags }; |
| 232 | |
| 233 | // Observe — fetch live cloud state. We never trust prior `output` |
| 234 | // blindly: the repository may have been deleted out-of-band. |
| 235 | let described = yield* ecr |
| 236 | .describeRepositories({ |
| 237 | repositoryNames: [repositoryName], |
| 238 | }) |
| 239 | .pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.undefined)); |
| 240 | let repository = described?.repositories?.[0]; |
| 241 | |
| 242 | // Ensure — create the repository if missing. Tolerate |
| 243 | // `RepositoryAlreadyExistsException` as a race with a peer |
| 244 | // reconciler: re-describe and continue with the sync path. |
| 245 | if (!repository?.repositoryArn || !repository.repositoryUri) { |
| 246 | const created = yield* ecr |
| 247 | .createRepository({ |
| 248 | repositoryName, |
| 249 | imageTagMutability: news.imageTagMutability, |
| 250 | imageScanningConfiguration: news.scanOnPush ? { scanOnPush: true } : undefined, |
| 251 | tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 252 | Key, |
| 253 | Value, |
| 254 | })), |
| 255 | }) |
| 256 | .pipe( |
| 257 | Effect.catchTag("RepositoryAlreadyExistsException", () => |
| 258 | ecr |
| 259 | .describeRepositories({ |
| 260 | repositoryNames: [repositoryName], |
| 261 | }) |
| 262 | .pipe( |
| 263 | Effect.map((res) => ({ |
| 264 | repository: res.repositories?.[0], |
| 265 | })), |
| 266 | ), |
| 267 | ), |
| 268 | ); |
| 269 | repository = created.repository; |
| 270 | if (!repository?.repositoryArn || !repository.repositoryUri) { |
| 271 | return yield* new ECRRepositoryUnexpectedResponse({ |
| 272 | message: `Failed to create or read repository ${repositoryName}`, |
| 273 | }); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | const repositoryArn = repository.repositoryArn as RepositoryArn; |
| 278 | |
| 279 | // Sync mutable repository settings against OBSERVED cloud state. |
| 280 | // These must converge for adopted repositories and out-of-band |
| 281 | // drift, not only when createRepository happens to run. |
| 282 | const desiredImageTagMutability = news.imageTagMutability ?? "MUTABLE"; |
| 283 | if ((repository.imageTagMutability ?? "MUTABLE") !== desiredImageTagMutability) { |
| 284 | yield* ecr.putImageTagMutability({ |
| 285 | repositoryName, |
| 286 | imageTagMutability: desiredImageTagMutability, |
| 287 | }); |
| 288 | } |
| 289 | |
| 290 | const desiredScanOnPush = news.scanOnPush ?? false; |
| 291 | if ((repository.imageScanningConfiguration?.scanOnPush ?? false) !== desiredScanOnPush) { |
| 292 | yield* ecr.putImageScanningConfiguration({ |
| 293 | repositoryName, |
| 294 | imageScanningConfiguration: { |
| 295 | scanOnPush: desiredScanOnPush, |
| 296 | }, |
| 297 | }); |
| 298 | } |
| 299 | |
| 300 | // Sync lifecycle policy — observed ↔ desired. |
| 301 | if (news.lifecyclePolicyText) { |
| 302 | yield* ecr.putLifecyclePolicy({ |
| 303 | repositoryName, |
| 304 | lifecyclePolicyText: news.lifecyclePolicyText, |
| 305 | }); |
| 306 | } |
| 307 | |
| 308 | // Sync repository policy — normalized observed ↔ desired. |
| 309 | const desiredPolicy = toPolicyText(news.policy); |
| 310 | yield* syncPolicy(repositoryName, desiredPolicy); |
| 311 | |
| 312 | // Sync tags — diff observed cloud tags against desired. |
| 313 | const listedTags = yield* ecr.listTagsForResource({ |
| 314 | resourceArn: repositoryArn, |
| 315 | }); |
| 316 | const observedTags = Object.fromEntries( |
| 317 | (listedTags.tags ?? []) |
| 318 | .filter( |
| 319 | (t): t is { Key: string; Value: string } => |
| 320 | typeof t.Key === "string" && typeof t.Value === "string", |
| 321 | ) |
| 322 | .map((t) => [t.Key, t.Value]), |
| 323 | ); |
| 324 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 325 | if (upsert.length > 0) { |
| 326 | yield* ecr.tagResource({ |
| 327 | resourceArn: repositoryArn, |
| 328 | tags: upsert, |
| 329 | }); |
| 330 | } |
| 331 | if (removed.length > 0) { |
| 332 | yield* ecr.untagResource({ |
| 333 | resourceArn: repositoryArn, |
| 334 | tagKeys: removed, |
| 335 | }); |
| 336 | } |
| 337 | |
| 338 | yield* session.note(repositoryArn); |
| 339 | return { |
| 340 | repositoryName, |
| 341 | repositoryArn, |
| 342 | repositoryUri: repository.repositoryUri as RepositoryUri, |
| 343 | registryId: repository.registryId!, |
| 344 | imageTagMutability: desiredImageTagMutability, |
| 345 | scanOnPush: desiredScanOnPush, |
| 346 | lifecyclePolicyText: yield* readLifecyclePolicy( |
| 347 | repositoryName, |
| 348 | news.lifecyclePolicyText, |
| 349 | ), |
| 350 | policy: yield* readPolicy(repositoryName), |
| 351 | tags: desiredTags, |
| 352 | }; |
| 353 | }), |
| 354 | // Enumerate every repository in the account/region. `describeRepositories` |
| 355 | // is paginated (items under `repositories`); for each repo we fetch the |
| 356 | // tags and lifecycle policy so each element matches the full Attributes |
| 357 | // shape `read` produces and is directly usable by `delete`. |
| 358 | list: () => |
| 359 | Effect.gen(function* () { |
| 360 | const repositories = yield* ecr.describeRepositories.pages({}).pipe( |
| 361 | Stream.runCollect, |
| 362 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.repositories ?? [])), |
| 363 | ); |
| 364 | return yield* Effect.forEach( |
| 365 | repositories.filter( |
| 366 | ( |
| 367 | r, |
| 368 | ): r is ecr.Repository & { |
| 369 | repositoryName: string; |
| 370 | repositoryArn: string; |
| 371 | repositoryUri: string; |
| 372 | } => r.repositoryName != null && r.repositoryArn != null && r.repositoryUri != null, |
| 373 | ), |
| 374 | (repository) => |
| 375 | Effect.gen(function* () { |
| 376 | const listedTags = yield* ecr.listTagsForResource({ |
| 377 | resourceArn: repository.repositoryArn, |
| 378 | }); |
| 379 | const tags = Object.fromEntries( |
| 380 | (listedTags.tags ?? []) |
| 381 | .filter( |
| 382 | (t): t is { Key: string; Value: string } => |
| 383 | typeof t.Key === "string" && typeof t.Value === "string", |
| 384 | ) |
| 385 | .map((t) => [t.Key, t.Value]), |
| 386 | ); |
| 387 | const lifecyclePolicyText = yield* ecr |
| 388 | .getLifecyclePolicy({ |
| 389 | repositoryName: repository.repositoryName, |
| 390 | }) |
| 391 | .pipe( |
| 392 | Effect.map((res) => res.lifecyclePolicyText), |
| 393 | Effect.catchTag("LifecyclePolicyNotFoundException", () => Effect.undefined), |
| 394 | ); |
| 395 | return { |
| 396 | repositoryName: repository.repositoryName, |
| 397 | repositoryArn: repository.repositoryArn as RepositoryArn, |
| 398 | repositoryUri: repository.repositoryUri as RepositoryUri, |
| 399 | registryId: repository.registryId!, |
| 400 | imageTagMutability: repository.imageTagMutability ?? "MUTABLE", |
| 401 | scanOnPush: repository.imageScanningConfiguration?.scanOnPush ?? false, |
| 402 | lifecyclePolicyText, |
| 403 | policy: yield* readPolicy(repository.repositoryName), |
| 404 | tags, |
| 405 | }; |
| 406 | }), |
| 407 | { concurrency: 10 }, |
| 408 | ); |
| 409 | }), |
| 410 | delete: Effect.fn(function* ({ output }) { |
| 411 | yield* ecr |
| 412 | .deleteRepository({ |
| 413 | repositoryName: output.repositoryName, |
| 414 | force: true, |
| 415 | }) |
| 416 | .pipe(Effect.catchTag("RepositoryNotFoundException", () => Effect.void)); |
| 417 | }), |
| 418 | }; |
| 419 | }), |
| 420 | ); |