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

main
ts 157 lines 5.57 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Data from "effect/Data";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as Schedule from "effect/Schedule";
9 import WebSocket from "ws";
10 import WebSocketTestFunctionLive, { WebSocketTestFunction } from "./ws-handler";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 class WebSocketFailure extends Data.TaggedError("WebSocketFailure")<{
15 readonly reason: string;
16 }> {}
17
18 class FixtureNotConsistent extends Data.TaggedError("FixtureNotConsistent") {}
19
20 /**
21 * Connect a wss client, send one frame, and resolve with the first frame
22 * received back. Encapsulates the socket in `Effect.callback` so fiber
23 * interruption (the outer `Effect.timeout`) closes the socket.
24 *
25 * An `{"message": "Internal server error"}` frame is API Gateway reporting
26 * that the route's Lambda invocation failed — right after a fresh deploy
27 * that is IAM/binding propagation, so it fails as a retryable
28 * `WebSocketFailure` rather than resolving.
29 */
30 const wsSendAndReceive = (url: string, message: string) =>
31 Effect.callback<string, WebSocketFailure>((resume, signal) => {
32 const socket = new WebSocket(url);
33 let settled = false;
34 const settle = (effect: Effect.Effect<string, WebSocketFailure>) => {
35 if (settled) return;
36 settled = true;
37 try {
38 socket.close();
39 } catch {
40 // already closed
41 }
42 resume(effect);
43 };
44 signal.addEventListener("abort", () =>
45 settle(Effect.fail(new WebSocketFailure({ reason: "interrupted" }))),
46 );
47 socket.on("open", () => socket.send(message));
48 socket.on("message", (data) => {
49 const frame = String(data);
50 if (frame.includes('"Internal server error"')) {
51 settle(
52 Effect.fail(
53 new WebSocketFailure({
54 reason: `route invocation failed: ${frame}`,
55 }),
56 ),
57 );
58 } else {
59 settle(Effect.succeed(frame));
60 }
61 });
62 socket.on("error", (error) =>
63 settle(Effect.fail(new WebSocketFailure({ reason: String(error) }))),
64 );
65 socket.on("close", (code) =>
66 settle(Effect.fail(new WebSocketFailure({ reason: `closed before echo (${code})` }))),
67 );
68 });
69
70 test.provider(
71 "WebSocket API echoes via ManageConnections",
72 (stack) =>
73 Effect.gen(function* () {
74 yield* stack.destroy();
75
76 const fn = yield* stack.deploy(
77 Effect.gen(function* () {
78 return yield* WebSocketTestFunction.pipe(Effect.provide(WebSocketTestFunctionLive));
79 }),
80 );
81 expect(fn.functionUrl).toBeTruthy();
82
83 // Discover the wss:// URL through the fixture's function URL.
84 // Two eventual-consistency windows to ride out: function-URL cold
85 // start (non-200s) and Lambda env-config propagation — an instance
86 // initialized before the binding env update serves `{}` until it is
87 // recycled, so poll until `wsUrl` is actually present.
88 const info = yield* HttpClient.get(fn.functionUrl!).pipe(
89 Effect.flatMap((response) =>
90 response.status === 200
91 ? response.json
92 : Effect.fail(new Error(`fixture returned ${response.status}`)),
93 ),
94 Effect.flatMap((body) =>
95 typeof (body as { wsUrl?: string }).wsUrl === "string"
96 ? Effect.succeed(body as { wsUrl: string; callbackUrl: string })
97 : Effect.fail(new FixtureNotConsistent()),
98 ),
99 Effect.retry({
100 schedule: Schedule.max([
101 Schedule.exponential("500 millis").pipe(
102 Schedule.modifyDelay(({ duration }) =>
103 Effect.succeed(
104 Duration.isGreaterThan(duration, Duration.seconds(3))
105 ? Duration.seconds(3)
106 : duration,
107 ),
108 ),
109 ),
110 Schedule.recurs(30),
111 ]),
112 }),
113 );
114 const { wsUrl, callbackUrl } = info;
115 expect(wsUrl).toMatch(/^wss:\/\//);
116 expect(callbackUrl).toMatch(/^https:\/\//);
117
118 // Connect, send, and expect the Lambda to push the echo back over
119 // the socket. The first connections retry through route/permission/
120 // IAM propagation (failed invocations surface as retryable
121 // "Internal server error" frames).
122 const echoed = yield* wsSendAndReceive(wsUrl, "hello-websocket").pipe(
123 Effect.timeout(Duration.seconds(15)),
124 Effect.retry({
125 schedule: Schedule.max([
126 Schedule.exponential("1 second").pipe(
127 Schedule.modifyDelay(({ duration }) =>
128 Effect.succeed(
129 Duration.isGreaterThan(duration, Duration.seconds(5))
130 ? Duration.seconds(5)
131 : duration,
132 ),
133 ),
134 ),
135 Schedule.recurs(10),
136 ]),
137 }),
138 );
139 expect(echoed).toBe("echo:hello-websocket");
140
141 // A second frame on a fresh connection round-trips too (no
142 // propagation retry needed once the first succeeded).
143 const second = yield* wsSendAndReceive(wsUrl, "again").pipe(
144 Effect.timeout(Duration.seconds(15)),
145 Effect.retry({
146 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(3)]),
147 }),
148 );
149 expect(second).toBe("echo:again");
150
151 yield* stack.destroy();
152 }),
153 {
154 tags: ["provider:aws", "provider:aws:apigatewayv2", "provider:aws:lambda", "live"],
155 timeout: 600_000,
156 },
157 );