import 'dart:async'; import 'dart:io'; /// Bounds how long a relay WebSocket may take to connect and upgrade. /// /// The OS gives up on a stalled TCP or TLS handshake only after minutes, and /// reconnecting starts only once this attempt fails, so an unbounded attempt /// leaves the app reconnecting for as long as the network stays stalled. const relayWebSocketConnectTimeout = Duration(seconds: 10); /// `User-Agent` sent on every relay WebSocket upgrade; [setRelayUserAgent] /// adds the app version once it is known. String relayUserAgent = 'Buzz-Mobile'; void setRelayUserAgent(String version) => relayUserAgent = 'Buzz-Mobile/$version'; /// Sets [relayUserAgent] from [lookupVersion] before any socket opens, giving /// up after [timeout] so a hung or failed lookup cannot stall launch. Future loadRelayUserAgent( Future Function() lookupVersion, { Duration timeout = const Duration(milliseconds: 500), }) async { try { setRelayUserAgent(await lookupVersion().timeout(timeout)); } catch (_) { // Keep the unversioned fallback. } } /// WebSocket's default HTTP client follows redirects, including custom headers. /// Keep key-bound assertions at their original origin and bound upgrade time. /// /// Each attempt gets its own HTTP client so a timed-out handshake can be /// force-closed instead of left running until the OS gives up on it. Future openRelayWebSocket( Uri uri, { required Map headers, required Duration pingInterval, Duration connectTimeout = relayWebSocketConnectTimeout, }) async { final HttpClient client = headers.isEmpty ? HttpClient() : _UpgradeClient(); client.userAgent = relayUserAgent; try { return await WebSocket.connect( uri.toString(), headers: headers.isEmpty ? null : headers, customClient: client, ) .then((socket) => socket..pingInterval = pingInterval) .timeout( connectTimeout, onTimeout: () { client.close(force: true); throw TimeoutException('Relay connection timed out'); }, ); } finally { client.close(); } } /// WebSocket.connect uses only openUrl on its supplied HTTP client. Keep this /// adapter limited to upgrades instead of exposing a second general transport. class _UpgradeClient implements HttpClient { final _inner = HttpClient(); @override Future openUrl(String method, Uri url) async { final request = await _inner.openUrl(method, url); request.followRedirects = false; return request; } @override String? get userAgent => _inner.userAgent; @override set userAgent(String? value) => _inner.userAgent = value; @override void close({bool force = false}) => _inner.close(force: force); @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); }