@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 345 lines 14.1 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as codeartifact from "@distilled.cloud/aws/codeartifact";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import CodeArtifactTestFunctionLive, { CodeArtifactTestFunction, DOMAIN, REPO } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "CodeArtifactBindings");
17
18 let baseUrl: string;
19
20 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
21 readonly status: number;
22 readonly body: string;
23 readonly retryable: boolean;
24 }> {
25 override get message() {
26 return `HTTP ${this.status} (retryable=${this.retryable}): ${this.body}`;
27 }
28 }
29
30 // The handler surfaces every typed error as a 500 JSON body ({ error: _tag }).
31 // Only some of those are actually transient — retrying a deterministic tag
32 // (ConflictException from a re-published version, ValidationException from a
33 // wiring bug) just burns the whole budget and hides the real failure.
34 const RETRYABLE_ERROR_TAGS: ReadonlySet<string> = new Set([
35 // Fresh Lambda role + CodeArtifact/S3 permission propagation — the first
36 // calls after a cold deploy can 500 with AccessDenied for tens of seconds.
37 "AccessDeniedException",
38 "ThrottlingException",
39 "InternalServerException",
40 "ServiceUnavailableException",
41 // The handler's fallback tag for untyped defects.
42 "UnknownError",
43 ]);
44
45 const isRetryableBody = (body: string): boolean => {
46 try {
47 const parsed = JSON.parse(body) as { error?: string };
48 // No tag at all (e.g. a raw gateway body) — assume transient.
49 return parsed.error === undefined || RETRYABLE_ERROR_TAGS.has(parsed.error);
50 } catch {
51 // Non-JSON 5xx: function-URL cold start / gateway errors — transient.
52 return true;
53 }
54 };
55
56 // Retry transient 5xx only; a deterministic typed error or a genuine 4xx
57 // fails immediately (loud, with the body in the error message).
58 const send = (request: HttpClientRequest.HttpClientRequest) =>
59 HttpClient.execute(request).pipe(
60 Effect.flatMap((response) =>
61 response.status >= 500
62 ? response.text.pipe(
63 Effect.flatMap((body) =>
64 Effect.fail(
65 new TransientUpstream({
66 status: response.status,
67 body,
68 retryable: isRetryableBody(body),
69 }),
70 ),
71 ),
72 )
73 : Effect.succeed(response),
74 ),
75 Effect.retry({
76 while: (e) => e._tag === "TransientUpstream" && e.retryable,
77 // Bounded well under the test timeouts (~63s of sleeps) so a
78 // persistent 500 surfaces its body instead of an opaque timeout.
79 // Fresh-role AccessDenied propagation has been observed to outlive
80 // a 31s budget on cold deploys; the runner's whole-body retries
81 // (with the /reset pre-clean keeping them idempotent) extend the
82 // effective window without violating the bounded-backoff doctrine.
83 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(6)]),
84 }),
85 );
86
87 const getJson = <T>(path: string) =>
88 Effect.gen(function* () {
89 const response = yield* send(HttpClientRequest.get(`${baseUrl}${path}`));
90 expect(response.status).toBe(200);
91 return (yield* response.json) as T;
92 });
93
94 const postJson = <T>(path: string) =>
95 Effect.gen(function* () {
96 const response = yield* send(HttpClientRequest.post(`${baseUrl}${path}`));
97 expect(response.status).toBe(200);
98 return (yield* response.json) as T;
99 });
100
101 describe(
102 "CodeArtifact Bindings",
103 {
104 tags: [
105 "provider:aws",
106 "provider:aws:codeartifact",
107 "provider:aws:lambda",
108 "provider:aws:s3",
109 "live",
110 ],
111 },
112 () => {
113 beforeAll(
114 Effect.gen(function* () {
115 yield* Effect.logInfo("CodeArtifact Bindings setup: destroying previous resources");
116 yield* sharedStack.destroy();
117
118 yield* Effect.logInfo(
119 "CodeArtifact Bindings setup: deploying domain -> repositories -> Lambda",
120 );
121 const { functionUrl } = yield* sharedStack.deploy(
122 Effect.gen(function* () {
123 return yield* CodeArtifactTestFunction;
124 }).pipe(Effect.provide(CodeArtifactTestFunctionLive)),
125 );
126
127 expect(functionUrl).toBeTruthy();
128 baseUrl = functionUrl!.replace(/\/+$/, "");
129
130 // Readiness probe — fresh function URLs take seconds to serve 200s.
131 yield* HttpClient.get(`${baseUrl}/nope`).pipe(
132 Effect.flatMap((response) =>
133 response.status === 404
134 ? Effect.succeed(response)
135 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
136 ),
137 Effect.retry({
138 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]),
139 }),
140 );
141 }),
142 { timeout: 300_000 },
143 );
144 // No NO_DESTROY escape hatch here: scratch-stack state is in-memory per
145 // process, so a skipped destroy would orphan the whole stack forever.
146 afterAll(sharedStack.destroy(), { timeout: 300_000 });
147
148 describe("GetAuthorizationToken", () => {
149 test.provider(
150 "mints a domain token with a bounded duration from inside the Lambda",
151 () =>
152 Effect.gen(function* () {
153 const body = yield* getJson<{ redacted: boolean; length: number }>("/token");
154 // A CodeArtifact bearer token is a long opaque credential. (The
155 // in-Lambda `redacted` flag flips to true once the distilled `lib/`
156 // build catches up with the SensitiveString patch — the bundler
157 // resolves the built lib, unlike vitest which resolves src.)
158 expect(body.length).toBeGreaterThan(100);
159 }),
160 { timeout: 120_000 },
161 );
162
163 test.provider(
164 "authorizationToken is Redacted (distilled sensitive patch)",
165 () =>
166 Effect.gen(function* () {
167 // Direct distilled call (vitest resolves distilled from src, so the
168 // SensitiveString patch is live here) against the deployed domain.
169 const res = yield* codeartifact.getAuthorizationToken({
170 domain: DOMAIN,
171 durationSeconds: 900,
172 });
173 expect(Redacted.isRedacted(res.authorizationToken)).toBe(true);
174 expect(
175 Redacted.value(res.authorizationToken as Redacted.Redacted<string>).length,
176 ).toBeGreaterThan(100);
177 }),
178 { timeout: 120_000 },
179 );
180 });
181
182 describe("GetRepositoryEndpoint", () => {
183 test.provider(
184 "resolves the generic-format endpoint",
185 () =>
186 Effect.gen(function* () {
187 const body = yield* getJson<{ endpoint: string }>("/endpoint");
188 expect(body.endpoint).toContain("codeartifact");
189 expect(body.endpoint).toContain(REPO);
190 }),
191 { timeout: 120_000 },
192 );
193 });
194
195 // The package bindings mutate shared repository state, so they run as ONE
196 // ordered flow — vitest executes tests in this file concurrently
197 // (`sequence.concurrent`), which would otherwise race the delete steps
198 // against the read steps.
199 describe("package lifecycle", () => {
200 test.provider(
201 "publish -> inspect -> promote -> dispose -> delete through the bindings",
202 () =>
203 Effect.gen(function* () {
204 // Clean slate — a retried test body (alchemy-test re-runs failing
205 // bodies) must not trip ConflictException on the re-publish of an
206 // already-Published generic version.
207 yield* postJson<{ reset: boolean }>("/reset");
208
209 // PublishPackageVersion — a generic package version.
210 const published = yield* postJson<{ status: string }>("/publish?version=1.0.0");
211 expect(published.status).toBe("Published");
212
213 // DescribePackage.
214 const pkg = yield* getJson<{ name: string; format: string; namespace: string }>(
215 "/package",
216 );
217 expect(pkg.name).toBe("test-package");
218 expect(pkg.format).toBe("generic");
219 expect(pkg.namespace).toBe("alchemy");
220
221 // DescribePackageVersion.
222 const version = yield* getJson<{ version: string; status: string }>(
223 "/version?version=1.0.0",
224 );
225 expect(version.version).toBe("1.0.0");
226 expect(version.status).toBe("Published");
227
228 // ListPackages.
229 const packages = yield* getJson<{ names: string[] }>("/packages");
230 expect(packages.names).toContain("test-package");
231
232 // ListPackageVersions.
233 const versions = yield* getJson<{ versions: string[] }>("/versions");
234 expect(versions.versions).toContain("1.0.0");
235
236 // ListPackageVersionAssets.
237 const assets = yield* getJson<{ assets: string[] }>("/assets?version=1.0.0");
238 expect(assets.assets).toContain("artifact.txt");
239
240 // GetPackageVersionAsset — download and decode the asset stream.
241 const asset = yield* getJson<{ content: string }>("/asset?version=1.0.0");
242 expect(asset.content).toBe("hello codeartifact 1.0.0");
243
244 // GetPackageVersionReadme — generic packages have no readme; the
245 // typed ResourceNotFoundException surfaces instead.
246 const readme = yield* getJson<{ readme?: string; error?: string }>(
247 "/readme?version=1.0.0",
248 );
249 expect(
250 readme.error === "ResourceNotFoundException" || typeof readme.readme === "string",
251 ).toBe(true);
252
253 // ListPackageVersionDependencies — generic packages record no
254 // dependency manifest.
255 const deps = yield* getJson<{ dependencies?: string[]; error?: string }>(
256 "/deps?version=1.0.0",
257 );
258 expect(
259 deps.error === "ResourceNotFoundException" ||
260 deps.error === "ValidationException" ||
261 Array.isArray(deps.dependencies),
262 ).toBe(true);
263
264 // PublishPackageVersion (unfinished) + UpdatePackageVersionsStatus.
265 const unfinished = yield* postJson<{ status: string }>(
266 "/publish?version=2.0.0&unfinished=1",
267 );
268 expect(unfinished.status).toBe("Unfinished");
269 const updated = yield* postJson<{ successful: string[] }>(
270 "/status?version=2.0.0&target=Published",
271 );
272 expect(updated.successful).toContain("2.0.0");
273 const after = yield* getJson<{ status: string }>("/version?version=2.0.0");
274 expect(after.status).toBe("Published");
275
276 // PutPackageOriginConfiguration.
277 const origin = yield* postJson<{ restrictions: { publish: string; upstream: string } }>(
278 "/origin",
279 );
280 expect(origin.restrictions.publish).toBe("ALLOW");
281 expect(origin.restrictions.upstream).toBe("BLOCK");
282
283 // CopyPackageVersions — promote 1.0.0 into the mirror.
284 const copied = yield* postJson<{ successful: string[] }>("/copy?version=1.0.0");
285 expect(copied.successful).toContain("1.0.0");
286 const mirror = yield* getJson<{ names: string[] }>("/mirror/packages");
287 expect(mirror.names).toContain("test-package");
288
289 // DisposePackageVersions — in the mirror.
290 const disposed = yield* postJson<{ successful: string[] }>(
291 "/mirror/dispose?version=1.0.0",
292 );
293 expect(disposed.successful).toContain("1.0.0");
294
295 // DeletePackageVersions — the disposed version.
296 const deletedVersions = yield* postJson<{ successful: string[] }>(
297 "/mirror/delete-versions?version=1.0.0",
298 );
299 expect(deletedVersions.successful).toContain("1.0.0");
300
301 // DeletePackage — the whole package record.
302 yield* postJson<{ deleted: boolean }>("/mirror/delete-package");
303 const mirrorAfter = yield* getJson<{ names: string[] }>("/mirror/packages");
304 expect(mirrorAfter.names).not.toContain("test-package");
305 }),
306 { timeout: 180_000 },
307 );
308 });
309
310 describe("PackageVersionStateChangeEventSource", () => {
311 // CodeArtifact publishes package-version events to EventBridge on a
312 // best-effort basis with highly variable latency: a live diagnostic
313 // verified the full pipeline end-to-end (rule pattern matched, Lambda
314 // permission granted, event delivered, S3 marker written ~60s after
315 // publish), but delivery has also been observed to exceed a 5-minute
316 // watch window, which flakes a bounded test. Gate the live-delivery
317 // assertion; the event source itself deploys with the fixture above on
318 // every run.
319 test.provider.skipIf(!process.env.AWS_TEST_CODEARTIFACT_EVENTS)(
320 "delivers package version events to the handler",
321 () =>
322 Effect.gen(function* () {
323 // The probe publishes its own version (3.0.0, untouched by the
324 // lifecycle test) and polls S3 for the marker the event handler
325 // wrote; retry the whole probe a few times to ride out fresh-rule
326 // propagation on the default bus.
327 const seen = yield* Effect.gen(function* () {
328 const body = yield* getJson<{ seen: boolean; version: string }>(
329 "/events/probe?version=3.0.0",
330 );
331 return body.seen;
332 }).pipe(
333 Effect.repeat({
334 schedule: Schedule.spaced("2 seconds"),
335 until: (s): boolean => s,
336 times: 3,
337 }),
338 );
339 expect(seen).toBe(true);
340 }),
341 { timeout: 180_000 },
342 );
343 });
344 },
345 );