Files
pipelines/app/lib/application/app_session.dart
T

174 lines
5.6 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../core/api_gateway.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 {
AppSession({required Uri? endpoint, PipelinesClient? client})
: _initialEndpoint = endpoint,
_client = client ?? PipelinesClient() {
_states = _client.states.listen(_onState);
_frames = _client.frames.listen(_onFrame);
}
final Uri? _initialEndpoint;
final PipelinesClient _client;
late final StreamSubscription<ConnectionState> _states;
late final StreamSubscription<JsonMap> _frames;
ConnectionState _connection = const ConnectionState(ConnectionKind.idle);
bool _subscribed = false, _disposed = false, _everConnected = false;
int _connectionEpoch = 0;
RunSubscriptionState _subscription = RunSubscriptionState.pending;
String _subscriptionError = '';
String? _subscribeRequest;
ApiGateway get gateway => _client;
/// 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<void> start() async {
if (_disposed || endpoint == null) return;
await _client.connect(endpoint!);
}
/// Retries now: reopens a disconnected socket, or repeats a refused watch on
/// a healthy one.
Future<void> 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<void> 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();
}
}