@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, 04:45 UTC

main
ts 266 lines 11.2 KB
Raw
1 import { makeFunctionBridge } from "@alchemy.run/neon/FunctionBridge";
2 import { FunctionRequest } from "@alchemy.run/neon/FunctionEnvironment";
3 import { makeFunctionRuntimeContext } from "@alchemy.run/neon/FunctionRuntimeContext";
4 import { FunctionUpgradeSockets } from "@alchemy.run/neon/FunctionUpgrade";
5 import { expect, test } from "@alchemy.run/test";
6 import * as ConfigProvider from "effect/ConfigProvider";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
9 import { HttpServerRequest } from "effect/http/HttpServerRequest";
10 import * as HttpServerResponse from "effect/http/HttpServerResponse";
11 import * as Scope from "effect/Scope";
12 import * as Stream from "effect/Stream";
13
14 for (const cancellation of ["abort", "body"] as const)
15 test.live(
16 `Function bridge closes the handler scope on ${cancellation} cancellation`,
17 () =>
18 Effect.gen(function* () {
19 const finalized = yield* Deferred.make<void>();
20 const streamFinalized = yield* Deferred.make<void>();
21 const runtime = yield* Effect.sync(() => makeFunctionRuntimeContext("Bridge"));
22 let closed = false;
23 yield* runtime.route(
24 "/stream",
25 Effect.gen(function* () {
26 const scope = yield* Effect.scope;
27 const request = yield* FunctionRequest;
28 expect((yield* HttpServerRequest).source).toBe(request);
29 yield* Effect.addFinalizer(() =>
30 Effect.sync(() => {
31 closed = true;
32 }).pipe(Effect.andThen(Deferred.succeed(finalized, undefined))),
33 );
34 return HttpServerResponse.stream(
35 Stream.fromEffect(
36 Effect.gen(function* () {
37 expect(yield* Effect.scope).toBe(scope);
38 return yield* Effect.sync(() => new TextEncoder().encode("first"));
39 }),
40 ).pipe(
41 Stream.concat(Stream.never),
42 Stream.ensuring(Deferred.succeed(streamFinalized, undefined)),
43 Stream.provideService(Scope.Scope, scope),
44 ),
45 );
46 }),
47 );
48 const bridge = yield* Effect.sync(() =>
49 makeFunctionBridge(Effect.succeed({ RuntimeContext: runtime })),
50 );
51 const controller = yield* Effect.sync(() => new AbortController());
52 const request = yield* Effect.sync(
53 () => new Request("https://function.test/stream", { signal: controller.signal }),
54 );
55 const response = yield* Effect.tryPromise(() => bridge.fetch(request));
56 const reader = yield* Effect.sync(() => response.body!.getReader());
57 const first = yield* Effect.tryPromise(() => reader.read());
58 expect(first.done).toBe(false);
59 expect(closed).toBe(false);
60 if (cancellation === "abort") yield* Effect.sync(() => controller.abort());
61 else yield* Effect.tryPromise(() => reader.cancel());
62 yield* Effect.all([Deferred.await(finalized), Deferred.await(streamFinalized)]).pipe(
63 Effect.timeout("1 second"),
64 Effect.ensuring(Effect.tryPromise(() => reader.cancel()).pipe(Effect.ignore)),
65 );
66 expect(closed).toBe(true);
67 }),
68 { tags: ["unit", "provider:neon", "provider:neon:function", "local"] },
69 );
70
71 for (const cancellation of ["abort", "body"] as const)
72 test.live(
73 `Function bridge preserves backpressure until ${cancellation} cancellation`,
74 () =>
75 Effect.gen(function* () {
76 const runtime = yield* Effect.sync(() => makeFunctionRuntimeContext("Backpressure"));
77 const finalized = yield* Deferred.make<void>();
78 const streamFinalized = yield* Deferred.make<void>();
79 let produced = 0;
80 let closed = false;
81 yield* runtime
82 .route(
83 "/",
84 Effect.gen(function* () {
85 yield* Effect.addFinalizer(() =>
86 Effect.sync(() => {
87 closed = true;
88 }).pipe(Effect.andThen(Deferred.succeed(finalized, undefined))),
89 );
90 return HttpServerResponse.stream(
91 Stream.fromEffectRepeat(
92 Effect.sync(() => new TextEncoder().encode(String(++produced))),
93 ).pipe(Stream.ensuring(Deferred.succeed(streamFinalized, undefined))),
94 );
95 }),
96 )
97 .pipe(
98 Effect.provideService(
99 ConfigProvider.ConfigProvider,
100 // The removed watchdog must not interpret a paused consumer as a disconnect.
101 ConfigProvider.fromUnknown({ ALCHEMY_NEON_STREAM_IDLE_TIMEOUT: "1 millis" }),
102 ),
103 );
104 const bridge = yield* Effect.sync(() =>
105 makeFunctionBridge(Effect.succeed({ RuntimeContext: runtime })),
106 );
107 const controller = yield* Effect.sync(() => new AbortController());
108 const request = yield* Effect.sync(
109 () => new Request("https://function.test/", { signal: controller.signal }),
110 );
111 const response = yield* Effect.tryPromise(() => bridge.fetch(request));
112 const reader = yield* Effect.sync(() => response.body!.getReader());
113 yield* Effect.gen(function* () {
114 const first = yield* Effect.tryPromise(() => reader.read());
115 expect(new TextDecoder().decode(first.value)).toBe("1");
116 yield* Effect.sleep("1200 millis");
117 expect(closed).toBe(false);
118 const second = yield* Effect.tryPromise(() => reader.read());
119 expect(new TextDecoder().decode(second.value)).toBe("2");
120 if (cancellation === "abort") yield* Effect.sync(() => controller.abort());
121 else yield* Effect.tryPromise(() => reader.cancel());
122 yield* Deferred.await(streamFinalized).pipe(Effect.timeout("1 second"));
123 yield* Deferred.await(finalized).pipe(Effect.timeout("1 second"));
124 expect(closed).toBe(true);
125 }).pipe(Effect.ensuring(Effect.tryPromise(() => reader.cancel()).pipe(Effect.ignore)));
126 }),
127 { tags: ["unit", "provider:neon", "provider:neon:function", "local"] },
128 );
129
130 for (const outcome of ["complete", "error"] as const)
131 test.live(
132 `Function bridge finalizes a streamed ${outcome} once`,
133 () =>
134 Effect.gen(function* () {
135 const runtime = yield* Effect.sync(() => makeFunctionRuntimeContext("Completion"));
136 const events: string[] = [];
137 yield* runtime.route(
138 "/",
139 Effect.gen(function* () {
140 yield* Effect.addFinalizer(() =>
141 Effect.sync(() => {
142 events.push("request");
143 }),
144 );
145 return HttpServerResponse.stream(
146 (outcome === "complete"
147 ? Stream.make(new Uint8Array([1, 2, 3]))
148 : Stream.fail(new Error("stream failure"))
149 ).pipe(
150 Stream.ensuring(
151 Effect.sync(() => {
152 events.push("stream");
153 }),
154 ),
155 ),
156 { status: 201, headers: { "x-stream-test": "preserved" } },
157 );
158 }),
159 );
160 const bridge = yield* Effect.sync(() =>
161 makeFunctionBridge(Effect.succeed({ RuntimeContext: runtime })),
162 );
163 const request = yield* Effect.sync(() => new Request("https://function.test/"));
164 const response = yield* Effect.tryPromise(() => bridge.fetch(request));
165 expect(response.status).toBe(201);
166 expect(response.headers.get("x-stream-test")).toBe("preserved");
167 const result = yield* Effect.tryPromise(() => response.arrayBuffer()).pipe(Effect.exit);
168 expect(result._tag).toBe(outcome === "complete" ? "Success" : "Failure");
169 expect(events).toEqual(["stream", "request"]);
170 }),
171 { tags: ["unit", "provider:neon", "provider:neon:function", "local"] },
172 );
173
174 for (const cancellation of ["close", "abort"] as const)
175 test.live(
176 `Function bridge preserves upgrade identity and finalizes once on ${cancellation}`,
177 () =>
178 Effect.gen(function* () {
179 const runtime = yield* Effect.sync(() => makeFunctionRuntimeContext("Upgrade"));
180 const finalized = yield* Deferred.make<void>();
181 const release = yield* Deferred.make<void>();
182 let count = 0;
183 const socket = yield* Effect.sync(
184 () => Object.assign(new EventTarget(), { readyState: 1, CLOSED: 3 }) as WebSocket,
185 );
186 const native = yield* Effect.sync(() => new Response(null));
187 yield* Effect.sync(() => FunctionUpgradeSockets.set(native, socket));
188 yield* runtime.route(
189 "/",
190 Effect.gen(function* () {
191 yield* Effect.addFinalizer(() =>
192 Deferred.await(release).pipe(
193 Effect.andThen(
194 Effect.sync(() => {
195 count++;
196 }),
197 ),
198 Effect.andThen(Deferred.succeed(finalized, undefined)),
199 ),
200 );
201 return HttpServerResponse.raw(native);
202 }),
203 );
204 const bridge = yield* Effect.sync(() =>
205 makeFunctionBridge(Effect.succeed({ RuntimeContext: runtime })),
206 );
207 const controller = yield* Effect.sync(() => new AbortController());
208 const request = yield* Effect.sync(
209 () => new Request("https://function.test/", { signal: controller.signal }),
210 );
211 const response = yield* Effect.tryPromise(() => bridge.fetch(request));
212 expect(response).toBe(native);
213 expect(count).toBe(0);
214 yield* Effect.sync(() =>
215 cancellation === "close" ? socket.dispatchEvent(new Event("close")) : controller.abort(),
216 );
217 expect(count).toBe(0);
218 yield* Deferred.succeed(release, undefined);
219 yield* Deferred.await(finalized).pipe(Effect.timeout("2 seconds"));
220 yield* Effect.sync(() => {
221 socket.dispatchEvent(new Event("close"));
222 controller.abort();
223 });
224 expect(count).toBe(1);
225 }),
226 { tags: ["unit", "provider:neon", "provider:neon:function", "local"] },
227 );
228
229 test.effect(
230 "Function bridge closes bodyless request scopes without consuming a stream",
231 () =>
232 Effect.gen(function* () {
233 const runtime = yield* Effect.sync(() => makeFunctionRuntimeContext("Bodyless"));
234 let finalized = 0;
235 let consumed = 0;
236 yield* runtime.route(
237 "/",
238 Effect.gen(function* () {
239 yield* Effect.addFinalizer(() =>
240 Effect.sync(() => {
241 finalized++;
242 }),
243 );
244 return HttpServerResponse.stream(
245 Stream.fromEffect(
246 Effect.sync(() => {
247 consumed++;
248 return new TextEncoder().encode("body");
249 }),
250 ),
251 );
252 }),
253 );
254 const bridge = yield* Effect.sync(() =>
255 makeFunctionBridge(Effect.succeed({ RuntimeContext: runtime })),
256 );
257 const request = yield* Effect.sync(
258 () => new Request("https://function.test/", { method: "HEAD" }),
259 );
260 const response = yield* Effect.tryPromise(() => bridge.fetch(request));
261 expect(response.body).toBe(null);
262 expect(finalized).toBe(1);
263 expect(consumed).toBe(0);
264 }),
265 { tags: ["unit", "provider:neon", "provider:neon:function", "local"] },
266 );