Open History to see the last commit
1/**
2 * Node.js implementations of the Effect `HttpClient`.
3 *
4 * This module supplies Node runtime backends for the platform-independent
5 * Effect HTTP client API. It re-exports the fetch-based client, defines an
6 * Undici-backed client, and defines a lower-level `node:http` / `node:https`
7 * client for integrations that need native agent configuration.
8 *
9 * **Mental model**
10 *
11 * All backends provide the same `HttpClient` service, so application code can
12 * depend on the Effect HTTP client interface while the layer chooses the Node
13 * implementation. The difference is where request execution and connection
14 * ownership live: fetch uses `globalThis.fetch`, Undici sends through a
15 * `Dispatcher`, and the `node:http` backend sends through scoped HTTP and HTTPS
16 * agents.
17 *
18 * **Common tasks**
19 *
20 * Use `layerFetch` when the built-in fetch implementation is enough. Use
21 * `layerUndici` for a scoped Undici `Agent`, or `layerUndiciNoDispatcher` when
22 * the caller provides the `Dispatcher` service, including the process-global
23 * dispatcher from `dispatcherLayerGlobal`. Use `layerNodeHttp` or
24 * `layerAgentOptions` when TLS, proxy, keep-alive, socket, or other native
25 * Node agent options must be configured directly.
26 *
27 * **Gotchas**
28 *
29 * Fetch, Undici, and `node:http` are not exact substitutes. They differ in
30 * dispatcher and agent hooks, request body support, abort behavior, upgrade
31 * support, and response body readers. Scoped layers destroy the agents or
32 * dispatchers they create when the layer scope ends; `dispatcherLayerGlobal`
33 * intentionally does not own or destroy Undici's process-global dispatcher.
34 * Body read failures are reported as `HttpClientError` decode or transport
35 * errors.
36 *
37 * @since 4.0.0
38 */
39import * as Context from "effect/Context"
40import * as Effect from "effect/Effect"
41import { flow } from "effect/Function"
42import * as Inspectable from "effect/Inspectable"
43import * as Layer from "effect/Layer"
44import * as Option from "effect/Option"
45import { type Pipeable, pipeArguments } from "effect/Pipeable"
46import type * as Schema from "effect/Schema"
47import type * as Scope from "effect/Scope"
48import * as Stream from "effect/Stream"
49import * as Cookies from "effect/unstable/http/Cookies"
50import * as Headers from "effect/unstable/http/Headers"
51import type * as Body from "effect/unstable/http/HttpBody"
52import * as Client from "effect/unstable/http/HttpClient"
53import * as Error from "effect/unstable/http/HttpClientError"
54import type { HttpClientRequest } from "effect/unstable/http/HttpClientRequest"
55import * as Response from "effect/unstable/http/HttpClientResponse"
56import type { HttpClientResponse } from "effect/unstable/http/HttpClientResponse"
57import * as IncomingMessage from "effect/unstable/http/HttpIncomingMessage"
58import * as UrlParams from "effect/unstable/http/UrlParams"
59import * as Http from "node:http"
60import * as Https from "node:https"
61import { Readable } from "node:stream"
62import { pipeline } from "node:stream/promises"
63import { NodeHttpIncomingMessage } from "./NodeHttpIncomingMessage.ts"
64import * as NodeSink from "./NodeSink.ts"
65import * as NodeStream from "./NodeStream.ts"
66import * as Undici from "./Undici.ts"
67
68// -----------------------------------------------------------------------------
69// Fetch
70// -----------------------------------------------------------------------------
71
72export {
73 /**
74 * Provides a fetch-based HTTP client implementation for Node.js.
75 *
76 * **When to use**
77 *
78 * Use to access or override the fetch implementation used by the Node
79 * fetch-based HTTP client.
80 *
81 * @category fetch
82 * @since 4.0.0
83 */
84 Fetch,
85 /**
86 * Layer that provides the fetch-based HTTP client implementation.
87 *
88 * @category Fetch
89 * @since 4.0.0
90 */
91 layer as layerFetch,
92 /**
93 * Provides request initialization options accepted by the fetch-based HTTP client.
94 *
95 * **When to use**
96 *
97 * Use to provide default fetch request options for Node HTTP requests.
98 *
99 * @category fetch
100 * @since 4.0.0
101 */
102 RequestInit
103} from "effect/unstable/http/FetchHttpClient"
104
105// -----------------------------------------------------------------------------
106// Undici
107// -----------------------------------------------------------------------------
108
109/**
110 * Service tag for the Undici `Dispatcher` used by the Undici-backed HTTP
111 * client.
112 *
113 * @category Dispatcher
114 * @since 4.0.0
115 */
116export class Dispatcher extends Context.Service<Dispatcher, Undici.Dispatcher>()(
117 "@effect/platform-node/NodeHttpClient/Dispatcher"
118) {}
119
120/**
121 * Acquires a new Undici `Agent` dispatcher and destroys it when the enclosing
122 * scope is finalized.
123 *
124 * @category Dispatcher
125 * @since 4.0.0
126 */
127export const makeDispatcher: Effect.Effect<Undici.Dispatcher, never, Scope.Scope> = Effect.acquireRelease(
128 Effect.sync(() => new Undici.Agent()),
129 (dispatcher) => Effect.promise(() => dispatcher.destroy())
130)
131
132/**
133 * Provides the `Dispatcher` service using a scoped Undici `Agent`.
134 *
135 * @category Dispatcher
136 * @since 4.0.0
137 */
138export const layerDispatcher: Layer.Layer<Dispatcher> = Layer.effect(Dispatcher)(makeDispatcher)
139
140/**
141 * Provides the `Dispatcher` service from Undici's process-global dispatcher,
142 * without creating or owning a new agent.
143 *
144 * @category Dispatcher
145 * @since 4.0.0
146 */
147export const dispatcherLayerGlobal: Layer.Layer<Dispatcher> = Layer.sync(Dispatcher)(() => Undici.getGlobalDispatcher())
148
149/**
150 * Fiber reference containing default Undici request options applied to requests
151 * sent by `makeUndici`.
152 *
153 * @category undici
154 * @since 4.0.0
155 */
156export const UndiciOptions = Context.Reference<Partial<Undici.Dispatcher.RequestOptions>>(
157 "@effect/platform-node/NodeHttpClient/UndiciOptions",
158 { defaultValue: () => ({}) }
159)
160
161/**
162 * Creates an `HttpClient` that sends requests through the current Undici
163 * `Dispatcher`, converts Effect HTTP bodies to Undici bodies, and maps
164 * transport and decode failures to `HttpClientError`.
165 *
166 * @category undici
167 * @since 4.0.0
168 */
169export const makeUndici = Effect.gen(function*() {
170 const dispatcher = yield* Dispatcher
171 return Client.make((request, url, signal, fiber) =>
172 convertBody(request.body).pipe(
173 Effect.flatMap((body) =>
174 Effect.tryPromise({
175 try: () =>
176 dispatcher.request({
177 ...fiber.getRef(UndiciOptions),
178 signal,
179 method: request.method,
180 headers: request.headers,
181 origin: url.origin,
182 path: url.pathname + url.search + url.hash,
183 body,
184 // leave timeouts to Effect.timeout etc
185 headersTimeout: 60 * 60 * 1000,
186 bodyTimeout: 0
187 }),
188 catch: (cause) =>
189 new Error.HttpClientError({
190 reason: new Error.TransportError({
191 request,
192 cause
193 })
194 })
195 })
196 ),
197 Effect.map((response) => new UndiciResponse(request, response))
198 )
199 )
200})
201
202function convertBody(
203 body: Body.HttpBody
204): Effect.Effect<Exclude<Undici.Dispatcher.DispatchOptions["body"], undefined>> {
205 switch (body._tag) {
206 case "Empty": {
207 return Effect.succeed(null)
208 }
209 case "Uint8Array":
210 case "Raw": {
211 return Effect.succeed(body.body as Uint8Array)
212 }
213 case "FormData": {
214 return Effect.succeed(body.formData as any)
215 }
216 case "Stream": {
217 return NodeStream.toReadable(body.stream)
218 }
219 }
220}
221
222function noopErrorHandler(_: any) {}
223
224class UndiciResponse extends Inspectable.Class implements HttpClientResponse, Pipeable {
225 readonly [IncomingMessage.TypeId]: typeof IncomingMessage.TypeId
226 readonly [Response.TypeId]: typeof Response.TypeId
227 readonly request: HttpClientRequest
228 readonly source: Undici.Dispatcher.ResponseData
229
230 constructor(
231 request: HttpClientRequest,
232 source: Undici.Dispatcher.ResponseData
233 ) {
234 super()
235 this[IncomingMessage.TypeId] = IncomingMessage.TypeId
236 this[Response.TypeId] = Response.TypeId
237 this.request = request
238 this.source = source
239 source.body.on("error", noopErrorHandler)
240 }
241
242 get status() {
243 return this.source.statusCode!
244 }
245
246 get statusText() {
247 return undefined
248 }
249
250 get headers(): Headers.Headers {
251 return Headers.fromInput(this.source.headers)
252 }
253
254 cachedCookies?: Cookies.Cookies
255 get cookies(): Cookies.Cookies {
256 if (this.cachedCookies !== undefined) {
257 return this.cachedCookies
258 }
259 const header = this.source.headers["set-cookie"]
260 return this.cachedCookies = header ? Cookies.fromSetCookie(header) : Cookies.empty
261 }
262
263 get remoteAddress(): Option.Option<string> {
264 return Option.none()
265 }
266
267 get stream(): Stream.Stream<Uint8Array, Error.HttpClientError> {
268 return NodeStream.fromReadable({
269 evaluate: () => this.source.body,
270 onError: (cause) =>
271 new Error.HttpClientError({
272 reason: new Error.DecodeError({
273 request: this.request,
274 response: this,
275 cause
276 })
277 })
278 })
279 }
280
281 get json(): Effect.Effect<Schema.Json, Error.HttpClientError> {
282 return Effect.flatMap(this.text, (text) =>
283 Effect.try({
284 try: () => text === "" ? null : JSON.parse(text),
285 catch: (cause) =>
286 new Error.HttpClientError({
287 reason: new Error.DecodeError({
288 request: this.request,
289 response: this,
290 cause
291 })
292 })
293 }))
294 }
295
296 private textBody?: Effect.Effect<string, Error.HttpClientError>
297 get text(): Effect.Effect<string, Error.HttpClientError> {
298 if (this.textBody) {
299 return this.textBody
300 }
301 this.textBody = Effect.tryPromise({
302 try: () => this.source.body.text(),
303 catch: (cause) =>
304 new Error.HttpClientError({
305 reason: new Error.DecodeError({
306 request: this.request,
307 response: this,
308 cause
309 })
310 })
311 }).pipe(Effect.cached, Effect.runSync)
312 this.arrayBufferBody = Effect.map(this.textBody, (_) => new TextEncoder().encode(_).buffer)
313 return this.textBody
314 }
315
316 get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, Error.HttpClientError> {
317 return Effect.flatMap(this.text, (_) =>
318 Effect.try({
319 try: () => UrlParams.fromInput(new URLSearchParams(_)),
320 catch: (cause) =>
321 new Error.HttpClientError({
322 reason: new Error.DecodeError({
323 request: this.request,
324 response: this,
325 cause
326 })
327 })
328 }))
329 }
330
331 private formDataBody?: Effect.Effect<FormData, Error.HttpClientError>
332 get formData(): Effect.Effect<FormData, Error.HttpClientError> {
333 return this.formDataBody ??= Effect.tryPromise({
334 try: () => this.source.body.formData() as Promise<FormData>,
335 catch: (cause) =>
336 new Error.HttpClientError({
337 reason: new Error.DecodeError({
338 request: this.request,
339 response: this,
340 cause
341 })
342 })
343 }).pipe(Effect.cached, Effect.runSync)
344 }
345
346 private arrayBufferBody?: Effect.Effect<ArrayBuffer, Error.HttpClientError>
347 get arrayBuffer(): Effect.Effect<ArrayBuffer, Error.HttpClientError> {
348 if (this.arrayBufferBody) {
349 return this.arrayBufferBody
350 }
351 this.arrayBufferBody = Effect.tryPromise({
352 try: () => this.source.body.arrayBuffer(),
353 catch: (cause) =>
354 new Error.HttpClientError({
355 reason: new Error.DecodeError({
356 request: this.request,
357 response: this,
358 cause
359 })
360 })
361 }).pipe(Effect.cached, Effect.runSync)
362 this.textBody = Effect.map(this.arrayBufferBody, (_) => new TextDecoder().decode(_))
363 return this.arrayBufferBody
364 }
365
366 toJSON(): unknown {
367 return IncomingMessage.inspect(this, {
368 _id: "effect/http/HttpClientResponse",
369 request: this.request.toJSON(),
370 status: this.status
371 })
372 }
373
374 pipe() {
375 return pipeArguments(this, arguments)
376 }
377}
378
379/**
380 * Provides an Undici-backed `HttpClient` using the current `Dispatcher`
381 * service.
382 *
383 * @category Undici
384 * @since 4.0.0
385 */
386export const layerUndiciNoDispatcher: Layer.Layer<
387 Client.HttpClient,
388 never,
389 Dispatcher
390> = Client.layerMergedContext(makeUndici)
391
392/**
393 * Provides an Undici-backed `HttpClient` together with a scoped default
394 * Undici `Agent` dispatcher.
395 *
396 * @category Undici
397 * @since 4.0.0
398 */
399export const layerUndici: Layer.Layer<Client.HttpClient> = Layer.provide(layerUndiciNoDispatcher, layerDispatcher)
400
401// -----------------------------------------------------------------------------
402// node:http
403// -----------------------------------------------------------------------------
404
405/**
406 * Service tag for the paired Node `http` and `https` agents used by the
407 * node:http-backed HTTP client.
408 *
409 * @category HttpAgent
410 * @since 4.0.0
411 */
412export class HttpAgent extends Context.Service<HttpAgent, {
413 readonly http: Http.Agent
414 readonly https: Https.Agent
415}>()("@effect/platform-node/NodeHttpClient/HttpAgent") {}
416
417/**
418 * Acquires Node `http` and `https` agents with the supplied options and
419 * destroys both agents when the enclosing scope is finalized.
420 *
421 * @category HttpAgent
422 * @since 4.0.0
423 */
424export const makeAgent = (options?: Https.AgentOptions): Effect.Effect<HttpAgent["Service"], never, Scope.Scope> =>
425 Effect.zipWith(
426 Effect.acquireRelease(
427 Effect.sync(() => new Http.Agent(options)),
428 (agent) => Effect.sync(() => agent.destroy())
429 ),
430 Effect.acquireRelease(
431 Effect.sync(() => new Https.Agent(options)),
432 (agent) => Effect.sync(() => agent.destroy())
433 ),
434 (http, https) => ({ http, https })
435 )
436
437/**
438 * Provides the `HttpAgent` service using scoped Node `http` and `https`
439 * agents configured with the supplied options.
440 *
441 * @category HttpAgent
442 * @since 4.0.0
443 */
444export const layerAgentOptions: (options?: Https.AgentOptions | undefined) => Layer.Layer<
445 HttpAgent
446> = flow(makeAgent, Layer.effect(HttpAgent))
447
448/**
449 * Provides the `HttpAgent` service using default scoped Node `http` and
450 * `https` agents.
451 *
452 * @category HttpAgent
453 * @since 4.0.0
454 */
455export const layerAgent: Layer.Layer<HttpAgent> = layerAgentOptions()
456
457/**
458 * Creates an `HttpClient` backed by Node `http` and `https`, using the
459 * current `HttpAgent`, streaming request bodies, and wrapping Node responses
460 * as `HttpClientResponse` values.
461 *
462 * @category node:http
463 * @since 4.0.0
464 */
465export const makeNodeHttp = Effect.gen(function*() {
466 const agent = yield* HttpAgent
467 return Client.make((request, url, signal) => {
468 const nodeRequest = url.protocol === "https:" ?
469 Https.request(url, {
470 agent: agent.https,
471 method: request.method,
472 headers: request.headers,
473 signal
474 }) :
475 Http.request(url, {
476 agent: agent.http,
477 method: request.method,
478 headers: request.headers,
479 signal
480 })
481 return Effect.forkChild(sendBody(nodeRequest, request, request.body)).pipe(
482 Effect.flatMap(() => waitForResponse(nodeRequest, request)),
483 Effect.map((_) => new NodeHttpResponse(request, _))
484 )
485 })
486})
487
488const sendBody = (
489 nodeRequest: Http.ClientRequest,
490 request: HttpClientRequest,
491 body: Body.HttpBody
492): Effect.Effect<void, Error.HttpClientError> =>
493 Effect.suspend((): Effect.Effect<void, Error.HttpClientError> => {
494 switch (body._tag) {
495 case "Empty": {
496 nodeRequest.end()
497 return waitForFinish(nodeRequest, request)
498 }
499 case "Uint8Array":
500 case "Raw": {
501 nodeRequest.end(body.body)
502 return waitForFinish(nodeRequest, request)
503 }
504 case "FormData": {
505 const response = new globalThis.Response(body.formData)
506
507 response.headers.forEach((value, key) => {
508 nodeRequest.setHeader(key, value)
509 })
510
511 return Effect.tryPromise({
512 try: () => pipeline(Readable.fromWeb(response.body! as any), nodeRequest),
513 catch: (cause) =>
514 new Error.HttpClientError({
515 reason: new Error.TransportError({
516 request,
517 cause
518 })
519 })
520 })
521 }
522 case "Stream": {
523 return Stream.run(
524 Stream.mapError(body.stream, (cause) =>
525 new Error.HttpClientError({
526 reason: new Error.EncodeError({
527 request,
528 cause
529 })
530 })),
531 NodeSink.fromWritable({
532 evaluate: () => nodeRequest,
533 onError: (cause) =>
534 new Error.HttpClientError({
535 reason: new Error.TransportError({
536 request,
537 cause
538 })
539 })
540 })
541 )
542 }
543 }
544 })
545
546const waitForResponse = (nodeRequest: Http.ClientRequest, request: HttpClientRequest) =>
547 Effect.callback<Http.IncomingMessage, Error.HttpClientError>((resume) => {
548 function onError(cause: Error) {
549 resume(Effect.fail(
550 new Error.HttpClientError({
551 reason: new Error.TransportError({
552 request,
553 cause
554 })
555 })
556 ))
557 }
558 nodeRequest.on("error", onError)
559
560 function onResponse(response: Http.IncomingMessage) {
561 nodeRequest.off("error", onError)
562 resume(Effect.succeed(response))
563 }
564 nodeRequest.on("upgrade", onResponse)
565 nodeRequest.on("response", onResponse)
566
567 return Effect.sync(() => {
568 nodeRequest.off("error", onError)
569 nodeRequest.off("upgrade", onResponse)
570 nodeRequest.off("response", onResponse)
571 })
572 })
573
574const waitForFinish = (nodeRequest: Http.ClientRequest, request: HttpClientRequest) =>
575 Effect.callback<void, Error.HttpClientError>((resume) => {
576 function onError(cause: Error) {
577 resume(Effect.fail(
578 new Error.HttpClientError({
579 reason: new Error.TransportError({
580 request,
581 cause
582 })
583 })
584 ))
585 }
586 nodeRequest.once("error", onError)
587
588 function onFinish() {
589 nodeRequest.off("error", onError)
590 resume(Effect.void)
591 }
592 nodeRequest.once("finish", onFinish)
593
594 return Effect.sync(() => {
595 nodeRequest.off("error", onError)
596 nodeRequest.off("finish", onFinish)
597 })
598 })
599
600class NodeHttpResponse extends NodeHttpIncomingMessage<Error.HttpClientError> implements HttpClientResponse, Pipeable {
601 readonly [Response.TypeId]: typeof Response.TypeId
602 readonly request: HttpClientRequest
603
604 constructor(
605 request: HttpClientRequest,
606 source: Http.IncomingMessage
607 ) {
608 super(source, (cause) =>
609 new Error.HttpClientError({
610 reason: new Error.DecodeError({
611 request,
612 response: this,
613 cause
614 })
615 }))
616 this[Response.TypeId] = Response.TypeId
617 this.request = request
618 }
619
620 get status() {
621 return this.source.statusCode!
622 }
623
624 cachedCookies?: Cookies.Cookies
625 get cookies(): Cookies.Cookies {
626 if (this.cachedCookies !== undefined) {
627 return this.cachedCookies
628 }
629 const header = this.source.headers["set-cookie"]
630 return this.cachedCookies = header ? Cookies.fromSetCookie(header) : Cookies.empty
631 }
632
633 get formData(): Effect.Effect<FormData, Error.HttpClientError> {
634 return Effect.tryPromise({
635 try: () => {
636 const init: {
637 headers: HeadersInit
638 status?: number
639 statusText?: string
640 } = {
641 headers: new globalThis.Headers(this.source.headers as any)
642 }
643
644 if (this.source.statusCode) {
645 init.status = this.source.statusCode
646 }
647
648 if (this.source.statusMessage) {
649 init.statusText = this.source.statusMessage
650 }
651
652 return new globalThis.Response(Readable.toWeb(this.source) as any, init).formData()
653 },
654 catch: this.onError
655 })
656 }
657
658 toJSON(): unknown {
659 return IncomingMessage.inspect(this, {
660 _id: "effect/http/HttpClientResponse",
661 request: this.request.toJSON(),
662 status: this.status
663 })
664 }
665
666 pipe() {
667 return pipeArguments(this, arguments)
668 }
669}
670
671/**
672 * Provides a node:http-backed `HttpClient` using the current `HttpAgent`
673 * service.
674 *
675 * @category node:http
676 * @since 4.0.0
677 */
678export const layerNodeHttpNoAgent: Layer.Layer<
679 Client.HttpClient,
680 never,
681 HttpAgent
682> = Client.layerMergedContext(makeNodeHttp)
683
684/**
685 * Provides a node:http-backed `HttpClient` together with default scoped Node
686 * `http` and `https` agents.
687 *
688 * @category node:http
689 * @since 4.0.0
690 */
691export const layerNodeHttp: Layer.Layer<Client.HttpClient> = Layer.provide(layerNodeHttpNoAgent, layerAgent)