Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 88 lines 2.66 KB
Raw
1 import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2 import { Effect } from 'effect';
3
4 /**
5 * Spin up a local HTTP server on an ephemeral port, run the callback,
6 * then tear down. Useful for integration-testing code that uses `fetch`.
7 */
8 export async function withHttpServer(
9 handler: (req: IncomingMessage, res: ServerResponse) => void,
10 run: (baseUrl: string) => Promise<void>
11 ): Promise<void> {
12 const server = createServer(handler);
13
14 await new Promise<void>((resolve, reject) => {
15 server.once('error', reject);
16 server.listen({ port: 0, host: '127.0.0.1' }, () => {
17 server.off('error', reject);
18 resolve();
19 });
20 });
21
22 const address = server.address();
23 if (address === null || typeof address === 'string') {
24 throw new Error('Failed to bind test server to an ephemeral port');
25 }
26
27 const baseUrl = `http://127.0.0.1:${address.port}`;
28
29 try {
30 await run(baseUrl);
31 } finally {
32 await new Promise<void>((resolve, reject) => {
33 server.close(error => {
34 if (error) {
35 reject(error);
36 return;
37 }
38 resolve();
39 });
40 });
41 }
42 }
43
44 /**
45 * Spin up a local HTTP server on an ephemeral port as a scoped resource and
46 * return its base URL. Scope closure tears the server down.
47 */
48 export const startTestHttpServer = (handler: (req: IncomingMessage, res: ServerResponse) => void) =>
49 Effect.map(
50 Effect.acquireRelease(
51 Effect.promise(
52 () =>
53 new Promise<Server>((resolve, reject) => {
54 const server = createServer(handler);
55 server.once('error', reject);
56 server.listen({ port: 0, host: '127.0.0.1' }, () => {
57 server.off('error', reject);
58 resolve(server);
59 });
60 })
61 ),
62 server =>
63 Effect.promise(
64 () =>
65 new Promise<void>((resolve, reject) => {
66 server.close(error => (error ? reject(error) : resolve()));
67 })
68 )
69 ),
70 server => {
71 const address = server.address();
72 if (address === null || typeof address === 'string') {
73 throw new Error('Failed to bind test server to an ephemeral port');
74 }
75 return `http://127.0.0.1:${address.port}`;
76 }
77 );
78
79 /**
80 * Effect variant of {@link withHttpServer}: the server lifecycle comes from
81 * {@link startTestHttpServer} so `use` can be an Effect run by @effect/vitest.
82 */
83 export function withHttpServerEffect<A, E, R>(
84 handler: (req: IncomingMessage, res: ServerResponse) => void,
85 use: (baseUrl: string) => Effect.Effect<A, E, R>
86 ): Effect.Effect<A, E, R> {
87 return Effect.scoped(Effect.flatMap(startTestHttpServer(handler), use));
88 }