Open History to see the last commit
1/**
2 * Node.js implementation of the Effect `HttpServer`.
3 *
4 * This module adapts a supplied Node `http.Server` into Effect's
5 * platform-independent HTTP server service. It starts the server with Node
6 * `listen` options, converts `request` events into `HttpServerRequest` values,
7 * writes `HttpServerResponse` bodies through Node's `ServerResponse`, and
8 * handles `upgrade` events by exposing the upgraded socket through
9 * `HttpServerRequest.upgrade`.
10 *
11 * Common use cases include serving an Effect HTTP application with {@link layer}
12 * or {@link layerConfig}, embedding request or upgrade handlers into an
13 * existing Node server with {@link makeHandler} and {@link makeUpgradeHandler},
14 * and using {@link layerTest} for integration tests that need an ephemeral
15 * listening port and a client pointed at it.
16 *
17 * Listen options are passed directly to Node, so host, port, backlog, and Unix
18 * socket path behavior follow `node:http`. The server begins listening when the
19 * `HttpServer` is acquired, and handlers are installed when `serve` is run.
20 * Request fibers are interrupted with `ClientAbort` when the client disconnects
21 * before a response finishes. WebSocket support only applies to Node `upgrade`
22 * requests, and ordinary HTTP requests fail if their application attempts to use
23 * `HttpServerRequest.upgrade`.
24 *
25 * Scope ownership is important: the server is closed when the acquiring scope
26 * finalizes, while each `serve` call installs its own request and upgrade
27 * listeners and removes them on finalization. Unless preemptive shutdown is
28 * disabled, finalizing a serve scope also starts a graceful server close, using
29 * the configured timeout or the default timeout.
30 *
31 * @since 4.0.0
32 */
33import * as Cause from "effect/Cause"
34import * as Config from "effect/Config"
35import * as Context from "effect/Context"
36import * as Duration from "effect/Duration"
37import * as Effect from "effect/Effect"
38import * as Fiber from "effect/Fiber"
39import type * as FileSystem from "effect/FileSystem"
40import { flow, type LazyArg } from "effect/Function"
41import * as Latch from "effect/Latch"
42import * as Layer from "effect/Layer"
43import type * as Option from "effect/Option"
44import type * as Path from "effect/Path"
45import type * as Record from "effect/Record"
46import * as Scope from "effect/Scope"
47import * as Stream from "effect/Stream"
48import * as Cookies from "effect/unstable/http/Cookies"
49import * as Etag from "effect/unstable/http/Etag"
50import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"
51import type * as Headers from "effect/unstable/http/Headers"
52import type { HttpClient } from "effect/unstable/http/HttpClient"
53import * as HttpEffect from "effect/unstable/http/HttpEffect"
54import * as HttpIncomingMessage from "effect/unstable/http/HttpIncomingMessage"
55import type { HttpMethod } from "effect/unstable/http/HttpMethod"
56import type * as Middleware from "effect/unstable/http/HttpMiddleware"
57import type * as HttpPlatform from "effect/unstable/http/HttpPlatform"
58import * as HttpServer from "effect/unstable/http/HttpServer"
59import {
60 causeResponse,
61 ClientAbort,
62 HttpServerError,
63 RequestParseError,
64 ResponseError,
65 ServeError
66} from "effect/unstable/http/HttpServerError"
67import * as Request from "effect/unstable/http/HttpServerRequest"
68import { HttpServerRequest } from "effect/unstable/http/HttpServerRequest"
69import type { HttpServerResponse } from "effect/unstable/http/HttpServerResponse"
70import type * as Multipart from "effect/unstable/http/Multipart"
71import * as Socket from "effect/unstable/socket/Socket"
72import * as Http from "node:http"
73import type * as Net from "node:net"
74import type { Duplex } from "node:stream"
75import { Readable } from "node:stream"
76import { pipeline } from "node:stream/promises"
77import { NodeHttpIncomingMessage } from "./NodeHttpIncomingMessage.ts"
78import * as NodeHttpPlatform from "./NodeHttpPlatform.ts"
79import * as NodeMultipart from "./NodeMultipart.ts"
80import * as NodeServices from "./NodeServices.ts"
81import { NodeWS } from "./NodeSocket.ts"
82
83/**
84 * Creates a scoped `HttpServer` from a Node `http.Server`, starts listening
85 * with the supplied options, registers request and upgrade handling, and closes
86 * the server during scope finalization with optional graceful-shutdown control.
87 *
88 * @category constructors
89 * @since 4.0.0
90 */
91export const make = Effect.fnUntraced(function*(
92 evaluate: LazyArg<Http.Server>,
93 options: Net.ListenOptions & {
94 readonly disablePreemptiveShutdown?: boolean | undefined
95 readonly gracefulShutdownTimeout?: Duration.Input | undefined
96 }
97) {
98 const scope = yield* Effect.scope
99 const server = evaluate()
100
101 const shutdown = yield* Effect.callback<void>((resume) => {
102 if (!server.listening) {
103 return resume(Effect.void)
104 }
105 server.close((error) => {
106 if (error) {
107 resume(Effect.die(error))
108 } else {
109 resume(Effect.void)
110 }
111 })
112 }).pipe(Effect.cached)
113
114 const preemptiveShutdown = options.disablePreemptiveShutdown ?
115 Effect.void :
116 Effect.timeoutOrElse(shutdown, {
117 duration: options.gracefulShutdownTimeout ?? Duration.seconds(20),
118 orElse: () => Effect.void
119 })
120
121 yield* Scope.addFinalizer(scope, shutdown)
122
123 yield* Effect.callback<void, ServeError>((resume) => {
124 function onError(cause: Error) {
125 resume(Effect.fail(new ServeError({ cause })))
126 }
127 server.on("error", onError)
128 server.listen(options, () => {
129 server.off("error", onError)
130 resume(Effect.void)
131 })
132 })
133
134 const address = server.address()!
135
136 const wss = yield* Effect.acquireRelease(
137 Effect.sync(() => new NodeWS.WebSocketServer({ noServer: true })),
138 (wss) =>
139 Effect.callback<void>((resume) => {
140 wss.close(() => resume(Effect.void))
141 })
142 ).pipe(
143 Scope.provide(scope),
144 Effect.cached
145 )
146
147 return HttpServer.make({
148 address: typeof address === "string" ?
149 {
150 _tag: "UnixAddress",
151 path: address
152 } :
153 {
154 _tag: "TcpAddress",
155 hostname: address.address === "::" ? "0.0.0.0" : address.address,
156 port: address.port
157 },
158 serve: Effect.fnUntraced(function*(httpApp, middleware) {
159 const serveScope = yield* Effect.scope
160 const scope = Scope.forkUnsafe(serveScope, "parallel")
161 const handler = yield* (makeHandler(httpApp, {
162 middleware: middleware as any,
163 scope
164 }) as Effect.Effect<(nodeRequest: Http.IncomingMessage, nodeResponse: Http.ServerResponse) => void>)
165 const upgradeHandler = yield* makeUpgradeHandler(wss, httpApp, {
166 middleware: middleware as any,
167 scope
168 })
169 yield* Scope.addFinalizerExit(serveScope, () => {
170 server.off("request", handler)
171 server.off("upgrade", upgradeHandler)
172 return preemptiveShutdown
173 })
174 server.on("request", handler)
175 server.on("upgrade", upgradeHandler)
176 })
177 })
178})
179
180/**
181 * Creates a Node `request` event handler for an Effect HTTP application,
182 * injecting a `HttpServerRequest` and interrupting the request fiber if the
183 * client closes the response before it finishes.
184 *
185 * @category Handlers
186 * @since 4.0.0
187 */
188export const makeHandler = <
189 R,
190 E,
191 App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>
192>(
193 httpEffect: Effect.Effect<HttpServerResponse, E, R>,
194 options: {
195 readonly scope: Scope.Scope
196 readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined
197 }
198): Effect.Effect<
199 (nodeRequest: Http.IncomingMessage, nodeResponse: Http.ServerResponse) => void,
200 never,
201 Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
202> => {
203 const handled = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware as any)
204 return Effect.withFiber((parent) => {
205 const services = parent.context
206 return Effect.succeed(function handler(
207 nodeRequest: Http.IncomingMessage,
208 nodeResponse: Http.ServerResponse
209 ) {
210 const map = new Map(services.mapUnsafe)
211 map.set(HttpServerRequest.key, new ServerRequestImpl(nodeRequest, nodeResponse))
212 const fiber = Fiber.runIn(Effect.runForkWith(Context.makeUnsafe<any>(map))(handled), options.scope)
213 nodeResponse.on("close", () => {
214 if (!nodeResponse.writableEnded) {
215 fiber.interruptUnsafe(parent.id, ClientAbort.annotation)
216 }
217 })
218 })
219 })
220}
221
222/**
223 * Creates a Node `upgrade` event handler for an Effect HTTP application,
224 * exposing the upgraded WebSocket as the request's `upgrade` effect and
225 * interrupting the request fiber when the socket closes early.
226 *
227 * @category Handlers
228 * @since 4.0.0
229 */
230export const makeUpgradeHandler = <
231 R,
232 E,
233 App extends Effect.Effect<HttpServerResponse, any, any> = Effect.Effect<HttpServerResponse, E, R>
234>(
235 lazyWss: Effect.Effect<NodeWS.WebSocketServer>,
236 httpEffect: Effect.Effect<HttpServerResponse, E, R>,
237 options: {
238 readonly scope: Scope.Scope
239 readonly middleware?: Middleware.HttpMiddleware.Applied<App, E, R> | undefined
240 }
241): Effect.Effect<
242 (nodeRequest: Http.IncomingMessage, socket: Duplex, head: Buffer) => void,
243 never,
244 Exclude<Effect.Services<App>, HttpServerRequest | Scope.Scope>
245> => {
246 const handledApp = HttpEffect.toHandled(httpEffect, handleResponse, options.middleware as any)
247 return Effect.withFiber((parent) => {
248 const services = parent.context
249 return Effect.succeed(function handler(
250 nodeRequest: Http.IncomingMessage,
251 socket: Duplex,
252 head: Buffer
253 ) {
254 let nodeResponse_: Http.ServerResponse | undefined = undefined
255 const nodeResponse = () => {
256 if (nodeResponse_ === undefined) {
257 nodeResponse_ = new Http.ServerResponse(nodeRequest)
258 nodeResponse_.assignSocket(socket as any)
259 nodeResponse_.on("finish", () => {
260 socket.end()
261 })
262 }
263 return nodeResponse_
264 }
265 const upgradeEffect = Socket.fromWebSocket(Effect.flatMap(
266 lazyWss,
267 (wss) =>
268 Effect.acquireRelease(
269 Effect.callback<globalThis.WebSocket>((resume) =>
270 wss.handleUpgrade(nodeRequest, socket, head, (ws) => {
271 resume(Effect.succeed(ws as any))
272 })
273 ),
274 (ws) => Effect.sync(() => ws.close())
275 )
276 ))
277 const map = new Map(services.mapUnsafe)
278 map.set(HttpServerRequest.key, new ServerRequestImpl(nodeRequest, nodeResponse, upgradeEffect))
279 const fiber = Fiber.runIn(Effect.runForkWith(Context.makeUnsafe<any>(map))(handledApp), options.scope)
280 socket.on("close", () => {
281 if (!socket.writableEnded) {
282 fiber.interruptUnsafe(parent.id, ClientAbort.annotation)
283 }
284 })
285 })
286 })
287}
288
289class ServerRequestImpl extends NodeHttpIncomingMessage<HttpServerError> implements HttpServerRequest {
290 readonly [Request.TypeId]: typeof Request.TypeId
291 readonly response: Http.ServerResponse | LazyArg<Http.ServerResponse>
292 private upgradeEffect?: Effect.Effect<Socket.Socket, HttpServerError> | undefined
293 readonly url: string
294 private headersOverride?: Headers.Headers | undefined
295
296 constructor(
297 source: Http.IncomingMessage,
298 response: Http.ServerResponse | LazyArg<Http.ServerResponse>,
299 upgradeEffect?: Effect.Effect<Socket.Socket, HttpServerError>,
300 url = source.url!,
301 headersOverride?: Headers.Headers,
302 remoteAddressOverride?: Option.Option<string>
303 ) {
304 super(source, (cause) =>
305 new HttpServerError({
306 reason: new RequestParseError({
307 request: this,
308 cause
309 })
310 }), remoteAddressOverride)
311 this[Request.TypeId] = Request.TypeId
312 this.response = response
313 this.upgradeEffect = upgradeEffect
314 this.url = url
315 this.headersOverride = headersOverride
316 }
317
318 private cachedCookies: Record.ReadonlyRecord<string, string> | undefined
319 get cookies() {
320 if (this.cachedCookies) {
321 return this.cachedCookies
322 }
323 return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? "")
324 }
325
326 get resolvedResponse(): Http.ServerResponse {
327 return typeof this.response === "function" ? this.response() : this.response
328 }
329
330 modify(
331 options: {
332 readonly url?: string | undefined
333 readonly headers?: Headers.Headers | undefined
334 readonly remoteAddress?: Option.Option<string> | undefined
335 }
336 ) {
337 return new ServerRequestImpl(
338 this.source,
339 this.response,
340 this.upgradeEffect,
341 options.url ?? this.url,
342 options.headers ?? this.headersOverride,
343 "remoteAddress" in options ? options.remoteAddress : this.remoteAddressOverride
344 )
345 }
346
347 get originalUrl(): string {
348 return this.source.url!
349 }
350
351 get method(): HttpMethod {
352 return this.source.method!.toUpperCase() as HttpMethod
353 }
354
355 override get headers(): Headers.Headers {
356 this.headersOverride ??= this.source.headers as Headers.Headers
357 return this.headersOverride
358 }
359
360 private multipartEffect:
361 | Effect.Effect<
362 Multipart.Persisted,
363 Multipart.MultipartError,
364 Scope.Scope | FileSystem.FileSystem | Path.Path
365 >
366 | undefined
367 get multipart(): Effect.Effect<
368 Multipart.Persisted,
369 Multipart.MultipartError,
370 Scope.Scope | FileSystem.FileSystem | Path.Path
371 > {
372 if (this.multipartEffect) {
373 return this.multipartEffect
374 }
375 this.multipartEffect = Effect.runSync(Effect.cached(
376 NodeMultipart.persisted(this.source, this.source.headers)
377 ))
378 return this.multipartEffect
379 }
380
381 get multipartStream(): Stream.Stream<Multipart.Part, Multipart.MultipartError> {
382 return NodeMultipart.stream(this.source, this.source.headers)
383 }
384
385 get upgrade(): Effect.Effect<Socket.Socket, HttpServerError> {
386 return this.upgradeEffect ?? Effect.fail(
387 new HttpServerError({
388 reason: new RequestParseError({
389 request: this,
390 description: "not an upgradeable ServerRequest"
391 })
392 })
393 )
394 }
395
396 override toString(): string {
397 return `ServerRequest(${this.method} ${this.url})`
398 }
399
400 toJSON(): unknown {
401 return HttpIncomingMessage.inspect(this, {
402 _id: "HttpServerRequest",
403 method: this.method,
404 url: this.originalUrl
405 })
406 }
407}
408
409/**
410 * Provides an `HttpServer` by creating and managing a scoped Node
411 * `http.Server` with the supplied listen and shutdown options.
412 *
413 * @category layers
414 * @since 4.0.0
415 */
416export const layerServer: (
417 evaluate: LazyArg<Http.Server<typeof Http.IncomingMessage, typeof Http.ServerResponse>>,
418 options: Net.ListenOptions & {
419 readonly disablePreemptiveShutdown?: boolean | undefined
420 readonly gracefulShutdownTimeout?: Duration.Input | undefined
421 }
422) => Layer.Layer<HttpServer.HttpServer, ServeError> = flow(make, Layer.effect(HttpServer.HttpServer))
423
424/**
425 * Provides the Node HTTP support services used by `NodeHttpServer`, including
426 * the HTTP platform, ETag generator, and core Node platform services.
427 *
428 * @category layers
429 * @since 4.0.0
430 */
431export const layerHttpServices: Layer.Layer<
432 NodeServices.NodeServices | HttpPlatform.HttpPlatform | Etag.Generator
433> = Layer.mergeAll(
434 NodeHttpPlatform.layer,
435 Etag.layerWeak,
436 NodeServices.layer
437)
438
439/**
440 * Provides a Node `HttpServer` together with the Node HTTP platform, ETag, and
441 * core platform services required to serve requests.
442 *
443 * @category layers
444 * @since 4.0.0
445 */
446export const layer = (
447 evaluate: LazyArg<Http.Server>,
448 options: Net.ListenOptions & {
449 readonly disablePreemptiveShutdown?: boolean | undefined
450 readonly gracefulShutdownTimeout?: Duration.Input | undefined
451 }
452): Layer.Layer<
453 HttpServer.HttpServer | NodeServices.NodeServices | HttpPlatform.HttpPlatform | Etag.Generator,
454 ServeError
455> =>
456 Layer.mergeAll(
457 layerServer(evaluate, options),
458 layerHttpServices
459 )
460
461/**
462 * Provides a Node `HttpServer` and HTTP support services, reading the listen
463 * and shutdown options from a `Config` value.
464 *
465 * @category layers
466 * @since 4.0.0
467 */
468export const layerConfig = (
469 evaluate: LazyArg<Http.Server>,
470 options: Config.Wrap<
471 Net.ListenOptions & {
472 readonly disablePreemptiveShutdown?: boolean | undefined
473 readonly gracefulShutdownTimeout?: Duration.Input | undefined
474 }
475 >
476): Layer.Layer<
477 HttpServer.HttpServer | FileSystem.FileSystem | Path.Path | HttpPlatform.HttpPlatform | Etag.Generator,
478 ServeError | Config.ConfigError
479> =>
480 Layer.mergeAll(
481 Layer.effect(HttpServer.HttpServer)(
482 Effect.flatMap(Config.unwrap(options), (options) => make(evaluate, options))
483 ),
484 layerHttpServices
485 )
486
487/**
488 * Provides a test HTTP server listening on an ephemeral port together with a
489 * Fetch-backed `HttpClient` configured for server integration tests.
490 *
491 * @category Testing
492 * @since 4.0.0
493 */
494export const layerTest: Layer.Layer<
495 | HttpServer.HttpServer
496 | FileSystem.FileSystem
497 | Path.Path
498 | HttpPlatform.HttpPlatform
499 | Etag.Generator
500 | HttpClient,
501 ServeError,
502 never
503> = HttpServer.layerTestClient.pipe(
504 Layer.provide(
505 Layer.fresh(FetchHttpClient.layer).pipe(
506 Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false }))
507 )
508 ),
509 Layer.provideMerge(layer(Http.createServer, { port: 0 }))
510)
511
512// -----------------------------------------------------------------------------
513// Internal
514// -----------------------------------------------------------------------------
515
516const handleResponse = (
517 request: HttpServerRequest,
518 response: HttpServerResponse
519): Effect.Effect<void, HttpServerError> => {
520 const nodeResponse = (request as ServerRequestImpl).resolvedResponse
521 if (nodeResponse.writableEnded) {
522 return Effect.void
523 }
524
525 let headers: Record<string, string | Array<string>> = response.headers
526 if (!Cookies.isEmpty(response.cookies)) {
527 headers = { ...headers }
528 const toSet = Cookies.toSetCookieHeaders(response.cookies)
529 if (headers["set-cookie"] !== undefined) {
530 toSet.push(headers["set-cookie"] as string)
531 }
532 headers["set-cookie"] = toSet
533 }
534
535 if (request.method === "HEAD") {
536 nodeResponse.writeHead(response.status, headers)
537 return Effect.callback<void>((resume) => {
538 nodeResponse.end(() => resume(Effect.void))
539 })
540 }
541 const body = response.body
542 switch (body._tag) {
543 case "Empty": {
544 nodeResponse.writeHead(response.status, headers)
545 nodeResponse.end()
546 return Effect.void
547 }
548 case "Raw": {
549 nodeResponse.writeHead(response.status, headers)
550 if (
551 typeof body.body === "object" && body.body !== null && "pipe" in body.body &&
552 typeof body.body.pipe === "function"
553 ) {
554 return Effect.tryPromise({
555 try: (signal) => pipeline(body.body as any, nodeResponse, { signal, end: true }),
556 catch: (cause) =>
557 new HttpServerError({
558 reason: new ResponseError({
559 request,
560 response,
561 description: "Error writing raw response",
562 cause
563 })
564 })
565 }).pipe(
566 Effect.interruptible,
567 Effect.tapCause(handleCause(nodeResponse, response))
568 )
569 }
570 return Effect.callback<void>((resume) => {
571 nodeResponse.end(body.body, () => resume(Effect.void))
572 })
573 }
574 case "Uint8Array": {
575 nodeResponse.writeHead(response.status, headers)
576 // If the body is less than 1MB, we skip the callback
577 if (body.body.length < 1024 * 1024) {
578 nodeResponse.end(body.body)
579 return Effect.void
580 }
581 return Effect.callback<void>((resume) => {
582 nodeResponse.end(body.body, () => resume(Effect.void))
583 })
584 }
585 case "FormData": {
586 return Effect.suspend(() => {
587 const r = new globalThis.Response(body.formData)
588 nodeResponse.writeHead(response.status, {
589 ...headers,
590 ...Object.fromEntries(r.headers)
591 })
592 return Effect.callback<void, HttpServerError>((resume, signal) => {
593 Readable.fromWeb(r.body as any, { signal })
594 .pipe(nodeResponse)
595 .on("error", (cause) => {
596 resume(Effect.fail(
597 new HttpServerError({
598 reason: new ResponseError({
599 request,
600 response,
601 description: "Error writing FormData response",
602 cause
603 })
604 })
605 ))
606 })
607 .once("finish", () => {
608 resume(Effect.void)
609 })
610 }).pipe(
611 Effect.interruptible,
612 Effect.tapCause(handleCause(nodeResponse, response))
613 )
614 })
615 }
616 case "Stream": {
617 nodeResponse.writeHead(response.status, headers)
618 const drainLatch = Latch.makeUnsafe()
619 nodeResponse.on("drain", () => drainLatch.openUnsafe())
620 return body.stream.pipe(
621 Stream.orDie,
622 Stream.runForEachArray((array) => {
623 let needDrain = false
624 for (let i = 0; i < array.length; i++) {
625 const written = nodeResponse.write(array[i])
626 if (!written && !needDrain) {
627 needDrain = true
628 drainLatch.closeUnsafe()
629 } else if (written && needDrain) {
630 needDrain = false
631 }
632 }
633 if (!needDrain) return Effect.void
634 return drainLatch.await
635 }),
636 Effect.interruptible,
637 Effect.matchCauseEffect({
638 onSuccess: () => Effect.sync(() => nodeResponse.end()),
639 onFailure: handleCause(nodeResponse, response)
640 })
641 )
642 }
643 }
644}
645
646const handleCause = (
647 nodeResponse: Http.ServerResponse,
648 originalResponse: HttpServerResponse
649) =>
650<E>(originalCause: Cause.Cause<E>) =>
651 Effect.flatMap(causeResponse(originalCause), ([response, cause]) => {
652 const headersSent = nodeResponse.headersSent
653 if (!headersSent) {
654 nodeResponse.writeHead(response.status)
655 }
656 if (!nodeResponse.writableEnded) {
657 nodeResponse.end()
658 }
659 return Effect.failCause(
660 headersSent
661 ? Cause.combine(originalCause, Cause.die(originalResponse))
662 : cause
663 )
664 })