close method
Gracefully closes all active HttpServer instances and drains in-flight requests.
- Stops accepting new socket connections immediately on all bound servers.
- Waits up to
gracePeriod(default 30 seconds) for in-flight requests to complete. - Rejects new incoming requests during drain with HTTP 503 Service Unavailable.
- Force-closes any sockets remaining open when
gracePeriodexpires.
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;
}