close method

Future<void> close({
  1. Duration gracePeriod = const Duration(seconds: 30),
})

Gracefully closes all active HttpServer instances and drains in-flight requests.

  1. Stops accepting new socket connections immediately on all bound servers.
  2. Waits up to gracePeriod (default 30 seconds) for in-flight requests to complete.
  3. Rejects new incoming requests during drain with HTTP 503 Service Unavailable.
  4. Force-closes any sockets remaining open when gracePeriod expires.

Example

ProcessSignal.sigterm.watch().listen((_) async {
  print('Shutting down gracefully...');
  await router.close(gracePeriod: Duration(seconds: 15));
  exit(0);
});

Implementation

Future<void> close(
    {Duration gracePeriod = const Duration(seconds: 30)}) async {
  _isClosing = true;

  // 1. Stop accepting new connections on all listening servers.
  for (final server in _servers) {
    try {
      await server.close(force: false);
    } catch (_) {}
  }

  // 2. Wait up to gracePeriod for in-flight requests to finish.
  if (_inFlightRequests.isNotEmpty) {
    try {
      await Future.wait(
        _inFlightRequests.map((c) => c.future),
      ).timeout(gracePeriod);
    } on TimeoutException {
      // Grace period expired with unfinished requests; proceed to force close.
    } catch (_) {}
  }

  // 3. Force-close any remaining active sockets.
  for (final server in _servers) {
    try {
      await server.close(force: true);
    } catch (_) {}
  }

  _servers.clear();
  _inFlightRequests.clear();
  _isClosing = false;
}