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

NodeHttpIncomingMessage.ts

156 lines4.9 KB

1/**
2 * Adapter base for exposing Node `http.IncomingMessage` values as Effect HTTP
3 * incoming messages.
4 *
5 * Server requests and Node client responses both arrive as Node readable
6 * streams with raw header objects, socket metadata, and one-shot body
7 * consumption. This module's `NodeHttpIncomingMessage` class keeps the original
8 * Node message available while presenting Effect's `HttpIncomingMessage` shape:
9 * typed headers, remote address lookup, stream access, and text, JSON,
10 * URL-encoded, and array-buffer body readers.
11 *
12 * **Mental model**
13 *
14 * The Node message remains the source of truth. The adapter translates headers
15 * and remote address on demand, delegates raw streaming to `NodeStream`, and
16 * lets subclasses choose how unknown Node errors are mapped into their HTTP
17 * error type.
18 *
19 * **Gotchas**
20 *
21 * Node request and response bodies are one-shot streams. The `text` and
22 * `arrayBuffer` readers are cached and share decoded values with each other,
23 * but direct `stream` access is not cached and can consume the underlying Node
24 * stream before a decoder reads it. Body readers honor
25 * `HttpIncomingMessage.MaxBodySize`.
26 *
27 * @since 4.0.0
28 */
29import * as Effect from "effect/Effect"
30import * as Inspectable from "effect/Inspectable"
31import * as Option from "effect/Option"
32import type * as Schema from "effect/Schema"
33import type * as Stream from "effect/Stream"
34import * as Headers from "effect/unstable/http/Headers"
35import * as IncomingMessage from "effect/unstable/http/HttpIncomingMessage"
36import * as UrlParams from "effect/unstable/http/UrlParams"
37import type * as Http from "node:http"
38import * as NodeStream from "./NodeStream.ts"
39​
40/**
41 * Adapts a Node `IncomingMessage` to Effect HTTP incoming messages.
42 *
43 * **When to use**
44 *
45 * Use to implement Node HTTP request or response adapters that expose the
46 * Effect HTTP incoming-message interface.
47 *
48 * **Details**
49 *
50 * The adapter exposes headers, remote address, stream access, and cached body
51 * decoders. Subclasses provide the error mapping for unknown Node errors.
52 *
53 * @category constructors
54 * @since 4.0.0
55 */
56export abstract class NodeHttpIncomingMessage<E> extends Inspectable.Class
57 implements IncomingMessage.HttpIncomingMessage<E>
59 /**
60 * Marks this value as an HTTP incoming message for runtime guards.
61 *
62 * @since 4.0.0
63 */
64 readonly [IncomingMessage.TypeId]: typeof IncomingMessage.TypeId
65 readonly source: Http.IncomingMessage
66 readonly onError: (error: unknown) => E
67 readonly remoteAddressOverride?: Option.Option<string> | undefined
68​
69 constructor(
70 source: Http.IncomingMessage,
71 onError: (error: unknown) => E,
72 remoteAddressOverride?: Option.Option<string>
73 ) {
74 super()
75 this[IncomingMessage.TypeId] = IncomingMessage.TypeId
76 this.source = source
77 this.onError = onError
78 this.remoteAddressOverride = remoteAddressOverride
79 }
80​
81 get headers() {
82 return Headers.fromInput(this.source.headers as any)
83 }
84​
85 get remoteAddress() {
86 return this.remoteAddressOverride ?? Option.fromNullishOr(this.source.socket.remoteAddress)
87 }
88​
89 private textEffect: Effect.Effect<string, E> | undefined
90 get text(): Effect.Effect<string, E> {
91 if (this.textEffect) {
92 return this.textEffect
93 }
94 this.textEffect = Effect.runSync(Effect.cached(
95 Effect.flatMap(
96 IncomingMessage.MaxBodySize,
97 (maxBodySize) =>
98 NodeStream.toString(() => this.source, {
99 onError: this.onError,
100 maxBytes: maxBodySize
101 })
102 )
103 ))
104 this.arrayBufferEffect = Effect.map(this.textEffect, (_) => new TextEncoder().encode(_).buffer)
105 return this.textEffect
106 }
107​
108 get textUnsafe(): string {
109 return Effect.runSync(this.text)
110 }
111​
112 get json(): Effect.Effect<Schema.Json, E> {
113 return Effect.flatMap(this.text, (text) =>
114 Effect.try({
115 try: () => text === "" ? null : JSON.parse(text),
116 catch: this.onError
117 }))
118 }
119​
120 get jsonUnsafe(): Schema.Json {
121 return Effect.runSync(this.json)
122 }
123​
124 get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, E> {
125 return Effect.flatMap(this.text, (_) =>
126 Effect.try({
127 try: () => UrlParams.fromInput(new URLSearchParams(_)),
128 catch: this.onError
129 }))
130 }
131​
132 get stream(): Stream.Stream<Uint8Array, E> {
133 return NodeStream.fromReadable({
134 evaluate: () => this.source,
135 onError: this.onError
136 })
137 }
138​
139 private arrayBufferEffect: Effect.Effect<ArrayBuffer, E> | undefined
140 get arrayBuffer(): Effect.Effect<ArrayBuffer, E> {
141 if (this.arrayBufferEffect) {
142 return this.arrayBufferEffect
143 }
144 this.arrayBufferEffect = Effect.withFiber((fiber) =>
145 NodeStream.toArrayBuffer(() => this.source, {
146 onError: this.onError,
147 maxBytes: fiber.getRef(IncomingMessage.MaxBodySize)
148 })
149 ).pipe(
150 Effect.cached,
151 Effect.runSync
152 )
153 this.textEffect = Effect.map(this.arrayBufferEffect, (_) => new TextDecoder().decode(_))
154 return this.arrayBufferEffect
155 }