import 'dart:async'; import 'package:flutter/foundation.dart'; import '../core/api_gateway.dart'; import '../core/servers/elevation/elevating_gateway.dart'; import '../core/servers/elevation/machine_elevation.dart'; import '../core/transport/pipelines_client.dart'; /// Whether this connection's send-only `subscribe` was accepted. /// /// A server that never acks leaves this [pending]; only an explicit refusal /// makes the session report that live updates are unavailable, so the UI never /// guesses "not live" from silence. enum RunSubscriptionState { pending, live, refused } /// Owns the one app-wide Pipelines socket and its run-event watch. /// /// The client reconnects on its own; this session re-sends the send-only /// `subscribe` on every connected transition because a new socket has no /// watch, and drops it deliberately with `unsubscribe` when the app stops. class AppSession extends ChangeNotifier { /// [knownServer]: this device has signed in to [endpoint] before, so the /// app opens straight away and reconnects behind a banner instead of the /// full connection screen. AppSession({ required Uri? endpoint, PipelinesClient? client, bool knownServer = false, List? addresses, }) : _initialEndpoint = endpoint, _initialAddresses = addresses, _client = client ?? PipelinesClient(), _everConnected = knownServer { _states = _client.states.listen(_onState); _frames = _client.frames.listen(_onFrame); _elevation = MachineElevation( name: endpoint?.host.isNotEmpty == true ? endpoint!.host : 'this server', gateway: _client, ); _gateway = ElevatingGateway(_client, _elevation); } late final MachineElevation _elevation; late final ElevatingGateway _gateway; final Uri? _initialEndpoint; final List? _initialAddresses; final PipelinesClient _client; late final StreamSubscription _states; late final StreamSubscription _frames; ConnectionState _connection = const ConnectionState(ConnectionKind.idle); bool _subscribed = false, _disposed = false; bool _everConnected; int _connectionEpoch = 0; RunSubscriptionState _subscription = RunSubscriptionState.pending; String _subscriptionError = ''; String? _subscribeRequest; /// Feature requests; a step-up refusal asks for the password and retries. ApiGateway get gateway => _gateway; /// Settings controls the same transport; it must never create another socket. PipelinesClient get client => _client; Uri? get endpoint => _client.endpoint ?? _initialEndpoint; ConnectionState get connection => _connection; bool get connected => _connection.kind == ConnectionKind.connected; /// True once any connection has succeeded. The Runs destination shows the /// full connection screen before this, then keeps the loaded screen mounted /// through later drops instead of discarding the operator's place. bool get everConnected => _everConnected; RunSubscriptionState get subscription => _subscription; String get subscriptionError => _subscriptionError; /// Advances on every connected transition. The Runs destination keys the /// screen's reload with this so a reconnect re-reads the list and the open /// detail without remounting the screen or losing its selection. int get connectionEpoch => _connectionEpoch; /// Connects the shared socket. A missing endpoint is a configuration state, /// so this is a no-op rather than a guessed endpoint. Future start() async { if (_disposed || endpoint == null) return; final addresses = _client.endpoints.isNotEmpty ? _client.endpoints : _initialAddresses ?? [endpoint!]; await _client.connectAny(addresses); } /// Retries now: reopens a disconnected socket, or repeats a refused watch on /// a healthy one. Future retry() async { if (_client.state.kind == ConnectionKind.connected) { resubscribe(); return; } await start(); } /// Repeats the send-only watch on the current socket. Used when the server /// explicitly refused the previous `subscribe`. void resubscribe() { if (_disposed) return; _subscribed = false; _subscribeRequest = null; _subscription = RunSubscriptionState.pending; _subscriptionError = ''; _subscribe(); notifyListeners(); } /// Stops the watch and the socket without disposing the session, so a later /// [start] can open a fresh connection. Future stop() async { if (_disposed) return; _sendUnsubscribe(); await _client.disconnect(); } void _onState(ConnectionState state) { if (_disposed) return; final wasConnected = connected; _connection = state; if (state.kind == ConnectionKind.connected) { _everConnected = true; _connectionEpoch++; _subscription = RunSubscriptionState.pending; _subscriptionError = ''; _subscribe(); } else if (wasConnected) { _subscribed = false; _subscribeRequest = null; _subscription = RunSubscriptionState.pending; _subscriptionError = ''; } notifyListeners(); } void _onFrame(JsonMap frame) { if (_disposed) return; final id = frame['id']; if (id is! String || id != _subscribeRequest) return; switch (frame['type']) { case 'subscribe': _subscription = RunSubscriptionState.live; _subscriptionError = ''; break; case 'error': _subscription = RunSubscriptionState.refused; final reason = '${frame['error'] ?? ''}'.trim(); _subscriptionError = reason.isEmpty ? 'Live run updates are unavailable.' : reason; break; default: return; } notifyListeners(); } void _subscribe() { if (_subscribed || !connected) return; try { _subscribeRequest = _client.sendOnly('subscribe', const { 'workspace': '', }); _subscribed = true; } on NotConnectedError { // A close raced the connected state; the next connected transition // subscribes instead of leaving a half-registered watch. } } void _sendUnsubscribe() { if (!_subscribed) return; _subscribed = false; _subscribeRequest = null; if (!connected) return; try { _client.sendOnly('unsubscribe'); } on NotConnectedError { // The socket already closed, which drops the watch server-side. } } @override void dispose() { if (_disposed) return; _disposed = true; _sendUnsubscribe(); unawaited(_states.cancel()); unawaited(_frames.cancel()); unawaited(_client.dispose()); super.dispose(); } }