Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NodeHttpServer.ts

652 lines20.8 KB

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