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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
'use strict'

const net = require('node:net')
const http = require('node:http')
const { test } = require('tap')
const Fastify = require('..')
const { Client } = require('undici')
const split = require('split2')
const { sleep } = require('./helper')

test('close callback', t => {
  t.plan(7)
  const fastify = Fastify()
  fastify.addHook('onClose', onClose)
  function onClose (instance, done) {
    t.type(fastify, this)
    t.type(fastify, instance)
    t.equal(fastify, this)
    t.equal(fastify, instance)
    done()
  }

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.close((err) => {
      t.error(err)
      t.ok('close callback')
    })
  })
})

test('inside register', t => {
  t.plan(5)
  const fastify = Fastify()
  fastify.register(function (f, opts, done) {
    f.addHook('onClose', onClose)
    function onClose (instance, done) {
      t.ok(instance.prototype === fastify.prototype)
      t.equal(instance, f)
      done()
    }

    done()
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.close((err) => {
      t.error(err)
      t.ok('close callback')
    })
  })
})

test('close order', t => {
  t.plan(5)
  const fastify = Fastify()
  const order = [1, 2, 3]

  fastify.register(function (f, opts, done) {
    f.addHook('onClose', (instance, done) => {
      t.equal(order.shift(), 1)
      done()
    })

    done()
  })

  fastify.addHook('onClose', (instance, done) => {
    t.equal(order.shift(), 2)
    done()
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.close((err) => {
      t.error(err)
      t.equal(order.shift(), 3)
    })
  })
})

test('close order - async', async t => {
  t.plan(3)
  const fastify = Fastify()
  const order = [1, 2, 3]

  fastify.register(function (f, opts, done) {
    f.addHook('onClose', async instance => {
      t.equal(order.shift(), 1)
    })

    done()
  })

  fastify.addHook('onClose', () => {
    t.equal(order.shift(), 2)
  })

  await fastify.listen({ port: 0 })
  await fastify.close()

  t.equal(order.shift(), 3)
})

test('should not throw an error if the server is not listening', t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.addHook('onClose', onClose)
  function onClose (instance, done) {
    t.type(fastify, instance)
    done()
  }

  fastify.close((err) => {
    t.error(err)
  })
})

test('onClose should keep the context', t => {
  t.plan(4)
  const fastify = Fastify()
  fastify.register(plugin)

  function plugin (instance, opts, done) {
    instance.decorate('test', true)
    instance.addHook('onClose', onClose)
    t.ok(instance.prototype === fastify.prototype)

    function onClose (i, done) {
      t.ok(i.test)
      t.equal(i, instance)
      done()
    }

    done()
  }

  fastify.close((err) => {
    t.error(err)
  })
})

test('Should return error while closing (promise) - injection', t => {
  t.plan(4)
  const fastify = Fastify()

  fastify.addHook('onClose', (instance, done) => { done() })

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })

  fastify.inject({
    method: 'GET',
    url: '/'
  }, (err, res) => {
    t.error(err)
    t.equal(res.statusCode, 200)
    fastify.close()

    process.nextTick(() => {
      fastify.inject({
        method: 'GET',
        url: '/'
      }).catch(err => {
        t.ok(err)
        t.equal(err.code, 'FST_ERR_REOPENED_CLOSE_SERVER')
      })
    }, 100)
  })
})

test('Should return error while closing (callback) - injection', t => {
  t.plan(4)
  const fastify = Fastify()

  fastify.addHook('onClose', (instance, done) => {
    setTimeout(done, 150)
  })

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })

  fastify.inject({
    method: 'GET',
    url: '/'
  }, (err, res) => {
    t.error(err)
    t.equal(res.statusCode, 200)
    fastify.close()

    setTimeout(() => {
      fastify.inject({
        method: 'GET',
        url: '/'
      }, (err, res) => {
        t.ok(err)
        t.equal(err.code, 'FST_ERR_REOPENED_CLOSE_SERVER')
      })
    }, 100)
  })
})

test('Current opened connection should NOT continue to work after closing and return "connection: close" header - return503OnClosing: false', t => {
  t.plan(4)
  const fastify = Fastify({
    return503OnClosing: false,
    forceCloseConnections: false
  })

  fastify.get('/', (req, reply) => {
    fastify.close()
    reply.send({ hello: 'world' })
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    const port = fastify.server.address().port
    const client = net.createConnection({ port }, () => {
      client.write('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')

      client.on('error', function () {
        // Depending on the Operating System
        // the socket could error or not.
        // However, it will always be closed.
      })

      client.on('close', function () {
        t.pass('close')
      })

      client.once('data', data => {
        t.match(data.toString(), /Connection:\s*keep-alive/i)
        t.match(data.toString(), /200 OK/i)

        client.write('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
      })
    })
  })
})

test('Current opened connection should not accept new incoming connections', t => {
  t.plan(3)
  const fastify = Fastify({ forceCloseConnections: false })
  fastify.get('/', (req, reply) => {
    fastify.close()
    setTimeout(() => {
      reply.send({ hello: 'world' })
    }, 250)
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)
    const instance = new Client('http://localhost:' + fastify.server.address().port)
    instance.request({ path: '/', method: 'GET' }).then(data => {
      t.equal(data.statusCode, 200)
    })
    instance.request({ path: '/', method: 'GET' }).then(data => {
      t.equal(data.statusCode, 503)
    })
  })
})

test('rejected incoming connections should be logged', t => {
  t.plan(2)
  const stream = split(JSON.parse)
  const fastify = Fastify({
    forceCloseConnections: false,
    logger: {
      stream,
      level: 'info'
    }
  })

  const messages = []
  stream.on('data', message => {
    messages.push(message)
  })
  fastify.get('/', (req, reply) => {
    fastify.close()
    setTimeout(() => {
      reply.send({ hello: 'world' })
    }, 250)
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)
    const instance = new Client('http://localhost:' + fastify.server.address().port)
    // initial request to trigger close
    instance.request({ path: '/', method: 'GET' })
    // subsequent request should be rejected
    instance.request({ path: '/', method: 'GET' }).then(() => {
      t.ok(messages.find(message => message.msg.includes('request aborted')))
    })
  })
})

test('Cannot be reopened the closed server without listen callback', async t => {
  t.plan(2)
  const fastify = Fastify()

  await fastify.listen({ port: 0 })
  await fastify.close()

  try {
    await fastify.listen({ port: 0 })
  } catch (err) {
    t.ok(err)
    t.equal(err.code, 'FST_ERR_REOPENED_CLOSE_SERVER')
  }
})

test('Cannot be reopened the closed server has listen callback', async t => {
  t.plan(2)
  const fastify = Fastify()

  await fastify.listen({ port: 0 })
  await fastify.close()

  await new Promise((resolve, reject) => {
    fastify.listen({ port: 0 }, err => {
      reject(err)
    })
  }).catch(err => {
    t.equal(err.code, 'FST_ERR_REOPENED_CLOSE_SERVER')
    t.ok(err)
  })
})

const server = http.createServer()
const noSupport = typeof server.closeAllConnections !== 'function'

test('shutsdown while keep-alive connections are active (non-async, native)', { skip: noSupport }, t => {
  t.plan(5)

  const timeoutTime = 2 * 60 * 1000
  const fastify = Fastify({ forceCloseConnections: true })

  fastify.server.setTimeout(timeoutTime)
  fastify.server.keepAliveTimeout = timeoutTime

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })

  fastify.listen({ port: 0 }, (err, address) => {
    t.error(err)

    const client = new Client(
      'http://localhost:' + fastify.server.address().port,
      { keepAliveTimeout: 1 * 60 * 1000 }
    )
    client.request({ path: '/', method: 'GET' }, (err, response) => {
      t.error(err)
      t.equal(client.closed, false)

      fastify.close((err) => {
        t.error(err)

        // Due to the nature of the way we reap these keep-alive connections,
        // there hasn't been enough time before the server fully closed in order
        // for the client to have seen the socket get destroyed. The mere fact
        // that we have reached this callback is enough indication that the
        // feature being tested works as designed.
        t.equal(client.closed, false)
      })
    })
  })
})

test('shutsdown while keep-alive connections are active (non-async, idle, native)', { skip: noSupport }, t => {
  t.plan(5)

  const timeoutTime = 2 * 60 * 1000
  const fastify = Fastify({ forceCloseConnections: 'idle' })

  fastify.server.setTimeout(timeoutTime)
  fastify.server.keepAliveTimeout = timeoutTime

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })

  fastify.listen({ port: 0 }, (err, address) => {
    t.error(err)

    const client = new Client(
      'http://localhost:' + fastify.server.address().port,
      { keepAliveTimeout: 1 * 60 * 1000 }
    )
    client.request({ path: '/', method: 'GET' }, (err, response) => {
      t.error(err)
      t.equal(client.closed, false)

      fastify.close((err) => {
        t.error(err)

        // Due to the nature of the way we reap these keep-alive connections,
        // there hasn't been enough time before the server fully closed in order
        // for the client to have seen the socket get destroyed. The mere fact
        // that we have reached this callback is enough indication that the
        // feature being tested works as designed.
        t.equal(client.closed, false)
      })
    })
  })
})

test('triggers on-close hook in the right order with multiple bindings', async t => {
  const expectedOrder = [1, 2, 3]
  const order = []
  const fastify = Fastify()

  t.plan(1)

  // Follows LIFO
  fastify.addHook('onClose', () => {
    order.push(2)
  })

  fastify.addHook('onClose', () => {
    order.push(1)
  })

  await fastify.listen({ port: 0 })

  await new Promise((resolve, reject) => {
    setTimeout(() => {
      fastify.close(err => {
        order.push(3)
        t.match(order, expectedOrder)

        if (err) t.error(err)
        else resolve()
      })
    }, 2000)
  })
})

test('triggers on-close hook in the right order with multiple bindings (forceCloseConnections - idle)', { skip: noSupport }, async t => {
  const expectedPayload = { hello: 'world' }
  const timeoutTime = 2 * 60 * 1000
  const expectedOrder = [1, 2]
  const order = []
  const fastify = Fastify({ forceCloseConnections: 'idle' })

  fastify.server.setTimeout(timeoutTime)
  fastify.server.keepAliveTimeout = timeoutTime

  fastify.get('/', async (req, reply) => {
    await new Promise((resolve) => {
      setTimeout(resolve, 1000)
    })

    return expectedPayload
  })

  fastify.addHook('onClose', () => {
    order.push(1)
  })

  await fastify.listen({ port: 0 })
  const addresses = fastify.addresses()
  const testPlan = (addresses.length * 2) + 1

  t.plan(testPlan)

  for (const addr of addresses) {
    const { family, address, port } = addr
    const host = family === 'IPv6' ? `[${address}]` : address
    const client = new Client(`http://${host}:${port}`, {
      keepAliveTimeout: 1 * 60 * 1000
    })

    client.request({ path: '/', method: 'GET' })
      .then((res) => res.body.json(), err => t.error(err))
      .then(json => {
        t.match(json, expectedPayload, 'should payload match')
        t.notOk(client.closed, 'should client not be closed')
      }, err => t.error(err))
  }

  await new Promise((resolve, reject) => {
    setTimeout(() => {
      fastify.close(err => {
        order.push(2)
        t.match(order, expectedOrder)

        if (err) t.error(err)
        else resolve()
      })
    }, 2000)
  })
})

test('triggers on-close hook in the right order with multiple bindings (forceCloseConnections - true)', { skip: noSupport }, async t => {
  const expectedPayload = { hello: 'world' }
  const timeoutTime = 2 * 60 * 1000
  const expectedOrder = [1, 2]
  const order = []
  const fastify = Fastify({ forceCloseConnections: true })

  fastify.server.setTimeout(timeoutTime)
  fastify.server.keepAliveTimeout = timeoutTime

  fastify.get('/', async (req, reply) => {
    await new Promise((resolve) => {
      setTimeout(resolve, 1000)
    })

    return expectedPayload
  })

  fastify.addHook('onClose', () => {
    order.push(1)
  })

  await fastify.listen({ port: 0 })
  const addresses = fastify.addresses()
  const testPlan = (addresses.length * 2) + 1

  t.plan(testPlan)

  for (const addr of addresses) {
    const { family, address, port } = addr
    const host = family === 'IPv6' ? `[${address}]` : address
    const client = new Client(`http://${host}:${port}`, {
      keepAliveTimeout: 1 * 60 * 1000
    })

    client.request({ path: '/', method: 'GET' })
      .then((res) => res.body.json(), err => t.error(err))
      .then(json => {
        t.match(json, expectedPayload, 'should payload match')
        t.notOk(client.closed, 'should client not be closed')
      }, err => t.error(err))
  }

  await new Promise((resolve, reject) => {
    setTimeout(() => {
      fastify.close(err => {
        order.push(2)
        t.match(order, expectedOrder)

        if (err) t.error(err)
        else resolve()
      })
    }, 2000)
  })
})

test('shutsdown while keep-alive connections are active (non-async, custom)', t => {
  t.plan(5)

  const timeoutTime = 2 * 60 * 1000
  const fastify = Fastify({
    forceCloseConnections: true,
    serverFactory (handler) {
      const server = http.createServer(handler)

      server.closeAllConnections = null

      return server
    }
  })

  fastify.server.setTimeout(timeoutTime)
  fastify.server.keepAliveTimeout = timeoutTime

  fastify.get('/', (req, reply) => {
    reply.send({ hello: 'world' })
  })

  fastify.listen({ port: 0 }, (err, address) => {
    t.error(err)

    const client = new Client(
      'http://localhost:' + fastify.server.address().port,
      { keepAliveTimeout: 1 * 60 * 1000 }
    )
    client.request({ path: '/', method: 'GET' }, (err, response) => {
      t.error(err)
      t.equal(client.closed, false)

      fastify.close((err) => {
        t.error(err)

        // Due to the nature of the way we reap these keep-alive connections,
        // there hasn't been enough time before the server fully closed in order
        // for the client to have seen the socket get destroyed. The mere fact
        // that we have reached this callback is enough indication that the
        // feature being tested works as designed.
        t.equal(client.closed, false)
      })
    })
  })
})

test('preClose callback', t => {
  t.plan(5)
  const fastify = Fastify()
  fastify.addHook('onClose', onClose)
  let preCloseCalled = false
  function onClose (instance, done) {
    t.equal(preCloseCalled, true)
    done()
  }
  fastify.addHook('preClose', preClose)

  function preClose (done) {
    t.type(this, fastify)
    preCloseCalled = true
    done()
  }

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.close((err) => {
      t.error(err)
      t.ok('close callback')
    })
  })
})

test('preClose async', async t => {
  t.plan(2)
  const fastify = Fastify()
  fastify.addHook('onClose', onClose)
  let preCloseCalled = false
  async function onClose () {
    t.equal(preCloseCalled, true)
  }
  fastify.addHook('preClose', preClose)

  async function preClose () {
    preCloseCalled = true
    t.type(this, fastify)
  }

  await fastify.listen({ port: 0 })

  await fastify.close()
})

test('preClose execution order', t => {
  t.plan(4)
  const fastify = Fastify()
  const order = []
  fastify.addHook('onClose', onClose)
  function onClose (instance, done) {
    t.same(order, [1, 2, 3])
    done()
  }

  fastify.addHook('preClose', (done) => {
    setTimeout(function () {
      order.push(1)
      done()
    }, 200)
  })

  fastify.addHook('preClose', async () => {
    await sleep(100)
    order.push(2)
  })

  fastify.addHook('preClose', (done) => {
    setTimeout(function () {
      order.push(3)
      done()
    }, 100)
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.close((err) => {
      t.error(err)
      t.ok('close callback')
    })
  })
})