stop method
Stops the server. With server.shutdown=graceful it stops accepting
connections and lets running requests finish for up to timeout
(30 seconds when null), then closes what is left; open event
streams and WebSocket sessions are closed at once.
Implementation
@override
Future<void> stop({Duration? timeout}) async {
final starting = _starting;
_starting = null;
if (starting != null) {
try {
await starting;
} on Object {
// It did not start: nothing to stop.
}
}
final server = _server;
if (server == null) {
return;
}
_server = null;
final accepting = _accepting;
_accepting = null;
final graceful = settings.shutdown == Shutdown.graceful;
if (graceful && accepting != null) {
// No new connections, while the open ones still work: closing the
// server at once would end every idle connection, and with it the
// request a client has just sent on one (a keep-alive connection
// looks idle until its next request is read).
_leaving = true;
await accepting.refuse();
}
// Open event streams and WebSockets end now (they would never finish
// by themselves).
for (final session in _sessions.toList()) {
unawaited(
session
.close(CloseStatus.goingAway.withReason('Server stopping'))
.catchError((Object _) {}),
);
}
for (final exchange in _exchanges.toList()) {
if (exchange.isStreaming) {
unawaited(exchange.abort());
}
}
final limit = timeout ?? const Duration(seconds: 30);
if (_leaving) {
await _letConnectionsLeave(server, limit);
}
final closing = server.close().whenComplete(
() => accepting?.close() ?? Future<void>.value(),
);
if (graceful) {
final active = _exchanges.isNotEmpty;
if (active) {
_log.info('Commencing graceful shutdown. Waiting for active requests');
}
// Running requests finish; then the non-forced close ends idle
// connections once their responses are out (a forced close could
// cut a response the client is still reading).
final completed =
await Future.wait([
for (final exchange in _exchanges) exchange.finished,
])
.then((_) => closing)
.then((_) => true)
.timeout(limit, onTimeout: () => false);
if (active || !completed) {
_log.info(
completed
? 'Graceful shutdown complete'
: 'Graceful shutdown aborted with one or more requests still '
'active',
);
}
if (completed) {
return;
}
}
await server.close(force: true);
await closing;
}