feat(app): add Flutter websocket transport
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
import '../api_gateway.dart';
|
||||
import 'server_url.dart';
|
||||
|
||||
enum ConnectionKind { idle, connecting, connected, disconnected }
|
||||
|
||||
class ConnectionState {
|
||||
const ConnectionState(this.kind, {this.attempt = 0, this.reason = '', this.retrying = false});
|
||||
final ConnectionKind kind;
|
||||
final int attempt;
|
||||
final String reason;
|
||||
final bool retrying;
|
||||
}
|
||||
|
||||
class ProtocolError implements Exception {
|
||||
const ProtocolError(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class NotConnectedError implements Exception {
|
||||
const NotConnectedError();
|
||||
@override
|
||||
String toString() => 'Not connected to the Pipelines server';
|
||||
}
|
||||
|
||||
typedef ChannelFactory = WebSocketChannel Function(Uri uri);
|
||||
|
||||
/// One correlated websocket transport shared by all feature gateways.
|
||||
class PipelinesClient implements ApiGateway {
|
||||
PipelinesClient({ChannelFactory? channelFactory,
|
||||
this.requestTimeout = const Duration(seconds: 30),
|
||||
this.backoffBase = const Duration(seconds: 1),
|
||||
this.backoffMax = const Duration(seconds: 30)}) : _factory = channelFactory ?? WebSocketChannel.connect;
|
||||
|
||||
final ChannelFactory _factory;
|
||||
final Duration requestTimeout, 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;
|
||||
Timer? _reconnect;
|
||||
int _generation = 0, _sequence = 0, _attempt = 0;
|
||||
bool _manual = true, _disposed = false;
|
||||
ConnectionState _state = const ConnectionState(ConnectionKind.idle);
|
||||
Future<void> _queue = Future.value();
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
Stream<ConnectionState> get states => _states.stream;
|
||||
ConnectionState get state => _state;
|
||||
|
||||
Future<void> connect(Uri uri) async {
|
||||
if (_disposed) throw StateError('Client has been disposed');
|
||||
final endpoint = ServerUrl.validate(uri.toString());
|
||||
_endpoint = Uri.parse(endpoint.wsUrl);
|
||||
_manual = false;
|
||||
_attempt = 0;
|
||||
_reconnect?.cancel();
|
||||
await _open();
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final endpoint = _endpoint;
|
||||
if (endpoint == null || _disposed) return;
|
||||
final generation = ++_generation;
|
||||
_setState(ConnectionState(ConnectionKind.connecting, attempt: ++_attempt));
|
||||
final old = _channel;
|
||||
_channel = null;
|
||||
await _subscription?.cancel();
|
||||
_failPending('Connection replaced');
|
||||
if (old != null) unawaited(old.sink.close());
|
||||
try {
|
||||
final channel = _factory(endpoint);
|
||||
_channel = channel;
|
||||
_subscription = channel.stream.listen((data) {
|
||||
if (generation == _generation) _onMessage(data);
|
||||
}, onError: (Object error) {
|
||||
if (generation == _generation) _closed(error.toString());
|
||||
}, onDone: () {
|
||||
if (generation == _generation) _closed('Connection closed');
|
||||
});
|
||||
await channel.ready;
|
||||
if (generation != _generation) return;
|
||||
_attempt = 0;
|
||||
_setState(const ConnectionState(ConnectionKind.connected));
|
||||
} catch (error) {
|
||||
if (generation == _generation) _closed(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _setState(ConnectionState value) { _state = value; if (!_states.isClosed) _states.add(value); }
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||
final completer = Completer<JsonMap>();
|
||||
final run = _queue.then((_) => _sendCall(type, fields, completer));
|
||||
_queue = run.catchError((_) {});
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Future<void> _sendCall(String type, JsonMap fields, Completer<JsonMap> result) async {
|
||||
final channel = _channel;
|
||||
if (channel == null || _state.kind != ConnectionKind.connected) { result.completeError(const NotConnectedError()); return; }
|
||||
final id = 'flutter-${++_sequence}';
|
||||
_pending[id] = result;
|
||||
final timer = Timer(requestTimeout, () {
|
||||
if (_pending.remove(id) != null) result.completeError(TimeoutException('request timed out after ${requestTimeout.inMilliseconds}ms'));
|
||||
});
|
||||
result.future.then<void>((_) => timer.cancel(), onError: (Object error, StackTrace stack) => timer.cancel());
|
||||
try {
|
||||
channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id}));
|
||||
} catch (error) {
|
||||
timer.cancel();
|
||||
if (_pending.remove(id) != null) result.completeError(error);
|
||||
}
|
||||
}
|
||||
|
||||
String sendOnly(String type, [JsonMap fields = const {}]) {
|
||||
final channel = _channel;
|
||||
if (channel == null || _state.kind != ConnectionKind.connected) throw const NotConnectedError();
|
||||
final id = 'flutter-${++_sequence}';
|
||||
channel.sink.add(jsonEncode({...fields, 'type': type, 'id': id}));
|
||||
return id;
|
||||
}
|
||||
|
||||
void _onMessage(dynamic data) {
|
||||
if (data is! String) return;
|
||||
final Object? decoded;
|
||||
try { decoded = jsonDecode(data); } on FormatException { return; }
|
||||
if (decoded is! Map<String, dynamic>) return;
|
||||
final message = decoded;
|
||||
final id = message['id'];
|
||||
final pending = id is String ? _pending.remove(id) : null;
|
||||
if (pending != null) {
|
||||
if (message['type'] == 'error') {
|
||||
final reason = (message['error'] as String? ?? '').trim();
|
||||
pending.completeError(ProtocolError(reason.isEmpty ? 'server error' : reason));
|
||||
} else {
|
||||
pending.complete(message);
|
||||
}
|
||||
} else if (!_frames.isClosed) { _frames.add(message); }
|
||||
}
|
||||
|
||||
void _failPending(String reason) {
|
||||
final values = _pending.values.toList(); _pending.clear();
|
||||
for (final item in values) { if (!item.isCompleted) item.completeError(StateError(reason)); }
|
||||
}
|
||||
|
||||
void _closed(String reason) {
|
||||
_generation++;
|
||||
_channel = null;
|
||||
_failPending(reason);
|
||||
if (_manual || _disposed) { _setState(const ConnectionState(ConnectionKind.idle)); return; }
|
||||
_setState(ConnectionState(ConnectionKind.disconnected, attempt: _attempt, reason: reason, retrying: true));
|
||||
final shift = (_attempt - 1).clamp(0, 6);
|
||||
final delay = backoffBase * (1 << shift);
|
||||
_reconnect?.cancel();
|
||||
_reconnect = Timer(delay > backoffMax ? backoffMax : delay, () => unawaited(_open()));
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
_manual = true; _reconnect?.cancel(); _generation++;
|
||||
final channel = _channel; _channel = null;
|
||||
await _subscription?.cancel(); _subscription = null;
|
||||
_failPending('Disconnected');
|
||||
if (channel != null) await channel.sink.close();
|
||||
_setState(const ConnectionState(ConnectionKind.idle));
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
await disconnect(); _disposed = true;
|
||||
await _frames.close(); await _states.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/// Validation result for a configured Pipelines websocket endpoint.
|
||||
class ServerUrl {
|
||||
const ServerUrl._({required this.wsUrl, required this.httpUrl,
|
||||
required this.host, required this.port, required this.secure});
|
||||
|
||||
final String wsUrl;
|
||||
final String httpUrl;
|
||||
final String host;
|
||||
final int port;
|
||||
final bool secure;
|
||||
|
||||
static ServerUrl validate(String raw) {
|
||||
final value = raw.trim();
|
||||
if (value.isEmpty) throw const FormatException('Enter the Pipelines server URL, for example ws://192.168.1.20:8081/connect');
|
||||
final uri = Uri.tryParse(value);
|
||||
if (uri == null || !uri.hasScheme) throw const FormatException('That is not a valid URL.');
|
||||
final scheme = uri.scheme.toLowerCase();
|
||||
if (scheme != 'ws' && scheme != 'wss') {
|
||||
throw FormatException('Unsupported scheme "$scheme"; use ws:// (trusted LAN/VPN) or wss://');
|
||||
}
|
||||
if (uri.userInfo.isNotEmpty) throw const FormatException('Credentials are not supported; the server has no authentication. Remove userinfo from the URL');
|
||||
if (uri.hasFragment) throw const FormatException('Remove the # fragment; it is not part of the server endpoint');
|
||||
if (uri.host.isEmpty) throw const FormatException('The URL is missing a host, for example ws://192.168.1.20:8081/connect');
|
||||
final secure = scheme == 'wss';
|
||||
final port = uri.hasPort ? uri.port : secure ? 443 : 80;
|
||||
final path = uri.path.isEmpty || uri.path == '/' ? '/connect' : uri.path;
|
||||
final authority = uri.hasPort ? '${uri.host}:$port' : uri.host;
|
||||
final suffix = uri.hasQuery ? '?${uri.query}' : '';
|
||||
return ServerUrl._(wsUrl: '$scheme://$authority$path$suffix',
|
||||
httpUrl: '${secure ? 'https' : 'http'}://$authority$path$suffix',
|
||||
host: uri.host, port: port, secure: secure);
|
||||
}
|
||||
|
||||
static Uri? resolveArtifactUrl(String configured, String artifactUrl) {
|
||||
final path = artifactUrl.trim();
|
||||
if (path.isEmpty) return null;
|
||||
final parsed = Uri.tryParse(path);
|
||||
if (parsed != null && (parsed.scheme == 'http' || parsed.scheme == 'https')) return parsed;
|
||||
try {
|
||||
final endpoint = validate(configured);
|
||||
final portPart = endpoint.port != (endpoint.secure ? 443 : 80) ? ':${endpoint.port}' : '';
|
||||
return Uri.parse('${endpoint.secure ? 'https' : 'http'}://${endpoint.host}$portPart/${path.replaceFirst(RegExp(r'^/+'), '')}');
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user