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

NodeHttpClient.ts

664 lines18.9 KB

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