-
Notifications
You must be signed in to change notification settings - Fork 47
/
listener.ts
225 lines (205 loc) · 7 KB
/
listener.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import type { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http'
import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2'
import {
getAbortController,
newRequest,
Request as LightweightRequest,
toRequestError,
} from './request'
import { cacheKey, getInternalBody, Response as LightweightResponse } from './response'
import type { CustomErrorHandler, FetchCallback, HttpBindings } from './types'
import { writeFromReadableStream, buildOutgoingHttpHeaders } from './utils'
import { X_ALREADY_SENT } from './utils/response/constants'
import './globals'
const regBuffer = /^no$/i
const regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i
const handleRequestError = (): Response =>
new Response(null, {
status: 400,
})
const handleFetchError = (e: unknown): Response =>
new Response(null, {
status:
e instanceof Error && (e.name === 'TimeoutError' || e.constructor.name === 'TimeoutError')
? 504 // timeout error emits 504 timeout
: 500,
})
const handleResponseError = (e: unknown, outgoing: ServerResponse | Http2ServerResponse) => {
const err = (e instanceof Error ? e : new Error('unknown error', { cause: e })) as Error & {
code: string
}
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
console.info('The user aborted a request.')
} else {
console.error(e)
if (!outgoing.headersSent) {
outgoing.writeHead(500, { 'Content-Type': 'text/plain' })
}
outgoing.end(`Error: ${err.message}`)
outgoing.destroy(err)
}
}
const responseViaCache = (
res: Response,
outgoing: ServerResponse | Http2ServerResponse
): undefined | Promise<undefined> => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [status, body, header] = (res as any)[cacheKey]
if (typeof body === 'string') {
header['Content-Length'] = Buffer.byteLength(body)
outgoing.writeHead(status, header)
outgoing.end(body)
} else {
outgoing.writeHead(status, header)
return writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing) as undefined
)
}
}
const responseViaResponseObject = async (
res: Response | Promise<Response>,
outgoing: ServerResponse | Http2ServerResponse,
options: { errorHandler?: CustomErrorHandler } = {}
) => {
if (res instanceof Promise) {
if (options.errorHandler) {
try {
res = await res
} catch (err) {
const errRes = await options.errorHandler(err)
if (!errRes) {
return
}
res = errRes
}
} else {
res = await res.catch(handleFetchError)
}
}
if (cacheKey in res) {
return responseViaCache(res as Response, outgoing)
}
const resHeaderRecord: OutgoingHttpHeaders = buildOutgoingHttpHeaders(res.headers)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const internalBody = getInternalBody(res as any)
if (internalBody) {
const { length, source, stream } = internalBody
if (source instanceof Uint8Array && source.byteLength !== length) {
// maybe `source` is detached, so we should send via res.body
} else {
// send via internal raw data
if (length) {
resHeaderRecord['content-length'] = length
}
outgoing.writeHead(res.status, resHeaderRecord)
if (typeof source === 'string' || source instanceof Uint8Array) {
outgoing.end(source)
} else if (source instanceof Blob) {
outgoing.end(new Uint8Array(await source.arrayBuffer()))
} else {
await writeFromReadableStream(stream, outgoing)
}
return
}
}
if (res.body) {
/**
* If content-encoding is set, we assume that the response should be not decoded.
* Else if transfer-encoding is set, we assume that the response should be streamed.
* Else if content-length is set, we assume that the response content has been taken care of.
* Else if x-accel-buffering is set to no, we assume that the response should be streamed.
* Else if content-type is not application/json nor text/* but can be text/event-stream,
* we assume that the response should be streamed.
*/
const {
'transfer-encoding': transferEncoding,
'content-encoding': contentEncoding,
'content-length': contentLength,
'x-accel-buffering': accelBuffering,
'content-type': contentType,
} = resHeaderRecord
if (
transferEncoding ||
contentEncoding ||
contentLength ||
// nginx buffering variant
(accelBuffering && regBuffer.test(accelBuffering as string)) ||
!regContentType.test(contentType as string)
) {
outgoing.writeHead(res.status, resHeaderRecord)
await writeFromReadableStream(res.body, outgoing)
} else {
const buffer = await res.arrayBuffer()
resHeaderRecord['content-length'] = buffer.byteLength
outgoing.writeHead(res.status, resHeaderRecord)
outgoing.end(new Uint8Array(buffer))
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
// do nothing, the response has already been sent
} else {
outgoing.writeHead(res.status, resHeaderRecord)
outgoing.end()
}
}
export const getRequestListener = (
fetchCallback: FetchCallback,
options: {
hostname?: string
errorHandler?: CustomErrorHandler
overrideGlobalObjects?: boolean
} = {}
) => {
if (options.overrideGlobalObjects !== false && global.Request !== LightweightRequest) {
Object.defineProperty(global, 'Request', {
value: LightweightRequest,
})
Object.defineProperty(global, 'Response', {
value: LightweightResponse,
})
}
return async (
incoming: IncomingMessage | Http2ServerRequest,
outgoing: ServerResponse | Http2ServerResponse
) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let res, req: any
try {
// `fetchCallback()` requests a Request object, but global.Request is expensive to generate,
// so generate a pseudo Request object with only the minimum required information.
req = newRequest(incoming, options.hostname)
// Detect if request was aborted.
outgoing.on('close', () => {
if (incoming.errored) {
req[getAbortController]().abort(incoming.errored.toString())
}
})
res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as
| Response
| Promise<Response>
if (cacheKey in res) {
// synchronous, cacheable response
return responseViaCache(res as Response, outgoing)
}
} catch (e: unknown) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e))
if (!res) {
return
}
} else if (!req) {
res = handleRequestError()
} else {
res = handleFetchError(e)
}
} else {
return handleResponseError(e, outgoing)
}
}
try {
return responseViaResponseObject(res, outgoing, options)
} catch (e) {
return handleResponseError(e, outgoing)
}
}
}