@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 202 lines 8.15 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 eventbridge from "@distilled.cloud/aws/eventbridge";
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 Schedule from "effect/Schedule";
11 import DataSyncTestFunctionLive, { DataSyncTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "DataSyncBindings");
16
17 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
18 // over 60s on a fresh deploy.
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22 let functionArn: string;
23
24 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
25 readonly status: number;
26 readonly body: string;
27 }> {}
28
29 // The shared Lambda fixture occasionally answers a transient 5xx under load
30 // (cold re-init, IAM propagation on the freshly attached policy that the
31 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
32 // 4xx/assertion failure surfaces immediately.
33 const send = (request: HttpClientRequest.HttpClientRequest) =>
34 HttpClient.execute(request).pipe(
35 Effect.flatMap((response) =>
36 response.status >= 500
37 ? response.text.pipe(
38 Effect.flatMap((body) =>
39 Effect.fail(new TransientUpstream({ status: response.status, body })),
40 ),
41 )
42 : Effect.succeed(response),
43 ),
44 Effect.retry({
45 while: (e) => e._tag === "TransientUpstream",
46 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
47 }),
48 );
49
50 const getJson = (path: string) =>
51 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
52
53 const postJson = (path: string) =>
54 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
55
56 describe.sequential(
57 "DataSync Bindings",
58 {
59 tags: [
60 "provider:aws",
61 "provider:aws:datasync",
62 "provider:aws:iam",
63 "provider:aws:lambda",
64 "provider:aws:location",
65 "provider:aws:s3",
66 "live",
67 ],
68 },
69 () => {
70 beforeAll(
71 Effect.gen(function* () {
72 yield* Effect.logInfo("DataSync test setup: destroying previous resources");
73 yield* sharedStack.destroy();
74
75 yield* Effect.logInfo("DataSync test setup: deploying fixture");
76 const attrs = yield* sharedStack.deploy(
77 Effect.gen(function* () {
78 return yield* DataSyncTestFunction;
79 }).pipe(Effect.provide(DataSyncTestFunctionLive)),
80 );
81
82 expect(attrs.functionUrl).toBeTruthy();
83 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
84 functionArn = attrs.functionArn;
85
86 const readinessUrl = `${baseUrl}/bindings`;
87 yield* Effect.logInfo(`DataSync test setup: probing readiness at ${readinessUrl}`);
88 yield* HttpClient.get(readinessUrl).pipe(
89 Effect.flatMap((response) =>
90 response.status === 200
91 ? Effect.succeed(response)
92 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
93 ),
94 Effect.tapError((error) =>
95 Effect.logWarning(`DataSync test setup: fixture not ready yet (${String(error)})`),
96 ),
97 Effect.retry({ schedule: readinessPolicy }),
98 );
99 }),
100 { timeout: 300_000 },
101 );
102
103 afterAll(sharedStack.destroy(), { timeout: 180_000 });
104
105 describe("binding registration", () => {
106 test.provider("all six capabilities initialize in the runtime", (_stack) =>
107 Effect.gen(function* () {
108 const response = (yield* getJson("/bindings")) as { bound: string[] };
109 expect(response.bound).toHaveLength(6);
110 expect(response.bound).toContain("startTaskExecution");
111 expect(response.bound).toContain("cancelTaskExecution");
112 }),
113 );
114 });
115
116 describe("DescribeTask", () => {
117 test.provider("reads the bound task's detail (injected task arn)", (_stack) =>
118 Effect.gen(function* () {
119 const response = (yield* getJson("/task")) as { taskArn: string; status: string };
120 expect(response.taskArn).toContain(":task/task-");
121 expect(typeof response.status).toBe("string");
122 }),
123 );
124 });
125
126 describe("StartTaskExecution / ListTaskExecutions / DescribeTaskExecution / UpdateTaskExecution / CancelTaskExecution", () => {
127 test.provider(
128 "starts a run, observes it, throttles, cancels, and waits it out",
129 (_stack) =>
130 Effect.gen(function* () {
131 // Start: the freshly-propagated IAM role can transiently fail the
132 // location access test (typed LocationAccessTestFailed, reported
133 // by the route as ok:false) — re-poll bounded.
134 const started = (yield* postJson("/start").pipe(
135 Effect.repeat({
136 schedule: Schedule.spaced("10 seconds"),
137 until: (r): boolean => (r as { ok: boolean }).ok === true,
138 times: 12,
139 }),
140 )) as { ok: boolean; executionArn?: string; tag?: string };
141 expect(started.ok).toBe(true);
142 expect(started.executionArn).toContain("/execution/exec-");
143 const executionArn = started.executionArn!;
144 const query = `?arn=${encodeURIComponent(executionArn)}`;
145
146 // Describe: the run reports a status.
147 const execution = (yield* getJson(`/execution${query}`)) as { status: string };
148 expect(typeof execution.status).toBe("string");
149
150 // List: the run is enumerated under the bound task.
151 const executions = (yield* getJson("/executions")) as { arns: string[] };
152 expect(executions.arns).toContain(executionArn);
153
154 // Throttle: valid only in launching/preparing/transferring/
155 // verifying — either it lands or DataSync rejects it with the
156 // typed InvalidRequestException the route reports.
157 const throttled = (yield* postJson(`/throttle${query}`)) as {
158 updated: boolean;
159 tag?: string;
160 };
161 if (!throttled.updated) {
162 expect(throttled.tag).toBe("InvalidRequestException");
163 }
164
165 // Cancel: a queued/launching run is cancellable; if the empty
166 // transfer raced to completion, DataSync rejects with the typed
167 // InvalidRequestException instead.
168 const cancelled = (yield* postJson(`/cancel${query}`)) as {
169 cancelled: boolean;
170 tag?: string;
171 };
172 if (!cancelled.cancelled) {
173 expect(cancelled.tag).toBe("InvalidRequestException");
174 }
175
176 // Observe the run after the cancel: a cancelled queued run parks
177 // in CANCELLING (sometimes for minutes) before landing in ERROR —
178 // any of the three proves the round-trip. `stack.destroy()`
179 // deletes the task cleanly even with a CANCELLING execution, so
180 // there is no need to wait for a terminal state.
181 const observed = (yield* getJson(`/execution${query}`)) as { status: string };
182 expect(["CANCELLING", "ERROR", "SUCCESS"]).toContain(observed.status);
183 }),
184 { timeout: 240_000 },
185 );
186 });
187
188 describe("consumeTaskEvents", { tags: ["provider:aws:eventbridge"] }, () => {
189 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
190 Effect.gen(function* () {
191 // Out-of-band via distilled: the fixture's consumeTaskEvents must
192 // have materialized as a rule on the default bus with the Lambda
193 // as target.
194 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
195 TargetArn: functionArn,
196 });
197 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
198 }),
199 );
200 });
201 },
202 );