Add ordered websocket address fallback
This commit is contained in:
@@ -17,18 +17,22 @@ class PipelinesClient implements ApiGateway {
|
||||
PipelinesClient({
|
||||
ChannelFactory? channelFactory,
|
||||
this.requestTimeout = const Duration(seconds: 30),
|
||||
this.connectionTimeout = const Duration(seconds: 5),
|
||||
this.backoffBase = const Duration(seconds: 1),
|
||||
this.backoffMax = const Duration(seconds: 30),
|
||||
}) : _factory = channelFactory ?? connectPipelinesChannel;
|
||||
|
||||
final ChannelFactory _factory;
|
||||
final Duration requestTimeout, backoffBase, backoffMax;
|
||||
final Duration requestTimeout, connectionTimeout, backoffBase, backoffMax;
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
final _states = StreamController<ConnectionState>.broadcast();
|
||||
final Map<String, Completer<JsonMap>> _pending = {};
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription<dynamic>? _subscription;
|
||||
Uri? _endpoint;
|
||||
List<Uri> _endpoints = const [];
|
||||
int _endpointIndex = 0;
|
||||
Completer<void>? _openingCancelled;
|
||||
Timer? _reconnect;
|
||||
int _generation = 0, _sequence = 0, _attempt = 0;
|
||||
bool _manual = true, _disposed = false;
|
||||
@@ -40,13 +44,28 @@ class PipelinesClient implements ApiGateway {
|
||||
Stream<ConnectionState> get states => _states.stream;
|
||||
ConnectionState get state => _state;
|
||||
|
||||
/// Last validated endpoint, including changes made through native Settings.
|
||||
/// Current attempted or connected address.
|
||||
Uri? get endpoint => _endpoint;
|
||||
|
||||
Future<void> connect(Uri uri) async {
|
||||
/// Immutable, normalized addresses for this logical server, in priority order.
|
||||
List<Uri> get endpoints => _endpoints;
|
||||
|
||||
Future<void> connect(Uri uri) => connectAny([uri]);
|
||||
|
||||
/// Starts at the primary address; automatic retries rotate only within [uris].
|
||||
Future<void> connectAny(List<Uri> uris) async {
|
||||
if (_disposed) throw StateError('Client has been disposed');
|
||||
final endpoint = ServerUrl.validate(uri.toString());
|
||||
_endpoint = Uri.parse(endpoint.wsUrl);
|
||||
if (uris.isEmpty) {
|
||||
throw ArgumentError.value(uris, 'uris', 'Must not be empty');
|
||||
}
|
||||
// Validate the entire replacement before changing a healthy connection.
|
||||
final candidates = uris
|
||||
.map((uri) => Uri.parse(ServerUrl.validate(uri.toString()).wsUrl))
|
||||
.toSet()
|
||||
.toList(growable: false);
|
||||
_endpoints = List.unmodifiable(candidates);
|
||||
_endpointIndex = 0;
|
||||
_endpoint = _endpoints.first;
|
||||
_manual = false;
|
||||
_attempt = 0;
|
||||
_reconnect?.cancel();
|
||||
@@ -57,6 +76,7 @@ class PipelinesClient implements ApiGateway {
|
||||
final endpoint = _endpoint;
|
||||
if (endpoint == null || _disposed) return;
|
||||
final generation = ++_generation;
|
||||
_cancelOpening();
|
||||
_setState(ConnectionState(ConnectionKind.connecting, attempt: ++_attempt));
|
||||
final old = _channel;
|
||||
_channel = null;
|
||||
@@ -66,6 +86,8 @@ class PipelinesClient implements ApiGateway {
|
||||
_subscription = null;
|
||||
await subscription?.cancel();
|
||||
if (generation != _generation || _manual || _disposed) return;
|
||||
final cancelled = Completer<void>();
|
||||
_openingCancelled = cancelled;
|
||||
try {
|
||||
final channel = _factory(endpoint);
|
||||
_channel = channel;
|
||||
@@ -80,15 +102,26 @@ class PipelinesClient implements ApiGateway {
|
||||
if (generation == _generation) _closed('Connection closed');
|
||||
},
|
||||
);
|
||||
await channel.ready;
|
||||
await Future.any([
|
||||
channel.ready,
|
||||
cancelled.future,
|
||||
]).timeout(connectionTimeout);
|
||||
if (generation != _generation) return;
|
||||
_attempt = 0;
|
||||
_setState(const ConnectionState(ConnectionKind.connected));
|
||||
} catch (error) {
|
||||
if (generation == _generation) _closed(error.toString());
|
||||
} finally {
|
||||
if (identical(_openingCancelled, cancelled)) _openingCancelled = null;
|
||||
}
|
||||
}
|
||||
|
||||
void _cancelOpening() {
|
||||
final cancelled = _openingCancelled;
|
||||
_openingCancelled = null;
|
||||
if (cancelled != null && !cancelled.isCompleted) cancelled.complete();
|
||||
}
|
||||
|
||||
void _setState(ConnectionState value) {
|
||||
_state = value;
|
||||
if (!_states.isClosed) _states.add(value);
|
||||
@@ -196,6 +229,7 @@ class PipelinesClient implements ApiGateway {
|
||||
|
||||
void _closed(String reason) {
|
||||
_generation++;
|
||||
_cancelOpening();
|
||||
final channel = _channel;
|
||||
final subscription = _subscription;
|
||||
_channel = null;
|
||||
@@ -217,17 +251,20 @@ class PipelinesClient implements ApiGateway {
|
||||
);
|
||||
final shift = (_attempt - 1).clamp(0, 6);
|
||||
final delay = backoffBase * (1 << shift);
|
||||
_endpointIndex = (_endpointIndex + 1) % _endpoints.length;
|
||||
_reconnect?.cancel();
|
||||
_reconnect = Timer(
|
||||
delay > backoffMax ? backoffMax : delay,
|
||||
() => unawaited(_open()),
|
||||
);
|
||||
_reconnect = Timer(delay > backoffMax ? backoffMax : delay, () {
|
||||
if (_manual || _disposed) return;
|
||||
_endpoint = _endpoints[_endpointIndex];
|
||||
unawaited(_open());
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
_manual = true;
|
||||
_reconnect?.cancel();
|
||||
final generation = ++_generation;
|
||||
_cancelOpening();
|
||||
final channel = _channel;
|
||||
_channel = null;
|
||||
final subscription = _subscription;
|
||||
|
||||
Reference in New Issue
Block a user