closeConnection method
Initiates graceful shutdown of a connection
Implementation
Future<void> closeConnection(TransportConn connection) async {
final state = _connections[connection];
if (state == null) {
// Connection is already removed from manager, nothing to do
return;
}
if (state == ConnectionState.closed || state == ConnectionState.error) {
return;
}
// Start graceful shutdown
updateState(connection, ConnectionState.closing);
try {
// Set up shutdown timeout
final completer = Completer<void>();
final timeout = Timer(shutdownTimeout, () {
if (!completer.isCompleted) {
completer.completeError(
TimeoutException('Connection shutdown timed out after ${shutdownTimeout.inSeconds} seconds'),
);
}
});
try {
// Attempt graceful shutdown
await connection.close().timeout(shutdownTimeout);
completer.complete();
} catch (e) {
if (!completer.isCompleted) {
completer.completeError(e);
}
}
// Wait for completion or timeout
await completer.future;
timeout.cancel();
// Only update state if connection is still registered
if (_connections.containsKey(connection)) {
updateState(connection, ConnectionState.closed);
}
} catch (e) {
// Only update state if connection is still registered
if (_connections.containsKey(connection)) {
updateState(connection, ConnectionState.error, error: e);
}
rethrow;
}
}