Skip to content

fastify.server.close() did not behave as expected. #4774

@hienngm

Description

@hienngm

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.17.0

Plugin version

No response

Node.js version

v16.19.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.6

Description

According to the Node.js documentation:

 /**
   * Stops the server from accepting new connections and keeps existing
   * connections. This function is asynchronous, the server is finally closed
   * when all connections are ended and the server emits a `'close'` event.
   * The optional `callback` will be called once the `'close'` event occurs. Unlike
   * that event, it will be called with an `Error` as its only argument if the server
   * was not open when it was closed.
   * @since v0.1.90
   * @param callback Called when the server is closed.
   */
  close(callback?: (err?: Error) => void): this;

The callback is supposed to be called when the server is closed. I've already tested it in the NodeJS HTTP server. However, in my case, when I call fastify.server.close(callback), the callback is invoked immediately, and the server is still processing incoming requests instead of being closed.

I'm reporting this issue because it breaks some of the shutdown features of NestJS (using Fastify adapter).

Steps to Reproduce

import Fastify from 'fastify';
const fastify = Fastify();

fastify.get('/', async (request, reply) => {
  await new Promise((resolve) => {
    setTimeout(() => resolve(1), 10000);
  });
  reply.send({ hello: 'world' });
});

setTimeout(() => {
  fastify.server.close((error) => {
    console.log('Server is closed', error);
  });
}, 5000);

// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err;
  // Server is now listening on ${address}
});

Start the server and call the API at localhost:3000.

Expected Behavior

The callback is only invoked when the server is actually closed as the original NodeJS HTTP server behaves.

I'm reporting this issue because it breaks some of the shutdown features of NestJS (using Fastify adapter).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions