The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import crypto from "node:crypto"; |
| 2 | import * as ECR from "@alchemy.run/aws/ECR"; |
| 3 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 4 | import * as S3 from "@alchemy.run/aws/S3"; |
| 5 | import * as Duration from "effect/Duration"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 8 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | import * as Redacted from "effect/Redacted"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import path from "pathe"; |
| 14 | |
| 15 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 16 | |
| 17 | // Deterministic, lowercase repository name scoped to this suite (distinct |
| 18 | // from Repository.test.ts / Image.test.ts repositories). |
| 19 | export const REPO = "alchemy-test-ecr-bindings"; |
| 20 | |
| 21 | /** Deterministic layer/config bytes per tag so retried pushes converge. */ |
| 22 | const layerBytesFor = (tag: string) => |
| 23 | Buffer.from(`alchemy ecr layer blob for ${tag}\n`.repeat(8), "utf8"); |
| 24 | const configBytesFor = (tag: string) => |
| 25 | Buffer.from( |
| 26 | JSON.stringify({ |
| 27 | architecture: "amd64", |
| 28 | os: "linux", |
| 29 | config: {}, |
| 30 | rootfs: { type: "layers", diff_ids: [`sha256:${"0".repeat(64)}`] }, |
| 31 | // Distinguish configs per tag so every tag gets its own digest. |
| 32 | "alchemy.tag": tag, |
| 33 | }), |
| 34 | "utf8", |
| 35 | ); |
| 36 | |
| 37 | export class EcrTestFunction extends Lambda.Function<Lambda.Function>()("EcrTestFunction") {} |
| 38 | |
| 39 | export default EcrTestFunction.make( |
| 40 | { |
| 41 | main, |
| 42 | functionUrl: true, |
| 43 | // A push fans out several registry calls; AWS's 3s default would |
| 44 | // intermittently time out. |
| 45 | timeout: Duration.seconds(60), |
| 46 | }, |
| 47 | Effect.gen(function* () { |
| 48 | const repository = yield* ECR.Repository("Repo", { |
| 49 | repositoryName: REPO, |
| 50 | }); |
| 51 | |
| 52 | // Marker store for the event source (events may arrive on another |
| 53 | // Lambda instance, so they must be observable out-of-band). |
| 54 | const bucket = yield* S3.Bucket("EventBucket", { forceDestroy: true }); |
| 55 | const putObject = yield* S3.PutObject(bucket); |
| 56 | const getObject = yield* S3.GetObject(bucket); |
| 57 | |
| 58 | // --- registry-scoped binding --- |
| 59 | const getAuthorizationToken = yield* ECR.GetAuthorizationToken(); |
| 60 | |
| 61 | // --- repository-scoped bindings --- |
| 62 | const describeImages = yield* ECR.DescribeImages(repository); |
| 63 | const listImages = yield* ECR.ListImages(repository); |
| 64 | const batchGetImage = yield* ECR.BatchGetImage(repository); |
| 65 | const getDownloadUrl = yield* ECR.GetDownloadUrlForLayer(repository); |
| 66 | const checkLayers = yield* ECR.BatchCheckLayerAvailability(repository); |
| 67 | const initiateUpload = yield* ECR.InitiateLayerUpload(repository); |
| 68 | const uploadPart = yield* ECR.UploadLayerPart(repository); |
| 69 | const completeUpload = yield* ECR.CompleteLayerUpload(repository); |
| 70 | const putImage = yield* ECR.PutImage(repository); |
| 71 | const batchDeleteImage = yield* ECR.BatchDeleteImage(repository); |
| 72 | const startImageScan = yield* ECR.StartImageScan(repository); |
| 73 | const describeScanFindings = yield* ECR.DescribeImageScanFindings(repository); |
| 74 | |
| 75 | // --- event source --- |
| 76 | // ECR publishes every completed push to the default bus; write a marker |
| 77 | // object per event so /events/probe can observe the delivery |
| 78 | // out-of-band. |
| 79 | yield* ECR.consumeImageActions( |
| 80 | { repositories: [REPO], actionTypes: ["PUSH"], results: ["SUCCESS"] }, |
| 81 | (events) => |
| 82 | Stream.runForEach(events, (event) => |
| 83 | putObject({ |
| 84 | Key: `events/${event.detail["image-tag"] ?? event.detail["image-digest"]}`, |
| 85 | Body: JSON.stringify(event.detail), |
| 86 | ContentType: "application/json", |
| 87 | }).pipe(Effect.orDie, Effect.asVoid), |
| 88 | ), |
| 89 | ); |
| 90 | |
| 91 | const sha256 = (bytes: Buffer) => |
| 92 | Effect.sync(() => `sha256:${crypto.createHash("sha256").update(bytes).digest("hex")}`); |
| 93 | |
| 94 | // Upload one blob through the initiate → upload → complete flow. |
| 95 | // `LayerAlreadyExistsException` means a previous push (or a retried one) |
| 96 | // already sealed this digest — the blob is present, so continue. |
| 97 | const uploadBlob = Effect.fn(function* (bytes: Buffer) { |
| 98 | const digest = yield* sha256(bytes); |
| 99 | const { uploadId } = yield* initiateUpload(); |
| 100 | yield* uploadPart({ |
| 101 | uploadId: uploadId!, |
| 102 | partFirstByte: 0, |
| 103 | partLastByte: bytes.length - 1, |
| 104 | layerPartBlob: new Uint8Array(bytes), |
| 105 | }); |
| 106 | yield* completeUpload({ |
| 107 | uploadId: uploadId!, |
| 108 | layerDigests: [digest], |
| 109 | }).pipe(Effect.catchTag("LayerAlreadyExistsException", () => Effect.succeed(undefined))); |
| 110 | return digest; |
| 111 | }); |
| 112 | |
| 113 | // Push a minimal-but-valid Docker v2 schema 2 image: a config blob and |
| 114 | // one layer blob, sealed by a manifest under `tag`. |
| 115 | const pushImage = Effect.fn(function* (tag: string) { |
| 116 | const configBytes = configBytesFor(tag); |
| 117 | const layerBytes = layerBytesFor(tag); |
| 118 | const configDigest = yield* uploadBlob(configBytes); |
| 119 | const layerDigest = yield* uploadBlob(layerBytes); |
| 120 | const manifest = JSON.stringify({ |
| 121 | schemaVersion: 2, |
| 122 | mediaType: "application/vnd.docker.distribution.manifest.v2+json", |
| 123 | config: { |
| 124 | mediaType: "application/vnd.docker.container.image.v1+json", |
| 125 | size: configBytes.length, |
| 126 | digest: configDigest, |
| 127 | }, |
| 128 | layers: [ |
| 129 | { |
| 130 | mediaType: "application/vnd.docker.image.rootfs.diff.tar.gzip", |
| 131 | size: layerBytes.length, |
| 132 | digest: layerDigest, |
| 133 | }, |
| 134 | ], |
| 135 | }); |
| 136 | // A retried push of an identical tag+manifest surfaces the typed |
| 137 | // ImageAlreadyExistsException — the image is present, so converge. |
| 138 | const put = yield* putImage({ |
| 139 | imageManifest: manifest, |
| 140 | imageManifestMediaType: "application/vnd.docker.distribution.manifest.v2+json", |
| 141 | imageTag: tag, |
| 142 | }).pipe(Effect.catchTag("ImageAlreadyExistsException", () => Effect.succeed(undefined))); |
| 143 | return { |
| 144 | digest: put?.image?.imageId?.imageDigest, |
| 145 | layerDigest, |
| 146 | configDigest, |
| 147 | }; |
| 148 | }); |
| 149 | |
| 150 | return { |
| 151 | fetch: Effect.gen(function* () { |
| 152 | const request = yield* HttpServerRequest; |
| 153 | const url = new URL(request.originalUrl); |
| 154 | const pathname = url.pathname; |
| 155 | const param = (name: string) => url.searchParams.get(name) ?? ""; |
| 156 | |
| 157 | // Mint the registry credential; prove it comes back Redacted and |
| 158 | // decodes to a `AWS:<password>` Docker login pair. |
| 159 | if (request.method === "GET" && pathname === "/token") { |
| 160 | const res = yield* getAuthorizationToken(); |
| 161 | const data = res.authorizationData?.[0]; |
| 162 | const token = data?.authorizationToken; |
| 163 | const raw = Redacted.isRedacted(token) ? Redacted.value(token) : (token ?? ""); |
| 164 | const decoded = Buffer.from(raw, "base64").toString("utf8"); |
| 165 | return yield* HttpServerResponse.json({ |
| 166 | redacted: Redacted.isRedacted(token), |
| 167 | length: raw.length, |
| 168 | decodesToAwsUser: decoded.startsWith("AWS:"), |
| 169 | proxyEndpoint: data?.proxyEndpoint, |
| 170 | }); |
| 171 | } |
| 172 | |
| 173 | if (request.method === "POST" && pathname === "/push") { |
| 174 | const res = yield* pushImage(param("tag")); |
| 175 | return yield* HttpServerResponse.json(res); |
| 176 | } |
| 177 | |
| 178 | if (request.method === "GET" && pathname === "/images") { |
| 179 | const res = yield* describeImages({ |
| 180 | imageIds: [{ imageTag: param("tag") }], |
| 181 | }); |
| 182 | const detail = res.imageDetails?.[0]; |
| 183 | return yield* HttpServerResponse.json({ |
| 184 | tags: detail?.imageTags, |
| 185 | digest: detail?.imageDigest, |
| 186 | sizeInBytes: detail?.imageSizeInBytes, |
| 187 | }); |
| 188 | } |
| 189 | |
| 190 | if (request.method === "GET" && pathname === "/image-ids") { |
| 191 | const res = yield* listImages({ filter: { tagStatus: "TAGGED" } }); |
| 192 | return yield* HttpServerResponse.json({ |
| 193 | tags: (res.imageIds ?? []).flatMap((id) => (id.imageTag ? [id.imageTag] : [])), |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | if (request.method === "GET" && pathname === "/manifest") { |
| 198 | const res = yield* batchGetImage({ |
| 199 | imageIds: [{ imageTag: param("tag") }], |
| 200 | }); |
| 201 | const image = res.images?.[0]; |
| 202 | return yield* HttpServerResponse.json({ |
| 203 | mediaType: image?.imageManifestMediaType, |
| 204 | manifestLength: image?.imageManifest?.length ?? 0, |
| 205 | failures: res.failures?.map((f) => f.failureCode), |
| 206 | }); |
| 207 | } |
| 208 | |
| 209 | if (request.method === "GET" && pathname === "/layer") { |
| 210 | const res = yield* getDownloadUrl({ layerDigest: param("digest") }); |
| 211 | return yield* HttpServerResponse.json({ |
| 212 | hasUrl: (res.downloadUrl ?? "").startsWith("https://"), |
| 213 | layerDigest: res.layerDigest, |
| 214 | }); |
| 215 | } |
| 216 | |
| 217 | if (request.method === "GET" && pathname === "/availability") { |
| 218 | const res = yield* checkLayers({ |
| 219 | layerDigests: [param("digest")], |
| 220 | }); |
| 221 | return yield* HttpServerResponse.json({ |
| 222 | availability: res.layers?.[0]?.layerAvailability, |
| 223 | failures: res.failures?.map((f) => f.failureCode), |
| 224 | }); |
| 225 | } |
| 226 | |
| 227 | // On-demand basic scan. The synthetic image is not a supported OS |
| 228 | // image, so ECR may answer with the typed |
| 229 | // UnsupportedImageTypeException (or throttle repeat scans with |
| 230 | // LimitExceededException) — surface the tag instead of dying. |
| 231 | if (request.method === "POST" && pathname === "/scan") { |
| 232 | const res = yield* startImageScan({ |
| 233 | imageId: { imageTag: param("tag") }, |
| 234 | }).pipe( |
| 235 | Effect.map((r) => ({ |
| 236 | status: r.imageScanStatus?.status, |
| 237 | error: undefined, |
| 238 | })), |
| 239 | Effect.catchTag( |
| 240 | ["UnsupportedImageTypeException", "LimitExceededException", "ValidationException"], |
| 241 | (e) => Effect.succeed({ status: undefined, error: e._tag }), |
| 242 | ), |
| 243 | ); |
| 244 | return yield* HttpServerResponse.json(res); |
| 245 | } |
| 246 | |
| 247 | // Scan findings for the synthetic image — either real findings or |
| 248 | // the typed ScanNotFoundException when no scan ever ran. |
| 249 | if (request.method === "GET" && pathname === "/scan-findings") { |
| 250 | const res = yield* describeScanFindings({ |
| 251 | imageId: { imageTag: param("tag") }, |
| 252 | }).pipe( |
| 253 | Effect.map((r) => ({ |
| 254 | status: r.imageScanStatus?.status, |
| 255 | error: undefined, |
| 256 | })), |
| 257 | Effect.catchTag(["ScanNotFoundException", "ValidationException"], (e) => |
| 258 | Effect.succeed({ status: undefined, error: e._tag }), |
| 259 | ), |
| 260 | ); |
| 261 | return yield* HttpServerResponse.json(res); |
| 262 | } |
| 263 | |
| 264 | // batchDeleteImage reports a missing image via `failures` (not an |
| 265 | // error), so this is naturally idempotent. |
| 266 | if (request.method === "POST" && pathname === "/delete") { |
| 267 | const res = yield* batchDeleteImage({ |
| 268 | imageIds: [{ imageTag: param("tag") }], |
| 269 | }); |
| 270 | return yield* HttpServerResponse.json({ |
| 271 | deleted: (res.imageIds ?? []).length, |
| 272 | failures: res.failures?.map((f) => f.failureCode), |
| 273 | }); |
| 274 | } |
| 275 | |
| 276 | // Push a fresh tag, then poll for the marker the image-action event |
| 277 | // handler wrote to S3 (bounded well under the 60s function timeout). |
| 278 | if (request.method === "GET" && pathname === "/events/probe") { |
| 279 | const tag = param("tag"); |
| 280 | yield* pushImage(tag); |
| 281 | const seen = yield* getObject({ Key: `events/${tag}` }).pipe( |
| 282 | Effect.retry({ |
| 283 | while: (e): boolean => e._tag === "NoSuchKey", |
| 284 | schedule: Schedule.spaced("2 seconds"), |
| 285 | times: 12, |
| 286 | }), |
| 287 | Effect.map(() => true), |
| 288 | Effect.catchTag("NoSuchKey", () => Effect.succeed(false)), |
| 289 | ); |
| 290 | return yield* HttpServerResponse.json({ seen, tag }); |
| 291 | } |
| 292 | |
| 293 | return yield* HttpServerResponse.json( |
| 294 | { error: "Not found", method: request.method, pathname }, |
| 295 | { status: 404 }, |
| 296 | ); |
| 297 | }).pipe( |
| 298 | // Surface typed errors in the 500 body so the test's transient-retry |
| 299 | // logs show the real failure instead of an opaque Internal Server |
| 300 | // Error. |
| 301 | Effect.catch((e) => |
| 302 | HttpServerResponse.json( |
| 303 | { |
| 304 | error: (e as { _tag?: string })._tag ?? "UnknownError", |
| 305 | message: String(e), |
| 306 | }, |
| 307 | { status: 500 }, |
| 308 | ), |
| 309 | ), |
| 310 | Effect.orDie, |
| 311 | ), |
| 312 | }; |
| 313 | }).pipe( |
| 314 | Effect.provide( |
| 315 | Layer.mergeAll( |
| 316 | Lambda.EventSource, |
| 317 | ECR.GetAuthorizationTokenHttp, |
| 318 | ECR.DescribeImagesHttp, |
| 319 | ECR.ListImagesHttp, |
| 320 | ECR.BatchGetImageHttp, |
| 321 | ECR.GetDownloadUrlForLayerHttp, |
| 322 | ECR.BatchCheckLayerAvailabilityHttp, |
| 323 | ECR.InitiateLayerUploadHttp, |
| 324 | ECR.UploadLayerPartHttp, |
| 325 | ECR.CompleteLayerUploadHttp, |
| 326 | ECR.PutImageHttp, |
| 327 | ECR.BatchDeleteImageHttp, |
| 328 | ECR.StartImageScanHttp, |
| 329 | ECR.DescribeImageScanFindingsHttp, |
| 330 | S3.PutObjectHttp, |
| 331 | S3.GetObjectHttp, |
| 332 | ), |
| 333 | ), |
| 334 | ), |
| 335 | ); |