forked from fastify/fastify
/
reply.js
648 lines (563 loc) · 16.8 KB
/
reply.js
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
'use strict'
const eos = require('stream').finished
const {
kFourOhFourContext,
kReplyErrorHandlerCalled,
kReplyHijacked,
kReplyStartTime,
kReplyEndTime,
kReplySerializer,
kReplySerializerDefault,
kReplyIsError,
kReplyHeaders,
kReplyHasStatusCode,
kReplyIsRunningOnErrorHook,
kReplyNextErrorHandler,
kDisableRequestLogging
} = require('./symbols.js')
const { hookRunner, hookIterator, onSendHookRunner } = require('./hooks')
const internals = require('./handleRequest')[Symbol.for('internals')]
const loggerUtils = require('./logger')
const now = loggerUtils.now
const { handleError } = require('./error-handler')
const { getSchemaSerializer } = require('./schemas')
const CONTENT_TYPE = {
JSON: 'application/json; charset=utf-8',
PLAIN: 'text/plain; charset=utf-8',
OCTET: 'application/octet-stream'
}
const {
FST_ERR_REP_INVALID_PAYLOAD_TYPE,
FST_ERR_REP_ALREADY_SENT,
FST_ERR_REP_SENT_VALUE,
FST_ERR_SEND_INSIDE_ONERR,
FST_ERR_BAD_STATUS_CODE
} = require('./errors')
const warning = require('./warnings')
function Reply (res, request, log) {
this.raw = res
this[kReplySerializer] = null
this[kReplyErrorHandlerCalled] = false
this[kReplyIsError] = false
this[kReplyIsRunningOnErrorHook] = false
this.request = request
this[kReplyHeaders] = {}
this[kReplyHasStatusCode] = false
this[kReplyStartTime] = undefined
this.log = log
}
Reply.props = []
Object.defineProperties(Reply.prototype, {
context: {
get () {
return this.request.context
}
},
server: {
get () {
return this.request.context.server
}
},
sent: {
enumerable: true,
get () {
// We are checking whether reply was hijacked or the response has ended.
return (this[kReplyHijacked] || this.raw.writableEnded) === true
},
set (value) {
warning.emit('FSTDEP010')
if (value !== true) {
throw new FST_ERR_REP_SENT_VALUE()
}
// We throw only if sent was overwritten from Fastify
if (this.sent && this[kReplyHijacked]) {
throw new FST_ERR_REP_ALREADY_SENT()
}
this[kReplyHijacked] = true
}
},
statusCode: {
get () {
return this.raw.statusCode
},
set (value) {
this.code(value)
}
}
})
Reply.prototype.hijack = function () {
this[kReplyHijacked] = true
return this
}
Reply.prototype.send = function (payload) {
if (this[kReplyIsRunningOnErrorHook] === true) {
throw new FST_ERR_SEND_INSIDE_ONERR()
}
if (this.sent) {
this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT() }, 'Reply already sent')
return this
}
if (payload instanceof Error || this[kReplyIsError] === true) {
this[kReplyIsError] = false
onErrorHook(this, payload, onSendHook)
return this
}
if (payload === undefined) {
onSendHook(this, payload)
return this
}
const contentType = this.getHeader('content-type')
const hasContentType = contentType !== undefined
if (payload !== null) {
if (typeof payload.pipe === 'function') {
onSendHook(this, payload)
return this
}
if (Buffer.isBuffer(payload)) {
if (hasContentType === false) {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.OCTET
}
onSendHook(this, payload)
return this
}
if (hasContentType === false && typeof payload === 'string') {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.PLAIN
onSendHook(this, payload)
return this
}
}
if (this[kReplySerializer] !== null) {
if (typeof payload !== 'string') {
preserializeHook(this, payload)
return this
} else {
payload = this[kReplySerializer](payload)
}
// The indexOf below also matches custom json mimetypes such as 'application/hal+json' or 'application/ld+json'
} else if (hasContentType === false || contentType.indexOf('json') > -1) {
if (hasContentType === false) {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.JSON
} else {
// If hasContentType === true, we have a JSON mimetype
if (contentType.indexOf('charset') === -1) {
// If we have simply application/json instead of a custom json mimetype
if (contentType.indexOf('/json') > -1) {
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.JSON
} else {
const currContentType = this[kReplyHeaders]['content-type']
// We extract the custom mimetype part (e.g. 'hal+' from 'application/hal+json')
const customJsonType = currContentType.substring(
currContentType.indexOf('/'),
currContentType.indexOf('json') + 4
)
// We ensure we set the header to the proper JSON content-type if necessary
// (e.g. 'application/hal+json' instead of 'application/json')
this[kReplyHeaders]['content-type'] = CONTENT_TYPE.JSON.replace('/json', customJsonType)
}
}
}
if (typeof payload !== 'string') {
preserializeHook(this, payload)
return this
}
}
onSendHook(this, payload)
return this
}
Reply.prototype.getHeader = function (key) {
key = key.toLowerCase()
const res = this.raw
let value = this[kReplyHeaders][key]
if (value === undefined && res.hasHeader(key)) {
value = res.getHeader(key)
}
return value
}
Reply.prototype.getHeaders = function () {
return {
...this.raw.getHeaders(),
...this[kReplyHeaders]
}
}
Reply.prototype.hasHeader = function (key) {
key = key.toLowerCase()
if (this[kReplyHeaders][key] !== undefined) {
return true
}
return this.raw.hasHeader(key)
}
Reply.prototype.removeHeader = function (key) {
// Node.js does not like headers with keys set to undefined,
// so we have to delete the key.
delete this[kReplyHeaders][key.toLowerCase()]
return this
}
Reply.prototype.header = function (key, value) {
const _key = key.toLowerCase()
// default the value to ''
value = value === undefined ? '' : value
if (this[kReplyHeaders][_key] && _key === 'set-cookie') {
// https://tools.ietf.org/html/rfc7230#section-3.2.2
if (typeof this[kReplyHeaders][_key] === 'string') {
this[kReplyHeaders][_key] = [this[kReplyHeaders][_key]]
}
if (Array.isArray(value)) {
Array.prototype.push.apply(this[kReplyHeaders][_key], value)
} else {
this[kReplyHeaders][_key].push(value)
}
} else {
this[kReplyHeaders][_key] = value
}
return this
}
Reply.prototype.headers = function (headers) {
const keys = Object.keys(headers)
/* eslint-disable no-var */
for (var i = 0; i !== keys.length; ++i) {
const key = keys[i]
this.header(key, headers[key])
}
return this
}
Reply.prototype.code = function (code) {
const intValue = parseInt(code)
if (isNaN(intValue) || intValue < 100 || intValue > 600) {
throw new FST_ERR_BAD_STATUS_CODE(code || String(code))
}
this.raw.statusCode = intValue
this[kReplyHasStatusCode] = true
return this
}
Reply.prototype.status = Reply.prototype.code
Reply.prototype.serialize = function (payload) {
if (this[kReplySerializer] !== null) {
return this[kReplySerializer](payload)
} else {
if (this.context && this.context[kReplySerializerDefault]) {
return this.context[kReplySerializerDefault](payload, this.raw.statusCode)
} else {
return serialize(this.context, payload, this.raw.statusCode)
}
}
}
Reply.prototype.serializer = function (fn) {
this[kReplySerializer] = fn
return this
}
Reply.prototype.type = function (type) {
this[kReplyHeaders]['content-type'] = type
return this
}
Reply.prototype.redirect = function (code, url) {
if (typeof code === 'string') {
url = code
code = this[kReplyHasStatusCode] ? this.raw.statusCode : 302
}
this.header('location', url).code(code).send()
}
Reply.prototype.callNotFound = function () {
notFound(this)
}
Reply.prototype.getResponseTime = function () {
let responseTime = 0
if (this[kReplyStartTime] !== undefined) {
responseTime = (this[kReplyEndTime] || now()) - this[kReplyStartTime]
}
return responseTime
}
// Make reply a thenable, so it could be used with async/await.
// See
// - https://github.com/fastify/fastify/issues/1864 for the discussions
// - https://promisesaplus.com/ for the definition of thenable
// - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then for the signature
Reply.prototype.then = function (fulfilled, rejected) {
if (this.sent) {
fulfilled()
return
}
eos(this.raw, (err) => {
// We must not treat ERR_STREAM_PREMATURE_CLOSE as
// an error because it is created by eos, not by the stream.
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
if (rejected) {
rejected(err)
} else {
this.log && this.log.warn('unhandled rejection on reply.then')
}
} else {
fulfilled()
}
})
}
function preserializeHook (reply, payload) {
if (reply.context.preSerialization !== null) {
onSendHookRunner(
reply.context.preSerialization,
reply.request,
reply,
payload,
preserializeHookEnd
)
} else {
preserializeHookEnd(null, reply.request, reply, payload)
}
}
function preserializeHookEnd (err, request, reply, payload) {
if (err != null) {
onErrorHook(reply, err)
return
}
try {
if (reply[kReplySerializer] !== null) {
payload = reply[kReplySerializer](payload)
} else if (reply.context && reply.context[kReplySerializerDefault]) {
payload = reply.context[kReplySerializerDefault](payload, reply.raw.statusCode)
} else {
payload = serialize(reply.context, payload, reply.raw.statusCode)
}
} catch (e) {
wrapSeralizationError(e, reply)
onErrorHook(reply, e)
return
}
onSendHook(reply, payload)
}
function wrapSeralizationError (error, reply) {
error.serialization = reply.context.config
}
function onSendHook (reply, payload) {
if (reply.context.onSend !== null) {
onSendHookRunner(
reply.context.onSend,
reply.request,
reply,
payload,
wrapOnSendEnd
)
} else {
onSendEnd(reply, payload)
}
}
function wrapOnSendEnd (err, request, reply, payload) {
if (err != null) {
onErrorHook(reply, err)
} else {
onSendEnd(reply, payload)
}
}
function onSendEnd (reply, payload) {
const res = reply.raw
const req = reply.request
const statusCode = res.statusCode
if (payload === undefined || payload === null) {
// according to https://tools.ietf.org/html/rfc7230#section-3.3.2
// we cannot send a content-length for 304 and 204, and all status code
// < 200.
// For HEAD we don't overwrite the `content-length`
if (statusCode >= 200 && statusCode !== 204 && statusCode !== 304 && req.method !== 'HEAD') {
reply[kReplyHeaders]['content-length'] = '0'
}
res.writeHead(statusCode, reply[kReplyHeaders])
// avoid ArgumentsAdaptorTrampoline from V8
res.end(null, null, null)
return
}
if (typeof payload.pipe === 'function') {
sendStream(payload, res, reply)
return
}
if (typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
throw new FST_ERR_REP_INVALID_PAYLOAD_TYPE(typeof payload)
}
if (!reply[kReplyHeaders]['content-length']) {
reply[kReplyHeaders]['content-length'] = '' + Buffer.byteLength(payload)
} else if (req.raw.method !== 'HEAD' && reply[kReplyHeaders]['content-length'] !== Buffer.byteLength(payload)) {
reply[kReplyHeaders]['content-length'] = '' + Buffer.byteLength(payload)
}
res.writeHead(statusCode, reply[kReplyHeaders])
// avoid ArgumentsAdaptorTrampoline from V8
res.end(payload, null, null)
}
function logStreamError (logger, err, res) {
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
if (!logger[kDisableRequestLogging]) {
logger.info({ res }, 'stream closed prematurely')
}
} else {
logger.warn({ err }, 'response terminated with an error with headers already sent')
}
}
function sendStream (payload, res, reply) {
let sourceOpen = true
let errorLogged = false
eos(payload, { readable: true, writable: false }, function (err) {
sourceOpen = false
if (err != null) {
if (res.headersSent || reply.request.raw.aborted === true) {
if (!errorLogged) {
errorLogged = true
logStreamError(reply.log, err, res)
}
res.destroy()
} else {
onErrorHook(reply, err)
}
}
// there is nothing to do if there is not an error
})
eos(res, function (err) {
if (sourceOpen) {
if (err != null && res.headersSent && !errorLogged) {
errorLogged = true
logStreamError(reply.log, err, res)
}
if (typeof payload.destroy === 'function') {
payload.destroy()
} else if (typeof payload.close === 'function') {
payload.close(noop)
} else if (typeof payload.abort === 'function') {
payload.abort()
} else {
reply.log.warn('stream payload does not end properly')
}
}
})
// streams will error asynchronously, and we want to handle that error
// appropriately, e.g. a 404 for a missing file. So we cannot use
// writeHead, and we need to resort to setHeader, which will trigger
// a writeHead when there is data to send.
if (!res.headersSent) {
for (const key in reply[kReplyHeaders]) {
res.setHeader(key, reply[kReplyHeaders][key])
}
} else {
reply.log.warn('response will send, but you shouldn\'t use res.writeHead in stream mode')
}
payload.pipe(res)
}
function onErrorHook (reply, error, cb) {
if (reply.context.onError !== null && !reply[kReplyNextErrorHandler]) {
reply[kReplyIsRunningOnErrorHook] = true
onSendHookRunner(
reply.context.onError,
reply.request,
reply,
error,
() => handleError(reply, error, cb)
)
} else {
handleError(reply, error, cb)
}
}
function setupResponseListeners (reply) {
reply[kReplyStartTime] = now()
const onResFinished = err => {
reply[kReplyEndTime] = now()
reply.raw.removeListener('finish', onResFinished)
reply.raw.removeListener('error', onResFinished)
const ctx = reply.context
if (ctx && ctx.onResponse !== null) {
hookRunner(
ctx.onResponse,
onResponseIterator,
reply.request,
reply,
onResponseCallback
)
} else {
onResponseCallback(err, reply.request, reply)
}
}
reply.raw.on('finish', onResFinished)
reply.raw.on('error', onResFinished)
}
function onResponseIterator (fn, request, reply, next) {
return fn(request, reply, next)
}
function onResponseCallback (err, request, reply) {
if (reply.log[kDisableRequestLogging]) {
return
}
const responseTime = reply.getResponseTime()
if (err != null) {
reply.log.error({
res: reply,
err,
responseTime
}, 'request errored')
return
}
reply.log.info({
res: reply,
responseTime
}, 'request completed')
}
function buildReply (R) {
const props = [...R.props]
function _Reply (res, request, log) {
this.raw = res
this[kReplyIsError] = false
this[kReplyErrorHandlerCalled] = false
this[kReplyHijacked] = false
this[kReplySerializer] = null
this.request = request
this[kReplyHeaders] = {}
this[kReplyStartTime] = undefined
this[kReplyEndTime] = undefined
this.log = log
// eslint-disable-next-line no-var
var prop
// eslint-disable-next-line no-var
for (var i = 0; i < props.length; i++) {
prop = props[i]
this[prop.key] = prop.value
}
}
Object.setPrototypeOf(_Reply.prototype, R.prototype)
Object.setPrototypeOf(_Reply, R)
_Reply.parent = R
_Reply.props = props
return _Reply
}
function notFound (reply) {
if (reply.context[kFourOhFourContext] === null) {
reply.log.warn('Trying to send a NotFound error inside a 404 handler. Sending basic 404 response.')
reply.code(404).send('404 Not Found')
return
}
reply.request.context = reply.context[kFourOhFourContext]
// preHandler hook
if (reply.context.preHandler !== null) {
hookRunner(
reply.context.preHandler,
hookIterator,
reply.request,
reply,
internals.preHandlerCallback
)
} else {
internals.preHandlerCallback(null, reply.request, reply)
}
}
/**
* This function runs when a payload that is not a string|buffer|stream or null
* should be serialized to be streamed to the response.
* This is the default serializer that can be customized by the user using the replySerializer
*
* @param {object} context the request context
* @param {object} data the JSON payload to serialize
* @param {number} statusCode the http status code
* @returns {string} the serialized payload
*/
function serialize (context, data, statusCode) {
const fnSerialize = getSchemaSerializer(context, statusCode)
if (fnSerialize) {
return fnSerialize(data)
}
return JSON.stringify(data)
}
function noop () { }
module.exports = Reply
module.exports.buildReply = buildReply
module.exports.setupResponseListeners = setupResponseListeners