@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 265 lines 9.91 KB
Raw
1 /**
2 * HTTP runtime bridges and platform services for Effect's HTTP APIs.
3 */
4 import * as Cause from "effect/Cause";
5 import * as Config from "effect/Config";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as ErrorReporter from "effect/ErrorReporter";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Etag from "effect/http/Etag";
11 import type { HttpBodyError } from "effect/http/HttpBody";
12 import * as HttpPlatform from "effect/http/HttpPlatform";
13 import { causeResponse, type HttpServerError } from "effect/http/HttpServerError";
14 import { HttpServerRequest } from "effect/http/HttpServerRequest";
15 import * as HttpServerResponse from "effect/http/HttpServerResponse";
16 import * as Layer from "effect/Layer";
17 import * as Option from "effect/Option";
18 import * as Path from "effect/Path";
19 import * as Scope from "effect/Scope";
20 import { ManagedHttpShutdown } from "./Runtime/ManagedHttpShutdown.ts";
21
22 export type HttpEffect<Req = never> = Effect.Effect<
23 HttpServerResponse.HttpServerResponse,
24 HttpServerError | HttpBodyError,
25 HttpServerRequest | Scope.Scope | Req
26 >;
27
28 /**
29 * `effect`'s HttpEffect brands a request scope as "ejected" when ownership
30 * is transferred to a consumer that outlives the handler's return — a
31 * streaming response body, a WebSocket upgrade, an RPC stream. Bridges check
32 * this before their close-on-return path: an ejected scope is closed by its
33 * new owner when it finishes, not by the bridge.
34 */
35 const scopeEjected = Symbol.for("effect/http/HttpEffect/scopeEjected");
36
37 export const isScopeEjected = (scope: Scope.Scope) => scopeEjected in scope;
38
39 export const serve = <Req = never>(
40 handler: Effect.Effect<
41 HttpServerResponse.HttpServerResponse,
42 HttpServerError | HttpBodyError,
43 HttpServerRequest | Scope.Scope | Req
44 >,
45 ) =>
46 Effect.serviceOption(HttpServer).pipe(
47 Effect.map(Option.getOrUndefined),
48 Effect.flatMap((http) =>
49 http
50 ? // `HttpServer.serve` registers the server on the ambient Scope and
51 // RETURNS; the server lives until that scope closes. A host program
52 // (ECS task/service, EC2 instance) must therefore park forever after
53 // a successful registration — otherwise a pure `{ fetch }` program
54 // completes immediately, `Effect.scoped` closes the scope, and the
55 // container exits 0 in a crash-loop. (One-shot `{ run }` programs
56 // never call `serve`, so they still exit when `run` completes.)
57 Effect.andThen(http.serve(handler), Effect.never)
58 : Effect.void,
59 ),
60 );
61
62 export class HttpServer extends Context.Service<
63 HttpServer,
64 {
65 serve: <Req = never>(
66 handler: Effect.Effect<
67 HttpServerResponse.HttpServerResponse,
68 HttpServerError | HttpBodyError,
69 Req
70 >,
71 options?: { port?: number },
72 ) => Effect.Effect<void, never, Exclude<Req, HttpServerRequest> | Scope.Scope>;
73 }
74 >()("HttpServer") {}
75
76 export const safeHttpEffect = <Req = never>(
77 handler: HttpEffect<Req> | Effect.Effect<HttpEffect<Req>>,
78 ): Effect.Effect<
79 HttpServerResponse.HttpServerResponse,
80 never,
81 Req | HttpServerRequest | Scope.Scope
82 > =>
83 Effect.catchCause(
84 handler.pipe(
85 // @ts-expect-error
86 Effect.flatMap((response) =>
87 HttpServerResponse.isHttpServerResponse(response) ? Effect.succeed(response) : response,
88 ),
89 ) as any as HttpEffect<Req>,
90 (cause) =>
91 // `causeResponse` is effect's native failure boundary: Respondable
92 // failures keep their intended response (e.g. RouteNotFound -> 404),
93 // client aborts map to 499, and everything else becomes an empty 500 —
94 // the cause is never echoed to the network, as it can contain sensitive
95 // data (prompt contents, API keys baked into error messages, internal
96 // file paths).
97 causeResponse(cause).pipe(
98 Effect.flatMap(([response, reportableCause]) =>
99 Effect.withFiber((fiber) =>
100 fiber.getRef(ErrorReporter.CurrentErrorReporters).size > 0
101 ? ErrorReporter.report(reportableCause)
102 : logUnreportedCause(reportableCause),
103 ).pipe(Effect.as(response)),
104 ),
105 ),
106 );
107
108 /**
109 * No `ErrorReporter` is registered by default, so without a fallback a defect
110 * in a deployed Function/Worker would produce a bare 500 and vanish without a
111 * trace. Log the cause server-side so operators can debug, applying the same
112 * filtering `ErrorReporter.make` reporters do: interrupts (client aborts) and
113 * `ErrorReporter.ignore`-annotated values (Respondable errors like
114 * RouteNotFound, and the response `causeResponse` appends) are not failures
115 * and are skipped.
116 */
117 const logUnreportedCause = (cause: Cause.Cause<unknown>) => {
118 const failures = cause.reasons.filter(
119 (reason) =>
120 reason._tag !== "Interrupt" &&
121 !ErrorReporter.isIgnored(reason._tag === "Fail" ? reason.error : reason.defect),
122 );
123 return failures.length === 0
124 ? Effect.void
125 : Effect.logError("HTTP handler failed", Cause.fromReasons(failures));
126 };
127
128 export const resolvePort = (options: { port?: number } | undefined) =>
129 options?.port !== undefined
130 ? Effect.succeed(options.port)
131 : Config.Number("PORT").pipe(Config.withDefault(3000));
132
133 export interface BunHttpServerOptions {
134 /**
135 * Network interface on which the Bun HTTP server listens.
136 *
137 * Always passed explicitly to `Bun.serve` so container bootstraps bind a
138 * predictable IPv4 wildcard regardless of the platform default
139 * (`@effect/platform-bun` ≥ 4.0.0-rc.115 defaults to `::`; rc.113/114
140 * crash-looped on the omitted-hostname case).
141 *
142 * @default "0.0.0.0"
143 */
144 hostname?: string;
145 }
146
147 export const BunHttpServer = (serverOptions?: BunHttpServerOptions) =>
148 Layer.effect(
149 HttpServer,
150 Effect.gen(function* () {
151 const BunHttpServerPlatform = yield* Effect.promise(
152 () => import("@effect/platform-bun/BunHttpServer"),
153 );
154 return {
155 serve: (handler, options) =>
156 Effect.gen(function* () {
157 const port = yield* resolvePort(options);
158 const server = yield* BunHttpServerPlatform.make({
159 port,
160 hostname: serverOptions?.hostname ?? "0.0.0.0",
161 });
162 yield* server.serve(safeHttpEffect(handler));
163 }).pipe(Effect.orDie),
164 };
165 }),
166 );
167
168 export interface NodeHttpServerOptions {
169 /**
170 * Address the Node HTTP server binds. Fly / Hetzner / Railway machines
171 * need `0.0.0.0`; omit to use that default.
172 * @default "0.0.0.0"
173 */
174 hostname?: string;
175 /**
176 * Port the Node HTTP server binds when the handler is served without an
177 * explicit port. Omit to read `PORT` (default `3000`).
178 */
179 port?: number;
180 }
181
182 export const NodeHttpServer = (serverOptions?: NodeHttpServerOptions) =>
183 Layer.effect(
184 HttpServer,
185 Effect.gen(function* () {
186 const NodeHttpServerPlatform = yield* Effect.promise(
187 () => import("@effect/platform-node/NodeHttpServer"),
188 );
189 const NodeHttp = yield* Effect.promise(() => import("node:http"));
190 return {
191 serve: (handler, options) =>
192 Effect.gen(function* () {
193 const port = yield* resolvePort({ port: options?.port ?? serverOptions?.port });
194 const shutdown = yield* Effect.serviceOption(ManagedHttpShutdown);
195 const managed = Option.getOrUndefined(shutdown);
196 if (managed?.isStopping()) return yield* Effect.interrupt;
197 const serve = Effect.gen(function* () {
198 const server = yield* NodeHttpServerPlatform.make(
199 () => {
200 const server = NodeHttp.createServer();
201 managed?.servers.add(server);
202 server.once("close", () => managed?.servers.delete(server));
203 return server;
204 },
205 {
206 port,
207 host: serverOptions?.hostname ?? "0.0.0.0",
208 gracefulShutdownTimeout: managed?.drainTimeoutMs,
209 },
210 );
211 // The Node bridge masks interruption, including streaming writes.
212 yield* managed
213 ? server.serve(safeHttpEffect(handler), (handled) =>
214 Effect.withFiber((fiber) => {
215 // Observe outside the adapter's request-scope finalization.
216 managed.observeRequest(fiber);
217 return Effect.interruptible(handled);
218 }),
219 )
220 : server.serve(safeHttpEffect(handler));
221 });
222 if (managed) {
223 const scope = yield* Scope.fork(managed.scope);
224 yield* serve.pipe(Scope.provide(scope));
225 } else {
226 yield* serve;
227 }
228 }).pipe(Effect.orDie),
229 };
230 }),
231 );
232
233 const HttpPlatformStub: Layer.Layer<HttpPlatform.HttpPlatform> = Layer.succeed(
234 HttpPlatform.HttpPlatform,
235 {
236 platform: "web",
237 // Advertises no algorithms, so the compression middleware never engages
238 // and compressResponse is never called.
239 compression: {
240 algorithms: new Set<HttpPlatform.CompressionAlgorithm>(),
241 compressResponse: (response) => Effect.succeed(response),
242 },
243 fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
244 fileWebResponse: () => Effect.die("HttpPlatform.fileWebResponse not supported"),
245 },
246 );
247
248 /**
249 * The `HttpPlatform`, `Etag`, `Path`, and no-op `FileSystem` services `HttpApiBuilder.layer`
250 * wants, for runtimes without a filesystem: Workers, Lambda. File responses
251 * die, compression never engages.
252 *
253 * Provide it to `HttpApiBuilder.layer(api)` in a Worker or a Lambda:
254 *
255 * ```typescript
256 * HttpApiBuilder.layer(Api).pipe(
257 * Layer.provide(handlers),
258 * Layer.provide(Http.Platform),
259 * HttpRouter.toHttpEffect,
260 * )
261 * ```
262 */
263 export const Platform: Layer.Layer<
264 Etag.Generator | HttpPlatform.HttpPlatform | Path.Path | FileSystem.FileSystem
265 > = Layer.mergeAll(Etag.layer, HttpPlatformStub, Path.layer, FileSystem.layerNoop({}));