diff --git a/app/lib/main.dart b/app/lib/main.dart index 5c6f9ea..ae6d338 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -5,6 +5,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'src/state/theme_provider.dart'; import 'src/theme/app_theme.dart'; import 'src/ui/profiles_screen.dart'; +import 'src/ui/widgets/session_banner.dart'; + +final _navigatorKey = GlobalKey(); void main() { WidgetsFlutterBinding.ensureInitialized(); @@ -30,6 +33,8 @@ class DockerMobileApp extends ConsumerWidget { theme: buildAppTheme(lightScheme), darkTheme: buildAppTheme(darkScheme), themeMode: settings.mode, + navigatorKey: _navigatorKey, + builder: (context, child) => SessionBannerHost(navigatorKey: _navigatorKey, child: child!), home: const ProfilesScreen(), ); }, diff --git a/app/lib/src/api/docker_api_client.dart b/app/lib/src/api/docker_api_client.dart index 486253d..fd88659 100644 --- a/app/lib/src/api/docker_api_client.dart +++ b/app/lib/src/api/docker_api_client.dart @@ -73,17 +73,40 @@ class DockerApiClient { Stream> _postStream(String path, {Map? query, Object? body}) => _wrapErrors(() => transport.postStream(_p(path), query: query, body: body)); - /// Re-raises anything the transport emits as a [DockerError]. Cancelling the - /// returned stream cancels the source at the source's next event (an async* - /// generator suspended at an await cannot be cancelled earlier). - Stream> _wrapErrors(Stream> Function() open) async* { + /// Re-raises anything the transport emits as a [DockerError]. Built from + /// stream operators, not an async* generator, so cancelling the returned + /// stream cancels the transport stream immediately. A synchronous throw + /// from the transport becomes an error event. + Stream> _wrapErrors(Stream> Function() open) { + final Stream> source; try { - final source = open(); - await for (final chunk in source) { - yield chunk; - } + source = open(); } catch (e, st) { - Error.throwWithStackTrace(DockerError.wrap(e), st); + return Stream>.error(DockerError.wrap(e), st); + } + return source.handleError( + (Object e, StackTrace st) => Error.throwWithStackTrace(DockerError.wrap(e), st), + ); + } + + /// Splits an NDJSON byte stream into parsed values, skipping blank and + /// malformed lines. A trailing line without a newline is still parsed when + /// the stream ends. Cancelling the result cancels [raw] immediately. + static Stream _ndjson(Stream> raw, T? Function(String line) parse) => raw + .transform(const Utf8Decoder(allowMalformed: true)) + .transform(const LineSplitter()) + .expand((line) { + final value = parse(line); + return value == null ? [] : [value]; + }); + + static T? _parseJson(String line, T Function(Map) fromJson) { + final t = line.trim(); + if (t.isEmpty) return null; + try { + return fromJson(jsonDecode(t) as Map); + } catch (_) { + return null; // skip a malformed line } } @@ -250,34 +273,8 @@ class DockerApiClient { return (jsonDecode(resp.body) as List).map((e) => ImageHistoryLayer.fromJson(e as Map)).toList(); } - Stream pullImage(String image, {String tag = 'latest'}) async* { - final raw = _postStream('/images/create', query: {'fromImage': image, 'tag': tag}); - final buffer = []; // buffer BYTES so a multi-byte UTF-8 char split across chunks survives - await for (final chunk in raw) { - buffer.addAll(chunk); - var nl = buffer.indexOf(0x0A); - while (nl != -1) { - final ev = _parsePullLine(utf8.decode(buffer.sublist(0, nl), allowMalformed: true)); - buffer.removeRange(0, nl + 1); - if (ev != null) yield ev; - nl = buffer.indexOf(0x0A); - } - } - if (buffer.isNotEmpty) { - final ev = _parsePullLine(utf8.decode(buffer, allowMalformed: true)); - if (ev != null) yield ev; - } - } - - PullEvent? _parsePullLine(String line) { - final t = line.trim(); - if (t.isEmpty) return null; - try { - return PullEvent.fromJson(jsonDecode(t) as Map); - } catch (_) { - return null; // skip a fragment that isn't a complete JSON object - } - } + Stream pullImage(String image, {String tag = 'latest'}) => + _ndjson(_postStream('/images/create', query: {'fromImage': image, 'tag': tag}), (line) => _parseJson(line, PullEvent.fromJson)); Future tagImage(String id, {required String repo, String tag = 'latest'}) async => _ensure(await _post('/images/$id/tag', query: {'repo': repo, 'tag': tag}), ok: const {201}); @@ -425,45 +422,13 @@ class DockerApiClient { if (includeVolumes) await pruneVolumes(); } - Stream streamContainerStats(String id) async* { - final raw = _stream('/containers/$id/stats', query: {'stream': 'true'}); - final buffer = []; - await for (final chunk in raw) { - buffer.addAll(chunk); - var nl = buffer.indexOf(0x0A); - while (nl != -1) { - final line = utf8.decode(buffer.sublist(0, nl), allowMalformed: true).trim(); - buffer.removeRange(0, nl + 1); - if (line.isNotEmpty) { - try { - yield ContainerStats.fromJson(jsonDecode(line) as Map); - } catch (_) { - // skip a malformed/partial line - } - } - nl = buffer.indexOf(0x0A); - } - } - } + Stream streamContainerStats(String id) => _ndjson( + _stream('/containers/$id/stats', query: {'stream': 'true'}), + (line) => _parseJson(line, ContainerStats.fromJson), + ); - Stream streamEvents({String? since}) async* { - final raw = _stream('/events', query: since == null ? null : {'since': since}); - final buffer = []; - await for (final chunk in raw) { - buffer.addAll(chunk); - var nl = buffer.indexOf(0x0A); - while (nl != -1) { - final line = utf8.decode(buffer.sublist(0, nl), allowMalformed: true).trim(); - buffer.removeRange(0, nl + 1); - if (line.isNotEmpty) { - try { - yield DockerEvent.fromJson(jsonDecode(line) as Map); - } catch (_) { - // skip a malformed/partial line - } - } - nl = buffer.indexOf(0x0A); - } - } - } + Stream streamEvents({String? since}) => _ndjson( + _stream('/events', query: since == null ? null : {'since': since}), + (line) => _parseJson(line, DockerEvent.fromJson), + ); } diff --git a/app/lib/src/api/stdcopy.dart b/app/lib/src/api/stdcopy.dart index 59059fa..3ee6f45 100644 --- a/app/lib/src/api/stdcopy.dart +++ b/app/lib/src/api/stdcopy.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:typed_data'; /// Upper bound on a single stdcopy frame's declared payload length. A header @@ -16,46 +17,46 @@ class LogChunk { /// Decodes Docker's stdcopy multiplexed stream (used for non-TTY containers): /// repeating `[type, 0,0,0, len(uint32 big-endian), ...payload]` frames. /// Reassembles frames split across input chunks; never throws on bad input. -Stream decodeStdcopy(Stream> input) async* { +/// Built as a transformer, so cancelling the result cancels [input] at once. +Stream decodeStdcopy(Stream> input) { var acc = Uint8List(0); - await for (final chunk in input) { - if (chunk.isEmpty) continue; - final merged = Uint8List(acc.length + chunk.length) - ..setRange(0, acc.length, acc) - ..setRange(acc.length, acc.length + chunk.length, chunk); - acc = merged; + return input.transform(StreamTransformer, LogChunk>.fromHandlers( + handleData: (chunk, sink) { + if (chunk.isEmpty) return; + final merged = Uint8List(acc.length + chunk.length) + ..setRange(0, acc.length, acc) + ..setRange(acc.length, acc.length + chunk.length, chunk); + acc = merged; - var offset = 0; - while (acc.length - offset >= 8) { - final type = acc[offset]; - if (type > 2) { - // Malformed/desynced: surface the rest defensively and stop parsing. - yield LogChunk(LogStream.stderr, acc.sublist(offset)); - offset = acc.length; - break; + var offset = 0; + while (acc.length - offset >= 8) { + final type = acc[offset]; + if (type > 2) { + // Malformed/desynced: surface the rest defensively and stop parsing. + sink.add(LogChunk(LogStream.stderr, acc.sublist(offset))); + offset = acc.length; + break; + } + final len = (acc[offset + 4] << 24) | + (acc[offset + 5] << 16) | + (acc[offset + 6] << 8) | + acc[offset + 7]; + if (len > _maxFrameLen) { + // Implausible length => corrupt header; surface the rest and stop. + sink.add(LogChunk(LogStream.stderr, acc.sublist(offset))); + offset = acc.length; + break; + } + if (acc.length - offset - 8 < len) break; // need more bytes + final payload = acc.sublist(offset + 8, offset + 8 + len); + sink.add(LogChunk(type == 2 ? LogStream.stderr : LogStream.stdout, payload)); + offset += 8 + len; } - final len = (acc[offset + 4] << 24) | - (acc[offset + 5] << 16) | - (acc[offset + 6] << 8) | - acc[offset + 7]; - if (len > _maxFrameLen) { - // Implausible length => corrupt header; surface the rest and stop. - yield LogChunk(LogStream.stderr, acc.sublist(offset)); - offset = acc.length; - break; - } - if (acc.length - offset - 8 < len) break; // need more bytes - final payload = acc.sublist(offset + 8, offset + 8 + len); - yield LogChunk(type == 2 ? LogStream.stderr : LogStream.stdout, payload); - offset += 8 + len; - } - acc = offset == 0 ? acc : acc.sublist(offset); - } + acc = offset == 0 ? acc : acc.sublist(offset); + }, + )); } /// TTY passthrough: TTY containers emit a single un-framed stream. -Stream decodeRawLog(Stream> input) async* { - await for (final chunk in input) { - yield LogChunk(LogStream.stdout, chunk); - } -} +Stream decodeRawLog(Stream> input) => + input.map((chunk) => LogChunk(LogStream.stdout, chunk)); diff --git a/app/lib/src/api/timestamps.dart b/app/lib/src/api/timestamps.dart index 0411622..a50b014 100644 --- a/app/lib/src/api/timestamps.dart +++ b/app/lib/src/api/timestamps.dart @@ -20,3 +20,15 @@ String? rfc3339ToUnixNanos(String ts) { frac = frac.length > 9 ? frac.substring(0, 9) : frac.padRight(9, '0'); return '$secs.$frac'; } + +/// An RFC3339(Nano) timestamp as epoch nanoseconds (fits in 64 bits until +/// the year 2262), keeping all nine fractional digits. Null if unparsable. +int? rfc3339ToEpochNanos(String ts) { + final s = rfc3339ToUnixNanos(ts); + if (s == null) return null; + final dot = s.indexOf('.'); + final secs = int.tryParse(s.substring(0, dot)); + final nanos = int.tryParse(s.substring(dot + 1)); + if (secs == null || nanos == null) return null; + return secs * 1000000000 + nanos; +} diff --git a/app/lib/src/connect/connection_launcher.dart b/app/lib/src/connect/connection_launcher.dart index 222bf99..a0a44b7 100644 --- a/app/lib/src/connect/connection_launcher.dart +++ b/app/lib/src/connect/connection_launcher.dart @@ -1,115 +1,49 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../session/transport_factory.dart'; import '../state/providers.dart'; -import '../storage/credential_store.dart'; import '../storage/profile_store.dart'; -import '../transport/connection_config.dart'; -import '../transport/ssh/host_key.dart'; -import '../transport/ssh/ssh_transport.dart'; -import '../transport/tls_security.dart'; -import '../transport/transport.dart'; import '../ui/home_screen.dart'; -/// Establishes a transport from a saved [profile] and navigates to the home -/// screen. The only place the SSH host-key TOFU dialog lives. -Future launchConnection(BuildContext context, WidgetRef ref, ConnectionProfile profile) async { - switch (profile.kind) { - case ConnectionKind.agent: - final a = profile.agent!; - ref.read(transportProvider.notifier).state = - AgentConnectionConfig(baseUri: Uri.parse(a.baseUri), token: a.token).build(); - Navigator.of(context).push(MaterialPageRoute(builder: (_) => const HomeScreen())); - case ConnectionKind.tls: - final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); - final t = profile.tls!; - final Transport transport; - try { - transport = TlsConnectionConfig( - host: t.host, port: t.port, - clientCertPem: t.clientCertPem, clientKeyPem: t.clientKeyPem, - caPem: t.caPem, insecure: t.insecure, - ).build(); - } on TlsConfigException catch (e) { - messenger.showSnackBar(SnackBar(content: Text('Invalid certificate: ${e.message}'))); - return; - } - ref.read(transportProvider.notifier).state = transport; - navigator.push(MaterialPageRoute(builder: (_) => const HomeScreen())); - case ConnectionKind.ssh: - await _launchSsh(context, ref, profile); - } -} - -Future _launchSsh(BuildContext context, WidgetRef ref, ConnectionProfile profile, {String? overridePin}) async { - final messenger = ScaffoldMessenger.of(context); +/// Connects the session to [profile] and opens Home when this very attempt +/// connected; one that failed or was cancelled opens nothing, whatever the +/// session is doing by then. The only place the SSH host-key TOFU dialog +/// lives. A failed connect stays in the session state, which the +/// Connections screen shows inline. +/// +/// The session lasts as long as Home does: once Home is closed, by the back +/// button or by a Disconnect action, the session is disconnected, and only +/// then does the returned future complete. +Future launchConnection(BuildContext context, WidgetRef ref, ConnectionProfile profile, + {String? pinOverride}) async { final navigator = Navigator.of(context); - final ssh = profile.ssh!; - final pin = overridePin ?? ssh.pinnedHostKey; - final creds = SshCredentials( - host: ssh.host, port: ssh.port, username: ssh.username, authMethod: ssh.authMethod, - password: ssh.password, privateKeyPem: ssh.privateKeyPem, passphrase: ssh.passphrase, pinnedHostKey: pin, - ); - final conn = ref.read(sshConnectionFactoryProvider)(creds); - String? presented; - var mismatch = false; - bool verifier(String fp) { - presented = fp; - if (verifyHostKey(pin, fp) == HostKeyVerdict.mismatch) { - mismatch = true; - return false; - } - return true; - } - + final session = ref.read(sessionProvider.notifier); + final bool connected; try { - await conn.connect(verifyHostKey: verifier); - } catch (e) { - await conn.close(); - if (mismatch && presented != null) { - if (!context.mounted) return; - final trust = await showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: const Text('Host key changed'), - content: const Text( - 'The server host key does not match the pinned key. This could be a man-in-the-middle attack. Trust the new key only if you expected this change.'), - actions: [ - TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')), - TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Trust new key')), - ], - ), - ); - if (trust == true && context.mounted) { - await _launchSsh(context, ref, profile, overridePin: presented); - } - return; + connected = await session.connect(profile, pinOverride: pinOverride); + } on HostKeyMismatchException catch (e) { + if (!context.mounted) return; + final trust = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Host key changed'), + content: const Text( + 'The server host key does not match the pinned key. This could be a man-in-the-middle attack. Trust the new key only if you expected this change.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Trust new key')), + ], + ), + ); + if (trust == true && context.mounted) { + await launchConnection(context, ref, profile, pinOverride: e.presentedFingerprint); } - messenger.showSnackBar(SnackBar(content: Text('Connection failed: $e'))); return; } - - // The originating widget (and its ref) may have been disposed during the - // handshake; don't read a dead ref - and don't leak the live SSH client. - if (!context.mounted) { - await conn.close(); - return; - } - final newPin = pin ?? presented; - if (newPin != ssh.pinnedHostKey) { - await ref.read(profileStoreProvider).update(profile.copyWith( - ssh: SshCredentials( - host: ssh.host, port: ssh.port, username: ssh.username, authMethod: ssh.authMethod, - password: ssh.password, privateKeyPem: ssh.privateKeyPem, passphrase: ssh.passphrase, pinnedHostKey: newPin, - ), - )); - if (!context.mounted) { - await conn.close(); - return; - } - ref.invalidate(profilesProvider); + if (connected && context.mounted) { + await navigator.push(MaterialPageRoute(builder: (_) => const HomeScreen())); + // Home is gone, however it was left: nothing can show this session any more. + await session.disconnect(); } - ref.read(transportProvider.notifier).state = SshTransport(openDuplex: conn.openChannel, onClose: conn.close); - navigator.push(MaterialPageRoute(builder: (_) => const HomeScreen())); } diff --git a/app/lib/src/connect/disconnect.dart b/app/lib/src/connect/disconnect.dart index 74f7883..61d291d 100644 --- a/app/lib/src/connect/disconnect.dart +++ b/app/lib/src/connect/disconnect.dart @@ -3,17 +3,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../state/providers.dart'; -/// Tears down the active connection and returns to the profiles list: -/// pop first (disposing the home screen + its providers), then detach and -/// close the transport (best-effort). -Future disconnect(BuildContext context, WidgetRef ref) async { - final navigator = Navigator.of(context); - final transport = ref.read(transportProvider); - navigator.popUntil((r) => r.isFirst); - ref.read(transportProvider.notifier).state = null; - // Best-effort teardown: the UI is already back at the list, so a close - // failure must not surface as an unhandled async error. - try { - await transport?.close(); - } catch (_) {} +/// Returns to the Connections list, then tears the session down: pop first +/// (disposing the screens that watch the connection), then disconnect. +/// Pass [navigator] when [context] sits above the app's navigator. +Future disconnect(BuildContext context, WidgetRef ref, {NavigatorState? navigator}) async { + final nav = navigator ?? Navigator.of(context); + final session = ref.read(sessionProvider.notifier); + nav.popUntil((r) => r.isFirst); + await session.disconnect(); } diff --git a/app/lib/src/session/docker_session.dart b/app/lib/src/session/docker_session.dart new file mode 100644 index 0000000..00cb645 --- /dev/null +++ b/app/lib/src/session/docker_session.dart @@ -0,0 +1,413 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart' show AppLifecycleState; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../api/api_version.dart'; +import '../api/docker_api_client.dart'; +import '../api/models/docker_event.dart'; +import '../api/models/system_info.dart'; +import '../storage/credential_store.dart'; +import '../storage/profile_store.dart'; +import '../transport/transport.dart'; +import 'events_hub.dart'; +import 'lifecycle_source.dart'; +import 'reconnect_policy.dart'; +import 'session_state.dart'; +import 'transport_factory.dart'; + +/// Builds the API client for a transport; a null [apiVersion] sends unversioned paths. +typedef ClientFactory = DockerApiClient Function(Transport transport, String? apiVersion); + +DockerApiClient _defaultClient(Transport transport, String? apiVersion) => + DockerApiClient(transport, apiVersion: apiVersion); + +/// Owns the connection to one daemon: connects and probes it, keeps an +/// events stream open as the liveness signal, reconnects with backoff when +/// that stream dies, and pauses in the background. +class DockerSession extends StateNotifier { + DockerSession({ + required TransportFactory transportFactory, + required ReconnectPolicy policy, + required LifecycleSource lifecycle, + required Invalidator invalidator, + required ProfileStore profileStore, + ClientFactory? clientFactory, + void Function(DockerEvent)? onEvent, + void Function()? onNewSession, + void Function()? onProfilesChanged, + Duration eventsDebounce = const Duration(milliseconds: 500), + Duration dashboardDebounce = const Duration(seconds: 2), + }) : _factory = transportFactory, + // ignore: prefer_initializing_formals + _policy = policy, + // ignore: prefer_initializing_formals + _lifecycle = lifecycle, + // ignore: prefer_initializing_formals + _invalidator = invalidator, + _profiles = profileStore, + _clientFactory = clientFactory ?? _defaultClient, + // ignore: prefer_initializing_formals + _onNewSession = onNewSession, + // ignore: prefer_initializing_formals + _onProfilesChanged = onProfilesChanged, + super(const SessionState()) { + _hub = EventsHub( + open: (since) { + final client = _client; + if (client == null) { + return Stream.error(const DockerError(DockerErrorKind.unknown, 'Not connected')); + } + return client.streamEvents(since: since); + }, + onEvent: (e) => onEvent?.call(e), + invalidator: invalidator, + onLost: livenessLost, + debounce: eventsDebounce, + dashboardDebounce: dashboardDebounce, + ); + } + + final TransportFactory _factory; + final ReconnectPolicy _policy; + final LifecycleSource _lifecycle; + final Invalidator _invalidator; + final ProfileStore _profiles; + final ClientFactory _clientFactory; + final void Function()? _onNewSession; + final void Function()? _onProfilesChanged; + late final EventsHub _hub; + + DockerApiClient? _client; + Timer? _retryTimer; + + /// Attempts used by reconnects whose events stream has not yet stayed up + /// for the policy cap; the next loss continues from here. + int _unsettled = 0; + Timer? _settleTimer; + StreamSubscription? _lifecycleSub; + /// Generation of the reconnect attempt in flight, if any. An attempt left + /// over from an older generation never blocks one for the current one. + int? _attemptGeneration; + + /// Bumped by every connect/disconnect; async work started under an older + /// generation discards its result. + int _generation = 0; + + bool _current(int gen) => mounted && gen == _generation; + + /// The client on the current transport, or null while not connected. It is + /// already the new one when listeners hear about a reconnect; providers + /// derived from [state] catch up only after their own listener has run. + DockerApiClient? get client => _client; + + /// Builds a transport for [profile], probes the daemon and goes live. + /// Returns true when this attempt connected the session, and false when it + /// failed (see `state.error`), was ignored because another attempt was + /// already in flight, or was cancelled or superseded before it finished. + /// Throws only [HostKeyMismatchException] (and only while this attempt is + /// still current). + Future connect(ConnectionProfile profile, {String? pinOverride}) async { + if (state.status == SessionStatus.connecting) return false; + _lifecycleSub ??= _lifecycle.changes.listen(_onLifecycle); + _stopActivity(); + final previous = state.transport; + final gen = ++_generation; + final sessionId = state.sessionId + 1; + state = SessionState( + status: SessionStatus.connecting, + profile: profile, + sessionId: sessionId, + foreground: state.foreground, + ); + unawaited(_closeQuietly(previous)); + _onNewSession?.call(); + + BuiltTransport? built; + try { + built = await _factory.build(profile, pinOverride: pinOverride); + if (!_current(gen)) { + await _closeQuietly(built.transport); + return false; + } + final probe = await _probe(built.transport); + if (!_current(gen)) { + await _closeQuietly(built.transport); + return false; + } + final pinned = await _persistPin(profile, pinOverride, built.presentedHostKey); + if (!_current(gen)) { + await _closeQuietly(built.transport); + return false; + } + _client = _clientFactory(built.transport, probe.apiVersion); + state = state.copyWith( + status: SessionStatus.connected, + profile: pinned, + transport: built.transport, + apiVersion: probe.apiVersion, + daemon: probe.daemon, + warning: _warningFor(probe.daemon.apiVersion), + attempt: 0, + ); + _hub.start(); + if (!state.foreground) _hub.pause(); + return true; + } on HostKeyMismatchException { + // A superseded handshake must not raise the trust dialog. + if (!_current(gen)) return false; + state = SessionState(profile: profile, sessionId: sessionId, foreground: state.foreground); + rethrow; + } catch (e) { + final t = built?.transport; + if (t != null) await _closeQuietly(t); + if (_current(gen)) { + state = SessionState( + profile: profile, + sessionId: sessionId, + foreground: state.foreground, + error: DockerError.wrap(e), + ); + } + return false; + } + } + + /// The events stream died (error or clean end): start reconnecting. A + /// reconnect counts as recovered only once the stream has stayed up for + /// the policy cap; a loss before that continues the attempt count, and + /// fails the session when the limit is used up. A return to the + /// foreground starts the count again. + void livenessLost(DockerError error) { + if (!mounted || state.status != SessionStatus.connected) return; + // Drop pending refreshes too: they would hit the dead connection, and a reconnect refreshes everything. + _hub.stop(); + _settleTimer?.cancel(); + _settleTimer = null; + if (_unsettled >= _policy.maxAttempts) { + state = state.copyWith(status: SessionStatus.failed, error: error); + return; + } + state = state.copyWith(status: SessionStatus.reconnecting, attempt: _unsettled + 1, error: error); + _scheduleAttempt(); + } + + /// From failed: try again now with a fresh attempt count. + void retry() { + if (state.status != SessionStatus.failed) return; + _unsettled = 0; + state = state.copyWith(status: SessionStatus.reconnecting, attempt: 1); + unawaited(_attemptReconnect()); + } + + /// Drops the connection and returns to disconnected. + Future disconnect() async { + _generation++; + _stopActivity(); + final t = state.transport; + state = SessionState(sessionId: state.sessionId, foreground: state.foreground); + await _closeQuietly(t); + } + + /// The UI showed [SessionState.warning]; clear it. + void acknowledgeWarning() { + if (state.warning != null) state = state.copyWith(clearWarning: true); + } + + @override + void dispose() { + _generation++; + _stopActivity(); + _lifecycleSub?.cancel(); + final t = state.transport; + unawaited(_closeQuietly(t)); + super.dispose(); + } + + void _stopActivity() { + _retryTimer?.cancel(); + _retryTimer = null; + _settleTimer?.cancel(); + _settleTimer = null; + _unsettled = 0; + _hub.stop(); + _client = null; + } + + void _scheduleAttempt() { + _retryTimer?.cancel(); + _retryTimer = null; + if (!state.foreground || state.status != SessionStatus.reconnecting) return; + _retryTimer = Timer(_policy.delay(state.attempt), () { + _retryTimer = null; + unawaited(_attemptReconnect()); + }); + } + + Future _attemptReconnect() async { + _retryTimer?.cancel(); + _retryTimer = null; + final profile = state.profile; + if (_attemptGeneration == _generation || profile == null) return; + if (state.status != SessionStatus.reconnecting || !state.foreground) return; + final gen = _generation; + _attemptGeneration = gen; + BuiltTransport? built; + try { + built = await _factory.build(profile); + if (!_current(gen) || state.status != SessionStatus.reconnecting) { + await _closeQuietly(built.transport); + return; + } + final probe = await _probe(built.transport); + if (!_current(gen) || state.status != SessionStatus.reconnecting) { + await _closeQuietly(built.transport); + return; + } + final old = state.transport; + // Recovered only once the events stream has stayed up for the cap. + _unsettled = state.attempt; + _settleTimer?.cancel(); + _settleTimer = Timer(_policy.cap, () { + _settleTimer = null; + _unsettled = 0; + }); + _client = _clientFactory(built.transport, probe.apiVersion); + state = state.copyWith( + status: SessionStatus.connected, + transport: built.transport, + apiVersion: probe.apiVersion, + daemon: probe.daemon, + attempt: 0, + clearError: true, + ); + // Adopted: the catch below must not close it. + built = null; + unawaited(_closeQuietly(old)); + // The events stream first: a refresh that throws must not leave the session without it. + if (state.foreground) _hub.resume(); + // What is on screen was fetched over the old transport: refresh it in place. + _invalidator.all(); + } on HostKeyMismatchException { + if (!_current(gen)) return; + state = state.copyWith( + status: SessionStatus.failed, + error: const DockerError( + DockerErrorKind.unauthorized, + 'Host key changed - reconnect from the Connections screen to review it', + ), + ); + } catch (e) { + final t = built?.transport; + if (t != null) await _closeQuietly(t); + if (!_current(gen) || state.status != SessionStatus.reconnecting) return; + final error = DockerError.wrap(e); + if (!error.retryable || state.attempt >= _policy.maxAttempts) { + state = state.copyWith(status: SessionStatus.failed, error: error); + } else { + state = state.copyWith(attempt: state.attempt + 1, error: error); + _scheduleAttempt(); + } + } finally { + if (_attemptGeneration == gen) _attemptGeneration = null; + } + } + + void _onLifecycle(AppLifecycleState s) { + if (!mounted) return; + if (s == AppLifecycleState.paused) { + if (!state.foreground) return; + state = state.copyWith(foreground: false); + // Pending refreshes too: they would fire in the background, possibly on a + // connection that died there, and the return refreshes everything. + _hub.stop(); + _retryTimer?.cancel(); + _retryTimer = null; + } else if (s == AppLifecycleState.resumed) { + if (state.foreground) return; + state = state.copyWith(foreground: true); + // What was closed on purpose in the background does not count against + // the attempt limit: a loss found now is a new one. + _settleTimer?.cancel(); + _settleTimer = null; + _unsettled = 0; + switch (state.status) { + case SessionStatus.connected: + unawaited(_checkAfterResume()); + case SessionStatus.reconnecting: + unawaited(_attemptReconnect()); + case SessionStatus.disconnected: + case SessionStatus.connecting: + case SessionStatus.failed: + break; + } + } + } + + Future _checkAfterResume() async { + final gen = _generation; + final client = _client; + if (client == null) return; + try { + await client.ping(); + // An answer about a client that has been replaced says nothing about the connection in use. + if (!_current(gen) || !identical(client, _client)) return; + if (state.status != SessionStatus.connected || !state.foreground) return; + _hub.resume(); + // The daemon keeps only a bounded backlog of events: what happened meanwhile may be gone from it. + _invalidator.all(); + } catch (e) { + if (!_current(gen) || !identical(client, _client)) return; + livenessLost(DockerError.wrap(e)); + } + } + + Future<({String apiVersion, VersionInfo daemon})> _probe(Transport transport) async { + final raw = _clientFactory(transport, null); + await raw.ping(); + final daemon = await raw.getVersion(); + return (apiVersion: negotiateApiVersion(daemon.apiVersion), daemon: daemon); + } + + /// Saves a first-use or newly trusted SSH host key into the profile. + Future _persistPin( + ConnectionProfile profile, + String? pinOverride, + String? presented, + ) async { + final ssh = profile.ssh; + if (profile.kind != ConnectionKind.ssh || ssh == null) return profile; + final newPin = pinOverride ?? ssh.pinnedHostKey ?? presented; + if (newPin == null || newPin == ssh.pinnedHostKey) return profile; + final updated = profile.copyWith( + ssh: SshCredentials( + host: ssh.host, + port: ssh.port, + username: ssh.username, + authMethod: ssh.authMethod, + password: ssh.password, + privateKeyPem: ssh.privateKeyPem, + passphrase: ssh.passphrase, + pinnedHostKey: newPin, + ), + ); + await _profiles.update(updated); + // The pin is stored whether or not this attempt is still wanted: the list has to show it. + if (mounted) _onProfilesChanged?.call(); + return updated; + } + + String? _warningFor(String daemonApiVersion) { + if (daemonApiVersion.trim().isEmpty || !isBelowMinSupported(daemonApiVersion)) return null; + return 'This daemon speaks Docker API $daemonApiVersion. docker-mobile is tested with ' + '$kMinSupportedApiVersion and newer, so some features may not work.'; + } + + static Future _closeQuietly(Transport? transport) async { + try { + await transport?.close(); + } catch (_) { + // best-effort teardown + } + } +} diff --git a/app/lib/src/session/events_hub.dart b/app/lib/src/session/events_hub.dart new file mode 100644 index 0000000..b3f54a8 --- /dev/null +++ b/app/lib/src/session/events_hub.dart @@ -0,0 +1,149 @@ +// Private fields are bound to public named constructor params (e.g. `open`), +// so keep the explicit initializer-list assignment. +// ignore_for_file: prefer_initializing_formals +import 'dart:async'; + +import '../api/docker_error.dart'; +import '../api/models/docker_event.dart'; +import '../api/timestamps.dart'; + +enum EventCategory { container, image, network, volume, other } + +EventCategory categoryOf(String type) => switch (type) { + 'container' => EventCategory.container, + 'image' => EventCategory.image, + 'network' => EventCategory.network, + 'volume' => EventCategory.volume, + _ => EventCategory.other, + }; + +/// Refreshes the data affected by daemon events. +abstract class Invalidator { + void list(EventCategory category); + void detail(EventCategory category, String id); + void dashboard(); + + /// The connection came back on a new transport, or the app returned to the + /// foreground: refresh everything shown. + void all(); +} + +/// Owns the session's single events subscription. Forwards every event, +/// schedules debounced refreshes, tracks a resume cursor, and reports a +/// lost stream (error or clean end) exactly once per subscription. +class EventsHub { + final Stream Function(String? since) _open; + final void Function(DockerEvent) _onEvent; + final Invalidator _invalidator; + final void Function(DockerError) _onLost; + final Duration debounce; + final Duration dashboardDebounce; + + StreamSubscription? _sub; + int _generation = 0; + int? _cursorNano; + final Map _timers = {}; + + EventsHub({ + required Stream Function(String? since) open, + required void Function(DockerEvent) onEvent, + required Invalidator invalidator, + required void Function(DockerError) onLost, + this.debounce = const Duration(milliseconds: 500), + this.dashboardDebounce = const Duration(seconds: 2), + }) : _open = open, + _onEvent = onEvent, + _invalidator = invalidator, + _onLost = onLost; + + /// Raw Engine time of the newest event seen, in nanoseconds. + int? get cursorNano => _cursorNano; + + bool get active => _sub != null; + + /// Begins a new subscription with no cursor (a new connection). + void start() { + _cancelSubscription(); + _cursorNano = null; + _listen(); + } + + /// Reopens after [pause], [stop] or a lost stream, from the cursor. + void resume() { + _cancelSubscription(); + _listen(); + } + + /// Stops reading without reporting a loss; keeps the cursor and timers. + void pause() => _cancelSubscription(); + + /// Stops reading and drops pending refreshes; keeps the cursor. + void stop() { + _cancelSubscription(); + for (final t in _timers.values) { + t.cancel(); + } + _timers.clear(); + } + + void _cancelSubscription() { + _generation++; + final sub = _sub; + _sub = null; + sub?.cancel(); + } + + void _listen() { + final gen = ++_generation; + final floor = _cursorNano; + final Stream stream; + try { + stream = _open(floor == null ? null : formatUnixNanos(floor)); + } catch (e) { + _lost(gen, DockerError.wrap(e)); + return; + } + _sub = stream.listen( + (e) { + if (gen != _generation) return; + final t = e.timeNano; + if (floor != null && t != null && t <= floor) return; // since is inclusive + if (t != null && (_cursorNano == null || t > _cursorNano!)) _cursorNano = t; + _onEvent(e); + _schedule(e); + }, + onError: (Object e) => _lost(gen, DockerError.wrap(e)), + onDone: () => _lost(gen, const DockerError(DockerErrorKind.network, 'The daemon closed the event stream')), + cancelOnError: true, + ); + } + + void _lost(int gen, DockerError error) { + if (gen != _generation) return; + _generation++; + _sub = null; + _onLost(error); + } + + void _schedule(DockerEvent e) { + final category = categoryOf(e.type); + if (category == EventCategory.other) return; + // Health checks run as exec_* events on every interval; they change + // nothing a list shows. + if (category == EventCategory.container && e.action.startsWith('exec_')) return; + _debounce('list:${category.name}', debounce, () => _invalidator.list(category)); + final hasDetail = category == EventCategory.container || category == EventCategory.image; + if (hasDetail && e.actorId.isNotEmpty) { + _debounce('detail:${category.name}:${e.actorId}', debounce, () => _invalidator.detail(category, e.actorId)); + } + _debounce('dashboard', dashboardDebounce, _invalidator.dashboard); + } + + void _debounce(String key, Duration delay, void Function() fire) { + _timers[key]?.cancel(); + _timers[key] = Timer(delay, () { + _timers.remove(key); + fire(); + }); + } +} diff --git a/app/lib/src/session/lifecycle_source.dart b/app/lib/src/session/lifecycle_source.dart new file mode 100644 index 0000000..52ce9be --- /dev/null +++ b/app/lib/src/session/lifecycle_source.dart @@ -0,0 +1,27 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// App foreground/background changes, abstracted so the session can be +/// tested without a widget binding. +abstract class LifecycleSource { + Stream get changes; +} + +/// Real source backed by [AppLifecycleListener]. The listener is attached on +/// the first subscription and detached when the last one cancels, so merely +/// constructing this object never touches the binding. +class AppLifecycleSource implements LifecycleSource { + AppLifecycleListener? _listener; + late final StreamController _controller = StreamController.broadcast( + sync: true, + onListen: () => _listener = AppLifecycleListener(onStateChange: _controller.add), + onCancel: () { + _listener?.dispose(); + _listener = null; + }, + ); + + @override + Stream get changes => _controller.stream; +} diff --git a/app/lib/src/session/reconnect_policy.dart b/app/lib/src/session/reconnect_policy.dart new file mode 100644 index 0000000..2b03541 --- /dev/null +++ b/app/lib/src/session/reconnect_policy.dart @@ -0,0 +1,32 @@ +import 'dart:math'; + +/// Exponential backoff with jitter: delay(n) = min(base x 2^(n-1), cap), +/// scaled by a random factor in [1 - jitter, 1 + jitter]. Shared by the +/// session reconnect loop and the stream supervisors. +class ReconnectPolicy { + final Duration base; + final Duration cap; + final double jitter; + + /// Attempts before giving up and reporting failure. + final int maxAttempts; + final Random _random; + + ReconnectPolicy({ + this.base = const Duration(seconds: 1), + this.cap = const Duration(seconds: 30), + this.jitter = 0.2, + this.maxAttempts = 5, + Random? random, + }) : _random = random ?? Random(); + + /// The wait before attempt [attempt] (1-based; values below 1 count as 1). + Duration delay(int attempt) { + final n = attempt < 1 ? 1 : attempt; + final exponent = min(n - 1, 30); // keep the shift far from overflow + final raw = base.inMicroseconds * (1 << exponent); + final capped = min(raw, cap.inMicroseconds); + final factor = 1 + jitter * (2 * _random.nextDouble() - 1); + return Duration(microseconds: (capped * factor).round()); + } +} diff --git a/app/lib/src/session/session_state.dart b/app/lib/src/session/session_state.dart new file mode 100644 index 0000000..dc10ea3 --- /dev/null +++ b/app/lib/src/session/session_state.dart @@ -0,0 +1,79 @@ +import '../api/docker_error.dart'; +import '../api/models/system_info.dart'; +import '../storage/profile_store.dart'; +import '../transport/transport.dart'; + +enum SessionStatus { disconnected, connecting, connected, reconnecting, failed } + +/// Everything the UI needs to know about the current daemon connection. +class SessionState { + final SessionStatus status; + + /// The profile being connected to or currently connected (kept after a + /// failed connect so the Connections screen can show the error inline). + final ConnectionProfile? profile; + final Transport? transport; + + /// Negotiated Engine API version, e.g. "1.45". + final String? apiVersion; + final VersionInfo? daemon; + final DockerError? error; + + /// 1-based reconnect attempt while reconnecting; 0 otherwise. + final int attempt; + final bool foreground; + + /// One-time notice for the UI (e.g. an old daemon); cleared once shown. + final String? warning; + + /// Increments on every connect() so per-connection state can reset. + final int sessionId; + + const SessionState({ + this.status = SessionStatus.disconnected, + this.profile, + this.transport, + this.apiVersion, + this.daemon, + this.error, + this.attempt = 0, + this.foreground = true, + this.warning, + this.sessionId = 0, + }); + + bool get isLive => status == SessionStatus.connected && foreground; + + /// Streams may run: in the foreground, and either connected or not + /// connected at all. (Disconnected counts as usable so screens driven by an + /// overridden transport in tests stream normally.) + bool get streamsUsable => + foreground && (status == SessionStatus.connected || status == SessionStatus.disconnected); + + SessionState copyWith({ + SessionStatus? status, + ConnectionProfile? profile, + Transport? transport, + String? apiVersion, + VersionInfo? daemon, + DockerError? error, + bool clearError = false, + int? attempt, + bool? foreground, + String? warning, + bool clearWarning = false, + int? sessionId, + }) => + SessionState( + status: status ?? this.status, + profile: profile ?? this.profile, + transport: transport ?? this.transport, + apiVersion: apiVersion ?? this.apiVersion, + daemon: daemon ?? this.daemon, + error: clearError ? null : (error ?? this.error), + attempt: attempt ?? this.attempt, + foreground: foreground ?? this.foreground, + warning: clearWarning ? null : (warning ?? this.warning), + sessionId: sessionId ?? this.sessionId, + ); +} diff --git a/app/lib/src/session/transport_factory.dart b/app/lib/src/session/transport_factory.dart new file mode 100644 index 0000000..60da3d7 --- /dev/null +++ b/app/lib/src/session/transport_factory.dart @@ -0,0 +1,104 @@ +import '../api/docker_error.dart'; +import '../storage/credential_store.dart'; +import '../storage/profile_store.dart'; +import '../transport/connection_config.dart'; +import '../transport/ssh/host_key.dart'; +import '../transport/ssh/ssh_connection.dart'; +import '../transport/ssh/ssh_transport.dart'; +import '../transport/tls_security.dart'; +import '../transport/transport.dart'; + +/// The SSH server presented a host key that differs from the pinned one. +class HostKeyMismatchException implements Exception { + final String presentedFingerprint; + const HostKeyMismatchException(this.presentedFingerprint); + + @override + String toString() => 'Host key changed (presented $presentedFingerprint)'; +} + +/// A freshly built transport plus, for SSH, the host key the server showed. +class BuiltTransport { + final Transport transport; + final String? presentedHostKey; + const BuiltTransport(this.transport, {this.presentedHostKey}); +} + +/// Builds a live [Transport] from a saved profile. No UI: the caller decides +/// what to do with a host-key mismatch. +class TransportFactory { + final SshConnection Function(SshCredentials) _sshConnectionFactory; + + TransportFactory({required SshConnection Function(SshCredentials) sshConnectionFactory}) + // ignore: prefer_initializing_formals + : _sshConnectionFactory = sshConnectionFactory; + + /// [pinOverride] replaces the stored SSH host-key pin (used after the user + /// trusts a changed key). + Future build(ConnectionProfile profile, {String? pinOverride}) async { + switch (profile.kind) { + case ConnectionKind.agent: + final a = profile.agent!; + final Uri uri; + try { + uri = Uri.parse(a.baseUri); + } on FormatException catch (e) { + throw DockerError(DockerErrorKind.badRequest, 'Invalid agent address: ${e.message}', cause: e); + } + return BuiltTransport(AgentConnectionConfig(baseUri: uri, token: a.token).build()); + case ConnectionKind.tls: + final t = profile.tls!; + try { + return BuiltTransport(TlsConnectionConfig( + host: t.host, + port: t.port, + clientCertPem: t.clientCertPem, + clientKeyPem: t.clientKeyPem, + caPem: t.caPem, + insecure: t.insecure, + ).build()); + } on TlsConfigException catch (e) { + throw DockerError(DockerErrorKind.badRequest, 'Invalid certificate: ${e.message}', cause: e); + } + case ConnectionKind.ssh: + return _buildSsh(profile.ssh!, pinOverride); + } + } + + Future _buildSsh(SshCredentials ssh, String? pinOverride) async { + final pin = pinOverride ?? ssh.pinnedHostKey; + final conn = _sshConnectionFactory(SshCredentials( + host: ssh.host, + port: ssh.port, + username: ssh.username, + authMethod: ssh.authMethod, + password: ssh.password, + privateKeyPem: ssh.privateKeyPem, + passphrase: ssh.passphrase, + pinnedHostKey: pin, + )); + String? presented; + var mismatch = false; + bool verifier(String fingerprint) { + presented = fingerprint; + if (verifyHostKey(pin, fingerprint) == HostKeyVerdict.mismatch) { + mismatch = true; + return false; + } + return true; + } + + try { + await conn.connect(verifyHostKey: verifier); + } catch (e, st) { + await conn.close(); + final shown = presented; + if (mismatch && shown != null) throw HostKeyMismatchException(shown); + Error.throwWithStackTrace(DockerError.wrap(e), st); + } + return BuiltTransport( + SshTransport(openDuplex: conn.openChannel, onClose: conn.close), + presentedHostKey: presented, + ); + } +} diff --git a/app/lib/src/state/events_feed.dart b/app/lib/src/state/events_feed.dart new file mode 100644 index 0000000..0a46fb0 --- /dev/null +++ b/app/lib/src/state/events_feed.dart @@ -0,0 +1,35 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../api/models/docker_event.dart'; + +const int kEventsBufferCap = 500; + +class EventsState { + final List events; + final String? filterType; + + const EventsState({this.events = const [], this.filterType}); + + List get visibleEvents => + filterType == null ? events : events.where((e) => e.type == filterType).toList(); + + EventsState copyWith({List? events, String? filterType, bool clearFilter = false}) => EventsState( + events: events ?? this.events, + filterType: clearFilter ? null : (filterType ?? this.filterType), + ); +} + +/// The session's event history (newest first, capped), fed by the events hub. +class EventsFeed extends StateNotifier { + EventsFeed() : super(const EventsState()); + + void add(DockerEvent e) { + final next = [e, ...state.events]; + state = state.copyWith(events: next.length > kEventsBufferCap ? next.sublist(0, kEventsBufferCap) : next); + } + + void clear() => state = state.copyWith(events: const []); + + void setFilter(String? type) => + state = type == null ? state.copyWith(clearFilter: true) : state.copyWith(filterType: type); +} diff --git a/app/lib/src/state/events_notifier.dart b/app/lib/src/state/events_notifier.dart deleted file mode 100644 index 4367722..0000000 --- a/app/lib/src/state/events_notifier.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'dart:async'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../api/docker_api_client.dart'; -import '../api/models/docker_event.dart'; -import 'providers.dart'; - -const int kEventsBufferCap = 500; - -enum EventsStatus { streaming, error } - -class EventsState { - final List events; - final String? filterType; - final EventsStatus status; - final String? error; - - const EventsState({ - this.events = const [], - this.filterType, - this.status = EventsStatus.streaming, - this.error, - }); - - List get visibleEvents => - filterType == null ? events : events.where((e) => e.type == filterType).toList(); - - EventsState copyWith({ - List? events, - String? filterType, - bool clearFilter = false, - EventsStatus? status, - String? error, - }) => - EventsState( - events: events ?? this.events, - filterType: clearFilter ? null : (filterType ?? this.filterType), - status: status ?? this.status, - error: error ?? this.error, - ); -} - -class EventsNotifier extends StateNotifier { - StreamSubscription? _sub; - - EventsNotifier(DockerApiClient client) : super(const EventsState()) { - _sub = client.streamEvents().listen( - (e) { - final next = [e, ...state.events]; - state = state.copyWith( - events: next.length > kEventsBufferCap ? next.sublist(0, kEventsBufferCap) : next, - status: EventsStatus.streaming, - ); - }, - onError: (Object e) => state = state.copyWith(status: EventsStatus.error, error: '$e'), - cancelOnError: true, - ); - } - - void setFilter(String? type) => - state = type == null ? state.copyWith(clearFilter: true) : state.copyWith(filterType: type); - - @override - void dispose() { - _sub?.cancel(); - super.dispose(); - } -} - -/// Live daemon events; auto-disposes (and cancels the stream) when the screen -/// that watches it leaves. -final eventsProvider = StateNotifierProvider.autoDispose((ref) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return EventsNotifier(client); -}); diff --git a/app/lib/src/state/exec_session_controller.dart b/app/lib/src/state/exec_session_controller.dart index 5814ffb..94b3d28 100644 --- a/app/lib/src/state/exec_session_controller.dart +++ b/app/lib/src/state/exec_session_controller.dart @@ -27,14 +27,18 @@ class ExecSessionController extends ChangeNotifier { bool _disposed = false; ExecStatus status = ExecStatus.connecting; int? exitCode; - String command = ''; // empty => default bash/sh chooser + String command; // empty => default bash/sh chooser - ExecSessionController(this.client, this.containerId) { + /// Bumped by every start, restart and end; a handshake that finishes under + /// an older generation closes its channel and changes nothing. + int _generation = 0; + + ExecSessionController(this.client, this.containerId, {this.command = ''}) { terminal.onOutput = (data) => _channel?.send(utf8.encode(data)); terminal.onResize = (w, h, pw, ph) { final id = _execId; if (id != null) { - client.resizeExec(id, cols: w, rows: h); + client.resizeExec(id, cols: w, rows: h).ignore(); } }; _start(); @@ -44,18 +48,20 @@ class ExecSessionController extends ChangeNotifier { command.trim().isEmpty ? _defaultShell : ['/bin/sh', '-c', command]; Future _start() async { + final gen = ++_generation; status = ExecStatus.connecting; exitCode = null; _execId = null; notifyListeners(); try { final id = await client.createExec(containerId, cmd: _cmd, tty: true); + if (_disposed || gen != _generation) return; final ch = await client.attachExec(id, cols: terminal.viewWidth, rows: terminal.viewHeight); - // If we were disposed while the handshake was in flight, tear down the - // freshly-resolved channel instead of leaking the hijacked agent conn, - // and never notify listeners after super.dispose(). - if (_disposed) { - unawaited(ch.close()); + // Disposed, ended or restarted while the handshake was in flight: tear + // down the freshly-resolved channel instead of leaking it, and never + // notify listeners after super.dispose(). + if (_disposed || gen != _generation) { + unawaited(_closeQuietly(ch)); return; } _execId = id; @@ -68,7 +74,7 @@ class ExecSessionController extends ChangeNotifier { onError: (_) => _onEnded(), ); } catch (_) { - if (_disposed) return; + if (_disposed || gen != _generation) return; status = ExecStatus.error; notifyListeners(); } @@ -76,29 +82,71 @@ class ExecSessionController extends ChangeNotifier { Future _onEnded() async { if (_disposed) return; + final gen = _generation; status = ExecStatus.ended; + notifyListeners(); // show "ended" now; the exit code can lag on a dead connection final id = _execId; - if (id != null) { - try { - exitCode = (await client.inspectExec(id)).exitCode; - } catch (_) {/* leave exitCode null */} - } - if (_disposed) return; + _execId = null; + // An ended session lets go of its channel. After an error event the + // subscription is still live, and the release cancels it: a late event of + // the old channel must not end a session that was restarted in between. + unawaited(_releaseChannel()); + if (id == null) return; + int? code; + try { + code = (await client.inspectExec(id)).exitCode; + } catch (_) {/* leave the exit code unknown */} + if (_disposed || gen != _generation) return; + exitCode = code; notifyListeners(); } Future restart(String newCommand) async { + if (_disposed) return; command = newCommand; - await _outputSub?.cancel(); - await _channel?.close(); + unawaited(_releaseChannel()); await _start(); } + /// Lets go of the channel: stops reading it, then closes it, best-effort. + /// The cancel comes first and takes effect at once, so nothing the channel + /// still sends, its own end included, reaches the session. Neither is waited + /// on here (a close on a dead connection must not hold anything up); the + /// returned future completes when the close has. + Future _releaseChannel() { + final sub = _outputSub; + _outputSub = null; + final channel = _channel; + _channel = null; + unawaited(sub?.cancel()); + return _closeQuietly(channel); + } + + static Future _closeQuietly(ExecChannel? channel) async { + try { + await channel?.close(); + } catch (_) { + // best-effort teardown + } + } + + /// Ends the session from outside (the connection it ran on is gone): stop + /// reading and close the channel. The exit code is unknown. + Future end() async { + if (_disposed || status == ExecStatus.ended) return; + _generation++; // discard a handshake still in flight + final closed = _releaseChannel(); + _execId = null; + status = ExecStatus.ended; + exitCode = null; + notifyListeners(); + await closed; + } + @override void dispose() { _disposed = true; - _outputSub?.cancel(); - _channel?.close(); + unawaited(_releaseChannel()); super.dispose(); } } diff --git a/app/lib/src/state/logs_notifier.dart b/app/lib/src/state/logs_notifier.dart index 1b02da6..d3204a5 100644 --- a/app/lib/src/state/logs_notifier.dart +++ b/app/lib/src/state/logs_notifier.dart @@ -4,14 +4,16 @@ import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/docker_api_client.dart'; -import '../api/models/container_inspect.dart'; import '../api/models/log_line.dart'; import '../api/stdcopy.dart'; +import '../api/timestamps.dart'; +import '../session/reconnect_policy.dart'; import 'providers.dart'; +import 'stream_supervisor.dart'; const int kLogBufferCap = 5000; -enum LogsStatus { streaming, paused, idle, error } +enum LogsStatus { streaming, paused, idle, reconnecting, error } class LogsState { final List lines; @@ -62,31 +64,58 @@ class LogsState { } class LogsNotifier extends StateNotifier { - final DockerApiClient _client; + final DockerApiClient? Function() _client; final String _id; final bool _tty; - StreamSubscription? _sub; + late final StreamSupervisor _supervisor; final Map _partial = {}; final List _buf = []; - LogsNotifier(this._client, this._id, this._tty) : super(const LogsState()) { - _start(); + /// Epoch nanoseconds of the newest line received; the resume point. + int? _cursor; + + /// How many lines carried exactly [_cursor]. + int _atCursor = 0; + + /// `since` is inclusive: a resume resends the lines stamped at the cursor. + /// Lines before [_floor], and the first [_repeats] lines at it, are repeats. + int? _floor; + int _repeats = 0; + bool _live = true; + + /// Whether the stream last opened follows; a one-off fetch does not. + bool _openFollows = true; + + /// A one-off fetch is owed: the tail changed while the session was away, + /// or the session dropped in the middle of one. + bool _reloadOwed = false; + + LogsNotifier(this._client, this._id, this._tty, {ReconnectPolicy? policy}) : super(const LogsState()) { + _supervisor = StreamSupervisor( + open: _open, + onData: _onChunk, + onStatus: _onStatus, + policy: policy, + ); + _supervisor.start(); } - void _start() { - _sub?.cancel(); + Stream _open() { + final client = _client(); + if (client == null) throw const DockerError(DockerErrorKind.unknown, 'Not connected'); _partial.clear(); - _buf.clear(); - state = state.copyWith(lines: _buf, status: LogsStatus.streaming, clearError: true); - _sub = _client - .streamContainerLogs( - _id, - tty: _tty, - follow: state.following, - tail: state.tail, - timestamps: state.timestamps, - ) - .listen(_onChunk, onError: _onError, onDone: _onDone, cancelOnError: true); + final cursor = _cursor; + _floor = cursor; + _repeats = _atCursor; + _openFollows = state.following; + return client.streamContainerLogs( + _id, + tty: _tty, + follow: state.following, + tail: cursor == null ? state.tail : null, + timestamps: true, + since: cursor == null ? null : formatUnixNanos(cursor), + ); } void _onChunk(LogChunk chunk) { @@ -94,84 +123,165 @@ class LogsNotifier extends StateNotifier { final combined = (_partial[chunk.source] ?? '') + text; final parts = combined.split('\n'); _partial[chunk.source] = parts.removeLast(); // trailing partial line - if (parts.isEmpty) return; - _buf.addAll(parts.map((p) => _toLine(chunk.source, p))); + var added = false; + for (final p in parts) { + final line = _toLine(chunk.source, p); + if (line != null) { + _buf.add(line); + added = true; + } + } + if (!added) return; if (_buf.length > kLogBufferCap) { _buf.removeRange(0, _buf.length - kLogBufferCap); } state = state.copyWith(lines: _buf); } - LogLine _toLine(LogStream source, String raw) { - if (!state.timestamps) return LogLine(source: source, text: raw); + /// Splits the daemon's leading RFC3339Nano timestamp off [raw]. Returns + /// null for a repeat of a line already shown before a resume. + LogLine? _toLine(LogStream source, String raw) { final space = raw.indexOf(' '); if (space > 0) { - final ts = DateTime.tryParse(raw.substring(0, space)); - if (ts != null) { - return LogLine(source: source, text: raw.substring(space + 1), timestamp: ts); + final rawTs = raw.substring(0, space); + final nanos = rfc3339ToEpochNanos(rawTs); + if (nanos != null) { + final floor = _floor; + if (floor != null) { + if (nanos < floor) return null; + if (nanos == floor && _repeats > 0) { + _repeats--; + return null; + } + } + final cursor = _cursor; + if (cursor == null || nanos > cursor) { + _cursor = nanos; + _atCursor = 1; + } else if (nanos == cursor) { + _atCursor++; + } + return LogLine( + source: source, + text: raw.substring(space + 1), + timestamp: DateTime.fromMicrosecondsSinceEpoch(nanos ~/ 1000, isUtc: true), + rawTimestamp: rawTs, + ); } } return LogLine(source: source, text: raw); } - void _onError(Object e, StackTrace _) => - state = state.copyWith(status: LogsStatus.error, error: e.toString()); + void _onStatus(SupervisorStatus s, DockerError? error) { + switch (s) { + case SupervisorStatus.streaming: + state = state.copyWith(status: LogsStatus.streaming, clearError: true); + case SupervisorStatus.retrying: + state = state.copyWith(status: LogsStatus.reconnecting); + case SupervisorStatus.paused: + state = state.copyWith(status: _live ? LogsStatus.paused : LogsStatus.reconnecting); + case SupervisorStatus.failed: + state = state.copyWith(status: LogsStatus.error, error: error?.message ?? 'Log stream failed'); + case SupervisorStatus.done: + state = state.copyWith(status: LogsStatus.idle); + case SupervisorStatus.idle: + break; + } + } - void _onDone() { - if (state.status != LogsStatus.error) { - state = state.copyWith(status: LogsStatus.idle); + /// Runs the stream only while the session is live and the user follows. + void _sync() { + final s = _supervisor.status; + if (_live && state.following) { + _reloadOwed = false; // following starts from the tail or the cursor anyway + if (s == SupervisorStatus.paused) { + _supervisor.resume(); + } else if (s == SupervisorStatus.done || s == SupervisorStatus.failed || !_openFollows) { + // Ended, gave up, or only a one-off fetch is running: follow from + // the cursor. + _supervisor.retry(); + } + return; } + final fetching = s == SupervisorStatus.streaming || s == SupervisorStatus.retrying; + if (!_live && fetching && !_openFollows) _reloadOwed = true; // cut short by the session + _supervisor.pause(); + if (_supervisor.status == SupervisorStatus.paused) { + state = state.copyWith(status: _live ? LogsStatus.paused : LogsStatus.reconnecting); + } + if (_live && _reloadOwed) { + // Make up the one-off fetch now that the session is back. + _reloadOwed = false; + _supervisor.retry(); + } + } + + /// The session is (not) usable: pause while reconnecting or backgrounded. + void setLive(bool live) { + // A new connection disposes this notifier, and the session update that + // does so still reaches the replaced provider's listener. + if (!mounted || live == _live) return; + _live = live; + _sync(); } - /// Pause = stop the live tail but KEEP the buffered lines (freeze). - /// Resume = restart streaming live. + /// Pause = freeze the view and stop reading; resume continues from the + /// last line received (no gap, no duplicates). void setFollowing(bool value) { if (value == state.following) return; - if (value) { - state = state.copyWith(following: true); - _start(); - } else { - _sub?.cancel(); - _sub = null; - state = state.copyWith(following: false, status: LogsStatus.paused); - } + state = state.copyWith(following: value); + _sync(); } - void setTimestamps(bool value) { - state = state.copyWith(timestamps: value); - _start(); - } + /// Display-only: the daemon always sends timestamps. + void setTimestamps(bool value) => state = state.copyWith(timestamps: value); + /// Starts over with a new tail size (a one-off fetch while paused). void setTail(int? value) { - state = state.copyWith(tail: value, clearTail: value == null); - _start(); + _cursor = null; + _atCursor = 0; + _floor = null; + _repeats = 0; + _buf.clear(); + state = state.copyWith(tail: value, clearTail: value == null, lines: _buf); + if (_live) { + _supervisor.retry(); + } else { + _reloadOwed = true; + } } void setSearch(String value) => state = state.copyWith(search: value); - void retry() => _start(); + /// Reopens now, continuing from the last line received. Ignored while the + /// session is away: the stream restarts by itself when it returns, if the + /// user follows. + void retry() { + if (_live) _supervisor.retry(); + } String snapshot() => state.lines.map((l) => l.text).join('\n'); @override void dispose() { - _sub?.cancel(); + _supervisor.dispose(); super.dispose(); } } -final containerInspectProvider = - FutureProvider.family((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.inspectContainer(id); -}); - final logsProvider = StateNotifierProvider.autoDispose.family( (ref, key) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return LogsNotifier(client, key.id, key.tty); + // A new connection resets the buffer; a reconnect within it does not. + ref.watch(sessionProvider.select((s) => s.sessionId)); + final notifier = LogsNotifier( + () => currentClient(ref), + key.id, + key.tty, + policy: ref.read(reconnectPolicyProvider), + ); + notifier.setLive(ref.read(sessionProvider).streamsUsable); + ref.listen(sessionProvider.select((s) => s.streamsUsable), (_, live) => notifier.setLive(live)); + return notifier; }, ); diff --git a/app/lib/src/state/providers.dart b/app/lib/src/state/providers.dart index aae4504..425babf 100644 --- a/app/lib/src/state/providers.dart +++ b/app/lib/src/state/providers.dart @@ -2,19 +2,24 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/docker_api_client.dart'; import '../api/models/container_detail.dart'; +import '../api/models/container_inspect.dart'; import '../api/models/docker_container.dart'; import '../api/models/docker_image.dart'; import '../api/models/docker_network.dart'; import '../api/models/docker_volume.dart'; import '../api/models/image_detail.dart'; import '../api/models/system_info.dart'; +import '../session/docker_session.dart'; +import '../session/events_hub.dart'; +import '../session/lifecycle_source.dart'; +import '../session/reconnect_policy.dart'; +import '../session/session_state.dart'; +import '../session/transport_factory.dart'; import '../storage/credential_store.dart'; import '../storage/profile_store.dart'; import '../transport/ssh/ssh_connection.dart'; import '../transport/transport.dart'; - -/// The active transport, set once the user connects. Null = not connected. -final transportProvider = StateProvider((ref) => null); +import 'events_feed.dart'; /// The saved connection profiles store (overridden with an in-memory fake in tests). final profileStoreProvider = Provider((ref) => SecureProfileStore()); @@ -26,75 +31,180 @@ final profilesProvider = FutureProvider>((ref) => ref.wa final sshConnectionFactoryProvider = Provider((ref) => RealSshConnection.new); -/// The single Docker client, derived from the active transport. +/// Builds transports from saved profiles (overridden with a fake in tests). +final transportFactoryProvider = Provider( + (ref) => TransportFactory(sshConnectionFactory: ref.watch(sshConnectionFactoryProvider)), +); + +/// Backoff for session reconnects and stream supervisors. +final reconnectPolicyProvider = Provider((ref) => ReconnectPolicy()); + +/// App foreground/background changes (overridden with a manual source in tests). +final lifecycleSourceProvider = Provider((ref) => AppLifecycleSource()); + +/// Daemon events seen since the current connection started (newest first). +final sessionEventsProvider = StateNotifierProvider((ref) => EventsFeed()); + +/// The connection to the current daemon: status, transport, reconnects. +final sessionProvider = StateNotifierProvider((ref) { + final feed = ref.read(sessionEventsProvider.notifier); + return DockerSession( + transportFactory: ref.read(transportFactoryProvider), + policy: ref.read(reconnectPolicyProvider), + lifecycle: ref.read(lifecycleSourceProvider), + invalidator: ProviderInvalidator(ref), + profileStore: ref.read(profileStoreProvider), + onEvent: feed.add, + onNewSession: feed.clear, + onProfilesChanged: () => ref.invalidate(profilesProvider), + ); +}); + +/// The active transport, derived from the session. Null = not connected. +final transportProvider = Provider((ref) => ref.watch(sessionProvider.select((s) => s.transport))); + +/// The single Docker client: the session's transport plus its negotiated +/// API version. Screens read it for one-off actions; resource providers go +/// through [resourceClient] and streams through [currentClient]. final dockerClientProvider = Provider((ref) { final transport = ref.watch(transportProvider); - return transport == null ? null : DockerApiClient(transport); + if (transport == null) return null; + final apiVersion = ref.watch(sessionProvider.select((s) => s.apiVersion)); + return DockerApiClient(transport, apiVersion: apiVersion); }); +/// The client for work started from a session listener, such as reopening a +/// stream when the session comes back. [dockerClientProvider] can still hold +/// the previous transport at that moment, so prefer the session's own client; +/// the provider is the fallback for an overridden transport without a +/// connected session. +DockerApiClient? currentClient(Ref ref) => + ref.read(sessionProvider.notifier).client ?? ref.read(dockerClientProvider); + +/// What the data on screen belongs to: the session id while a transport is +/// up, else null. It changes when a connection starts or ends, not when the +/// session reconnects. +final connectionScopeProvider = Provider((ref) { + final connected = ref.watch(transportProvider.select((t) => t != null)); + final sessionId = ref.watch(sessionProvider.select((s) => s.sessionId)); + return connected ? sessionId : null; +}); + +/// The client for a resource provider (lists, details, the dashboard). +/// +/// The provider is tied to the connection scope instead of the client. A new +/// connection is then a dependency change, so screens show their loading +/// state and nothing from the previous daemon. A reconnect leaves the +/// provider alone and the session refreshes it (see [ProviderInvalidator.all]), +/// which keeps the old data on screen until the new arrives. +DockerApiClient resourceClient(Ref ref) { + ref.watch(connectionScopeProvider); + final client = currentClient(ref); + if (client == null) throw StateError('Not connected'); + return client; +} + +/// Maps event categories to the providers that show them. [all] refreshes +/// everything after a reconnect, which keeps the old data on screen meanwhile. +/// +/// Invalidates through [Ref.container] rather than the [Ref] itself: the ref +/// belongs to [sessionProvider], and the resource providers depend back on it +/// (via [connectionScopeProvider]), so `Ref.invalidate`'s +/// debug dependency assert would build the target and throw a +/// CircularDependencyError. The container skips that assert and ignores +/// providers that were never created (no fetch for unseen detail ids). +class ProviderInvalidator implements Invalidator { + final Ref _ref; + ProviderInvalidator(this._ref); + + @override + void list(EventCategory category) { + switch (category) { + case EventCategory.container: + _ref.container.invalidate(containersProvider); + case EventCategory.image: + _ref.container.invalidate(imagesProvider); + case EventCategory.network: + _ref.container.invalidate(networksProvider); + case EventCategory.volume: + _ref.container.invalidate(volumesProvider); + case EventCategory.other: + break; + } + } + + @override + void detail(EventCategory category, String id) { + switch (category) { + case EventCategory.container: + _ref.container.invalidate(containerDetailProvider(id)); + case EventCategory.image: + _ref.container.invalidate(imageDetailProvider(id)); + case EventCategory.network: + case EventCategory.volume: + case EventCategory.other: + break; + } + } + + @override + void dashboard() => _ref.container.invalidate(systemDashboardProvider); + + @override + void all() { + for (final provider in resourceProviders) { + _ref.container.invalidate(provider); + } + } +} + /// The container list for the current connection. final containersProvider = FutureProvider>((ref) async { - final client = ref.watch(dockerClientProvider); - if (client == null) { - throw StateError('Not connected'); - } - return client.listContainers(); + return resourceClient(ref).listContainers(); }); /// Rich inspect for the container detail screen. final containerDetailProvider = FutureProvider.family((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.inspectContainerDetail(id); + return resourceClient(ref).inspectContainerDetail(id); +}); + +/// Plain inspect (the TTY flag) for the logs screen. +final containerInspectProvider = FutureProvider.family((ref, id) { + return resourceClient(ref).inspectContainer(id); }); /// The image list for the current connection. final imagesProvider = FutureProvider>((ref) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.listImages(); + return resourceClient(ref).listImages(); }); final imageDetailProvider = FutureProvider.family((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.inspectImage(id); + return resourceClient(ref).inspectImage(id); }); final imageHistoryProvider = FutureProvider.family, String>((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.imageHistory(id); + return resourceClient(ref).imageHistory(id); }); final networksProvider = FutureProvider>((ref) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.listNetworks(); + return resourceClient(ref).listNetworks(); }); final networkDetailProvider = FutureProvider.family((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.inspectNetwork(id); + return resourceClient(ref).inspectNetwork(id); }); final volumesProvider = FutureProvider>((ref) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.listVolumes(); + return resourceClient(ref).listVolumes(); }); final volumeDetailProvider = FutureProvider.family((ref, name) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return client.inspectVolume(name); + return resourceClient(ref).inspectVolume(name); }); final systemDashboardProvider = FutureProvider<({SystemInfo info, VersionInfo version, DiskUsage df})>((ref) async { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); + final client = resourceClient(ref); // eagerError so the first failure (typically a timeout) surfaces immediately // instead of waiting on the slowest call; Future.wait still attaches handlers // to every future, so later errors are not unhandled. @@ -102,3 +212,18 @@ final systemDashboardProvider = await Future.wait([client.getInfo(), client.getVersion(), client.getDiskUsage()], eagerError: true); return (info: results[0] as SystemInfo, version: results[1] as VersionInfo, df: results[2] as DiskUsage); }); + +/// Every provider that shows daemon data. A reconnect refreshes them all. +final List resourceProviders = [ + containersProvider, + containerDetailProvider, + containerInspectProvider, + imagesProvider, + imageDetailProvider, + imageHistoryProvider, + networksProvider, + networkDetailProvider, + volumesProvider, + volumeDetailProvider, + systemDashboardProvider, +]; diff --git a/app/lib/src/state/stats_notifier.dart b/app/lib/src/state/stats_notifier.dart index 948af14..2afed2e 100644 --- a/app/lib/src/state/stats_notifier.dart +++ b/app/lib/src/state/stats_notifier.dart @@ -4,18 +4,20 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/docker_api_client.dart'; import '../api/models/container_stats.dart'; +import '../session/reconnect_policy.dart'; import 'providers.dart'; +import 'stream_supervisor.dart'; const int kStatsWindow = 60; -enum StatsStatus { loading, streaming, error } +enum StatsStatus { loading, streaming, reconnecting, error } class StatsState { final ContainerStats? latest; final List cpuHistory; final List memHistory; final StatsStatus status; - final String? error; + final DockerError? error; const StatsState({ this.latest, @@ -30,48 +32,116 @@ class StatsState { List? cpuHistory, List? memHistory, StatsStatus? status, - String? error, + DockerError? error, + bool clearError = false, }) => StatsState( latest: latest ?? this.latest, cpuHistory: cpuHistory ?? this.cpuHistory, memHistory: memHistory ?? this.memHistory, status: status ?? this.status, - error: error ?? this.error, + error: clearError ? null : (error ?? this.error), ); } class StatsNotifier extends StateNotifier { - StreamSubscription? _sub; + final DockerApiClient? Function() _client; + final String _id; + late final StreamSupervisor _supervisor; + bool _live = true; - StatsNotifier(DockerApiClient client, String id) : super(const StatsState()) { - _sub = client.streamContainerStats(id).listen( - (s) { - final cpu = [...state.cpuHistory, s.cpuPercent]; - final mem = [...state.memHistory, s.memoryPercent]; + /// The first sample of a stream has no previous CPU reading, so its CPU + /// figure is a lifetime average. With a history to continue, drop it. + bool _dropNext = false; + + StatsNotifier(this._client, this._id, {ReconnectPolicy? policy}) : super(const StatsState()) { + _supervisor = StreamSupervisor( + open: _open, + onData: _onSample, + onStatus: _onStatus, + policy: policy, + ); + _supervisor.start(); + } + + Stream _open() { + final client = _client(); + if (client == null) throw const DockerError(DockerErrorKind.unknown, 'Not connected'); + _dropNext = state.latest != null; + return client.streamContainerStats(_id); + } + + void _onSample(ContainerStats s) { + if (_dropNext) { + _dropNext = false; + return; + } + final cpu = [...state.cpuHistory, s.cpuPercent]; + final mem = [...state.memHistory, s.memoryPercent]; + state = state.copyWith( + latest: s, + cpuHistory: cpu.length > kStatsWindow ? cpu.sublist(cpu.length - kStatsWindow) : cpu, + memHistory: mem.length > kStatsWindow ? mem.sublist(mem.length - kStatsWindow) : mem, + status: StatsStatus.streaming, + clearError: true, + ); + } + + void _onStatus(SupervisorStatus s, DockerError? error) { + switch (s) { + case SupervisorStatus.retrying: + case SupervisorStatus.paused: + state = state.copyWith(status: StatsStatus.reconnecting); + case SupervisorStatus.failed: + state = state.copyWith(status: StatsStatus.error, error: error); + case SupervisorStatus.streaming: state = state.copyWith( - latest: s, - cpuHistory: cpu.length > kStatsWindow ? cpu.sublist(cpu.length - kStatsWindow) : cpu, - memHistory: mem.length > kStatsWindow ? mem.sublist(mem.length - kStatsWindow) : mem, - status: StatsStatus.streaming, + status: state.latest == null ? StatsStatus.loading : StatsStatus.streaming, + clearError: true, ); - }, - onError: (Object e) => state = state.copyWith(status: StatsStatus.error, error: '$e'), - cancelOnError: true, - ); + case SupervisorStatus.idle: + case SupervisorStatus.done: + break; + } + } + + /// The session is (not) usable: pause while reconnecting or backgrounded; + /// the history is kept and sampling restarts on resume. + void setLive(bool live) { + if (live == _live) return; + _live = live; + if (!live) { + _supervisor.pause(); + return; + } + final s = _supervisor.status; + if (s == SupervisorStatus.done || s == SupervisorStatus.failed) { + // Ended or gave up earlier: try again now that the session is back. + _supervisor.retry(); + } else { + _supervisor.resume(); + } + } + + /// Reopens now with a fresh attempt count (the error view's Retry). Ignored + /// while the session is away: the stream restarts by itself when it returns. + void retry() { + if (_live) _supervisor.retry(); } @override void dispose() { - _sub?.cancel(); + _supervisor.dispose(); super.dispose(); } } /// Live stats for a container; auto-disposes (and cancels the stream) when the -/// screen that watches it leaves. +/// screen that watches it leaves. A new connection resets the history. final statsProvider = StateNotifierProvider.autoDispose.family((ref, id) { - final client = ref.watch(dockerClientProvider); - if (client == null) throw StateError('Not connected'); - return StatsNotifier(client, id); + ref.watch(sessionProvider.select((s) => s.sessionId)); + final notifier = StatsNotifier(() => currentClient(ref), id, policy: ref.read(reconnectPolicyProvider)); + notifier.setLive(ref.read(sessionProvider).streamsUsable); + ref.listen(sessionProvider.select((s) => s.streamsUsable), (_, live) => notifier.setLive(live)); + return notifier; }); diff --git a/app/lib/src/state/stream_supervisor.dart b/app/lib/src/state/stream_supervisor.dart new file mode 100644 index 0000000..0fb171e --- /dev/null +++ b/app/lib/src/state/stream_supervisor.dart @@ -0,0 +1,167 @@ +// Private fields are bound to public named constructor params (e.g. `open`), +// so keep the explicit initializer-list assignment. +// ignore_for_file: prefer_initializing_formals +import 'dart:async'; + +import '../api/docker_error.dart'; +import '../session/reconnect_policy.dart'; + +/// Where a [StreamSupervisor] is in its lifecycle. +enum SupervisorStatus { idle, streaming, paused, retrying, failed, done } + +/// Keeps one long-lived stream alive: reopens it with backoff after retryable +/// errors, pauses and resumes it on request, and reports every transition. +/// [open] is called afresh on every (re)connect, so it can pick up a new +/// transport or a resume cursor. A stream that stays open for the policy cap +/// without an error counts as recovered. +class StreamSupervisor { + final Stream Function() _open; + final void Function(T) _onData; + final void Function(SupervisorStatus status, DockerError? error) _onStatus; + final ReconnectPolicy _policy; + /// Treats a clean end of the stream as a retryable loss instead of done. + final bool retryOnDone; + + StreamSubscription? _sub; + Timer? _timer; + Timer? _stableTimer; + int _attempt = 0; + int _generation = 0; + bool _resumable = false; + bool _disposed = false; + SupervisorStatus _status = SupervisorStatus.idle; + + StreamSupervisor({ + required Stream Function() open, + required void Function(T) onData, + required void Function(SupervisorStatus status, DockerError? error) onStatus, + ReconnectPolicy? policy, + this.retryOnDone = false, + }) : _open = open, + _onData = onData, + _onStatus = onStatus, + _policy = policy ?? ReconnectPolicy(); + + /// The current lifecycle status. + SupervisorStatus get status => _status; + + /// Opens the stream for the first time. + void start() { + _attempt = 0; + _connect(); + } + + /// Stops reading (stream cancelled, retry timer cancelled) while streaming + /// or retrying. Anything else is left alone. + void pause() { + if (_disposed) return; + if (_status != SupervisorStatus.streaming && _status != SupervisorStatus.retrying) return; + _cancel(); + _resumable = true; + _set(SupervisorStatus.paused); + } + + /// Reopens a stream that [pause] stopped. + void resume() { + if (_disposed || _status != SupervisorStatus.paused || !_resumable) return; + _resumable = false; + _attempt = 0; + _connect(); + } + + /// Reopens now with a fresh attempt count, whatever the current status. + void retry() { + if (_disposed) return; + _resumable = false; + _attempt = 0; + _connect(); + } + + /// Cancels the stream and any pending retry; no status is reported after. + void dispose() { + _disposed = true; + _cancel(); + } + + void _set(SupervisorStatus s, [DockerError? error]) { + _status = s; + if (!_disposed) _onStatus(s, error); + } + + void _cancel() { + _generation++; + _timer?.cancel(); + _timer = null; + _cancelStable(); + final sub = _sub; + _sub = null; + sub?.cancel(); + } + + void _cancelStable() { + _stableTimer?.cancel(); + _stableTimer = null; + } + + void _connect() { + _cancel(); + if (_disposed) return; + final gen = _generation; + final Stream stream; + try { + stream = _open(); + } catch (e) { + _handleError(e); + return; + } + _set(SupervisorStatus.streaming); + if (gen != _generation || _disposed) return; + _sub = stream.listen( + (data) { + if (gen != _generation) return; + _attempt = 0; + _onData(data); + }, + onError: (Object e) { + if (gen != _generation) return; + _sub = null; + _cancelStable(); + _handleError(e); + }, + onDone: () { + if (gen != _generation) return; + _sub = null; + _cancelStable(); + if (retryOnDone) { + _handleError(const DockerError(DockerErrorKind.network, 'The stream closed')); + } else { + _set(SupervisorStatus.done); + } + }, + cancelOnError: true, + ); + _stableTimer = Timer(_policy.cap, () { + if (gen != _generation) return; + _stableTimer = null; + _attempt = 0; + }); + } + + void _handleError(Object e) { + if (_disposed) return; + final error = DockerError.wrap(e); + _attempt++; + if (!error.retryable || _attempt > _policy.maxAttempts) { + _set(SupervisorStatus.failed, error); + return; + } + final gen = _generation; + _set(SupervisorStatus.retrying, error); + if (gen != _generation || _disposed) return; + _timer = Timer(_policy.delay(_attempt), () { + if (gen != _generation) return; + _timer = null; + _connect(); + }); + } +} diff --git a/app/lib/src/transport/agent_transport.dart b/app/lib/src/transport/agent_transport.dart index 71b7c89..965ff30 100644 --- a/app/lib/src/transport/agent_transport.dart +++ b/app/lib/src/transport/agent_transport.dart @@ -17,6 +17,9 @@ class AgentTransport implements Transport { final http.Client _client; final http.Client Function() _streamClientFactory; + /// Per-stream clients that are still open, so [close] can tear them down. + final Set _openStreamClients = {}; + /// Budget for the response headers of a GET stream; stream bodies never time out. final Duration streamHeaderTimeout; @@ -50,12 +53,14 @@ class AgentTransport implements Transport { Stream> _openStream(http.Request request, Duration headerBudget) { final client = _streamClientFactory(); + _openStreamClients.add(client); final controller = StreamController>(); StreamSubscription>? sub; var clientClosed = false; void closeClient() { if (!clientClosed) { clientClosed = true; + _openStreamClients.remove(client); client.close(); } } @@ -147,8 +152,16 @@ class AgentTransport implements Transport { return _WebSocketExecChannel(channel); } + /// Closes the shared client and every stream still open on this transport. @override - Future close() async => _client.close(); + Future close() async { + _client.close(); + final open = _openStreamClients.toList(); + _openStreamClients.clear(); + for (final c in open) { + c.close(); + } + } } class _WebSocketExecChannel implements ExecChannel { diff --git a/app/lib/src/transport/ssh/ssh_transport.dart b/app/lib/src/transport/ssh/ssh_transport.dart index 34850d9..5159dae 100644 --- a/app/lib/src/transport/ssh/ssh_transport.dart +++ b/app/lib/src/transport/ssh/ssh_transport.dart @@ -47,7 +47,7 @@ class SshTransport implements Transport { try { conn = await _openDuplex(); } catch (e, st) { - Error.throwWithStackTrace(DockerError.wrap(e), st); + Error.throwWithStackTrace(mapSshError(e), st); } try { final h = {...?headers}; @@ -61,7 +61,7 @@ class SshTransport implements Transport { final r = await readBufferedResponse(conn.input); return http.Response.bytes(r.body, r.statusCode, headers: r.headers); } catch (e, st) { - Error.throwWithStackTrace(DockerError.wrap(e), st); + Error.throwWithStackTrace(mapSshError(e), st); } finally { await conn.close(); } @@ -111,7 +111,9 @@ class SshTransport implements Transport { return attempt().timeout(budget, onTimeout: () { timedOut = true; - throw TimeoutException('No response from the daemon within $budget', budget); + // Already the daemon timeout every transport reports: left as a bare + // TimeoutException, mapSshError would call it a timed-out SSH connection. + throw DockerError.fromException(TimeoutException('No response from the daemon within $budget', budget)); }); } @@ -152,7 +154,7 @@ class SshTransport implements Transport { // the controller AND the channel, mirroring onDone. onError: (Object e, StackTrace st) async { if (cancelled) return; - controller.addError(DockerError.wrap(e), st); + controller.addError(mapSshError(e), st); await controller.close(); await conn!.close(); }, @@ -168,7 +170,7 @@ class SshTransport implements Transport { // onCancel closed the channel, or a late channel _openAndSend closed // unused - so swallow it like the body's post-cancel errors. if (cancelled) return; - controller.addError(DockerError.wrap(e), st); + controller.addError(mapSshError(e), st); await controller.close(); await conn?.close(); } @@ -216,7 +218,7 @@ class SshTransport implements Transport { return SocketExecChannel(input: resp.body, onSend: open.add, onClose: open.close); } catch (e, st) { await conn?.close(); // never leak the dial-stdio channel on a failed upgrade - Error.throwWithStackTrace(DockerError.wrap(e), st); + Error.throwWithStackTrace(mapSshError(e), st); } } diff --git a/app/lib/src/transport/tls_transport.dart b/app/lib/src/transport/tls_transport.dart index 0fa75fc..95fc8fb 100644 --- a/app/lib/src/transport/tls_transport.dart +++ b/app/lib/src/transport/tls_transport.dart @@ -62,9 +62,23 @@ class TlsTransport implements Transport { Stream> _openStream(http.Request request, Duration headerBudget) { final controller = StreamController>(); StreamSubscription>? sub; + var cancelled = false; controller.onListen = () async { try { - final response = await _client.send(request).timeout(headerBudget); + final pending = _client.send(request); + final http.StreamedResponse response; + try { + response = await pending.timeout(headerBudget); + } on TimeoutException { + // The response may still arrive, and nobody will read it then. + pending.then(_release).ignore(); + rethrow; + } + if (cancelled) { + // The listener left while the headers were on their way. + _release(response); + return; + } if (response.statusCode != 200) { final body = await response.stream.bytesToString(); controller.addError(DockerError.fromResponse(response.statusCode, body)); @@ -83,10 +97,17 @@ class TlsTransport implements Transport { } }; // Cancel just stops reading; the shared client stays alive for other calls. - controller.onCancel = () async => sub?.cancel(); + controller.onCancel = () async { + cancelled = true; + await sub?.cancel(); + }; return controller.stream; } + /// Lets go of the connection of a response that nobody will read: its body + /// would otherwise keep arriving until the transport is closed. + static void _release(http.StreamedResponse response) => unawaited(response.stream.listen((_) {}).cancel()); + @override Stream> stream(String path, {Map? query}) => _openStream(http.Request('GET', baseUri.replace(path: path, queryParameters: query)), streamHeaderTimeout); diff --git a/app/lib/src/ui/connect/agent_form.dart b/app/lib/src/ui/connect/agent_form.dart index d71d8f5..935ad00 100644 --- a/app/lib/src/ui/connect/agent_form.dart +++ b/app/lib/src/ui/connect/agent_form.dart @@ -1,11 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../connect/connection_launcher.dart'; -import '../../state/providers.dart'; import '../../storage/credential_store.dart'; import '../../storage/profile_store.dart'; import '../widgets/app_text_field.dart'; +import 'profile_form_save.dart'; class AgentForm extends ConsumerStatefulWidget { final ConnectionProfile? editing; @@ -14,7 +13,7 @@ class AgentForm extends ConsumerStatefulWidget { ConsumerState createState() => _AgentFormState(); } -class _AgentFormState extends ConsumerState { +class _AgentFormState extends ConsumerState with ProfileFormSave { final _name = TextEditingController(); final _host = TextEditingController(); final _port = TextEditingController(text: '8080'); @@ -44,7 +43,11 @@ class _AgentFormState extends ConsumerState { super.dispose(); } - ConnectionProfile? _build() { + @override + bool get isEditing => widget.editing != null; + + @override + ConnectionProfile? buildProfile() { final name = _name.text.trim(); final host = _host.text.trim(); final port = int.tryParse(_port.text.trim()); @@ -61,28 +64,6 @@ class _AgentFormState extends ConsumerState { ); } - Future _persist(ConnectionProfile p) async { - final store = ref.read(profileStoreProvider); - widget.editing == null ? await store.add(p) : await store.update(p); - ref.invalidate(profilesProvider); - } - - Future _save() async { - final p = _build(); - if (p == null) return; - final navigator = Navigator.of(context); - await _persist(p); - navigator.pop(); - } - - Future _saveAndConnect() async { - final p = _build(); - if (p == null) return; - await _persist(p); - if (!mounted) return; - await launchConnection(context, ref, p); - } - @override Widget build(BuildContext context) { return Column( @@ -90,13 +71,13 @@ class _AgentFormState extends ConsumerState { AppTextField(controller: _name, label: 'Name', icon: Icons.label), AppTextField(controller: _host, label: 'Host / IP', icon: Icons.dns), AppTextField(controller: _port, label: 'Port', icon: Icons.numbers, keyboardType: TextInputType.number), - AppTextField(controller: _token, label: 'Token', icon: Icons.key, obscure: true, last: true, onSubmit: _saveAndConnect), + AppTextField(controller: _token, label: 'Token', icon: Icons.key, obscure: true, last: true, onSubmit: saveAndConnect), SwitchListTile(title: const Text('Use TLS (https)'), value: _useTls, onChanged: (v) => setState(() => _useTls = v)), const SizedBox(height: 16), Row(children: [ - Expanded(child: OutlinedButton(onPressed: _save, child: const Text('Save'))), + Expanded(child: OutlinedButton(onPressed: save, child: const Text('Save'))), const SizedBox(width: 8), - Expanded(child: FilledButton(onPressed: _saveAndConnect, child: const Text('Save & Connect'))), + Expanded(child: FilledButton(onPressed: saveAndConnect, child: const Text('Save & Connect'))), ]), ], ); diff --git a/app/lib/src/ui/connect/profile_form_save.dart b/app/lib/src/ui/connect/profile_form_save.dart new file mode 100644 index 0000000..3fc9fcd --- /dev/null +++ b/app/lib/src/ui/connect/profile_form_save.dart @@ -0,0 +1,56 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../state/providers.dart'; +import '../../storage/profile_store.dart'; +import '../route_is_open.dart'; + +/// Save handling shared by the connection forms: write the profile once, +/// then close the editor, returning the profile for "Save & Connect". +mixin ProfileFormSave on ConsumerState { + /// The profile from the form's fields, or null when they do not validate. + ConnectionProfile? buildProfile(); + + /// True when the form edits an existing profile. + bool get isEditing; + + bool _saving = false; + + /// Saves the profile and closes the editor. + Future save() async { + if (_saving) return; + final p = buildProfile(); + if (p == null) return; + await _persistOnce(p); + if (!mounted) return; + closeRoute(context); + } + + /// Saves and returns the profile to the Connections list, which connects + /// and shows the progress or the error. + Future saveAndConnect() async { + if (_saving) return; + final p = buildProfile(); + if (p == null) return; + await _persistOnce(p); + if (!mounted) return; + closeRoute(context, p); + } + + /// Saves [p]; further taps are ignored from here on (the editor is closing). + /// A failed save lets the user try again and rethrows. + Future _persistOnce(ConnectionProfile p) async { + _saving = true; + try { + await _persist(p); + } catch (_) { + _saving = false; + rethrow; + } + } + + Future _persist(ConnectionProfile p) async { + final store = ref.read(profileStoreProvider); + isEditing ? await store.update(p) : await store.add(p); + ref.invalidate(profilesProvider); + } +} diff --git a/app/lib/src/ui/connect/ssh_form.dart b/app/lib/src/ui/connect/ssh_form.dart index 40c53ed..3226cbc 100644 --- a/app/lib/src/ui/connect/ssh_form.dart +++ b/app/lib/src/ui/connect/ssh_form.dart @@ -1,11 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../connect/connection_launcher.dart'; -import '../../state/providers.dart'; import '../../storage/credential_store.dart'; import '../../storage/profile_store.dart'; import '../widgets/app_text_field.dart'; +import 'profile_form_save.dart'; class SshForm extends ConsumerStatefulWidget { final ConnectionProfile? editing; @@ -14,7 +13,7 @@ class SshForm extends ConsumerStatefulWidget { ConsumerState createState() => _SshFormState(); } -class _SshFormState extends ConsumerState { +class _SshFormState extends ConsumerState with ProfileFormSave { final _name = TextEditingController(); final _host = TextEditingController(); final _port = TextEditingController(text: '22'); @@ -57,7 +56,11 @@ class _SshFormState extends ConsumerState { void _snack(String m) => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m))); - ConnectionProfile? _build() { + @override + bool get isEditing => widget.editing != null; + + @override + ConnectionProfile? buildProfile() { final name = _name.text.trim(); final host = _host.text.trim(); final port = int.tryParse(_port.text.trim()); @@ -88,28 +91,6 @@ class _SshFormState extends ConsumerState { ); } - Future _persist(ConnectionProfile p) async { - final store = ref.read(profileStoreProvider); - widget.editing == null ? await store.add(p) : await store.update(p); - ref.invalidate(profilesProvider); - } - - Future _save() async { - final p = _build(); - if (p == null) return; - final navigator = Navigator.of(context); - await _persist(p); - navigator.pop(); - } - - Future _saveAndConnect() async { - final p = _build(); - if (p == null) return; - await _persist(p); - if (!mounted) return; - await launchConnection(context, ref, p); - } - @override Widget build(BuildContext context) { return Column( @@ -129,16 +110,16 @@ class _SshFormState extends ConsumerState { onSelectionChanged: (s) => setState(() => _authMethod = s.first), ), if (_authMethod == SshAuthMethod.password) - AppTextField(key: const ValueKey('ssh-password'), controller: _password, label: 'Password', icon: Icons.lock, obscure: true, last: true, onSubmit: _saveAndConnect) + AppTextField(key: const ValueKey('ssh-password'), controller: _password, label: 'Password', icon: Icons.lock, obscure: true, last: true, onSubmit: saveAndConnect) else ...[ AppTextField(key: const ValueKey('ssh-key'), controller: _key, label: 'Private key (PEM)', icon: Icons.vpn_key, maxLines: 4), - AppTextField(key: const ValueKey('ssh-passphrase'), controller: _passphrase, label: 'Passphrase (optional)', icon: Icons.password, obscure: true, last: true, onSubmit: _saveAndConnect), + AppTextField(key: const ValueKey('ssh-passphrase'), controller: _passphrase, label: 'Passphrase (optional)', icon: Icons.password, obscure: true, last: true, onSubmit: saveAndConnect), ], const SizedBox(height: 16), Row(children: [ - Expanded(child: OutlinedButton(onPressed: _save, child: const Text('Save'))), + Expanded(child: OutlinedButton(onPressed: save, child: const Text('Save'))), const SizedBox(width: 8), - Expanded(child: FilledButton(onPressed: _saveAndConnect, child: const Text('Save & Connect'))), + Expanded(child: FilledButton(onPressed: saveAndConnect, child: const Text('Save & Connect'))), ]), ], ); diff --git a/app/lib/src/ui/connect/tls_form.dart b/app/lib/src/ui/connect/tls_form.dart index 5b04eb8..1434c3b 100644 --- a/app/lib/src/ui/connect/tls_form.dart +++ b/app/lib/src/ui/connect/tls_form.dart @@ -1,11 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../connect/connection_launcher.dart'; -import '../../state/providers.dart'; import '../../storage/credential_store.dart'; import '../../storage/profile_store.dart'; import '../widgets/app_text_field.dart'; +import 'profile_form_save.dart'; class TlsForm extends ConsumerStatefulWidget { final ConnectionProfile? editing; @@ -14,7 +13,7 @@ class TlsForm extends ConsumerStatefulWidget { ConsumerState createState() => _TlsFormState(); } -class _TlsFormState extends ConsumerState { +class _TlsFormState extends ConsumerState with ProfileFormSave { final _name = TextEditingController(); final _host = TextEditingController(); final _port = TextEditingController(text: '2376'); @@ -52,7 +51,11 @@ class _TlsFormState extends ConsumerState { void _snack(String m) => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m))); - ConnectionProfile? _build() { + @override + bool get isEditing => widget.editing != null; + + @override + ConnectionProfile? buildProfile() { final name = _name.text.trim(); final host = _host.text.trim(); final port = int.tryParse(_port.text.trim()); @@ -77,28 +80,6 @@ class _TlsFormState extends ConsumerState { ); } - Future _persist(ConnectionProfile p) async { - final store = ref.read(profileStoreProvider); - widget.editing == null ? await store.add(p) : await store.update(p); - ref.invalidate(profilesProvider); - } - - Future _save() async { - final p = _build(); - if (p == null) return; - final navigator = Navigator.of(context); - await _persist(p); - navigator.pop(); - } - - Future _saveAndConnect() async { - final p = _build(); - if (p == null) return; - await _persist(p); - if (!mounted) return; - await launchConnection(context, ref, p); - } - @override Widget build(BuildContext context) { return Column( @@ -113,9 +94,9 @@ class _TlsFormState extends ConsumerState { SwitchListTile(title: const Text('Allow insecure (skip server verification)'), value: _insecure, onChanged: (v) => setState(() => _insecure = v)), const SizedBox(height: 16), Row(children: [ - Expanded(child: OutlinedButton(onPressed: _save, child: const Text('Save'))), + Expanded(child: OutlinedButton(onPressed: save, child: const Text('Save'))), const SizedBox(width: 8), - Expanded(child: FilledButton(onPressed: _saveAndConnect, child: const Text('Save & Connect'))), + Expanded(child: FilledButton(onPressed: saveAndConnect, child: const Text('Save & Connect'))), ]), ], ); diff --git a/app/lib/src/ui/container_stats_screen.dart b/app/lib/src/ui/container_stats_screen.dart index ea8b369..c51096f 100644 --- a/app/lib/src/ui/container_stats_screen.dart +++ b/app/lib/src/ui/container_stats_screen.dart @@ -4,6 +4,8 @@ import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../session/session_state.dart'; +import '../state/providers.dart'; import '../state/stats_notifier.dart'; import 'widgets/error_view.dart'; import 'widgets/resource_widgets.dart'; @@ -44,15 +46,22 @@ class ContainerStatsScreen extends ConsumerWidget { return ErrorView( key: const ValueKey('error'), error: s.error ?? 'Stats stream failed', - onRetry: () => ref.invalidate(statsProvider(containerId)), + onRetry: () => ref.read(statsProvider(containerId).notifier).retry(), ); } final latest = s.latest; if (latest == null) return const SkeletonCards(key: ValueKey('loading')); + // The stream waits for the session, so it still reports reconnecting once the session has given up. + final sessionFailed = ref.watch(sessionProvider.select((session) => session.status == SessionStatus.failed)); return ListView( key: const ValueKey('data'), padding: const EdgeInsets.all(16), children: [ + if (s.status == StatsStatus.reconnecting) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Text(sessionFailed ? 'Connection lost' : 'Reconnecting...'), + ), _chartCard(context, 'CPU', '${latest.cpuPercent.toStringAsFixed(1)} %', null, s.cpuHistory, _cpuMaxY(s.cpuHistory)), const SizedBox(height: 12), _chartCard( diff --git a/app/lib/src/ui/create_container_screen.dart b/app/lib/src/ui/create_container_screen.dart index f0faf29..bf43a2b 100644 --- a/app/lib/src/ui/create_container_screen.dart +++ b/app/lib/src/ui/create_container_screen.dart @@ -8,6 +8,7 @@ import '../api/models/container_create_config.dart'; import '../api/models/pull_event.dart'; import '../state/providers.dart'; import 'pull_sheet.dart' show parseImageRef; +import 'route_is_open.dart'; import 'widgets/app_text_field.dart'; import 'widgets/key_value_editor.dart'; import 'widgets/port_mapping_editor.dart'; @@ -71,7 +72,6 @@ class _CreateContainerScreenState extends ConsumerState { Future _create() async { final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); final client = ref.read(dockerClientProvider); if (client == null) return; final image = _image.text.trim(); @@ -89,7 +89,8 @@ class _CreateContainerScreenState extends ConsumerState { id = await client.createContainer(config, name: name.isEmpty ? null : name); } on DockerError catch (e) { if (e.statusCode != 404 && !e.message.contains('No such image')) rethrow; - if (!mounted) return; + // A screen that was closed meanwhile must not open a dialog over whatever is underneath. + if (!mounted || !routeIsOpen(context)) return; final pull = await _confirmPull(image); if (pull != true) { if (mounted) setState(() => _busy = false); @@ -113,12 +114,12 @@ class _CreateContainerScreenState extends ConsumerState { startError = '$e'; } } - if (!mounted) return; // guard the ref/messenger/navigator after the awaits + if (!mounted) return; // guard the ref and the context after the awaits ref.invalidate(containersProvider); messenger.showSnackBar(SnackBar( content: Text(startError == null ? 'Container created.' : 'Created, but failed to start: $startError'), )); - navigator.pop(); + closeRoute(context); } catch (e) { if (mounted) setState(() => _busy = false); messenger.showSnackBar(SnackBar(content: Text('Failed: $e'))); @@ -236,10 +237,10 @@ class _PullProgressDialogState extends State<_PullProgressDialog> { } }), onError: (Object e) { - if (mounted) Navigator.of(context).pop(false); + if (mounted) closeRoute(context, false); }, onDone: () { - if (mounted) Navigator.of(context).pop(_error == null); + if (mounted) closeRoute(context, _error == null); }, ); } diff --git a/app/lib/src/ui/events_screen.dart b/app/lib/src/ui/events_screen.dart index 75c5ab9..a892c5b 100644 --- a/app/lib/src/ui/events_screen.dart +++ b/app/lib/src/ui/events_screen.dart @@ -1,7 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../state/events_notifier.dart'; +import '../session/session_state.dart'; +import '../state/providers.dart'; import 'widgets/error_view.dart'; import 'widgets/resource_widgets.dart'; @@ -33,8 +34,9 @@ class EventsScreen extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final state = ref.watch(eventsProvider); - final notifier = ref.read(eventsProvider.notifier); + final state = ref.watch(sessionEventsProvider); + final notifier = ref.read(sessionEventsProvider.notifier); + final session = ref.watch(sessionProvider.select((s) => (s.status, s.error))); final visible = state.visibleEvents; return Scaffold( appBar: AppBar(title: const Text('Events')), @@ -55,8 +57,11 @@ class EventsScreen extends ConsumerWidget { ), ), Expanded( - child: state.status == EventsStatus.error - ? ErrorView(error: state.error ?? 'Event stream failed', onRetry: () => ref.invalidate(eventsProvider)) + child: session.$1 == SessionStatus.failed + ? ErrorView( + error: session.$2 ?? 'Connection lost', + onRetry: () => ref.read(sessionProvider.notifier).retry(), + ) : visible.isEmpty ? const EmptyState( icon: Icons.bolt, diff --git a/app/lib/src/ui/exec_screen.dart b/app/lib/src/ui/exec_screen.dart index 0aa2cf9..340552a 100644 --- a/app/lib/src/ui/exec_screen.dart +++ b/app/lib/src/ui/exec_screen.dart @@ -4,6 +4,7 @@ import 'package:xterm/xterm.dart'; import '../state/exec_session_controller.dart'; import '../state/providers.dart'; +import '../transport/transport.dart'; class ExecScreen extends ConsumerStatefulWidget { final String containerId; @@ -16,14 +17,41 @@ class ExecScreen extends ConsumerStatefulWidget { class _ExecScreenState extends ConsumerState { ExecSessionController? _session; + + /// The transport [_session] was started on. When the current transport is + /// a different one, the session cannot be restarted in place. + Transport? _sessionTransport; + final _cmd = TextEditingController(); @override void initState() { super.initState(); + _newSession(); + } + + /// Starts a fresh exec on the current connection with the typed command + /// (blank = the default shell). + void _newSession() { + final old = _session; + old?.removeListener(_onChange); + old?.dispose(); final client = ref.read(dockerClientProvider); - if (client != null) { - _session = ExecSessionController(client, widget.containerId)..addListener(_onChange); + _sessionTransport = ref.read(transportProvider); + _session = client == null + ? null + : (ExecSessionController(client, widget.containerId, command: _cmd.text)..addListener(_onChange)); + if (old != null) setState(() {}); + } + + /// Runs the typed command: in place while the session's connection is + /// still the current one, otherwise as a new session. + void _run() { + final session = _session; + if (session == null || !identical(_sessionTransport, ref.read(transportProvider))) { + _newSession(); + } else { + session.restart(_cmd.text); } } @@ -39,6 +67,12 @@ class _ExecScreenState extends ConsumerState { @override Widget build(BuildContext context) { + ref.listen(transportProvider, (previous, next) { + if (previous != null && !identical(previous, next)) _session?.end(); + }); + // Starting an exec waits for a usable session: while it reconnects, the + // client at hand is still the old, dead one. + final usable = ref.watch(sessionProvider.select((s) => s.streamsUsable)); final session = _session; return Scaffold( appBar: AppBar(title: Text(widget.containerName)), @@ -46,18 +80,18 @@ class _ExecScreenState extends ConsumerState { ? const Center(child: Text('Not connected')) : Column( children: [ - _CommandBar(controller: _cmd, onRun: () => session.restart(_cmd.text)), + _CommandBar(controller: _cmd, onRun: usable ? _run : null), if (session.status == ExecStatus.error) MaterialBanner( content: const Text('Exec failed'), - actions: [TextButton(onPressed: () => session.restart(_cmd.text), child: const Text('Retry'))], + actions: [TextButton(onPressed: usable ? _newSession : null, child: const Text('Retry'))], ), if (session.status == ExecStatus.ended) MaterialBanner( content: Text('Session ended${session.exitCode != null ? ' (exit ${session.exitCode})' : ''}'), - actions: [TextButton(onPressed: () => session.restart(_cmd.text), child: const Text('Restart'))], + actions: [TextButton(onPressed: usable ? _newSession : null, child: const Text('New session'))], ), - Expanded(child: TerminalView(session.terminal)), + Expanded(child: TerminalView(session.terminal, key: ObjectKey(session))), ], ), ); @@ -66,7 +100,9 @@ class _ExecScreenState extends ConsumerState { class _CommandBar extends StatelessWidget { final TextEditingController controller; - final VoidCallback onRun; + + /// Null disables the Run button. + final VoidCallback? onRun; const _CommandBar({required this.controller, required this.onRun}); @override diff --git a/app/lib/src/ui/home_screen.dart b/app/lib/src/ui/home_screen.dart index 6918670..9ac9784 100644 --- a/app/lib/src/ui/home_screen.dart +++ b/app/lib/src/ui/home_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../state/providers.dart'; import 'containers_screen.dart'; import 'images_screen.dart'; import 'networks_screen.dart'; @@ -18,12 +19,34 @@ class HomeScreen extends ConsumerStatefulWidget { class _HomeScreenState extends ConsumerState { int _index = 0; + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _showWarning()); + } + + void _showWarning() { + if (!mounted) return; + final warning = ref.read(sessionProvider).warning; + if (warning == null) return; + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(warning))); + ref.read(sessionProvider.notifier).acknowledgeWarning(); + } + @override Widget build(BuildContext context) { return Scaffold( body: IndexedStack( index: _index, - children: const [ContainersScreen(), ImagesScreen(), NetworksScreen(), VolumesScreen(), SystemScreen()], + children: [ + const ContainersScreen(), + const ImagesScreen(), + const NetworksScreen(), + const VolumesScreen(), + // Every tab stays mounted. The dashboard's disk-usage call can take + // minutes, so that one is fetched only while its tab shows. + SystemScreen(active: _index == 4), + ], ), bottomNavigationBar: NavigationBar( selectedIndex: _index, diff --git a/app/lib/src/ui/image_detail_screen.dart b/app/lib/src/ui/image_detail_screen.dart index 49c6051..2d8acef 100644 --- a/app/lib/src/ui/image_detail_screen.dart +++ b/app/lib/src/ui/image_detail_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../state/providers.dart'; import 'create_container_screen.dart'; +import 'route_is_open.dart'; import 'widgets/error_view.dart'; class ImageDetailScreen extends ConsumerWidget { @@ -69,7 +70,7 @@ class ImageDetailScreen extends ConsumerWidget { final opts = await _removeImageDialog(context); if (opts != null && client != null && context.mounted) { await run(() => client.removeImage(imageId, force: opts.$1, noprune: opts.$2), 'Removed'); - if (context.mounted) Navigator.of(context).pop(); + if (context.mounted) closeRoute(context); } }, child: const Text('Remove'), diff --git a/app/lib/src/ui/logs_screen.dart b/app/lib/src/ui/logs_screen.dart index d7ec805..8b9f896 100644 --- a/app/lib/src/ui/logs_screen.dart +++ b/app/lib/src/ui/logs_screen.dart @@ -4,7 +4,9 @@ import 'package:share_plus/share_plus.dart'; import '../api/models/log_line.dart'; import '../api/stdcopy.dart'; +import '../session/session_state.dart'; import '../state/logs_notifier.dart'; +import '../state/providers.dart'; class LogsScreen extends ConsumerWidget { final String containerId; @@ -17,6 +19,11 @@ class LogsScreen extends ConsumerWidget { return Scaffold( appBar: AppBar(title: Text(containerName)), body: inspect.when( + // The inspect only tells the TTY flag. Once the body is up, a reload or a failed refetch + // must not take the log buffer away; a container that is gone shows in the stream's own + // error banner. + skipLoadingOnReload: true, + skipError: true, loading: () => const Center(child: CircularProgressIndicator()), error: (e, _) => _ErrorBanner( message: '$e', @@ -77,6 +84,8 @@ class _LogsBodyState extends ConsumerState<_LogsBody> { final state = ref.watch(logsProvider(key)); final notifier = ref.read(logsProvider(key).notifier); final lines = state.visibleLines; + // The stream waits for the session, so it still reports reconnecting once the session has given up. + final sessionFailed = ref.watch(sessionProvider.select((s) => s.status == SessionStatus.failed)); // Keep pinned to newest while following and already at the bottom. WidgetsBinding.instance.addPostFrameCallback((_) { @@ -100,6 +109,18 @@ class _LogsBodyState extends ConsumerState<_LogsBody> { ), if (state.status == LogsStatus.error) _ErrorBanner(message: state.error ?? 'stream error', onRetry: notifier.retry), + if (state.status == LogsStatus.reconnecting) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Row(children: [ + if (sessionFailed) + const Icon(Icons.cloud_off, size: 16) + else + const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)), + const SizedBox(width: 8), + Text(sessionFailed ? 'Connection lost' : 'Reconnecting stream...'), + ]), + ), Expanded( child: ListView.builder( controller: _scroll, @@ -211,15 +232,16 @@ class _Controls extends StatelessWidget { icon: Icon(state.timestamps ? Icons.schedule : Icons.schedule_outlined), onPressed: () => onTimestamps(!state.timestamps), ), - PopupMenuButton( + PopupMenuButton( tooltip: 'Tail', icon: const Icon(Icons.format_list_numbered), - onSelected: onTail, + // 0 stands for "all": a null value would read as a dismissed menu. + onSelected: (v) => onTail(v == 0 ? null : v), itemBuilder: (_) => const [ PopupMenuItem(value: 100, child: Text('Tail 100')), PopupMenuItem(value: 500, child: Text('Tail 500')), PopupMenuItem(value: 1000, child: Text('Tail 1000')), - PopupMenuItem(value: null, child: Text('All')), + PopupMenuItem(value: 0, child: Text('All')), ], ), IconButton(tooltip: 'Share', icon: const Icon(Icons.ios_share), onPressed: onShare), diff --git a/app/lib/src/ui/network_create_sheet.dart b/app/lib/src/ui/network_create_sheet.dart index 100f1bb..d79b662 100644 --- a/app/lib/src/ui/network_create_sheet.dart +++ b/app/lib/src/ui/network_create_sheet.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/models/docker_network.dart'; import '../state/providers.dart'; +import 'route_is_open.dart'; import 'widgets/key_value_editor.dart'; class _SubnetRow { @@ -53,7 +54,6 @@ class _NetworkCreateSheetState extends ConsumerState { final client = ref.read(dockerClientProvider); if (client == null) return; final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); setState(() => _busy = true); try { await client.createNetwork( @@ -69,8 +69,9 @@ class _NetworkCreateSheetState extends ConsumerState { labels: _labels, options: _options, ); + if (!mounted) return; ref.invalidate(networksProvider); - navigator.pop(); + closeRoute(context); messenger.showSnackBar(const SnackBar(content: Text('Network created'))); } catch (e) { if (mounted) setState(() => _busy = false); // sheet may be popped mid-flight diff --git a/app/lib/src/ui/network_detail_screen.dart b/app/lib/src/ui/network_detail_screen.dart index 5cf70a5..ddc243d 100644 --- a/app/lib/src/ui/network_detail_screen.dart +++ b/app/lib/src/ui/network_detail_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../state/providers.dart'; +import 'route_is_open.dart'; import 'widgets/error_view.dart'; class NetworkDetailScreen extends ConsumerWidget { @@ -45,7 +46,6 @@ class NetworkDetailScreen extends ConsumerWidget { ElevatedButton( onPressed: () async { final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); final ok = await showDialog( context: context, builder: (ctx) => AlertDialog( @@ -60,8 +60,9 @@ class NetworkDetailScreen extends ConsumerWidget { if (ok != true || client == null) return; try { await client.removeNetwork(networkId); + if (!context.mounted) return; ref.invalidate(networksProvider); - navigator.pop(); + closeRoute(context); messenger.showSnackBar(const SnackBar(content: Text('Removed'))); } catch (e) { messenger.showSnackBar(SnackBar(content: Text('Failed: $e'))); diff --git a/app/lib/src/ui/profiles_screen.dart b/app/lib/src/ui/profiles_screen.dart index 89e8d80..c0b5b93 100644 --- a/app/lib/src/ui/profiles_screen.dart +++ b/app/lib/src/ui/profiles_screen.dart @@ -3,6 +3,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../connect/connection_launcher.dart'; +import '../session/session_state.dart'; import '../state/providers.dart'; import '../storage/profile_store.dart'; import 'connection_screen.dart'; @@ -20,9 +21,24 @@ class ProfilesScreen extends ConsumerWidget { ConnectionKind.ssh => Icons.terminal, }; + /// Opens the editor. "Save & Connect" there returns the saved profile; the + /// connect runs here so its progress and any error show on the list. + Future _openEditor(BuildContext context, WidgetRef ref, {ConnectionProfile? editing}) async { + final saved = await Navigator.of(context).push( + MaterialPageRoute(builder: (_) => ConnectionScreen(editing: editing)), + ); + if (saved != null && context.mounted) await launchConnection(context, ref, saved); + } + @override Widget build(BuildContext context, WidgetRef ref) { final profiles = ref.watch(profilesProvider); + final (status, sessionProfileId, sessionProfileName, sessionError) = + ref.watch(sessionProvider.select((s) => (s.status, s.profile?.id, s.profile?.name, s.error))); + // While a connect is in flight the screen is busy: nothing on it reacts but Settings and + // the Cancel in the bar at the bottom. + final connecting = status == SessionStatus.connecting; + final scheme = Theme.of(context).colorScheme; return Scaffold( appBar: AppBar( title: const Text('Connections'), @@ -34,10 +50,46 @@ class ProfilesScreen extends ConsumerWidget { ), ], ), - floatingActionButton: FloatingActionButton( - onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ConnectionScreen())), - child: const Icon(Icons.add), - ), + // Not shown while connecting: a FAB with a null handler looks enabled. + floatingActionButton: connecting + ? null + : FloatingActionButton( + // No hero: when a connect succeeds, this button comes back in the frame that pushes + // Home, while the Scaffold still animates the previous one out. Two heroes with one + // tag in the route being left is an error. + heroTag: null, + onPressed: () => _openEditor(context, ref), + child: const Icon(Icons.add), + ), + bottomNavigationBar: connecting + ? Material( + elevation: 3, + color: scheme.surfaceContainerHigh, + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 8, 4), + child: Row( + children: [ + const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)), + const SizedBox(width: 12), + Expanded( + child: Text( + 'Connecting to ${sessionProfileName ?? 'the daemon'}...', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + TextButton( + onPressed: () => ref.read(sessionProvider.notifier).disconnect(), + child: const Text('Cancel'), + ), + ], + ), + ), + ), + ) + : null, body: AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: profiles.when( @@ -51,7 +103,7 @@ class ProfilesScreen extends ConsumerWidget { title: 'No connections', message: 'Add a Docker host to get started.', action: FilledButton.icon( - onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ConnectionScreen())), + onPressed: connecting ? null : () => _openEditor(context, ref), icon: const Icon(Icons.add), label: const Text('Add connection'), ), @@ -61,20 +113,43 @@ class ProfilesScreen extends ConsumerWidget { for (final p in list) Card( child: ListTile( - leading: LeadingAvatar(icon: _icon(p.kind)), + leading: connecting && sessionProfileId == p.id + ? const SizedBox( + width: 44, + height: 44, + child: Center( + child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2)), + ), + ) + : LeadingAvatar(icon: _icon(p.kind)), title: Text(p.name, style: const TextStyle(fontWeight: FontWeight.w600)), - subtitle: Row( + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - MetaChip(p.kind.name), - const SizedBox(width: 8), - Expanded(child: MonoText(p.host, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall)), + Row( + children: [ + MetaChip(p.kind.name), + const SizedBox(width: 8), + Expanded(child: MonoText(p.host, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.bodySmall)), + ], + ), + if (status == SessionStatus.disconnected && sessionError != null && sessionProfileId == p.id) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + sessionError.message, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: scheme.error), + ), + ), ], ), - onTap: () { HapticFeedback.lightImpact(); launchConnection(context, ref, p); }, + onTap: connecting ? null : () { HapticFeedback.lightImpact(); launchConnection(context, ref, p); }, trailing: PopupMenuButton( + enabled: !connecting, onSelected: (v) async { if (v == 'edit') { - await Navigator.of(context).push(MaterialPageRoute(builder: (_) => ConnectionScreen(editing: p))); + await _openEditor(context, ref, editing: p); } else if (v == 'delete') { await ref.read(profileStoreProvider).delete(p.id); ref.invalidate(profilesProvider); diff --git a/app/lib/src/ui/route_is_open.dart b/app/lib/src/ui/route_is_open.dart new file mode 100644 index 0000000..84bfac8 --- /dev/null +++ b/app/lib/src/ui/route_is_open.dart @@ -0,0 +1,22 @@ +import 'package:flutter/widgets.dart'; + +/// Whether the screen that [context] belongs to is still open, that is, +/// whether its route is still on the navigator. +/// +/// A popped route keeps its widgets mounted until its exit transition ends, +/// so `mounted` alone cannot tell an action that waited for something whether +/// its screen was closed in the meantime; a pop at that point closes the +/// screen underneath instead. Needs a mounted [context]. +bool routeIsOpen(BuildContext context) => ModalRoute.of(context)?.isActive ?? false; + +/// Closes the route [context] belongs to, together with anything pushed on +/// top of it, unless that route was closed already. [result] is returned to +/// whoever pushed it. +void closeRoute(BuildContext context, [Object? result]) { + if (!context.mounted) return; + final route = ModalRoute.of(context); + if (route == null || !route.isActive) return; + final navigator = Navigator.of(context); + navigator.popUntil((r) => identical(r, route)); + navigator.pop(result); +} diff --git a/app/lib/src/ui/system_screen.dart b/app/lib/src/ui/system_screen.dart index 326c81d..a3c68b6 100644 --- a/app/lib/src/ui/system_screen.dart +++ b/app/lib/src/ui/system_screen.dart @@ -19,10 +19,15 @@ String _humanSize(int bytes) { } class SystemScreen extends ConsumerWidget { - const SystemScreen({super.key}); + const SystemScreen({super.key, this.active = true}); + + /// False while another Home tab is showing: the dashboard is then not + /// watched, so nothing refetches it until the tab is opened. + final bool active; @override Widget build(BuildContext context, WidgetRef ref) { + if (!active) return const SizedBox.shrink(); final dash = ref.watch(systemDashboardProvider); return Scaffold( appBar: AppBar( diff --git a/app/lib/src/ui/volume_create_sheet.dart b/app/lib/src/ui/volume_create_sheet.dart index 2ca8e88..8b6927b 100644 --- a/app/lib/src/ui/volume_create_sheet.dart +++ b/app/lib/src/ui/volume_create_sheet.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../state/providers.dart'; +import 'route_is_open.dart'; import 'widgets/key_value_editor.dart'; class VolumeCreateSheet extends ConsumerStatefulWidget { @@ -35,7 +36,6 @@ class _VolumeCreateSheetState extends ConsumerState { final client = ref.read(dockerClientProvider); if (client == null) return; final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); setState(() => _busy = true); try { await client.createVolume( @@ -44,8 +44,9 @@ class _VolumeCreateSheetState extends ConsumerState { labels: _labels, driverOpts: _opts, ); + if (!mounted) return; ref.invalidate(volumesProvider); - navigator.pop(); + closeRoute(context); messenger.showSnackBar(const SnackBar(content: Text('Volume created'))); } catch (e) { if (mounted) setState(() => _busy = false); diff --git a/app/lib/src/ui/volume_detail_screen.dart b/app/lib/src/ui/volume_detail_screen.dart index 0ab18fe..dfb1f01 100644 --- a/app/lib/src/ui/volume_detail_screen.dart +++ b/app/lib/src/ui/volume_detail_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../state/providers.dart'; +import 'route_is_open.dart'; import 'widgets/error_view.dart'; class VolumeDetailScreen extends ConsumerWidget { @@ -38,13 +39,13 @@ class VolumeDetailScreen extends ConsumerWidget { ElevatedButton( onPressed: () async { final messenger = ScaffoldMessenger.of(context); - final navigator = Navigator.of(context); final force = await _removeDialog(context); if (force == null || client == null || !context.mounted) return; try { await client.removeVolume(volumeName, force: force); + if (!context.mounted) return; ref.invalidate(volumesProvider); - navigator.pop(); + closeRoute(context); messenger.showSnackBar(const SnackBar(content: Text('Removed'))); } catch (e) { messenger.showSnackBar(SnackBar(content: Text('Failed: $e'))); diff --git a/app/lib/src/ui/widgets/session_banner.dart b/app/lib/src/ui/widgets/session_banner.dart new file mode 100644 index 0000000..f7c74eb --- /dev/null +++ b/app/lib/src/ui/widgets/session_banner.dart @@ -0,0 +1,135 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../connect/disconnect.dart'; +import '../../session/session_state.dart'; +import '../../state/providers.dart'; + +/// Shows the session's reconnect progress or failure; nothing otherwise. +class SessionBanner extends ConsumerWidget { + const SessionBanner({super.key, this.navigatorKey}); + + /// The app's navigator when the banner sits above it (see + /// [SessionBannerHost]); otherwise the nearest navigator is used. + final GlobalKey? navigatorKey; + + /// Whether the banner shows anything for [status]. + static bool showsFor(SessionStatus status) => switch (status) { + SessionStatus.reconnecting || SessionStatus.failed => true, + SessionStatus.disconnected || SessionStatus.connecting || SessionStatus.connected => false, + }; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final (status, attempt, error) = ref.watch(sessionProvider.select((s) => (s.status, s.attempt, s.error))); + final scheme = Theme.of(context).colorScheme; + switch (status) { + case SessionStatus.reconnecting: + final max = ref.watch(reconnectPolicyProvider).maxAttempts; + return Material( + color: scheme.secondaryContainer, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 2, 8, 2), + child: Row( + children: [ + const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)), + const SizedBox(width: 12), + Expanded( + child: Text( + 'Reconnecting... (attempt $attempt of $max)', + style: TextStyle(color: scheme.onSecondaryContainer), + ), + ), + TextButton( + style: TextButton.styleFrom(foregroundColor: scheme.onSecondaryContainer), + onPressed: () => disconnect(context, ref, navigator: navigatorKey?.currentState), + child: const Text('Disconnect'), + ), + ], + ), + ), + ), + ); + case SessionStatus.failed: + return Material( + color: scheme.errorContainer, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 10, 8, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.cloud_off, color: scheme.onErrorContainer), + const SizedBox(width: 12), + Expanded( + child: Text( + error?.message ?? 'Connection lost', + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onErrorContainer), + ), + ), + const SizedBox(width: 8), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + style: TextButton.styleFrom(foregroundColor: scheme.onErrorContainer), + onPressed: () => ref.read(sessionProvider.notifier).retry(), + child: const Text('Retry'), + ), + TextButton( + style: TextButton.styleFrom(foregroundColor: scheme.onErrorContainer), + onPressed: () => disconnect(context, ref, navigator: navigatorKey?.currentState), + child: const Text('Disconnect'), + ), + ], + ), + ], + ), + ), + ), + ); + case SessionStatus.disconnected: + case SessionStatus.connecting: + case SessionStatus.connected: + return const SizedBox.shrink(); + } + } +} + +/// Puts the [SessionBanner] above every route, so a lost connection shows +/// (and can be retried) on whatever screen the user is on. +class SessionBannerHost extends ConsumerWidget { + const SessionBannerHost({super.key, required this.navigatorKey, required this.child}); + + /// The app's navigator, which is [child]. + final GlobalKey navigatorKey; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final visible = ref.watch(sessionProvider.select((s) => SessionBanner.showsFor(s.status))); + return Column( + children: [ + SessionBanner(navigatorKey: navigatorKey), + Expanded( + child: MediaQuery.removePadding( + context: context, + removeTop: visible, // the banner already sits under the status bar + child: child, + ), + ), + ], + ); + } +} diff --git a/app/test/api/stream_cancellation_test.dart b/app/test/api/stream_cancellation_test.dart new file mode 100644 index 0000000..8b2c539 --- /dev/null +++ b/app/test/api/stream_cancellation_test.dart @@ -0,0 +1,75 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_api_client.dart'; +import 'package:docker_mobile/src/api/stdcopy.dart'; + +import '../support/fake_transport.dart'; + +/// Opens [open] against a transport whose stream never emits, cancels it +/// while it is idle, and reports whether the transport stream saw the cancel. +Future cancelReachesSource(Stream Function(DockerApiClient c) open, {bool post = false}) async { + var cancelled = false; + final source = StreamController>(onCancel: () => cancelled = true); + final t = FakeTransport(); + if (post) { + t.onPostStream(RegExp('.*'), (_) => source.stream); + } else { + t.onStream(RegExp('.*'), (_) => source.stream); + } + final sub = open(DockerApiClient(t)).listen((_) {}); + await pumpEventQueue(); + unawaited(sub.cancel()); + await pumpEventQueue(); + return cancelled; +} + +void main() { + test('cancelling an idle events stream cancels the transport stream', () async { + expect(await cancelReachesSource((c) => c.streamEvents()), isTrue); + }); + + test('cancelling an idle stats stream cancels the transport stream', () async { + expect(await cancelReachesSource((c) => c.streamContainerStats('a')), isTrue); + }); + + test('cancelling an idle non-TTY logs stream cancels the transport stream', () async { + expect(await cancelReachesSource((c) => c.streamContainerLogs('a', tty: false)), isTrue); + }); + + test('cancelling an idle TTY logs stream cancels the transport stream', () async { + expect(await cancelReachesSource((c) => c.streamContainerLogs('a', tty: true)), isTrue); + }); + + test('cancelling an idle pull cancels the transport stream', () async { + expect(await cancelReachesSource((c) => c.pullImage('nginx'), post: true), isTrue); + }); + + test('decodeStdcopy forwards a cancel to its input', () async { + var cancelled = false; + final input = StreamController>(onCancel: () => cancelled = true); + final sub = decodeStdcopy(input.stream).listen((_) {}); + await pumpEventQueue(); + unawaited(sub.cancel()); + await pumpEventQueue(); + expect(cancelled, isTrue); + }); + + test('an event split mid-character across chunks still decodes', () async { + final bytes = utf8.encode('{"Type":"container","Action":"start","Actor":{"ID":"c1","Attributes":{"name":"caf\u00e9"}}}\n'); + final cut = bytes.length - 5; // inside the trailing JSON, after the two-byte e-acute + final split = bytes.indexOf(0xA9); // second byte of e-acute (0xC3 0xA9) + final t = FakeTransport() + ..onStream(RegExp('.*'), (_) => Stream.fromIterable([bytes.sublist(0, split), bytes.sublist(split, cut), bytes.sublist(cut)])); + final events = await DockerApiClient(t).streamEvents().toList(); + expect(events.single.target, 'caf\u00e9'); + }); + + test('blank and malformed NDJSON lines are skipped, a trailing unterminated pull line is kept', () async { + final t = FakeTransport() + ..onPostStream(RegExp('.*'), (_) => Stream.value(utf8.encode('\n{not json}\n{"status":"Pulling"}\n{"status":"Done"}'))); + final events = await DockerApiClient(t).pullImage('nginx').toList(); + expect(events.map((e) => e.status), ['Pulling', 'Done']); + }); +} diff --git a/app/test/api/timestamps_test.dart b/app/test/api/timestamps_test.dart index 28c45ab..264c73f 100644 --- a/app/test/api/timestamps_test.dart +++ b/app/test/api/timestamps_test.dart @@ -21,4 +21,13 @@ void main() { expect(rfc3339ToUnixNanos('not a time'), isNull); expect(rfc3339ToUnixNanos(''), isNull); }); + + test('rfc3339ToEpochNanos keeps nanosecond precision as one integer', () { + final secs = DateTime.utc(2026, 1, 2, 3, 4, 5).millisecondsSinceEpoch ~/ 1000; + expect(rfc3339ToEpochNanos('2026-01-02T03:04:05.000000001Z'), secs * 1000000000 + 1); + expect(rfc3339ToEpochNanos('2026-01-02T03:04:05Z'), secs * 1000000000); + expect(rfc3339ToEpochNanos('nope'), isNull); + // DateTime accepts a space before the zone; the fraction is then not a number. + expect(rfc3339ToEpochNanos('2026-01-02T03:04:05.123 Z'), isNull); + }); } diff --git a/app/test/connect/connection_launcher_test.dart b/app/test/connect/connection_launcher_test.dart index 13a44aa..dd4f5be 100644 --- a/app/test/connect/connection_launcher_test.dart +++ b/app/test/connect/connection_launcher_test.dart @@ -1,40 +1,65 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/api/docker_error.dart'; import 'package:docker_mobile/src/connect/connection_launcher.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/session/transport_factory.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/storage/credential_store.dart'; import 'package:docker_mobile/src/storage/profile_store.dart'; -import 'package:docker_mobile/src/transport/agent_transport.dart'; -import 'package:docker_mobile/src/transport/ssh/ssh_connection.dart'; -import 'package:docker_mobile/src/transport/ssh/ssh_transport.dart'; +import 'package:docker_mobile/src/ui/home_screen.dart'; +import 'package:docker_mobile/src/ui/widgets/session_banner.dart'; -class _FakeSshConnection implements SshConnection { - final String fingerprint; - _FakeSshConnection(this.fingerprint); - @override - Future connect({required HostKeyVerifier verifyHostKey}) async { - if (!verifyHostKey(fingerprint)) throw Exception('host key rejected'); +import '../support/fake_session.dart'; +import '../support/fake_transport.dart'; + +const agent = ConnectionProfile(id: '1', name: 'A', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://127.0.0.1:8080', token: 't')); +ConnectionProfile ssh({String? pin}) => ConnectionProfile(id: '9', name: 'S', kind: ConnectionKind.ssh, + ssh: SshCredentials(host: '127.0.0.1', port: 22, username: 'u', authMethod: SshAuthMethod.password, password: 'p', pinnedHostKey: pin)); + +/// A daemon's transport that counts how often it is closed. Its events +/// stream stays open until the test breaks it through [events]. +class _CountingTransport extends FakeTransport { + _CountingTransport() { + onGet('/_ping', (_) => http.Response('OK', 200)); + onGet('/version', (_) => http.Response('{"Version":"27.0","ApiVersion":"1.46"}', 200)); + onStream(RegExp(r'/events$'), (_) => events.stream); } + + final events = StreamController>(); + int closes = 0; + @override - Future openChannel() async => Duplex(input: const Stream.empty(), add: (_) {}, close: () async {}); - @override - Future close() async {} + Future close() { + closes++; + return super.close(); + } } -Future _launch(WidgetTester tester, ConnectionProfile p, - {ProfileStore? store, SshConnection Function(SshCredentials)? sshFactory}) async { - final s = store ?? InMemoryProfileStore(); +/// Taps a button that launches a connection to [p]. With [bannerOver], the +/// session banner sits above that navigator, as it does in the app. +Future pumpLauncher(WidgetTester tester, ConnectionProfile p, FakeTransportFactory factory, + {ProfileStore? store, GlobalKey? bannerOver}) async { late ProviderContainer container; await tester.pumpWidget(ProviderScope( overrides: [ - profileStoreProvider.overrideWithValue(s), - if (sshFactory != null) sshConnectionFactoryProvider.overrideWithValue(sshFactory), + profileStoreProvider.overrideWithValue(store ?? InMemoryProfileStore()), + transportFactoryProvider.overrideWithValue(factory), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), ], child: MaterialApp( + navigatorKey: bannerOver, + builder: bannerOver == null + ? null + : (context, child) => SessionBannerHost(navigatorKey: bannerOver, child: child!), home: Consumer(builder: (context, ref, _) { container = ProviderScope.containerOf(context); - return ElevatedButton(onPressed: () => launchConnection(context, ref, p), child: const Text('go')); + return Scaffold(body: ElevatedButton(onPressed: () => launchConnection(context, ref, p), child: const Text('go'))); }), ), )); @@ -45,44 +70,122 @@ Future _launch(WidgetTester tester, ConnectionProfile p, } void main() { - testWidgets('agent profile sets an AgentTransport', (tester) async { - final c = await _launch(tester, - const ConnectionProfile(id: '1', name: 'A', kind: ConnectionKind.agent, - agent: AgentCredentials(baseUri: 'http://127.0.0.1:8080', token: 't'))); - expect(c.read(transportProvider), isA()); + testWidgets('a reachable daemon connects the session and opens Home', (tester) async { + final d = FakeDaemon(); + final c = await pumpLauncher(tester, agent, FakeTransportFactory([d.transport])); + await tester.pump(const Duration(milliseconds: 500)); + expect(c.read(transportProvider), same(d.transport)); + expect(c.read(dockerClientProvider)!.apiVersion, '1.45'); + expect(find.byType(HomeScreen), findsOneWidget); }); - testWidgets('SSH firstUse pins the fingerprint into the stored profile', (tester) async { + testWidgets('a failed connect stays put and reports the error', (tester) async { + final c = await pumpLauncher(tester, agent, + FakeTransportFactory([const DockerError(DockerErrorKind.network, 'refused')])); + await tester.pump(); + expect(find.byType(HomeScreen), findsNothing); + expect(c.read(transportProvider), isNull); + // No snackbar: the Connections screen shows the session's error inline. + expect(find.byType(SnackBar), findsNothing); + expect(c.read(sessionProvider).error!.message, 'refused'); + }); + + testWidgets('SSH first use pins the presented key into the stored profile', (tester) async { final store = InMemoryProfileStore(); - const profile = ConnectionProfile(id: '9', name: 'S', kind: ConnectionKind.ssh, - ssh: SshCredentials(host: '127.0.0.1', port: 22, username: 'u', authMethod: SshAuthMethod.password, password: 'p')); - await store.add(profile); - final c = await _launch(tester, profile, store: store, sshFactory: (_) => _FakeSshConnection('FP-NEW')); - expect(c.read(transportProvider), isA()); + await store.add(ssh()); + final d = FakeDaemon(); + await pumpLauncher(tester, ssh(), FakeTransportFactory([BuiltTransport(d.transport, presentedHostKey: 'FP-NEW')]), + store: store); expect((await store.list()).single.ssh!.pinnedHostKey, 'FP-NEW'); }); - testWidgets('SSH mismatch shows the dialog; Trust re-pins the stored profile', (tester) async { + testWidgets('SSH mismatch shows the dialog; Trust reconnects with the new key and re-pins', (tester) async { final store = InMemoryProfileStore(); - const profile = ConnectionProfile(id: '9', name: 'S', kind: ConnectionKind.ssh, - ssh: SshCredentials(host: '127.0.0.1', port: 22, username: 'u', authMethod: SshAuthMethod.password, password: 'p', pinnedHostKey: 'FP-OLD')); - await store.add(profile); - await tester.pumpWidget(ProviderScope( - overrides: [ - profileStoreProvider.overrideWithValue(store), - sshConnectionFactoryProvider.overrideWithValue((_) => _FakeSshConnection('FP-NEW')), - ], - child: MaterialApp( - home: Consumer(builder: (context, ref, _) => - ElevatedButton(onPressed: () => launchConnection(context, ref, profile), child: const Text('go'))), - ), - )); - await tester.tap(find.text('go')); + await store.add(ssh(pin: 'FP-OLD')); + final d = FakeDaemon(); + final factory = FakeTransportFactory([ + const HostKeyMismatchException('FP-NEW'), + BuiltTransport(d.transport, presentedHostKey: 'FP-NEW'), + ]); + await pumpLauncher(tester, ssh(pin: 'FP-OLD'), factory, store: store); await tester.pumpAndSettle(); - expect(find.textContaining('host key'), findsWidgets); + expect(find.text('Host key changed'), findsOneWidget); await tester.tap(find.widgetWithText(TextButton, 'Trust new key')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); + expect(factory.pinOverrides, [null, 'FP-NEW']); expect((await store.list()).single.ssh!.pinnedHostKey, 'FP-NEW'); + expect(find.byType(HomeScreen), findsOneWidget); // the trusted connect opens Home like any other + }); + + testWidgets('Cancel on the mismatch dialog leaves the pin alone', (tester) async { + final store = InMemoryProfileStore(); + await store.add(ssh(pin: 'FP-OLD')); + final factory = FakeTransportFactory([const HostKeyMismatchException('FP-NEW')]); + await pumpLauncher(tester, ssh(pin: 'FP-OLD'), factory, store: store); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); + await tester.pumpAndSettle(); + expect(factory.builds, 1); + expect((await store.list()).single.ssh!.pinnedHostKey, 'FP-OLD'); + }); + + /// The session is over and its one transport was closed, exactly once. + void expectEnded(ProviderContainer c, _CountingTransport t, FakeTransportFactory factory) { + expect(find.byType(HomeScreen), findsNothing); + expect(find.text('go'), findsOneWidget); + final session = c.read(sessionProvider); + expect(session.status, SessionStatus.disconnected); + expect(session.error, isNull); + expect(session.transport, isNull); + expect(t.closes, 1); + expect(t.events.hasListener, isFalse); + expect(factory.builds, 1); + } + + testWidgets('leaving Home ends the session', (tester) async { + final t = _CountingTransport(); + final factory = FakeTransportFactory([t]); + final c = await pumpLauncher(tester, agent, factory); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(HomeScreen), findsOneWidget); + expect(c.read(sessionProvider).status, SessionStatus.connected); + + await tester.pageBack(); // the arrow in the tab's app bar + await tester.pumpAndSettle(); + expectEnded(c, t, factory); + }); + + testWidgets('the Disconnect action on Home still ends the session once, without an error', (tester) async { + final t = _CountingTransport(); + final factory = FakeTransportFactory([t]); + final c = await pumpLauncher(tester, agent, factory); + await tester.pump(const Duration(milliseconds: 500)); + await tester.tap(find.byIcon(Icons.monitor_heart)); // the System tab + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.logout)); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Disconnect')); + await tester.pumpAndSettle(); + expectEnded(c, t, factory); + }); + + testWidgets('Disconnect in the banner over Home still ends the session once, without an error', (tester) async { + final t = _CountingTransport(); + final factory = FakeTransportFactory([t]); + final c = await pumpLauncher(tester, agent, factory, bannerOver: GlobalKey()); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(HomeScreen), findsOneWidget); + + t.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await tester.pump(); // the session notices + await tester.pump(); // and the banner is drawn + expect(c.read(sessionProvider).status, SessionStatus.reconnecting); + + await tester.tap(find.widgetWithText(TextButton, 'Disconnect')); + await tester.pump(); // the banner and its spinner go + await tester.pumpAndSettle(); + expectEnded(c, t, factory); }); } diff --git a/app/test/connect/disconnect_test.dart b/app/test/connect/disconnect_test.dart index 57fba5f..8aaba9b 100644 --- a/app/test/connect/disconnect_test.dart +++ b/app/test/connect/disconnect_test.dart @@ -1,17 +1,24 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/connect/disconnect.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; -import '../support/fake_transport.dart'; +import '../support/fake_session.dart'; +import '../support/stub_session.dart'; void main() { - testWidgets('disconnect pops to the first route, nulls and closes the transport', (tester) async { - final fake = FakeTransport(); + testWidgets('disconnect pops to the first route and closes the session', (tester) async { + final d = FakeDaemon(); late ProviderContainer container; await tester.pumpWidget(ProviderScope( - overrides: [transportProvider.overrideWith((ref) => fake)], + overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([d.transport])), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + ], child: MaterialApp( home: Builder(builder: (ctx) { container = ProviderScope.containerOf(ctx); @@ -31,14 +38,51 @@ void main() { }), ), )); + await container.read(sessionProvider.notifier).connect(const ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://h:1', token: 't'))); + expect(container.read(sessionProvider).status, SessionStatus.connected); + await tester.tap(find.text('go')); await tester.pumpAndSettle(); await tester.tap(find.text('disconnect')); await tester.pumpAndSettle(); + expect(container.read(sessionProvider).status, SessionStatus.disconnected); expect(container.read(transportProvider), isNull); - expect(fake.closed, isTrue); - expect(find.text('go'), findsOneWidget); // back on the first route + expect(d.transport.closed, isTrue); + expect(find.text('go'), findsOneWidget); expect(find.text('disconnect'), findsNothing); }); + + testWidgets('disconnect pops through the given navigator when the context has none', (tester) async { + final key = GlobalKey(); + final stub = StubSession(const SessionState(status: SessionStatus.connected)); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: MaterialApp( + navigatorKey: key, + // The button sits above the navigator, so its context has no Navigator. + builder: (context, child) => Material( + child: Column(children: [ + Consumer(builder: (c, ref, _) => TextButton( + onPressed: () => disconnect(c, ref, navigator: key.currentState), + child: const Text('disconnect'), + )), + Expanded(child: child!), + ]), + ), + home: const Scaffold(body: Text('first')), + ), + )); + key.currentState!.push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('second')))); + await tester.pumpAndSettle(); + expect(find.text('second'), findsOneWidget); + expect(find.text('first'), findsNothing); + + await tester.tap(find.text('disconnect')); + await tester.pumpAndSettle(); + expect(find.text('first'), findsOneWidget); + expect(find.text('second'), findsNothing); + expect(stub.disconnects, 1); + }); } diff --git a/app/test/session/docker_session_test.dart b/app/test/session/docker_session_test.dart new file mode 100644 index 0000000..8d84010 --- /dev/null +++ b/app/test/session/docker_session_test.dart @@ -0,0 +1,1154 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/api/models/docker_event.dart'; +import 'package:docker_mobile/src/session/docker_session.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/session/transport_factory.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; + +import '../support/fake_session.dart'; +import '../support/fake_transport.dart'; + +const agentA = ConnectionProfile(id: 'a', name: 'A', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://a:1', token: 't')); +const agentB = ConnectionProfile(id: 'b', name: 'B', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://b:1', token: 't')); +ConnectionProfile sshProfile({String? pin}) => ConnectionProfile(id: 's', name: 'S', kind: ConnectionKind.ssh, + ssh: SshCredentials(host: 'h', port: 22, username: 'u', authMethod: SshAuthMethod.password, password: 'p', pinnedHostKey: pin)); + +const _down = DockerError(DockerErrorKind.network, 'down'); + +/// Fails the full refresh; everything else is recorded. +class _ThrowingInvalidator extends RecordingInvalidator { + @override + void all() => throw StateError('refresh failed'); +} + +/// A daemon whose `/_ping` answers only once [answer] is completed. +class _HeldPing extends FakeTransport { + _HeldPing() { + onGet('/_ping', (_) => http.Response('OK', 200)); + onGet('/version', (_) => http.Response(jsonEncode({'Version': '27.0', 'ApiVersion': '1.46'}), 200)); + } + + final answer = Completer(); + + @override + Future get(String path, {Map? query}) async { + if (path == '/_ping') await answer.future; + return super.get(path, query: query); + } +} + +/// A daemon whose `/_ping` answers the probe at once. Every later ping waits +/// in [pings] until the test completes it, or fails it with an error. +class _PingsOnHold extends FakeTransport { + _PingsOnHold() { + onGet('/_ping', (_) => http.Response('OK', 200)); + onGet('/version', (_) => http.Response(jsonEncode({'Version': '27.0', 'ApiVersion': '1.46'}), 200)); + onStream(RegExp(r'/events$'), (_) { + final events = StreamController>(); + eventStreams.add(events); + return events.stream; + }); + } + + final pings = >[]; + + /// Every events stream opened, oldest first. + final eventStreams = >>[]; + bool _probed = false; + + @override + Future get(String path, {Map? query}) async { + if (path == '/_ping') { + if (_probed) { + final held = Completer(); + pings.add(held); + await held.future; + } + _probed = true; + } + return super.get(path, query: query); + } +} + +/// A daemon that answers the probe but ends its events stream as soon as it +/// is opened, like a proxy that lets ping and version through and cannot stream. +FakeDaemon _noEventsDaemon() => + FakeDaemon()..transport.onStream(RegExp(r'/events$'), (_) => const Stream>.empty()); + +/// A profile store whose `update` finishes only once [written] is completed. +class _HeldUpdateStore extends InMemoryProfileStore { + final written = Completer(); + + @override + Future update(ConnectionProfile profile) async { + await written.future; + return super.update(profile); + } +} + +class _Harness { + _Harness(List builds, {ReconnectPolicy? policy, RecordingInvalidator? invalidator, InMemoryProfileStore? store}) + : factory = FakeTransportFactory(builds), + lifecycle = ManualLifecycleSource(), + invalidator = invalidator ?? RecordingInvalidator(), + store = store ?? InMemoryProfileStore() { + session = DockerSession( + transportFactory: factory, + policy: policy ?? ReconnectPolicy(jitter: 0), + lifecycle: lifecycle, + invalidator: this.invalidator, + profileStore: this.store, + onEvent: events.add, + onNewSession: () => newSessions++, + onProfilesChanged: () => profileChanges++, + ); + } + + final FakeTransportFactory factory; + final ManualLifecycleSource lifecycle; + final RecordingInvalidator invalidator; + final InMemoryProfileStore store; + late final DockerSession session; + final events = []; + int newSessions = 0; + int profileChanges = 0; + + SessionState get s => session.state; +} + +/// Connects [h] to [profile] and loses the event stream of [d]. +// ignore: library_private_types_in_public_api +void connectThenLose(FakeAsync async, _Harness h, FakeDaemon d, {ConnectionProfile profile = agentA}) { + h.session.connect(profile); + async.flushMicrotasks(); + d.events.addError(const SocketException('reset')); + async.flushMicrotasks(); +} + +void main() { + group('connect', () { + test('pings, negotiates, opens the events stream and goes live', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.apiVersion, '1.45'); + expect(h.s.daemon!.apiVersion, '1.46'); + expect(h.s.transport, same(d.transport)); + expect(h.s.sessionId, 1); + expect(h.s.warning, isNull); + expect(h.newSessions, 1); + expect( + d.transport.calls.map((c) => '${c.method} ${c.path}'), + containsAllInOrder(['GET /_ping', 'GET /version', 'STREAM /v1.45/events']), + ); + expect(d.activeEventStreams, 1); + }); + }); + + test('a failed probe leaves the session disconnected with the error and closes the transport', () { + fakeAsync((async) { + final d = FakeDaemon(pingStatus: 401); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.error!.kind, DockerErrorKind.unauthorized); + expect(h.s.profile!.id, 'a'); + expect(h.s.transport, isNull); + expect(d.transport.closed, isTrue); + expect(d.eventOpens, isEmpty); + }); + }); + + test('a failed build leaves the session disconnected with the error', () { + fakeAsync((async) { + final h = _Harness([const DockerError(DockerErrorKind.network, 'refused')]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.error!.message, 'refused'); + }); + }); + + test('a host-key mismatch is rethrown with no error left in state', () { + fakeAsync((async) { + final h = _Harness([const HostKeyMismatchException('FP-NEW')]); + Object? thrown; + h.session.connect(sshProfile(pin: 'FP-OLD')).then((_) {}, onError: (Object e) { + thrown = e; + }); + async.flushMicrotasks(); + expect(thrown, isA()); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.error, isNull); + }); + }); + + test('SSH first use persists the presented host key', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([BuiltTransport(d.transport, presentedHostKey: 'FP')]); + h.store.add(sshProfile()); + async.flushMicrotasks(); + h.session.connect(sshProfile()); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.profile!.ssh!.pinnedHostKey, 'FP'); + h.store.list().then((ps) => expect(ps.single.ssh!.pinnedHostKey, 'FP')); + async.flushMicrotasks(); + expect(h.profileChanges, 1); + }); + }); + + test('trusting a changed key connects with the override and re-pins', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([BuiltTransport(d.transport, presentedHostKey: 'FP-NEW')]); + h.store.add(sshProfile(pin: 'FP-OLD')); + async.flushMicrotasks(); + h.session.connect(sshProfile(pin: 'FP-OLD'), pinOverride: 'FP-NEW'); + async.flushMicrotasks(); + expect(h.factory.pinOverrides, ['FP-NEW']); + h.store.list().then((ps) => expect(ps.single.ssh!.pinnedHostKey, 'FP-NEW')); + async.flushMicrotasks(); + expect(h.profileChanges, 1); + }); + }); + + test('an old daemon connects with a one-time warning that can be acknowledged', () { + fakeAsync((async) { + final h = _Harness([FakeDaemon(apiVersion: '1.40').transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.apiVersion, '1.40'); + expect(h.s.warning, contains('1.40')); + h.session.acknowledgeWarning(); + expect(h.s.warning, isNull); + }); + }); + + test('a daemon reporting no API version gets no warning and the client version', () { + fakeAsync((async) { + final h = _Harness([FakeDaemon(apiVersion: '').transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.warning, isNull); + expect(h.s.apiVersion, '1.45'); + }); + }); + + test('a second connect while connecting is ignored', () { + fakeAsync((async) { + final pending = Completer(); + final h = _Harness([pending.future]); + h.session.connect(agentA); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.factory.builds, 1); + }); + }); + + test('a host-key mismatch from a superseded connect is swallowed', () { + fakeAsync((async) { + final pending = Completer(); + final h = _Harness([pending.future]); + Object? error; + var completed = false; + h.session.connect(sshProfile(pin: 'FP-OLD')).then((_) { + completed = true; + }, onError: (Object e) { + error = e; + }); + async.flushMicrotasks(); + h.session.disconnect(); + async.flushMicrotasks(); + pending.completeError(const HostKeyMismatchException('FP')); + async.flushMicrotasks(); + expect(error, isNull); + expect(completed, isTrue); + expect(h.s.status, SessionStatus.disconnected); + }); + }); + + test('connecting to another profile closes the previous transport and starts a new session', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.session.connect(agentB); + async.flushMicrotasks(); + expect(d1.transport.closed, isTrue); + expect(d1.activeEventStreams, 0); + expect(h.s.transport, same(d2.transport)); + expect(h.s.profile!.id, 'b'); + expect(h.s.sessionId, 2); + expect(h.newSessions, 2); + }); + }); + + group('connect reports whether this attempt connected:', () { + /// Starts a connect; the returned reader gives what it reported, or null while it is in flight. + bool? Function() report(_Harness h, ConnectionProfile profile) { + bool? result; + h.session.connect(profile).then((v) => result = v); + return () => result; + } + + test('true for a good connect', () { + fakeAsync((async) { + final h = _Harness([FakeDaemon().transport]); + final result = report(h, agentA); + async.flushMicrotasks(); + expect(result(), isTrue); + expect(h.s.status, SessionStatus.connected); + }); + }); + + test('false for a refused one, with the error in state', () { + fakeAsync((async) { + final h = _Harness([const DockerError(DockerErrorKind.network, 'refused')]); + final result = report(h, agentA); + async.flushMicrotasks(); + expect(result(), isFalse); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.error!.message, 'refused'); + }); + }); + + test('false for a daemon that fails the probe', () { + fakeAsync((async) { + final h = _Harness([FakeDaemon(pingStatus: 401).transport]); + final result = report(h, agentA); + async.flushMicrotasks(); + expect(result(), isFalse); + expect(h.s.error!.kind, DockerErrorKind.unauthorized); + }); + }); + + test('false for a second call while the first is in flight, which still reports true', () { + fakeAsync((async) { + final pending = Completer(); + final h = _Harness([pending.future]); + final first = report(h, agentA); + final second = report(h, agentB); + async.flushMicrotasks(); + expect(second(), isFalse); // ignored at once + expect(first(), isNull); // still in flight + pending.complete(BuiltTransport(FakeDaemon().transport)); + async.flushMicrotasks(); + expect(first(), isTrue); + expect(h.s.profile!.id, 'a'); + expect(h.factory.builds, 1); + }); + }); + + final lateHandshakes = , FakeDaemon)>{ + 'answers': (pending, d) => pending.complete(BuiltTransport(d.transport)), + 'fails': (pending, d) => pending.completeError(const DockerError(DockerErrorKind.timeout, 'timed out')), + 'reports a changed host key': (pending, d) => pending.completeError(const HostKeyMismatchException('FP')), + }; + for (final MapEntry(key: outcome, value: finish) in lateHandshakes.entries) { + test('false for an attempt cancelled by disconnect() whose handshake $outcome later', () { + fakeAsync((async) { + final pending = Completer(); + final d = FakeDaemon(); + final h = _Harness([pending.future]); + bool? result; + Object? error; + h.session.connect(sshProfile(pin: 'FP-OLD')).then((v) { + result = v; + }, onError: (Object e) { + error = e; + }); + async.flushMicrotasks(); + h.session.disconnect(); + async.flushMicrotasks(); + expect(result, isNull); // its handshake is still out + + finish(pending, d); + async.flushMicrotasks(); + expect(result, isFalse); + expect(error, isNull); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.error, isNull); + if (outcome == 'answers') { + expect(d.transport.closed, isTrue); + expect(d.transport.calls, isEmpty); + } + }); + }); + } + + test('false for an attempt cancelled while its probe is out; its transport is closed', () { + fakeAsync((async) { + final t = _HeldPing(); + final h = _Harness([t]); + final result = report(h, agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connecting); + h.session.disconnect(); + async.flushMicrotasks(); + t.answer.complete(); + async.flushMicrotasks(); + expect(result(), isFalse); + expect(h.s.status, SessionStatus.disconnected); + expect(t.closed, isTrue); + }); + }); + + test('false for an attempt cancelled while its host key is being saved; its transport is closed', () { + fakeAsync((async) { + final d = FakeDaemon(); + final store = _HeldUpdateStore(); + final h = _Harness([BuiltTransport(d.transport, presentedHostKey: 'FP')], store: store); + store.add(sshProfile()); + async.flushMicrotasks(); + final result = report(h, sshProfile()); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connecting); // the probe is done, the pin write is out + h.session.disconnect(); + async.flushMicrotasks(); + store.written.complete(); + async.flushMicrotasks(); + expect(result(), isFalse); + expect(h.s.status, SessionStatus.disconnected); + expect(d.transport.closed, isTrue); + // The write went through all the same: the pin is stored, so the list must hear of it, + // or the next tap would connect with the unpinned copy. + h.store.list().then((ps) => expect(ps.single.ssh!.pinnedHostKey, 'FP')); + async.flushMicrotasks(); + expect(h.profileChanges, 1); + }); + }); + }); + + test('a host key saved after the session was disposed is not announced', () { + fakeAsync((async) { + final d = FakeDaemon(); + final store = _HeldUpdateStore(); + final h = _Harness([BuiltTransport(d.transport, presentedHostKey: 'FP')], store: store); + store.add(sshProfile()); + async.flushMicrotasks(); + h.session.connect(sshProfile()); + async.flushMicrotasks(); + h.session.dispose(); + store.written.complete(); + async.flushMicrotasks(); + expect(h.profileChanges, 0); // nobody is left to refresh + expect(d.transport.closed, isTrue); + }); + }); + }); + + group('reconnect', () { + test('a lost event stream reconnects with backoff, swaps the transport and resumes from the cursor', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + d1.events.add(utf8.encode(eventLine(timeNano: 1700000000000000123))); + async.flushMicrotasks(); + expect(h.events, hasLength(1)); + d1.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 1); + async.elapse(const Duration(milliseconds: 999)); + expect(h.factory.builds, 1); + async.elapse(const Duration(milliseconds: 2)); + expect(h.factory.builds, 2); + expect(h.s.status, SessionStatus.connected); + expect(h.s.attempt, 0); + expect(h.s.error, isNull); + expect(h.s.transport, same(d2.transport)); + expect(d1.transport.closed, isTrue); + expect(d2.eventOpens.last.query, {'since': '1700000000.000000123'}); + }); + }); + + test('a cleanly closed event stream also reconnects', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, FakeDaemon().transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + d1.events.close(); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + async.elapse(const Duration(seconds: 2)); + expect(h.s.status, SessionStatus.connected); + }); + }); + + test('gives up after five attempts', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, _down, _down, _down, _down, _down]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1 + 2 + 4 + 8 + 15)); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 5); + async.elapse(const Duration(seconds: 2)); + expect(h.s.status, SessionStatus.failed); + expect(h.s.error!.message, 'down'); + expect(h.factory.builds, 6); + async.elapse(const Duration(minutes: 5)); + expect(h.factory.builds, 6); + }); + }); + + test('a non-retryable error fails at once', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, FakeDaemon(pingStatus: 401).transport]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.failed); + expect(h.s.error!.kind, DockerErrorKind.unauthorized); + expect(h.factory.builds, 2); + }); + }); + + test('a host-key mismatch during reconnect fails with a clear message', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, const HostKeyMismatchException('FP2')]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.failed); + expect(h.s.error!.message, contains('Host key changed')); + }); + }); + + test('retry() from failed tries again at once', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d3 = FakeDaemon(); + final h = _Harness([d1.transport, FakeDaemon(pingStatus: 401).transport, d3.transport]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.failed); + h.session.retry(); + expect(h.s.status, SessionStatus.reconnecting); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d3.transport)); + }); + }); + + test('disconnect during an in-flight attempt closes the late transport', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final pending = Completer(); + final h = _Harness([d1.transport, pending.future]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.factory.builds, 2); + h.session.disconnect(); + async.flushMicrotasks(); + pending.complete(BuiltTransport(d2.transport)); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.transport, isNull); + expect(d2.transport.closed, isTrue); + }); + }); + + test("a stale in-flight attempt does not block the next connection's reconnect", () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final d3 = FakeDaemon(); + final stale = Completer(); + final h = _Harness([d1.transport, stale.future, d2.transport, d3.transport]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.factory.builds, 2); + h.session.connect(agentB); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + d2.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + async.elapse(const Duration(seconds: 1)); + expect(h.factory.builds, 4); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d3.transport)); + final lateDaemon = FakeDaemon(); + stale.complete(BuiltTransport(lateDaemon.transport)); + async.flushMicrotasks(); + expect(lateDaemon.transport.closed, isTrue); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d3.transport)); + }); + }); + + test('disconnect while waiting cancels the loop', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, FakeDaemon().transport]); + connectThenLose(async, h, d1); + h.session.disconnect(); + async.elapse(const Duration(minutes: 1)); + expect(h.factory.builds, 1); + expect(h.s.status, SessionStatus.disconnected); + expect(d1.transport.closed, isTrue); + }); + }); + + test('a successful reconnect asks for a full refresh once; a first connect does not', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.invalidator.calls, isNot(contains('all'))); + d1.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + expect(h.invalidator.calls.where((c) => c == 'all'), hasLength(1)); + }); + }); + + test('a failed reconnect attempt asks for no refresh', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, _down]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.factory.builds, 2); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 2); + expect(h.invalidator.calls, isNot(contains('all'))); + }); + }); + + test('refreshes pending when the stream is lost are dropped; the reconnect refreshes everything', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + // The first retry comes after every debounce window (0.5 s for lists and details, 2 s for the dashboard). + final h = _Harness( + [d1.transport, d2.transport], + policy: ReconnectPolicy(base: const Duration(seconds: 5), jitter: 0), + ); + h.session.connect(agentA); + async.flushMicrotasks(); + d1.events.add(utf8.encode(eventLine(action: 'die', timeNano: 1700000000000000123))); + async.flushMicrotasks(); + expect(h.events, hasLength(1)); + d1.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + + async.elapse(const Duration(seconds: 3)); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.invalidator.calls, isEmpty); + + async.elapse(const Duration(seconds: 2)); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + expect(d2.eventOpens.single.query, {'since': '1700000000.000000123'}); + async.elapse(const Duration(seconds: 3)); + expect(h.invalidator.calls, ['all']); + }); + }); + + test('a refresh that throws after a reconnect leaves the new transport open', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport], invalidator: _ThrowingInvalidator()); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + expect(d2.transport.closed, isFalse); + }); + }); + + test('a refresh that throws after a reconnect still leaves the events stream open on the new transport', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport, FakeDaemon().transport], invalidator: _ThrowingInvalidator()); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.connected); + expect(d2.eventOpens, hasLength(1)); + expect(d2.activeEventStreams, 1); + + // So the next loss is noticed too. + d2.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + }); + }); + + test('an events stream that never stays up ends in failed after the attempt limit', () { + fakeAsync((async) { + // More daemons than the limit allows: without it the session would go through them all. + final h = _Harness([for (var i = 0; i < 10; i++) _noEventsDaemon().transport]); + final attempts = []; + h.session.addListener((s) { + if (s.status == SessionStatus.reconnecting) attempts.add(s.attempt); + }, fireImmediately: false); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); // connected, and the stream ended at once + + async.elapse(const Duration(seconds: 1 + 2 + 4 + 8)); // four reconnects, each lost again at once + expect(attempts, [1, 2, 3, 4, 5]); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.factory.builds, 5); + + async.elapse(const Duration(seconds: 16)); // the fifth holds no better + expect(h.s.status, SessionStatus.failed); + expect(h.s.error!.message, 'The daemon closed the event stream'); + expect(attempts, [1, 2, 3, 4, 5]); + expect(h.factory.builds, 6); + + async.elapse(const Duration(minutes: 5)); + expect(h.s.status, SessionStatus.failed); + expect(h.factory.builds, 6); + }); + }); + + test('a reconnect that holds for the policy cap starts the count again', () { + fakeAsync((async) { + final daemons = [for (var i = 0; i < 5; i++) FakeDaemon()]; + final h = _Harness([for (final d in daemons) d.transport]); + void lose(FakeDaemon d) { + d.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + } + + connectThenLose(async, h, daemons[0]); + expect(h.s.attempt, 1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.transport, same(daemons[1].transport)); + + // Lost at once: the count goes on. + lose(daemons[1]); + expect(h.s.attempt, 2); + async.elapse(const Duration(seconds: 2)); + expect(h.s.transport, same(daemons[2].transport)); + + // Lost just short of the cap (30 s), which runs from this reconnect and + // not from the one before it: the count still goes on. + async.elapse(const Duration(milliseconds: 29999)); + lose(daemons[2]); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 3); + async.elapse(const Duration(seconds: 4)); + expect(h.s.transport, same(daemons[3].transport)); + + // This one holds for the cap: the next loss is a new one. + async.elapse(const Duration(seconds: 30)); + lose(daemons[3]); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 1); + }); + }); + + test('Retry after such a failure starts at attempt 1', () { + fakeAsync((async) { + final good = FakeDaemon(); + final h = _Harness([ + for (var i = 0; i < 6; i++) _noEventsDaemon().transport, + good.transport, + FakeDaemon().transport, + ]); + h.session.connect(agentA); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1 + 2 + 4 + 8 + 16)); + expect(h.s.status, SessionStatus.failed); + expect(h.factory.builds, 6); + + h.session.retry(); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 1); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(good.transport)); + + // The count is the retry's own: one attempt used, not the five of the failure before it. + good.events.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 2); + }); + }); + + test('a new connection starts the count again and disconnect leaves no timer behind', () { + fakeAsync((async) { + final d1 = FakeDaemon(), d2 = FakeDaemon(), d3 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport, d3.transport, FakeDaemon().transport]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.transport, same(d2.transport)); // reconnected a moment ago: one attempt is counted + + h.session.disconnect(); + async.flushMicrotasks(); + expect(async.pendingTimers, isEmpty); + + connectThenLose(async, h, d3, profile: agentB); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 1); + }); + }); + }); + + group('lifecycle', () { + test('backgrounding while connected pauses the events stream; foregrounding pings and resumes', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(d.activeEventStreams, 1); + h.lifecycle.emit(AppLifecycleState.paused); + async.flushMicrotasks(); + expect(h.s.foreground, isFalse); + expect(d.activeEventStreams, 0); + final pings = d.transport.calls.where((c) => c.path == '/_ping').length; + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(d.transport.calls.where((c) => c.path == '/_ping').length, pings + 1); + expect(d.activeEventStreams, 1); + expect(h.s.status, SessionStatus.connected); + }); + }); + + test('a failed ping on foreground starts reconnecting', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.lifecycle.emit(AppLifecycleState.paused); + d.transport.onGet('/_ping', (_) => http.Response('{"message":"gone"}', 500)); + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + }); + }); + + test('backgrounding suspends the reconnect wait; foregrounding tries at once', () { + fakeAsync((async) { + final d1 = FakeDaemon(); + final h = _Harness([d1.transport, FakeDaemon().transport]); + connectThenLose(async, h, d1); + h.lifecycle.emit(AppLifecycleState.paused); + async.elapse(const Duration(seconds: 10)); + expect(h.factory.builds, 1); + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(h.factory.builds, 2); + expect(h.s.status, SessionStatus.connected); + }); + }); + + test('rapid lifecycle toggling leaves one events subscription', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.lifecycle + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed) + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(d.activeEventStreams, 1); + expect(h.s.status, SessionStatus.connected); + expect(h.factory.builds, 1); + }); + }); + + test('inactive and hidden are ignored', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.lifecycle + ..emit(AppLifecycleState.inactive) + ..emit(AppLifecycleState.hidden); + async.flushMicrotasks(); + expect(h.s.foreground, isTrue); + expect(d.activeEventStreams, 1); + }); + }); + + test('returning to the foreground with a good ping refreshes everything once and resumes from the cursor', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + d.events.add(utf8.encode(eventLine(timeNano: 1700000000000000123))); + async.elapse(const Duration(seconds: 3)); // the refreshes of that event are done + h.invalidator.calls.clear(); + + h.lifecycle.emit(AppLifecycleState.paused); + async.elapse(const Duration(hours: 1)); // longer than the daemon keeps its backlog of events + expect(h.invalidator.calls, isEmpty); + + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.invalidator.calls, ['all']); + expect(d.eventOpens, hasLength(2)); + expect(d.eventOpens.last.query, {'since': '1700000000.000000123'}); + expect(d.activeEventStreams, 1); + async.elapse(const Duration(minutes: 1)); + expect(h.invalidator.calls, ['all']); + }); + }); + + test('a refresh pending when the app goes to the background never fires there', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + d.events.add(utf8.encode(eventLine(action: 'die', timeNano: 1700000000000000123))); + async.flushMicrotasks(); + expect(h.events, hasLength(1)); // seen: its refreshes wait for the debounce (0.5 s and 2 s) + + h.lifecycle.emit(AppLifecycleState.paused); + async.elapse(const Duration(minutes: 5)); + expect(h.invalidator.calls, isEmpty); + + // The return makes up for them, and the event that was seen is not asked for again. + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(h.invalidator.calls, ['all']); + expect(d.eventOpens.last.query, {'since': '1700000000.000000123'}); + async.elapse(const Duration(minutes: 1)); + expect(h.invalidator.calls, ['all']); + }); + }); + + final latePings = )>{ + 'fails': (ping) => ping.completeError(const SocketException('reset')), + 'answers': (ping) => ping.complete(), + }; + for (final MapEntry(key: outcome, value: finish) in latePings.entries) { + test('a resume ping that $outcome only after a reconnect leaves the new connection alone', () { + fakeAsync((async) { + final t1 = _PingsOnHold(); + final d2 = FakeDaemon(); + final h = _Harness([t1, d2.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + + // In the foreground again twice in a row: two pings are out on the old connection. + h.lifecycle + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed) + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(t1.pings, hasLength(2)); + + // The second one fails and the session reconnects. + t1.pings[1].completeError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + async.elapse(const Duration(seconds: 1)); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + expect(d2.eventOpens, hasLength(1)); + expect(h.invalidator.calls, ['all']); + + // The first one finishes only now. It was asked of the old connection and says nothing about this one. + finish(t1.pings[0]); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(d2.transport)); + expect(d2.eventOpens, hasLength(1)); + expect(d2.activeEventStreams, 1); + expect(h.invalidator.calls, ['all']); + expect(h.factory.builds, 2); + }); + }); + } + + test('a resume ping that answers after the app went to the background again opens and refreshes nothing', () { + fakeAsync((async) { + final t = _PingsOnHold(); + final h = _Harness([t]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.lifecycle + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed) + ..emit(AppLifecycleState.paused); + async.flushMicrotasks(); + + t.pings.single.complete(); + async.flushMicrotasks(); + expect(t.eventStreams, hasLength(1)); // the one the connect opened, cancelled since + expect(t.eventStreams.single.hasListener, isFalse); + expect(h.invalidator.calls, isEmpty); + }); + }); + + test('a resume ping that answers while the session is reconnecting opens and refreshes nothing', () { + fakeAsync((async) { + final t = _PingsOnHold(); + final h = _Harness([t, FakeDaemon().transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.lifecycle + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed) + ..emit(AppLifecycleState.paused) + ..emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + t.pings[1].completeError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + + // The connection is taken for dead: a late answer on it must not be acted on. + t.pings[0].complete(); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + expect(t.eventStreams, hasLength(1)); + expect(h.invalidator.calls, isEmpty); + }); + }); + + test('a loss found on return to the foreground starts at attempt 1, however soon after a reconnect', () { + fakeAsync((async) { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + final h = _Harness([d1.transport, d2.transport, FakeDaemon().transport]); + connectThenLose(async, h, d1); + async.elapse(const Duration(seconds: 1)); + expect(h.s.transport, same(d2.transport)); // reconnected this instant: far from settled + + // The app goes away at once, and the connection dies while it is away. + h.lifecycle.emit(AppLifecycleState.paused); + d2.transport.throwOn('GET', '/_ping', const SocketException('reset')); + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.reconnecting); + expect(h.s.attempt, 1); + }); + }); + + test('five short visits that each find the connection dead never end in failed', () { + fakeAsync((async) { + final daemons = [for (var i = 0; i < 7; i++) FakeDaemon()]; + final h = _Harness([for (final d in daemons) d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + + // Come back, find the connection dead, look for 20 s (less than the + // 30 s cap) and lock the phone: five times, and then come back once + // more. No time passes in the background. + final found = []; + for (var visit = 1; visit <= 6; visit++) { + h.lifecycle.emit(AppLifecycleState.paused); + daemons[visit - 1].transport.throwOn('GET', '/_ping', const SocketException('reset')); + h.lifecycle.emit(AppLifecycleState.resumed); + async.flushMicrotasks(); + found.add('${h.s.status.name} ${h.s.attempt}'); + async.elapse(const Duration(seconds: 20)); + } + expect(found, List.filled(6, 'reconnecting 1')); + expect(h.s.status, SessionStatus.connected); + expect(h.s.transport, same(daemons[6].transport)); + expect(h.factory.builds, 7); // the connect and one reconnect for every return + }); + }); + }); + + group('events', () { + test('events reach the feed callback and refresh lists', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + d.events.add(utf8.encode(eventLine())); + async.elapse(const Duration(milliseconds: 600)); + expect(h.events, hasLength(1)); + expect(h.invalidator.calls, contains('list:container')); + }); + }); + }); + + test('disconnect closes the transport, stops events and resets the state', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.session.disconnect(); + async.flushMicrotasks(); + expect(h.s.status, SessionStatus.disconnected); + expect(h.s.transport, isNull); + expect(h.s.sessionId, 1); + expect(d.transport.closed, isTrue); + expect(d.activeEventStreams, 0); + }); + }); + + test('dispose during an in-flight connect closes the late transport and never writes state', () { + fakeAsync((async) { + final d = FakeDaemon(); + final pending = Completer(); + final h = _Harness([pending.future]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.session.dispose(); + pending.complete(BuiltTransport(d.transport)); + async.flushMicrotasks(); + expect(d.transport.closed, isTrue); + expect(d.transport.calls, isEmpty); + }); + }); + + test('dispose closes the transport', () { + fakeAsync((async) { + final d = FakeDaemon(); + final h = _Harness([d.transport]); + h.session.connect(agentA); + async.flushMicrotasks(); + h.session.dispose(); + async.flushMicrotasks(); + expect(d.transport.closed, isTrue); + }); + }); +} diff --git a/app/test/session/events_hub_test.dart b/app/test/session/events_hub_test.dart new file mode 100644 index 0000000..14ef2d8 --- /dev/null +++ b/app/test/session/events_hub_test.dart @@ -0,0 +1,162 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/api/models/docker_event.dart'; +import 'package:docker_mobile/src/session/events_hub.dart'; + +import '../support/fake_session.dart'; + +DockerEvent ev(String type, {String action = 'start', String id = 'c1', int? t}) => + DockerEvent(type: type, action: action, target: id, actorId: id, timeNano: t); + +class _Hub { + final opens = []; + final controllers = >[]; + final seen = []; + final lost = []; + final inv = RecordingInvalidator(); + late final EventsHub hub = EventsHub( + open: (since) { + opens.add(since); + final c = StreamController(); + controllers.add(c); + return c.stream; + }, + onEvent: seen.add, + invalidator: inv, + onLost: lost.add, + ); + StreamController get last => controllers.last; +} + +void main() { + test('forwards every event and debounces list, detail and dashboard refreshes', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + for (var i = 0; i < 10; i++) { + h.last.add(ev('container')); + async.elapse(const Duration(milliseconds: 10)); + } + expect(h.seen, hasLength(10)); + async.elapse(const Duration(milliseconds: 489)); + expect(h.inv.calls, isEmpty); + async.elapse(const Duration(milliseconds: 20)); + expect(h.inv.calls, unorderedEquals(['list:container', 'detail:container:c1'])); + async.elapse(const Duration(seconds: 2)); + expect(h.inv.calls.where((c) => c == 'dashboard'), hasLength(1)); + }); + }); + + test('categories map to the right invalidations', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last + ..add(ev('image', id: 'sha256:abc')) + ..add(ev('network', id: 'n1')) + ..add(ev('volume', id: 'v1')) + ..add(ev('plugin', id: 'p1')); + async.elapse(const Duration(seconds: 3)); + expect( + h.inv.calls, + unorderedEquals(['list:image', 'detail:image:sha256:abc', 'list:network', 'list:volume', 'dashboard']), + ); + expect(h.seen, hasLength(4)); + }); + }); + + test('health-check exec events reach the feed but refresh nothing', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last + ..add(ev('container', action: 'exec_create: /bin/sh -c curl -f localhost')) + ..add(ev('container', action: 'exec_start: /bin/sh -c curl -f localhost')) + ..add(ev('container', action: 'exec_die')); + async.elapse(const Duration(seconds: 3)); + expect(h.seen, hasLength(3)); + expect(h.inv.calls, isEmpty); + }); + }); + + test('tracks the cursor; resume asks for since and drops events at or before it', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + expect(h.opens, [null]); + h.last + ..add(ev('container', t: 100)) + ..add(ev('container', t: 200)); + async.flushMicrotasks(); + expect(h.hub.cursorNano, 200); + h.hub.pause(); + async.flushMicrotasks(); + expect(h.last.hasListener, isFalse); + expect(h.lost, isEmpty); + h.hub.resume(); + expect(h.opens.last, '0.000000200'); + h.last + ..add(ev('container', t: 200)) + ..add(ev('container', t: 300)); + async.flushMicrotasks(); + expect(h.seen.map((e) => e.timeNano), [100, 200, 300]); + expect(h.hub.cursorNano, 300); + }); + }); + + test('start resets the cursor', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last.add(ev('container', t: 500)); + async.flushMicrotasks(); + h.hub.stop(); + h.hub.start(); + expect(h.opens.last, isNull); + expect(h.hub.cursorNano, isNull); + }); + }); + + test('a stream error reports liveness lost once, as a network error', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last.addError(const SocketException('reset')); + async.flushMicrotasks(); + expect(h.lost, hasLength(1)); + expect(h.lost.single.kind, DockerErrorKind.network); + expect(h.hub.active, isFalse); + }); + }); + + test('a clean end of the stream reports liveness lost', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last.close(); + async.flushMicrotasks(); + expect(h.lost, hasLength(1)); + expect(h.lost.single.retryable, isTrue); + }); + }); + + test('pausing never reports a loss, even if the old stream later errors', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + final old = h.last; + h.hub.pause(); + old.addError(const SocketException('late')); + async.flushMicrotasks(); + expect(h.lost, isEmpty); + }); + }); + + test('stop cancels pending refreshes', () { + fakeAsync((async) { + final h = _Hub()..hub.start(); + h.last.add(ev('container')); + async.flushMicrotasks(); + h.hub.stop(); + expect(async.pendingTimers, isEmpty); + async.elapse(const Duration(seconds: 3)); + expect(h.inv.calls, isEmpty); + }); + }); +} diff --git a/app/test/session/lifecycle_source_lazy_test.dart b/app/test/session/lifecycle_source_lazy_test.dart new file mode 100644 index 0000000..5f4067b --- /dev/null +++ b/app/test/session/lifecycle_source_lazy_test.dart @@ -0,0 +1,10 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/session/lifecycle_source.dart'; + +// Plain test()s only: a testWidgets anywhere in this file would initialise +// the binding when declared and this test could no longer fail. +void main() { + test('creating an AppLifecycleSource does not touch the binding', () { + expect(AppLifecycleSource.new, returnsNormally); + }); +} diff --git a/app/test/session/lifecycle_source_test.dart b/app/test/session/lifecycle_source_test.dart new file mode 100644 index 0000000..cd02dee --- /dev/null +++ b/app/test/session/lifecycle_source_test.dart @@ -0,0 +1,39 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/session/lifecycle_source.dart'; + +import '../support/fake_session.dart'; + +void main() { + testWidgets('AppLifecycleSource reports app lifecycle changes while listened to', (tester) async { + final source = AppLifecycleSource(); + final seen = []; + final sub = source.changes.listen(seen.add); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + expect(seen, contains(AppLifecycleState.paused)); + unawaited(sub.cancel()); // awaiting a cancel inside testWidgets hangs teardown + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + expect(seen, isNot(contains(AppLifecycleState.resumed))); + + // Listening again attaches a fresh listener. + final again = []; + final sub2 = source.changes.listen(again.add); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + expect(again, [AppLifecycleState.inactive]); + unawaited(sub2.cancel()); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + }); + + test('ManualLifecycleSource delivers synchronously', () { + final m = ManualLifecycleSource(); + final seen = []; + m.changes.listen(seen.add); + m.emit(AppLifecycleState.paused); + expect(seen, [AppLifecycleState.paused]); + }); +} diff --git a/app/test/session/reconnect_policy_test.dart b/app/test/session/reconnect_policy_test.dart new file mode 100644 index 0000000..09d01d6 --- /dev/null +++ b/app/test/session/reconnect_policy_test.dart @@ -0,0 +1,32 @@ +import 'dart:math'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; + +void main() { + test('delays double from 1 s and cap at 30 s without jitter', () { + final p = ReconnectPolicy(jitter: 0); + expect(p.delay(1), const Duration(seconds: 1)); + expect(p.delay(2), const Duration(seconds: 2)); + expect(p.delay(3), const Duration(seconds: 4)); + expect(p.delay(5), const Duration(seconds: 16)); + expect(p.delay(6), const Duration(seconds: 30)); + expect(p.delay(60), const Duration(seconds: 30)); + }); + + test('attempt below 1 is treated as the first attempt', () { + expect(ReconnectPolicy(jitter: 0).delay(0), const Duration(seconds: 1)); + }); + + test('jitter stays within plus or minus 20 percent', () { + final p = ReconnectPolicy(random: Random(42)); + for (var i = 0; i < 200; i++) { + final d = p.delay(3).inMicroseconds; + expect(d, inInclusiveRange(3200000, 4800000)); + } + }); + + test('defaults to five attempts', () { + expect(ReconnectPolicy().maxAttempts, 5); + }); +} diff --git a/app/test/session/session_state_test.dart b/app/test/session/session_state_test.dart new file mode 100644 index 0000000..353818e --- /dev/null +++ b/app/test/session/session_state_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; + +void main() { + test('starts disconnected, foreground, attempt 0, session 0', () { + const s = SessionState(); + expect(s.status, SessionStatus.disconnected); + expect(s.foreground, isTrue); + expect(s.attempt, 0); + expect(s.sessionId, 0); + expect(s.isLive, isFalse); + }); + + test('isLive needs connected and foreground', () { + const s = SessionState(status: SessionStatus.connected); + expect(s.isLive, isTrue); + expect(s.copyWith(foreground: false).isLive, isFalse); + expect(s.copyWith(status: SessionStatus.reconnecting).isLive, isFalse); + }); + + test('streamsUsable needs the foreground and a session that is connected or not connected at all', () { + const s = SessionState(status: SessionStatus.connected); + expect(s.streamsUsable, isTrue); + expect(s.copyWith(status: SessionStatus.disconnected).streamsUsable, isTrue); + expect(s.copyWith(status: SessionStatus.connecting).streamsUsable, isFalse); + expect(s.copyWith(status: SessionStatus.reconnecting).streamsUsable, isFalse); + expect(s.copyWith(status: SessionStatus.failed).streamsUsable, isFalse); + expect(s.copyWith(foreground: false).streamsUsable, isFalse); + }); + + test('copyWith keeps fields unless told, and clears error and warning on request', () { + const err = DockerError(DockerErrorKind.network, 'down'); + final s = const SessionState().copyWith(error: err, warning: 'old', attempt: 2, apiVersion: '1.45', sessionId: 3); + expect(s.error, same(err)); + expect(s.copyWith(attempt: 3).error, same(err)); + expect(s.copyWith(clearError: true).error, isNull); + expect(s.copyWith(clearWarning: true).warning, isNull); + expect(s.copyWith().apiVersion, '1.45'); + expect(s.copyWith().sessionId, 3); + }); +} diff --git a/app/test/session/transport_factory_test.dart b/app/test/session/transport_factory_test.dart new file mode 100644 index 0000000..5bd87c0 --- /dev/null +++ b/app/test/session/transport_factory_test.dart @@ -0,0 +1,103 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/transport_factory.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/transport/agent_transport.dart'; +import 'package:docker_mobile/src/transport/ssh/ssh_transport.dart'; +import 'package:docker_mobile/src/transport/tls_transport.dart'; + +import '../support/fake_session.dart'; + +ConnectionProfile sshProfile({String? pin}) => ConnectionProfile( + id: 's', name: 'S', kind: ConnectionKind.ssh, + ssh: SshCredentials(host: 'h', port: 22, username: 'u', authMethod: SshAuthMethod.password, password: 'p', pinnedHostKey: pin), + ); + +void main() { + test('agent profiles build an AgentTransport', () async { + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP')); + final b = await f.build(const ConnectionProfile(id: 'a', name: 'A', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://10.0.0.5:8080', token: 't'))); + expect(b.transport, isA()); + expect(b.presentedHostKey, isNull); + await b.transport.close(); + }); + + test('a malformed agent address is a badRequest DockerError', () async { + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP')); + await expectLater( + f.build(const ConnectionProfile(id: 'a', name: 'A', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://[::1', token: 't'))), + throwsA(isA() + .having((e) => e.kind, 'kind', DockerErrorKind.badRequest) + .having((e) => e.message, 'message', startsWith('Invalid agent address'))), + ); + }); + + test('TLS profiles build a TlsTransport from valid PEMs', () async { + final cert = File('test/fixtures/client-cert.pem').readAsStringSync(); + final key = File('test/fixtures/client-key.pem').readAsStringSync(); + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP')); + final b = await f.build(ConnectionProfile(id: 't', name: 'T', kind: ConnectionKind.tls, + tls: TlsCredentials(host: 'h', port: 2376, clientCertPem: cert, clientKeyPem: key))); + expect(b.transport, isA()); + await b.transport.close(); + }); + + test('a bad certificate is a badRequest DockerError', () async { + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP')); + await expectLater( + f.build(const ConnectionProfile(id: 't', name: 'T', kind: ConnectionKind.tls, + tls: TlsCredentials(host: 'h', port: 2376, clientCertPem: 'nope', clientKeyPem: 'nope'))), + throwsA(isA() + .having((e) => e.kind, 'kind', DockerErrorKind.badRequest) + .having((e) => e.message, 'message', startsWith('Invalid certificate'))), + ); + }); + + test('SSH first use builds an SshTransport and reports the presented key', () async { + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP-NEW')); + final b = await f.build(sshProfile()); + expect(b.transport, isA()); + expect(b.presentedHostKey, 'FP-NEW'); + }); + + test('SSH with a matching pin connects', () async { + final f = TransportFactory(sshConnectionFactory: (_) => FakeSshConnection('FP')); + expect((await f.build(sshProfile(pin: 'FP'))).transport, isA()); + }); + + test('SSH host-key mismatch throws HostKeyMismatchException and closes the connection', () async { + final conn = FakeSshConnection('FP-NEW'); + final f = TransportFactory(sshConnectionFactory: (_) => conn); + await expectLater( + f.build(sshProfile(pin: 'FP-OLD')), + throwsA(isA().having((e) => e.presentedFingerprint, 'presented', 'FP-NEW')), + ); + expect(conn.closed, isTrue); + }); + + test('pinOverride replaces the stored pin', () async { + SshCredentials? seen; + final f = TransportFactory(sshConnectionFactory: (c) { + seen = c; + return FakeSshConnection('FP-NEW'); + }); + await f.build(sshProfile(pin: 'FP-OLD'), pinOverride: 'FP-NEW'); + expect(seen!.pinnedHostKey, 'FP-NEW'); + }); + + test('other SSH failures surface as DockerError and close the connection', () async { + final conn = FakeSshConnection('FP', + connectError: const DockerError(DockerErrorKind.unauthorized, 'SSH authentication failed')); + final f = TransportFactory(sshConnectionFactory: (_) => conn); + await expectLater( + f.build(sshProfile(pin: 'FP')), + throwsA(isA().having((e) => e.kind, 'kind', DockerErrorKind.unauthorized)), + ); + expect(conn.closed, isTrue); + }); +} diff --git a/app/test/state/events_feed_test.dart b/app/test/state/events_feed_test.dart new file mode 100644 index 0000000..cf47074 --- /dev/null +++ b/app/test/state/events_feed_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/models/docker_event.dart'; +import 'package:docker_mobile/src/state/events_feed.dart'; + +DockerEvent ev(String type, String target) => DockerEvent(type: type, action: 'start', target: target); + +void main() { + test('adds newest first and caps the buffer', () { + final f = EventsFeed(); + for (var i = 0; i < kEventsBufferCap + 5; i++) { + f.add(ev('container', 'c$i')); + } + expect(f.state.events, hasLength(kEventsBufferCap)); + expect(f.state.events.first.target, 'c${kEventsBufferCap + 4}'); + }); + + test('filters by type and clears the filter', () { + final f = EventsFeed() + ..add(ev('container', 'web')) + ..add(ev('image', 'nginx')); + f.setFilter('image'); + expect(f.state.visibleEvents.single.target, 'nginx'); + f.setFilter(null); + expect(f.state.visibleEvents, hasLength(2)); + }); + + test('clear empties the feed but keeps the filter', () { + final f = EventsFeed() + ..add(ev('container', 'web')) + ..setFilter('container'); + f.clear(); + expect(f.state.events, isEmpty); + expect(f.state.filterType, 'container'); + }); +} diff --git a/app/test/state/events_notifier_test.dart b/app/test/state/events_notifier_test.dart deleted file mode 100644 index 0fe464d..0000000 --- a/app/test/state/events_notifier_test.dart +++ /dev/null @@ -1,42 +0,0 @@ -import 'dart:convert'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:docker_mobile/src/api/docker_api_client.dart'; -import 'package:docker_mobile/src/state/events_notifier.dart'; - -import '../support/fake_transport.dart'; - -void main() { - test('prepends newest-first, caps the buffer, and filters by type', () async { - final lines = StringBuffer(); - for (var i = 0; i < kEventsBufferCap + 5; i++) { - lines.writeln('{"Type":"container","Action":"start","Actor":{"Attributes":{"name":"c$i"}}}'); - } - lines.writeln('{"Type":"image","Action":"pull","Actor":{"Attributes":{"name":"nginx"}}}'); - final client = DockerApiClient( - FakeTransport()..onStream('/events', (_) => Stream.value(utf8.encode(lines.toString())))); - final n = EventsNotifier(client); - await pumpEventQueue(); - - expect(n.state.events.length, kEventsBufferCap); // capped - expect(n.state.events.first.target, 'nginx'); // newest first (last fed) - expect(n.state.visibleEvents.length, kEventsBufferCap); // no filter - - n.setFilter('image'); - expect(n.state.visibleEvents.length, 1); - expect(n.state.visibleEvents.single.type, 'image'); - - n.setFilter(null); - expect(n.state.visibleEvents.length, kEventsBufferCap); - n.dispose(); - }); - - test('a stream error sets error status', () async { - final client = DockerApiClient( - FakeTransport()..onStream('/events', (_) => Stream.error(Exception('boom')))); - final n = EventsNotifier(client); - await pumpEventQueue(); - expect(n.state.status, EventsStatus.error); - expect(n.state.error, contains('boom')); - n.dispose(); - }); -} diff --git a/app/test/state/exec_session_controller_test.dart b/app/test/state/exec_session_controller_test.dart index 1f6b3d8..c1e2809 100644 --- a/app/test/state/exec_session_controller_test.dart +++ b/app/test/state/exec_session_controller_test.dart @@ -1,9 +1,11 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:docker_mobile/src/api/docker_api_client.dart'; import 'package:docker_mobile/src/state/exec_session_controller.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; import '../support/fake_transport.dart'; @@ -12,6 +14,76 @@ FakeTransport execFake({int exitCode = 0, bool failCreate = false}) => FakeTrans ..onPost(RegExp(r'/exec$'), (_) => failCreate ? http.Response('boom', 500) : http.Response('{"Id":"e1"}', 201)) ..onPost(RegExp(r'/resize$'), (_) => http.Response('', 200)); +/// The [execFake] rules, with more for the test to control: while [attachGate] +/// or [inspectGate] is set, the attach or the exit-code inspect waits for it; +/// with [failClose] the channels fail when they are closed, and [newChannel] +/// hands out any other kind of channel. +class _ControlledExecFake extends FakeTransport { + Completer? attachGate; + Completer? inspectGate; + bool failClose = false; + FakeExecChannel Function()? newChannel; + + _ControlledExecFake({int exitCode = 0}) { + onGet(RegExp(r'/exec/[^/]+/json$'), (_) => http.Response('{"Running":false,"ExitCode":$exitCode}', 200)); + onPost(RegExp(r'/exec$'), (_) => http.Response('{"Id":"e1"}', 201)); + onPost(RegExp(r'/resize$'), (_) => http.Response('', 200)); + } + + @override + Future execAttach(String execId, {required int cols, required int rows}) async { + await attachGate?.future; + final FakeExecChannel Function()? make = failClose ? _FailingCloseChannel.new : newChannel; + if (make == null) return super.execAttach(execId, cols: cols, rows: rows); + final ch = make(); + execChannels.add(ch); + return ch; + } + + @override + Future get(String path, {Map? query}) async { + if (path.endsWith('/json')) await inspectGate?.future; + return super.get(path, query: query); + } +} + +/// A channel whose close fails, as a connection that is already gone does. It counts the attempts. +class _FailingCloseChannel extends FakeExecChannel { + int closeCalls = 0; + + @override + Future close() async { + closeCalls++; + closed = true; + // Not waited on: for a channel nobody listened to it would never complete. + if (!controller.isClosed) unawaited(controller.close()); + throw const DockerError(DockerErrorKind.network, 'connection closed'); + } +} + +/// A channel on a synchronous stream, so the session hears from it the moment +/// the test says so. With [endsOnClose] its close reports the end at once; +/// without, the output stays open after the close, like a connection whose +/// other side has not hung up yet. While [closeGate] is set, the close does +/// not complete. +class _SyncChannel extends FakeExecChannel { + final bool endsOnClose; + final out = StreamController>(sync: true); + Completer? closeGate; + + _SyncChannel({required this.endsOnClose}); + + @override + Stream> get output => out.stream; + + @override + Future close() async { + closed = true; + if (endsOnClose) unawaited(out.close()); + await closeGate?.future; + } +} + void main() { test('forwards terminal input to the channel', () async { final t = execFake(); @@ -101,4 +173,411 @@ void main() { // (which would throw and fail this test). expect(t.execChannels.every((ch) => ch.closed), isTrue); }); + + test('end() marks the session ended and closes the channel without inspecting it', () async { + final fake = execFake(); + final c = ExecSessionController(DockerApiClient(fake), 'web'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + final inspectsBefore = fake.calls.where((x) => x.path.endsWith('/json')).length; + await c.end(); + expect(c.status, ExecStatus.ended); + expect(c.exitCode, isNull); + expect(fake.lastChannel.closed, isTrue); + await pumpEventQueue(); + expect(fake.calls.where((x) => x.path.endsWith('/json')).length, inspectsBefore); + c.dispose(); + }); + + test('a starting command is used for the first exec', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid', command: 'top'); + await pumpEventQueue(); + + final createPosts = t.posts.where((p) => p.path.endsWith('/exec')).toList(); + expect(createPosts, hasLength(1)); + expect((createPosts.single.body as Map)['Cmd'], ['/bin/sh', '-c', 'top']); + expect(t.execChannels, hasLength(1)); + c.dispose(); + }); + + test('end() while connecting stays ended and leaves no open channel', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + unawaited(c.end()); // the handshake is still in flight + await pumpEventQueue(); + + expect(c.status, ExecStatus.ended); + expect(t.execChannels.where((ch) => !ch.closed), isEmpty); + expect(t.execChannels, isEmpty); // never attached: the attach is what would start the command + c.dispose(); + }); + + test('restart while connecting leaves exactly one live channel', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + unawaited(c.restart('top')); // the first handshake is still in flight + await pumpEventQueue(); + + expect(t.execChannels.where((ch) => !ch.closed), hasLength(1)); + expect(t.execChannels, hasLength(1)); // the superseded handshake never attached + expect(c.status, ExecStatus.connected); + final createPosts = t.posts.where((p) => p.path.endsWith('/exec')).toList(); + expect((createPosts.last.body as Map)['Cmd'], ['/bin/sh', '-c', 'top']); + c.dispose(); + }); + + test('ended is reported before the exit code arrives', () async { + final t = execFake()..hangOn('GET', RegExp(r'/exec/[^/]+/json$')); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + var notifications = 0; + c.addListener(() => notifications++); + + await t.lastChannel.controller.close(); // the process exits; the inspect never answers + await pumpEventQueue(); + + expect(c.status, ExecStatus.ended); + expect(c.exitCode, isNull); + expect(notifications, greaterThan(0)); // told about "ended" without waiting for the exit code + c.dispose(); + }); + + test('an ended session sends no resize', () async { + int resizes(FakeTransport t) => t.posts.where((p) => p.path.endsWith('/resize')).length; + + // Ended from outside. + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + c.terminal.onResize?.call(90, 20, 0, 0); + expect(resizes(t), 1); // a live session does send it + await c.end(); + c.terminal.onResize?.call(100, 30, 0, 0); + await pumpEventQueue(); + expect(resizes(t), 1); + c.dispose(); + + // Ended because the output closed by itself. + final t2 = execFake(); + final c2 = ExecSessionController(DockerApiClient(t2), 'cid'); + await pumpEventQueue(); + await t2.lastChannel.controller.close(); + await pumpEventQueue(); + expect(c2.status, ExecStatus.ended); + c2.terminal.onResize?.call(100, 30, 0, 0); + await pumpEventQueue(); + expect(resizes(t2), 0); + c2.dispose(); + }); + + test('a failed resize is not an unhandled error', () async { + final t = execFake() + ..throwOn('POST', RegExp(r'/resize$'), const DockerError(DockerErrorKind.network, 'connection closed')); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + + c.terminal.onResize?.call(100, 30, 0, 0); + await pumpEventQueue(); // an error nobody handles would fail the test here + + expect(t.posts.where((p) => p.path.endsWith('/resize')), hasLength(1)); // it was sent, and it failed + expect(c.status, ExecStatus.connected); + c.dispose(); + }); + + test('end() while the attach is pending closes the late channel and stays ended', () async { + final t = _ControlledExecFake()..attachGate = Completer(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); // the exec is created, the attach is waiting + expect(c.status, ExecStatus.connecting); + + unawaited(c.end()); + var notifications = 0; + c.addListener(() => notifications++); + t.attachGate!.complete(); + await pumpEventQueue(); + + expect(t.execChannels.single.closed, isTrue); + expect(c.status, ExecStatus.ended); + expect(notifications, 0); + c.dispose(); + }); + + test('dispose() while the attach is pending closes the late channel', () async { + final t = _ControlledExecFake()..attachGate = Completer(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); // the exec is created, the attach is waiting + c.dispose(); + t.attachGate!.complete(); + await pumpEventQueue(); + + // A broken guard shows here, as a channel left open. Its notification + // after dispose would not: that throw is swallowed by _start()'s own catch. + expect(t.execChannels.single.closed, isTrue); + }); + + test('a late exit code of the previous exec does not land on a restarted session', () async { + final t = _ControlledExecFake(exitCode: 7); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + t.inspectGate = Completer(); + + await t.lastChannel.controller.close(); // the output closes; the exit-code inspect is held open + await pumpEventQueue(); + expect(c.status, ExecStatus.ended); + expect(c.exitCode, isNull); + + await c.restart('x'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + + t.inspectGate!.complete(); // the previous exec's inspect answers now, with exit code 7 + await pumpEventQueue(); + expect(c.exitCode, isNull); + expect(c.status, ExecStatus.connected); + c.dispose(); + }); + + test('end() notifies once; the channel it closes is not reported as a second ending', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + var notifications = 0; + c.addListener(() => notifications++); + + await c.end(); + await pumpEventQueue(); + + expect(notifications, 1); + c.dispose(); + }); + + test('a restart never reports the old session as ended', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final seen = []; + c.addListener(() => seen.add(c.status)); + + await c.restart('top'); + await pumpEventQueue(); + + expect(seen, [ExecStatus.connecting, ExecStatus.connected]); + c.dispose(); + }); + + test('restart() after dispose does nothing', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + c.dispose(); + + await c.restart('top'); // starting again would notify after dispose and throw + await pumpEventQueue(); + + expect(t.posts.where((p) => p.path.endsWith('/exec')), hasLength(1)); + }); + + test('a channel that fails to close does not stop a restart or an end()', () async { + final t = _ControlledExecFake()..failClose = true; + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + + await c.restart('top'); + await pumpEventQueue(); // the old channel's close error must not surface as unhandled + expect(t.execChannels.first.closed, isTrue); + expect(c.status, ExecStatus.connected); + + await c.end(); // completes although the close throws + expect(t.execChannels.last.closed, isTrue); + expect(c.status, ExecStatus.ended); + c.dispose(); + }); + + test('dispose() with a channel that fails to close is not an unhandled error', () async { + final t = _ControlledExecFake()..failClose = true; + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + + c.dispose(); + await pumpEventQueue(); // an error nobody handles would fail the test here + + expect(t.lastChannel.closed, isTrue); + }); + + test('a late channel that fails to close is not an unhandled error', () async { + final t = _ControlledExecFake() + ..attachGate = Completer() + ..failClose = true; + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); // the exec is created, the attach is waiting + + unawaited(c.end()); + t.attachGate!.complete(); + await pumpEventQueue(); // an error nobody handles would fail the test here + + expect(t.execChannels.single.closed, isTrue); + c.dispose(); + }); + + test('a session whose output closed lets go of its channel', () async { + final t = execFake(); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final channel = t.lastChannel; + + await channel.controller.close(); // the process exits + await pumpEventQueue(); + expect(c.status, ExecStatus.ended); + expect(channel.closed, isTrue); + + c.terminal.onOutput?.call('x'); + expect(channel.sent, isEmpty); + c.dispose(); + }); + + test('after the output closed, end() and dispose() close nothing a second time', () async { + final t = _ControlledExecFake()..failClose = true; + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final channel = t.lastChannel as _FailingCloseChannel; + + await channel.controller.close(); // the process exits + await pumpEventQueue(); + expect(channel.closeCalls, 1); + + await c.end(); + c.dispose(); + await pumpEventQueue(); // an error nobody handles would fail the test here + expect(channel.closeCalls, 1); + }); + + test('after an output error the old channel cannot end the restarted session', () async { + final t = _ControlledExecFake()..newChannel = () => _SyncChannel(endsOnClose: false); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final old = t.lastChannel as _SyncChannel; + + old.out.addError(const DockerError(DockerErrorKind.network, 'reset')); // the session ends on it + await pumpEventQueue(); + expect(c.status, ExecStatus.ended); + expect(old.closed, isTrue); + + await c.restart('top'); + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + + unawaited(old.out.close()); // the old connection hangs up at last + await pumpEventQueue(); + expect(c.status, ExecStatus.connected); + expect(t.lastChannel.closed, isFalse); + c.dispose(); + }); + + test('a channel that reports its end inside close() is not taken for an ending', () async { + final t = _ControlledExecFake()..newChannel = () => _SyncChannel(endsOnClose: true); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final seen = []; + c.addListener(() => seen.add(c.status)); + + await c.restart('top'); + await pumpEventQueue(); + expect(seen, [ExecStatus.connecting, ExecStatus.connected]); + + await c.end(); + await pumpEventQueue(); + expect(seen, [ExecStatus.connecting, ExecStatus.connected, ExecStatus.ended]); + c.dispose(); + }); + + test('a close that takes its time holds up neither a restart nor the exit code', () async { + final t = _ControlledExecFake(exitCode: 7)..newChannel = () => _SyncChannel(endsOnClose: false); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final first = (t.lastChannel as _SyncChannel)..closeGate = Completer(); + + unawaited(c.restart('top')); // the old channel's close never completes + await pumpEventQueue(); + expect(first.closed, isTrue); + expect(t.execChannels, hasLength(2)); + expect(c.status, ExecStatus.connected); + + final second = (t.lastChannel as _SyncChannel)..closeGate = Completer(); + unawaited(second.out.close()); // the process exits, and this close hangs as well + await pumpEventQueue(); + expect(second.closed, isTrue); + expect(c.status, ExecStatus.ended); + expect(c.exitCode, 7); + c.dispose(); + }); + + test('end() completes once the channel has closed', () async { + final t = _ControlledExecFake()..newChannel = () => _SyncChannel(endsOnClose: false); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + final gate = (t.lastChannel as _SyncChannel).closeGate = Completer(); + var completed = false; + + unawaited(c.end().then((_) => completed = true)); + await pumpEventQueue(); + expect(c.status, ExecStatus.ended); // told at once + expect(completed, isFalse); // the close is still under way + + gate.complete(); + await pumpEventQueue(); + expect(completed, isTrue); + c.dispose(); + }); + + test('end() while the exec creation is failing stays ended, not error', () async { + final t = execFake(failCreate: true); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + unawaited(c.end()); // the create is still in flight, and it will fail + await pumpEventQueue(); + + expect(c.status, ExecStatus.ended); + c.dispose(); + }); + + test('the exit code arrives as a second notification', () async { + final t = _ControlledExecFake(exitCode: 7); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + t.inspectGate = Completer(); + final seen = <(ExecStatus, int?)>[]; + c.addListener(() => seen.add((c.status, c.exitCode))); + + await t.lastChannel.controller.close(); // the output closes; the exit-code inspect is held open + await pumpEventQueue(); + expect(seen, [(ExecStatus.ended, null)]); + + t.inspectGate!.complete(); + await pumpEventQueue(); + expect(seen, [(ExecStatus.ended, null), (ExecStatus.ended, 7)]); + c.dispose(); + }); + + test('end() on a session that already ended keeps its exit code and notifies nobody', () async { + final t = execFake(exitCode: 137); + final c = ExecSessionController(DockerApiClient(t), 'cid'); + await pumpEventQueue(); + await t.lastChannel.controller.close(); // the process exits + await pumpEventQueue(); + expect(c.exitCode, 137); + var notifications = 0; + c.addListener(() => notifications++); + + await c.end(); + await pumpEventQueue(); + + expect(c.status, ExecStatus.ended); + expect(c.exitCode, 137); + expect(notifications, 0); + c.dispose(); + }); } diff --git a/app/test/state/logs_notifier_test.dart b/app/test/state/logs_notifier_test.dart index 171201c..997bbb0 100644 --- a/app/test/state/logs_notifier_test.dart +++ b/app/test/state/logs_notifier_test.dart @@ -1,10 +1,13 @@ import 'dart:async'; import 'dart:convert'; +import 'package:fake_async/fake_async.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:docker_mobile/src/api/stdcopy.dart'; import 'package:docker_mobile/src/api/docker_api_client.dart'; +import 'package:docker_mobile/src/api/timestamps.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; import 'package:docker_mobile/src/state/logs_notifier.dart'; import 'package:docker_mobile/src/state/providers.dart'; @@ -27,7 +30,7 @@ void main() { frame(1, utf8.encode('lo\nwor')), frame(1, utf8.encode('ld\n')), ])); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); await pumpEventQueue(); expect(n.state.lines.map((l) => l.text).toList(), ['hello', 'world']); n.dispose(); @@ -35,7 +38,7 @@ void main() { test('tags stderr lines', () async { final client = DockerApiClient(chunksFake([frame(2, utf8.encode('boom\n'))])); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); await pumpEventQueue(); expect(n.state.lines.single.source, LogStream.stderr); n.dispose(); @@ -43,7 +46,7 @@ void main() { test('search filters visible lines', () async { final client = DockerApiClient(chunksFake([frame(1, utf8.encode('apple\nbanana\n'))])); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); await pumpEventQueue(); n.setSearch('ban'); expect(n.state.visibleLines.map((l) => l.text).toList(), ['banana']); @@ -53,7 +56,7 @@ void main() { test('caps the buffer at kLogBufferCap lines', () async { final many = '${List.generate(kLogBufferCap + 10, (i) => 'line$i').join('\n')}\n'; final client = DockerApiClient(chunksFake([frame(1, utf8.encode(many))])); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); await pumpEventQueue(); expect(n.state.lines.length, kLogBufferCap); expect(n.state.lines.last.text, 'line${kLogBufferCap + 9}'); // newest kept @@ -62,7 +65,7 @@ void main() { test('reaches idle status when a non-following stream completes', () async { final client = DockerApiClient(chunksFake([frame(1, utf8.encode('x\n'))])); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); await pumpEventQueue(); expect(n.state.status, LogsStatus.idle); n.dispose(); @@ -71,7 +74,7 @@ void main() { test('pause stops the live stream and preserves buffered lines', () async { final controller = StreamController>(); final client = DockerApiClient(FakeTransport.streaming(controller.stream)); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); controller.add(frame(1, utf8.encode('one\n'))); await pumpEventQueue(); @@ -94,7 +97,7 @@ void main() { test('enters error status and preserves lines on stream error', () async { final controller = StreamController>(); final client = DockerApiClient(FakeTransport.streaming(controller.stream)); - final n = LogsNotifier(client, 'a', false); + final n = LogsNotifier(() => client, 'a', false); controller.add(frame(1, utf8.encode('before\n'))); await pumpEventQueue(); @@ -138,8 +141,8 @@ void main() { test('parses the leading RFC3339 timestamp when timestamps enabled', () async { final line = '2026-01-02T03:04:05.000000000Z hello\n'; final client = DockerApiClient(chunksFake([frame(1, utf8.encode(line))])); - final n = LogsNotifier(client, 'a', false); - n.setTimestamps(true); // re-subscribes with timestamps on + final n = LogsNotifier(() => client, 'a', false); + n.setTimestamps(true); // display-only: the daemon always sends them await pumpEventQueue(); final l = n.state.lines.single; @@ -148,4 +151,442 @@ void main() { expect(l.timestamp!.toUtc(), DateTime.utc(2026, 1, 2, 3, 4, 5)); n.dispose(); }); + + String ts(int nanos) => '2026-01-02T03:04:05.${nanos.toString().padLeft(9, '0')}Z'; + final base = DateTime.utc(2026, 1, 2, 3, 4, 5).millisecondsSinceEpoch ~/ 1000 * 1000000000; + + test('always asks the daemon for timestamps; the toggle is display-only', () async { + final t = chunksFake([frame(1, utf8.encode('${ts(1)} one\n'))]); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(t.lastQuery!['timestamps'], 'true'); + final opens = t.calls.where((c) => c.method == 'STREAM').length; + n.setTimestamps(true); + n.setTimestamps(false); + await pumpEventQueue(); + expect(t.calls.where((c) => c.method == 'STREAM').length, opens); + expect(n.state.lines.single.text, 'one'); + expect(n.state.lines.single.rawTimestamp, ts(1)); + n.dispose(); + }); + + test('a retryable error reopens from the cursor and drops the repeated boundary line', () { + fakeAsync((async) { + final controllers = >>[]; + final t = FakeTransport() + ..onStream('/containers/a/logs', (_) { + final c = StreamController>(); + controllers.add(c); + return c.stream; + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false, policy: ReconnectPolicy(jitter: 0)); + async.flushMicrotasks(); + controllers.last.add(frame(1, utf8.encode('${ts(1)} one\n'))); + async.flushMicrotasks(); + controllers.last.addError(const DockerError(DockerErrorKind.network, 'reset')); + async.flushMicrotasks(); + expect(n.state.status, LogsStatus.reconnecting); + async.elapse(const Duration(seconds: 1)); + final q = t.calls.where((c) => c.method == 'STREAM').last.query!; + expect(q['since'], formatUnixNanos(base + 1)); + expect(q['tail'], 'all'); + controllers.last.add(frame(1, utf8.encode('${ts(1)} one\n${ts(2)} two\n'))); + async.flushMicrotasks(); + expect(n.state.lines.map((l) => l.text), ['one', 'two']); + expect(n.state.status, LogsStatus.streaming); + n.dispose(); + }); + }); + + test('setLive(false) pauses as reconnecting; setLive(true) resumes from the cursor', () { + fakeAsync((async) { + final controllers = >>[]; + var cancelled = 0; + final t = FakeTransport() + ..onStream('/containers/a/logs', (_) { + final c = StreamController>(onCancel: () => cancelled++); + controllers.add(c); + return c.stream; + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + async.flushMicrotasks(); + controllers.last.add(frame(1, utf8.encode('${ts(5)} five\n'))); + async.flushMicrotasks(); + n.setLive(false); + async.flushMicrotasks(); + expect(cancelled, 1); + expect(n.state.status, LogsStatus.reconnecting); + n.setLive(true); + expect(controllers, hasLength(2)); + expect(t.calls.where((c) => c.method == 'STREAM').last.query!['since'], formatUnixNanos(base + 5)); + n.dispose(); + }); + }); + + test('a user pause survives the session going away and coming back', () { + fakeAsync((async) { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + async.flushMicrotasks(); + n.setFollowing(false); + n.setLive(false); + n.setLive(true); + async.flushMicrotasks(); + expect(n.state.status, LogsStatus.paused); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(1)); + n.dispose(); + }); + }); + + test('a user pause while the session is away stays paused when it comes back', () { + fakeAsync((async) { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + async.flushMicrotasks(); + n.setLive(false); + n.setFollowing(false); + n.setLive(true); + async.flushMicrotasks(); + expect(n.state.status, LogsStatus.paused); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(1)); + n.dispose(); + }); + }); + + test('a stream that ends cleanly settles on idle without reopening', () { + fakeAsync((async) { + final t = chunksFake([frame(1, utf8.encode('${ts(1)} only\n'))]); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false, policy: ReconnectPolicy(jitter: 0)); + async.flushMicrotasks(); + async.elapse(const Duration(minutes: 1)); + expect(n.state.status, LogsStatus.idle); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(1)); + n.dispose(); + }); + }); + + test('setTail starts over without a cursor', () async { + final t = chunksFake([frame(1, utf8.encode('${ts(1)} one\n'))]); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + n.setTail(100); + await pumpEventQueue(); + final q = t.calls.where((c) => c.method == 'STREAM').last.query!; + expect(q['tail'], '100'); + expect(q.containsKey('since'), isFalse); + expect(n.state.lines.single.text, 'one'); + n.dispose(); + }); + + /// A log stream that ends after one line on every open: open n sends the + /// line stamped ts(n). + FakeTransport endingFake() { + var count = 0; + return FakeTransport() + ..onStream('/containers/a/logs', (_) { + count++; + return Stream.value(frame(1, utf8.encode('${ts(count)} line$count\n'))); + }); + } + + test('play after the stream ended reopens it from the cursor', () async { + final t = endingFake(); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(n.state.status, LogsStatus.idle); + expect(n.state.lines.map((l) => l.text), ['line1']); + + n.setFollowing(false); + n.setFollowing(true); + await pumpEventQueue(); + + final opens = t.calls.where((c) => c.method == 'STREAM').toList(); + expect(opens, hasLength(2)); + expect(opens.last.query!['since'], formatUnixNanos(base + 1)); + expect(n.state.lines.map((l) => l.text), ['line1', 'line2']); + n.dispose(); + }); + + test('the session coming back reopens a stream that had ended', () async { + final t = endingFake(); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(n.state.status, LogsStatus.idle); + + n.setLive(false); + n.setLive(true); + await pumpEventQueue(); + + final opens = t.calls.where((c) => c.method == 'STREAM').toList(); + expect(opens, hasLength(2)); + expect(opens.last.query!['since'], formatUnixNanos(base + 1)); + expect(n.state.lines.map((l) => l.text), ['line1', 'line2']); + n.dispose(); + }); + + test('setTail while paused refetches the tail once without follow', () async { + final lines = frame(1, utf8.encode('${ts(1)} one\n${ts(2)} two\n')); + final t = FakeTransport() + ..onStream('/containers/a/logs', (call) { + // Like the daemon: a follow stays open, a one-off fetch ends. + if (call.query!['follow'] == 'true') return (StreamController>()..add(lines)).stream; + return Stream.value(lines); + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(n.state.lines.map((l) => l.text), ['one', 'two']); + + n.setFollowing(false); + expect(n.state.status, LogsStatus.paused); + n.setTail(100); + await pumpEventQueue(); + + final opens = t.calls.where((c) => c.method == 'STREAM').toList(); + expect(opens, hasLength(2)); // the follow, then one refetch + final q = opens.last.query!; + expect(q['tail'], '100'); + expect(q.containsKey('since'), isFalse); + expect(q['follow'], 'false'); + expect(n.state.lines.map((l) => l.text), ['one', 'two']); + expect(n.state.following, isFalse); + expect(n.state.status, LogsStatus.idle); + n.dispose(); + }); + + /// A log stream whose first open fails with a 404 (not retryable); every + /// later open sends one line and ends. + FakeTransport failingOnceFake() { + var count = 0; + return FakeTransport() + ..onStream('/containers/a/logs', (_) { + count++; + if (count == 1) return Stream.error(DockerError.fromResponse(404, '{"message":"gone"}')); + return Stream.value(frame(1, utf8.encode('${ts(1)} back\n'))); + }); + } + + test('play after the stream failed reopens it', () async { + final t = failingOnceFake(); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(n.state.status, LogsStatus.error); + + n.setFollowing(false); + n.setFollowing(true); + await pumpEventQueue(); + + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(2)); + expect(n.state.lines.map((l) => l.text), ['back']); + expect(n.state.status, LogsStatus.idle); + n.dispose(); + }); + + test('the session coming back reopens a stream that had failed', () async { + final t = failingOnceFake(); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + expect(n.state.status, LogsStatus.error); + + n.setLive(false); + n.setLive(true); + await pumpEventQueue(); + + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(2)); + expect(n.state.lines.map((l) => l.text), ['back']); + expect(n.state.status, LogsStatus.idle); + n.dispose(); + }); + + test('play during a one-off fetch starts following', () async { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + + n.setFollowing(false); + n.setTail(100); // a one-off fetch, still open + n.setFollowing(true); + await pumpEventQueue(); + + final opens = t.calls.where((c) => c.method == 'STREAM').toList(); + expect(opens.last.query!['follow'], 'true'); + expect(opens.last.query!['tail'], '100'); + expect(opens, hasLength(3)); // the first follow, the one-off fetch, the follow that replaces it + expect(n.state.status, LogsStatus.streaming); + n.dispose(); + }); + + test('a tail change while paused and away is fetched when the session returns', () async { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + + n.setFollowing(false); + n.setLive(false); + n.setTail(100); + await pumpEventQueue(); + expect(opens(), hasLength(1)); // nothing is fetched while the session is away + + n.setLive(true); + await pumpEventQueue(); + expect(opens(), hasLength(2)); + final q = opens().last.query!; + expect(q['tail'], '100'); + expect(q['follow'], 'false'); + expect(q.containsKey('since'), isFalse); + expect(n.state.following, isFalse); + n.dispose(); + }); + + test('a tail change while following and away comes with the stream that reopens, and a later pause fetches nothing', + () async { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + + n.setLive(false); + n.setTail(100); + n.setLive(true); // the follow reopens with the new tail: no one-off fetch is owed any more + await pumpEventQueue(); + expect(opens(), hasLength(2)); + expect(opens().last.query!['tail'], '100'); + expect(opens().last.query!['follow'], 'true'); + + n.setFollowing(false); + await pumpEventQueue(); + expect(opens(), hasLength(2)); + expect(n.state.status, LogsStatus.paused); + n.dispose(); + }); + + test('a tail change made up when the session returned is not fetched again on the next return', () async { + final t = FakeTransport() + ..onStream('/containers/a/logs', (call) { + // Like the daemon: a follow stays open, a one-off fetch ends. + if (call.query!['follow'] == 'true') return StreamController>().stream; + return Stream.value(frame(1, utf8.encode('${ts(1)} one\n'))); + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + + n.setFollowing(false); + n.setLive(false); + n.setTail(100); + n.setLive(true); // the one-off fetch that was owed + await pumpEventQueue(); + expect(opens(), hasLength(2)); + expect(opens().last.query!['follow'], 'false'); + expect(n.state.status, LogsStatus.idle); // it ran to its end + expect(n.state.lines.single.text, 'one'); + + n.setLive(false); + n.setLive(true); // nothing is owed any more + await pumpEventQueue(); + expect(opens(), hasLength(2)); + expect(n.state.lines.single.text, 'one'); + n.dispose(); + }); + + test('a one-off fetch cut short by the session is made up from the cursor', () async { + final controllers = >>[]; + final t = FakeTransport() + ..onStream('/containers/a/logs', (_) { + final c = StreamController>(); + controllers.add(c); + return c.stream; + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + + n.setFollowing(false); + n.setTail(100); // the one-off fetch + controllers.last.add(frame(1, utf8.encode('${ts(7)} seven\n'))); + await pumpEventQueue(); + expect(n.state.lines.single.text, 'seven'); + + n.setLive(false); // the session drops before the fetch is done + n.setLive(true); + await pumpEventQueue(); + + expect(opens(), hasLength(3)); + final q = opens().last.query!; + expect(q['follow'], 'false'); + expect(q['since'], formatUnixNanos(base + 7)); + expect(n.state.following, isFalse); + n.dispose(); + }); + + test('retry is ignored while the session is away', () async { + final t = FakeTransport()..onStream('/containers/a/logs', (_) => StreamController>().stream); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false); + await pumpEventQueue(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + + n.setLive(false); + n.retry(); + await pumpEventQueue(); + expect(opens(), hasLength(1)); + expect(n.state.status, LogsStatus.reconnecting); + + n.setLive(true); // the stream restarts by itself + n.retry(); // and Retry works again + await pumpEventQueue(); + expect(opens(), hasLength(3)); + n.dispose(); + }); + + test('a resume keeps a new line that shares the cursor timestamp', () { + fakeAsync((async) { + final controllers = >>[]; + final t = FakeTransport() + ..onStream('/containers/a/logs', (_) { + final c = StreamController>(); + controllers.add(c); + return c.stream; + }); + final n = LogsNotifier(() => DockerApiClient(t), 'a', false, policy: ReconnectPolicy(jitter: 0)); + async.flushMicrotasks(); + void send(String lines) { + controllers.last.add(frame(1, utf8.encode(lines))); + async.flushMicrotasks(); + } + + // Breaks the stream with a retryable error; the supervisor reopens it. + void cut() { + controllers.last.addError(const DockerError(DockerErrorKind.network, 'reset')); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + } + + Iterable shown() => n.state.lines.map((l) => l.text); + + send('${ts(1)} a\n'); + cut(); + send('${ts(1)} a\n${ts(1)} b\n${ts(2)} c\n'); // b is new and carries the stamp of a + expect(shown(), ['a', 'b', 'c']); + + cut(); + send('${ts(1)} a\n${ts(1)} b\n${ts(2)} c\n${ts(3)} d\n'); + expect(shown(), ['a', 'b', 'c', 'd']); // b is not shown twice + + // Two lines already shown at the cursor: both are repeats, a third one is new. + send('${ts(3)} e\n'); + cut(); + send('${ts(3)} d\n${ts(3)} e\n${ts(3)} f\n${ts(4)} g\n'); + expect(shown(), ['a', 'b', 'c', 'd', 'e', 'f', 'g']); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(4)); + n.dispose(); + }); + }); + + test('the line timestamp is the daemon stamp in UTC, to the microsecond', () async { + final client = DockerApiClient(chunksFake([frame(1, utf8.encode('2026-01-02T03:04:05.123456789Z hello\n'))])); + final n = LogsNotifier(() => client, 'a', false); + await pumpEventQueue(); + expect(n.state.lines.single.timestamp, DateTime.utc(2026, 1, 2, 3, 4, 5, 123, 456)); + n.dispose(); + }); } diff --git a/app/test/state/provider_invalidator_test.dart b/app/test/state/provider_invalidator_test.dart new file mode 100644 index 0000000..2a8e1cb --- /dev/null +++ b/app/test/state/provider_invalidator_test.dart @@ -0,0 +1,116 @@ +import 'dart:io'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/models/docker_container.dart'; +import 'package:docker_mobile/src/session/events_hub.dart'; +import 'package:docker_mobile/src/state/providers.dart'; + +final _invalidatorProvider = Provider((ref) => ProviderInvalidator(ref)); + +void main() { + test('list(container) re-runs the container list', () async { + var runs = 0; + final c = ProviderContainer(overrides: [ + containersProvider.overrideWith((ref) async { + runs++; + return const []; + }), + ]); + addTearDown(c.dispose); + c.listen(containersProvider, (_, _) {}); + await c.read(containersProvider.future); + c.read(_invalidatorProvider).list(EventCategory.container); + await c.read(containersProvider.future); + expect(runs, 2); + }); + + test('detail(container, id) re-runs only that container detail', () async { + final runs = []; + final c = ProviderContainer(overrides: [ + containerDetailProvider.overrideWith((ref, id) async { + runs.add(id); + throw UnimplementedError(); + }), + ]); + addTearDown(c.dispose); + c.listen(containerDetailProvider('a'), (_, _) {}); + c.listen(containerDetailProvider('b'), (_, _) {}); + await pumpEventQueue(); + c.read(_invalidatorProvider).detail(EventCategory.container, 'a'); + c.read(containerDetailProvider('a')); + await pumpEventQueue(); + expect(runs.where((id) => id == 'a'), hasLength(2)); + expect(runs.where((id) => id == 'b'), hasLength(1)); + }); + + test('dashboard() re-runs the system dashboard and other categories are no-ops', () async { + var runs = 0; + final c = ProviderContainer(overrides: [ + systemDashboardProvider.overrideWith((ref) async { + runs++; + throw UnimplementedError(); + }), + ]); + addTearDown(c.dispose); + c.listen(systemDashboardProvider, (_, _) {}); + await pumpEventQueue(); + final inv = c.read(_invalidatorProvider) + ..list(EventCategory.other) + ..detail(EventCategory.network, 'n') + ..dashboard(); + expect(inv, isNotNull); + c.read(systemDashboardProvider); + await pumpEventQueue(); + expect(runs, 2); + }); + + test('`all` refreshes each resource provider and creates none', () async { + var lists = 0; + final details = []; + final c = ProviderContainer(overrides: [ + containersProvider.overrideWith((ref) async { + lists++; + return const []; + }), + containerDetailProvider.overrideWith((ref, id) async { + details.add(id); + throw UnimplementedError(); + }), + ]); + addTearDown(c.dispose); + await c.read(containersProvider.future); + c.read(containerDetailProvider('a')); + await pumpEventQueue(); + expect(lists, 1); + expect(details, ['a']); + + c.read(_invalidatorProvider).all(); + await c.read(containersProvider.future); + c.read(containerDetailProvider('a')); + await pumpEventQueue(); + expect(lists, 2); + expect(details, ['a', 'a']); + // Nothing is created for a provider or a family member that was never read. + expect(c.exists(imagesProvider), isFalse); + expect(c.exists(containerDetailProvider('b')), isFalse); + }); + + test('every provider that uses resourceClient is listed in resourceProviders', () { + // A provider that takes its client from resourceClient is refreshed after a + // reconnect only if `all` knows it. Count the calls in the sources (tests + // run with the package root as the working directory). + final call = RegExp(r'\bresourceClient\('); + final declaration = RegExp(r'^DockerApiClient resourceClient\(', multiLine: true); + final callsByFile = {}; + for (final entity in Directory('lib').listSync(recursive: true)) { + if (entity is! File || !entity.path.endsWith('.dart')) continue; + final source = entity.readAsStringSync(); + final calls = call.allMatches(source).length - declaration.allMatches(source).length; + if (calls > 0) callsByFile[entity.path.replaceAll(r'\', '/')] = calls; + } + expect(callsByFile.keys, ['lib/src/state/providers.dart'], reason: 'resource providers live next to the list'); + expect(callsByFile['lib/src/state/providers.dart'], resourceProviders.length, + reason: 'calls of resourceClient versus entries in resourceProviders'); + }); +} diff --git a/app/test/state/reconnect_refresh_test.dart b/app/test/state/reconnect_refresh_test.dart new file mode 100644 index 0000000..d241a7a --- /dev/null +++ b/app/test/state/reconnect_refresh_test.dart @@ -0,0 +1,241 @@ +import 'dart:convert'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; + +import '../support/fake_session.dart'; + +const _profileA = ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://a:1', token: 't')); +const _profileB = ConnectionProfile( + id: '2', name: 'B', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://b:1', token: 't')); + +const _oneContainer = '[{"Id":"c1","Names":["/web"],"Image":"nginx","State":"running","Status":"Up"}]'; + +/// A container over the real session. The session takes [daemons] in order: +/// the first on connect, the next on every reconnect or new connection. +/// Reconnects are immediate unless [policy] says otherwise. +ProviderContainer _container(List daemons, {ReconnectPolicy? policy}) { + final c = ProviderContainer(overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([for (final d in daemons) d.transport])), + reconnectPolicyProvider.overrideWithValue(policy ?? immediatePolicy()), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + profileStoreProvider.overrideWithValue(InMemoryProfileStore()), + ]); + addTearDown(c.dispose); + return c; +} + +/// Breaks [daemon]'s events stream, so the session reconnects through the next daemon. +Future _dropConnection(FakeDaemon daemon) async { + daemon.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await pumpEventQueue(); +} + +/// How many GETs [daemon] received on a path ending in [suffix]. +int _gets(FakeDaemon daemon, String suffix) => + daemon.transport.calls.where((call) => call.method == 'GET' && call.path.endsWith(suffix)).length; + +/// What a screen's `when` (with its defaults) shows for [value]. +String _shown(AsyncValue value) => + value.when(data: (_) => 'data', error: (_, _) => 'error', loading: () => 'loading'); + +/// [_shown], with a refresh in flight marked. +String _phase(AsyncValue value) => '${_shown(value)}${value.isRefreshing ? ', refreshing' : ''}'; + +/// A daemon that answers every resource endpoint the tests read. +FakeDaemon _fullDaemon() { + final d = FakeDaemon(); + d.transport + ..onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)) + ..onGet(RegExp(r'/containers/(c1|c2|idle)/json$'), (_) => http.Response('{"Id":"c"}', 200)) + ..onGet(RegExp(r'/images/json$'), (_) => http.Response('[]', 200)) + ..onGet(RegExp(r'/images/i1/json$'), (_) => http.Response('{"Id":"i1"}', 200)) + ..onGet(RegExp(r'/images/i1/history$'), (_) => http.Response('[]', 200)) + ..onGet(RegExp(r'/networks$'), (_) => http.Response('[]', 200)) + ..onGet(RegExp(r'/networks/n1$'), (_) => http.Response('{"Id":"n1"}', 200)) + ..onGet(RegExp(r'/volumes$'), (_) => http.Response('{"Volumes":[]}', 200)) + ..onGet(RegExp(r'/volumes/v1$'), (_) => http.Response('{"Name":"v1"}', 200)) + ..onGet(RegExp(r'/info$'), (_) => http.Response('{}', 200)) + ..onGet(RegExp(r'/system/df$'), (_) => http.Response('{}', 200)); + return d; +} + +void main() { + test('a reconnect refreshes the list in place: the old data stays until the new arrives', () async { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + d1.transport.onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)); + d2.transport.hangOn('GET', RegExp(r'/containers/json')); + final c = _container([d1, d2]); + c.listen(containersProvider, (_, _) {}); + await c.read(sessionProvider.notifier).connect(_profileA); + await c.read(containersProvider.future); + + await _dropConnection(d1); + + expect(c.read(sessionProvider).transport, same(d2.transport)); + final v = c.read(containersProvider); + expect(v.isRefreshing, isTrue, reason: 'a refresh keeps the data on screen; the state is $v'); + expect(v.isReloading, isFalse); + expect(v.requireValue, hasLength(1)); + expect(_shown(v), 'data'); + expect(_gets(d2, '/containers/json'), 1); + }); + + test('every reconnect refreshes in place, not only the first', () async { + final daemons = [for (var i = 0; i < 4; i++) FakeDaemon()]; + for (final d in daemons) { + d.transport.onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)); + } + final c = _container(daemons); + final seen = []; + c.listen(containersProvider, (_, next) => seen.add(_phase(next))); + await c.read(sessionProvider.notifier).connect(_profileA); + await c.read(containersProvider.future); + seen.clear(); + + for (var i = 1; i < daemons.length; i++) { + await _dropConnection(daemons[i - 1]); + final why = 'reconnect $i'; + expect(c.read(sessionProvider).transport, same(daemons[i].transport), reason: why); + expect(_gets(daemons[i], '/containers/json'), 1, reason: why); + // The transport that was replaced is not asked again. + expect(_gets(daemons[i - 1], '/containers/json'), 1, reason: why); + expect(seen, ['data, refreshing', 'data'], reason: why); + seen.clear(); + } + }); + + test('a new connection reloads: nothing from the previous daemon is shown', () async { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + d1.transport.onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)); + d2.transport.hangOn('GET', RegExp(r'/containers/json')); + final c = _container([d1, d2]); + c.listen(containersProvider, (_, _) {}); + await c.read(sessionProvider.notifier).connect(_profileA); + await c.read(containersProvider.future); + expect(c.read(containersProvider).requireValue, hasLength(1)); + + await c.read(sessionProvider.notifier).connect(_profileB); + await pumpEventQueue(); + + expect(c.read(sessionProvider).transport, same(d2.transport)); + final v = c.read(containersProvider); + expect(v.isLoading, isTrue, reason: 'the new daemon has not answered yet; the state is $v'); + expect(v.isRefreshing, isFalse); + expect(_shown(v), 'loading'); + expect(_gets(d2, '/containers/json'), 1); + }); + + test('a provider nobody listens to reloads on its next read after a new connection', () async { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + d1.transport.onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)); + d2.transport.hangOn('GET', RegExp(r'/containers/json')); + final c = _container([d1, d2]); + final session = c.read(sessionProvider.notifier); + await session.connect(_profileA); + expect(await c.read(containersProvider.future), hasLength(1)); + + await session.disconnect(); + await session.connect(_profileB); + await pumpEventQueue(); + expect(c.read(sessionProvider).transport, same(d2.transport)); + // Nobody listens, so the new connection alone fetches nothing. + expect(_gets(d2, '/containers/json'), 0); + + final v = c.read(containersProvider); + expect(_shown(v), 'loading', reason: 'the state is $v'); + expect(_gets(d2, '/containers/json'), 1); + }); + + test('a refresh pending when the connection is lost never runs: the list stays up until the reconnect', () { + fakeAsync((async) { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + for (final d in [d1, d2]) { + d.transport.onGet(RegExp(r'/containers/json$'), (_) => http.Response(_oneContainer, 200)); + } + // The first retry comes well after the refresh debounce (0.5 s). + final c = _container([d1, d2], policy: ReconnectPolicy(base: const Duration(seconds: 5), jitter: 0)); + final seen = []; + c.listen(containersProvider, (_, next) => seen.add(_phase(next))); + c.read(sessionProvider.notifier).connect(_profileA); + async.elapse(Duration.zero); + expect(_shown(c.read(containersProvider)), 'data'); + seen.clear(); + + // A container dies and the daemon goes away right after it said so. + d1.transport.throwOn('GET', RegExp(r'/containers/json$'), const DockerError(DockerErrorKind.network, 'down')); + d1.events.add(utf8.encode(eventLine(action: 'die', timeNano: 1700000000000000123))); + async.flushMicrotasks(); + d1.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + async.flushMicrotasks(); + expect(c.read(sessionProvider).status, SessionStatus.reconnecting); + + async.elapse(const Duration(seconds: 3)); + expect(c.read(sessionProvider).status, SessionStatus.reconnecting); + expect(seen, isEmpty, reason: 'nothing may be asked of the dead connection'); + expect(_shown(c.read(containersProvider)), 'data'); + expect(_gets(d1, '/containers/json'), 1); + + async.elapse(const Duration(seconds: 3)); + expect(c.read(sessionProvider).transport, same(d2.transport)); + expect(seen, ['data, refreshing', 'data']); + expect(_gets(d2, '/containers/json'), 1); + expect(_gets(d1, '/containers/json'), 1); + }); + }); + + test('a reconnect refreshes every resource provider that is listened to and builds none that is not', () async { + final d1 = _fullDaemon(), d2 = _fullDaemon(); + final c = _container([d1, d2]); + // Every resource provider, with an endpoint only it reads. + final listened = , String>{ + containersProvider: '/containers/json', + containerDetailProvider('c1'): '/containers/c1/json', + containerInspectProvider('c2'): '/containers/c2/json', + imagesProvider: '/images/json', + imageDetailProvider('i1'): '/images/i1/json', + imageHistoryProvider('i1'): '/images/i1/history', + networksProvider: '/networks', + networkDetailProvider('n1'): '/networks/n1', + volumesProvider: '/volumes', + volumeDetailProvider('v1'): '/volumes/v1', + systemDashboardProvider: '/info', + }; + final seen = {for (final endpoint in listened.values) endpoint: []}; + listened.forEach((provider, endpoint) { + c.listen(provider, (_, next) => seen[endpoint]!.add(_phase(next as AsyncValue))); + }); + await c.read(sessionProvider.notifier).connect(_profileA); + // Read once and then left alone: nothing listens to it. + await c.read(containerDetailProvider('idle').future); + await pumpEventQueue(); + for (final endpoint in listened.values) { + expect(_gets(d1, endpoint), 1, reason: 'the first load of $endpoint'); + expect(seen[endpoint]!.last, 'data', reason: 'the first load of $endpoint'); + seen[endpoint]!.clear(); + } + + await _dropConnection(d1); + + expect(c.read(sessionProvider).transport, same(d2.transport)); + for (final endpoint in listened.values) { + expect(_gets(d2, endpoint), 1, reason: 'the refetch of $endpoint'); + expect(seen[endpoint], ['data, refreshing', 'data'], reason: 'what $endpoint shows meanwhile'); + } + // The dashboard's other two calls (the session's probe asks for /version too). + expect(_gets(d2, '/system/df'), 1); + expect(_gets(d2, '/version'), 2); + // Nothing is fetched for a provider that nobody listens to, seen before or not. + expect(_gets(d2, '/containers/idle/json'), 0); + expect(c.exists(containerDetailProvider('never-seen')), isFalse); + }); +} diff --git a/app/test/state/session_refresh_test.dart b/app/test/state/session_refresh_test.dart new file mode 100644 index 0000000..846daff --- /dev/null +++ b/app/test/state/session_refresh_test.dart @@ -0,0 +1,50 @@ +import 'dart:async'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; + +import '../support/fake_session.dart'; + +void main() { + test('a container event refreshes the list through the real session without errors', () { + fakeAsync((async) { + final errors = []; + final d = FakeDaemon(); + d.transport.onGet(RegExp(r'/containers/json'), (_) => http.Response('[]', 200)); + late ProviderContainer c; + int listCalls() => d.transport.calls.where((call) => call.path.endsWith('/containers/json')).length; + + // The session, its events stream and its refresh timers all start in + // this zone: whatever one of them throws with nobody waiting for it + // lands in [errors]. + runZonedGuarded(() { + c = ProviderContainer(overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([d.transport])), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + profileStoreProvider.overrideWithValue(InMemoryProfileStore()), + ]); + c.listen(containersProvider, (_, _) {}); + c.read(sessionProvider.notifier).connect(const ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://h:1', token: 't'))); + }, (e, _) => errors.add(e)); + addTearDown(() => c.dispose()); + async.elapse(Duration.zero); + expect(c.read(containersProvider).hasValue, isTrue); + expect(listCalls(), 1); + + d.events.add(eventLine(type: 'container', id: 'never-seen').codeUnits); + async.elapse(const Duration(milliseconds: 600)); // past the 500 ms debounce + expect(errors, isEmpty); + expect(listCalls(), 2); + expect(c.read(containersProvider).isLoading, isFalse); // the refetch is back, + expect(c.read(containersProvider).hasError, isFalse); // with a list + expect(c.exists(containerDetailProvider('never-seen')), isFalse); + expect(d.transport.calls.where((call) => call.path.contains('/containers/never-seen/json')), isEmpty); + }); + }); +} diff --git a/app/test/state/stats_notifier_test.dart b/app/test/state/stats_notifier_test.dart index 0111603..c0b4c48 100644 --- a/app/test/state/stats_notifier_test.dart +++ b/app/test/state/stats_notifier_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:docker_mobile/src/api/docker_api_client.dart'; @@ -15,7 +16,7 @@ void main() { final lines = '${[for (var i = 0; i < kStatsWindow + 5; i++) _line((i + 1) * 1000000)].join('\n')}\n'; final client = DockerApiClient( FakeTransport()..onStream('/containers/a/stats', (_) => Stream.value(utf8.encode(lines)))); - final n = StatsNotifier(client, 'a'); + final n = StatsNotifier(() => client, 'a'); await pumpEventQueue(); expect(n.state.status, StatsStatus.streaming); expect(n.state.latest, isNotNull); @@ -26,11 +27,116 @@ void main() { test('a stream error sets error status', () async { final client = DockerApiClient( - FakeTransport()..onStream('/containers/a/stats', (_) => Stream.error(Exception('boom')))); - final n = StatsNotifier(client, 'a'); + FakeTransport()..onStream('/containers/a/stats', (_) => Stream.error(DockerError.fromResponse(404, '{"message":"boom"}')))); + final n = StatsNotifier(() => client, 'a'); await pumpEventQueue(); expect(n.state.status, StatsStatus.error); - expect(n.state.error, contains('boom')); + expect(n.state.error!.message, 'boom'); + n.dispose(); + }); + + test('setLive(false) shows reconnecting; setLive(true) reopens the stream', () async { + final t = FakeTransport()..onStream('/containers/a/stats', (_) => StreamController>().stream); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + await pumpEventQueue(); + n.setLive(false); + expect(n.state.status, StatsStatus.reconnecting); + n.setLive(true); + await pumpEventQueue(); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(2)); + n.dispose(); + }); + + test('a retry that opens before any sample shows loading and clears the error', () async { + var opens = 0; + final t = FakeTransport() + ..onStream('/containers/a/stats', (_) { + opens++; + if (opens == 1) return Stream.error(DockerError.fromResponse(404, '{"message":"boom"}')); + return StreamController>().stream; // open, no sample yet + }); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + await pumpEventQueue(); + expect(n.state.status, StatsStatus.error); + + n.retry(); + await pumpEventQueue(); + expect(n.state.status, StatsStatus.loading); + expect(n.state.error, isNull); + n.dispose(); + }); + + test('the session coming back reopens a stream that had ended', () async { + final t = FakeTransport() + ..onStream('/containers/a/stats', (_) => Stream.value(utf8.encode('${_line(1000000)}\n'))); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + await pumpEventQueue(); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(1)); + + n.setLive(false); + n.setLive(true); + await pumpEventQueue(); + + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(2)); + expect(n.state.cpuHistory, hasLength(1)); // kept; the reopened stream's first sample is dropped + n.dispose(); + }); + + test('the session coming back reopens a stream that had failed', () async { + final t = FakeTransport() + ..onStream('/containers/a/stats', (_) => Stream.error(DockerError.fromResponse(404, '{"message":"boom"}'))); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + await pumpEventQueue(); + expect(n.state.status, StatsStatus.error); + + n.setLive(false); + n.setLive(true); + await pumpEventQueue(); + + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(2)); + n.dispose(); + }); + + test('retry is ignored while the session is away', () async { + final t = FakeTransport()..onStream('/containers/a/stats', (_) => StreamController>().stream); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + await pumpEventQueue(); + + n.setLive(false); + n.retry(); + await pumpEventQueue(); + expect(t.calls.where((c) => c.method == 'STREAM'), hasLength(1)); + expect(n.state.status, StatsStatus.reconnecting); + n.dispose(); + }); + + test('a reopened stream drops its first sample and appends the next', () async { + final controllers = >>[]; + final t = FakeTransport() + ..onStream('/containers/a/stats', (_) { + final c = StreamController>(); + controllers.add(c); + return c.stream; + }); + final n = StatsNotifier(() => DockerApiClient(t), 'a'); + controllers.last.add(utf8.encode('${_line(1000000)}\n')); + await pumpEventQueue(); + expect(n.state.cpuHistory, hasLength(1)); + final shown = n.state.latest; + + n.setLive(false); + n.setLive(true); + controllers.last.add(utf8.encode('${_line(2000000)}\n')); // no previous CPU reading behind it + await pumpEventQueue(); + expect(n.state.cpuHistory, hasLength(1)); + expect(n.state.memHistory, hasLength(1)); + expect(n.state.latest, same(shown)); + + controllers.last.add(utf8.encode('${_line(3000000)}\n')); + await pumpEventQueue(); + expect(n.state.cpuHistory, hasLength(2)); + expect(n.state.memHistory, hasLength(2)); + expect(n.state.latest, isNot(same(shown))); n.dispose(); }); } diff --git a/app/test/state/stream_reconnect_test.dart b/app/test/state/stream_reconnect_test.dart new file mode 100644 index 0000000..1c70567 --- /dev/null +++ b/app/test/state/stream_reconnect_test.dart @@ -0,0 +1,152 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/widgets.dart' show AppLifecycleState; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/api/timestamps.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/state/logs_notifier.dart'; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/state/stats_notifier.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; + +import '../support/fake_session.dart'; + +const _profileA = ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://a:1', token: 't')); +const _profileB = ConnectionProfile( + id: '2', name: 'B', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://b:1', token: 't')); + +/// The logs of container `a`: a TTY, so log bytes are sent unframed. +const _logs = (id: 'a', tty: true); + +/// A container over the real session. The session takes [transports] in +/// order: the first on connect, the next on every reconnect or new +/// connection. A future of a transport holds that connection open until it +/// completes. The test moves the app to the background and back through +/// [lifecycle]. +ProviderContainer _container(List transports, {ManualLifecycleSource? lifecycle}) { + final c = ProviderContainer(overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory(transports)), + reconnectPolicyProvider.overrideWithValue(immediatePolicy()), + lifecycleSourceProvider.overrideWithValue(lifecycle ?? ManualLifecycleSource()), + profileStoreProvider.overrideWithValue(InMemoryProfileStore()), + ]); + addTearDown(c.dispose); + return c; +} + +void main() { + test('after every reconnect logs and stats reopen once, on the new transport, from the cursor', () async { + final daemons = [for (var i = 0; i < 4; i++) FakeContainerDaemon()]; + final c = _container([for (final d in daemons) d.transport]); + await c.read(sessionProvider.notifier).connect(_profileA); + c.listen(logsProvider(_logs), (_, _) {}); + c.listen(statsProvider('a'), (_, _) {}); + await pumpEventQueue(); + expect(daemons.first.logOpens, hasLength(1)); + expect(daemons.first.statsOpens, hasLength(1)); + + daemons.first.logs.add(utf8.encode('$firstLogStamp first\n')); + await pumpEventQueue(); + expect(c.read(logsProvider(_logs)).lines.single.text, 'first'); + + for (var i = 1; i < daemons.length; i++) { + final old = daemons[i - 1], current = daemons[i]; + old.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await pumpEventQueue(); + + final why = 'reconnect $i'; + expect(c.read(sessionProvider).transport, same(current.transport), reason: why); + expect(current.logOpens, hasLength(1), reason: why); + expect(current.statsOpens, hasLength(1), reason: why); + expect(current.logOpens.single.query!['since'], rfc3339ToUnixNanos(firstLogStamp), reason: why); + // The transport that was replaced is not used again. + expect(old.logOpens, hasLength(1), reason: why); + expect(old.statsOpens, hasLength(1), reason: why); + } + + daemons.last.logs.add(utf8.encode('$secondLogStamp second\n')); + await pumpEventQueue(); + expect(c.read(logsProvider(_logs)).lines.map((l) => l.text), ['first', 'second']); + }); + + test('a new connection gives a fresh stream on the new transport', () async { + final d1 = FakeContainerDaemon(), d2 = FakeContainerDaemon(); + final handshake = Completer(); // keeps the second connection in `connecting` + final c = _container([d1.transport, handshake.future]); + final session = c.read(sessionProvider.notifier); + await session.connect(_profileA); + c.listen(logsProvider(_logs), (_, _) {}); + c.listen(statsProvider('a'), (_, _) {}); + await pumpEventQueue(); + d1.logs.add(utf8.encode('$firstLogStamp first\n')); + await pumpEventQueue(); + expect(c.read(logsProvider(_logs)).lines.single.text, 'first'); + + final connected = session.connect(_profileB); + await pumpEventQueue(); // the stream providers rebuild while there is no client yet + expect(c.read(sessionProvider).status, SessionStatus.connecting); + handshake.complete(d2.transport); + await connected; + await pumpEventQueue(); + + expect(c.read(sessionProvider).transport, same(d2.transport)); + expect(d2.logOpens, hasLength(1)); + expect(d2.logOpens.single.query!.containsKey('since'), isFalse); + expect(d2.statsOpens, hasLength(1)); + // Nothing of the first daemon is left, and the new streams are running. + expect(c.read(logsProvider(_logs)).lines, isEmpty); + expect(c.read(logsProvider(_logs)).status, LogsStatus.streaming); + expect(c.read(statsProvider('a')).status, StatsStatus.loading); + }); + + test('a new connection while the logs are paused starts over without an error', () async { + final d1 = FakeContainerDaemon(), d2 = FakeContainerDaemon(); + final c = _container([d1.transport, d2.transport]); + final session = c.read(sessionProvider.notifier); + await session.connect(_profileA); + c.listen(logsProvider(_logs), (_, _) {}); + await pumpEventQueue(); + c.read(logsProvider(_logs).notifier).setFollowing(false); + + // The provider is rebuilt for the new connection, yet its old session + // listener still hears this update, after the notifier was disposed. An + // error thrown there is uncaught and fails the test. + await session.connect(_profileB); + await pumpEventQueue(); + + expect(d2.logOpens, hasLength(1)); + expect(c.read(logsProvider(_logs)).following, isTrue); + expect(c.read(logsProvider(_logs)).status, LogsStatus.streaming); + }); + + test('the background cancels the logs stream; the foreground reopens it once, from the cursor', () async { + final d = FakeContainerDaemon(); + final lifecycle = ManualLifecycleSource(); + final c = _container([d.transport], lifecycle: lifecycle); + await c.read(sessionProvider.notifier).connect(_profileA); + c.listen(logsProvider(_logs), (_, _) {}); + await pumpEventQueue(); + d.logs.add(utf8.encode('$firstLogStamp first\n')); + await pumpEventQueue(); + final before = d.logs; + expect(before.hasListener, isTrue); + + lifecycle.emit(AppLifecycleState.paused); + await pumpEventQueue(); + expect(before.hasListener, isFalse); + expect(d.logOpens, hasLength(1)); + + lifecycle.emit(AppLifecycleState.resumed); + await pumpEventQueue(); + expect(d.logOpens, hasLength(2)); + expect(d.logOpens.last.query!['since'], rfc3339ToUnixNanos(firstLogStamp)); + expect(d.logs.hasListener, isTrue); + expect(c.read(logsProvider(_logs)).lines.single.text, 'first'); + }); +} diff --git a/app/test/state/stream_supervisor_test.dart b/app/test/state/stream_supervisor_test.dart new file mode 100644 index 0000000..892052e --- /dev/null +++ b/app/test/state/stream_supervisor_test.dart @@ -0,0 +1,301 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; +import 'package:docker_mobile/src/state/stream_supervisor.dart'; + +const _net = DockerError(DockerErrorKind.network, 'down'); + +class _Opens { + final controllers = >[]; + int cancelled = 0; + Object? throwNext; + + Stream open() { + final t = throwNext; + if (t != null) { + throwNext = null; + throw t; + } + final c = StreamController(onCancel: () => cancelled++); + controllers.add(c); + return c.stream; + } +} + +class _Harness { + final opens = _Opens(); + final data = []; + final statuses = <(SupervisorStatus, DockerError?)>[]; + late final StreamSupervisor sup; + + _Harness({bool retryOnDone = false, int maxAttempts = 5}) { + sup = StreamSupervisor( + open: opens.open, + onData: data.add, + onStatus: (s, e) => statuses.add((s, e)), + policy: ReconnectPolicy(jitter: 0, maxAttempts: maxAttempts), + retryOnDone: retryOnDone, + ); + } + + SupervisorStatus get last => statuses.last.$1; +} + +void main() { + test('forwards data while streaming', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.add(1); + async.flushMicrotasks(); + expect(h.data, [1]); + expect(h.last, SupervisorStatus.streaming); + }); + }); + + test('a retryable error reopens after the backoff delay', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.retrying); + expect(h.statuses.last.$2, same(_net)); + async.elapse(const Duration(milliseconds: 999)); + expect(h.opens.controllers, hasLength(1)); + async.elapse(const Duration(milliseconds: 2)); + expect(h.opens.controllers, hasLength(2)); + expect(h.last, SupervisorStatus.streaming); + }); + }); + + test('gives up after maxAttempts retries', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + for (var i = 1; i <= 5; i++) { + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.retrying); + async.elapse(Duration(seconds: 1 << (i - 1))); + } + expect(h.opens.controllers, hasLength(6)); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.failed); + expect(h.statuses.last.$2, same(_net)); + async.elapse(const Duration(minutes: 5)); + expect(h.opens.controllers, hasLength(6)); + }); + }); + + test('a non-retryable error fails at once', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(DockerError.fromResponse(404, '{"message":"No such container"}')); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.failed); + expect(h.statuses.last.$2!.message, 'No such container'); + async.elapse(const Duration(minutes: 1)); + expect(h.opens.controllers, hasLength(1)); + }); + }); + + test('data resets the attempt count', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + h.opens.controllers.last.add(7); + async.flushMicrotasks(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); // 1 s again, not 2 s + expect(h.opens.controllers, hasLength(3)); + }); + }); + + test('pause cancels the stream and resume reopens with a fresh open()', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + async.flushMicrotasks(); + h.sup.pause(); + async.flushMicrotasks(); + expect(h.opens.cancelled, 1); + expect(h.last, SupervisorStatus.paused); + h.sup.resume(); + expect(h.opens.controllers, hasLength(2)); + expect(h.last, SupervisorStatus.streaming); + }); + }); + + test('pause while retrying cancels the timer; resume reopens at once', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + h.sup.pause(); + async.elapse(const Duration(seconds: 10)); + expect(h.opens.controllers, hasLength(1)); + h.sup.resume(); + expect(h.opens.controllers, hasLength(2)); + }); + }); + + test('pause and resume do nothing once failed or done', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.close(); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.done); + h.sup.pause(); + h.sup.resume(); + expect(h.last, SupervisorStatus.done); + expect(h.opens.controllers, hasLength(1)); + }); + }); + + test('done stays done', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.close(); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.done); + async.elapse(const Duration(minutes: 1)); + expect(h.opens.controllers, hasLength(1)); + }); + }); + + test('retryOnDone treats a clean end as a retryable loss', () { + fakeAsync((async) { + final h = _Harness(retryOnDone: true)..sup.start(); + h.opens.controllers.last.close(); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.retrying); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(2)); + }); + }); + + test('retry() reopens from failed with a fresh attempt count', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(DockerError.fromResponse(404, '')); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.failed); + h.sup.retry(); + expect(h.opens.controllers, hasLength(2)); + expect(h.last, SupervisorStatus.streaming); + }); + }); + + test('a synchronous throw from open() is handled like a stream error', () { + fakeAsync((async) { + final h = _Harness(); + h.opens.throwNext = const SocketException('refused'); + h.sup.start(); + expect(h.last, SupervisorStatus.retrying); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(1)); + expect(h.last, SupervisorStatus.streaming); + }); + }); + + test('dispose cancels the stream and any pending retry and goes quiet', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + final count = h.statuses.length; + h.sup.dispose(); + expect(async.pendingTimers, isEmpty); + async.elapse(const Duration(minutes: 1)); + expect(h.statuses.length, count); + expect(h.opens.controllers, hasLength(1)); + }); + }); + + test('a stream open for the policy cap without error counts as recovered', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(2)); + async.elapse(const Duration(seconds: 30)); // quiet, no data + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + expect(h.last, SupervisorStatus.retrying); + async.elapse(const Duration(seconds: 1)); // 1 s again, not 2 s + expect(h.opens.controllers, hasLength(3)); + }); + }); + + test('an error within the policy cap keeps backing off', () { + fakeAsync((async) { + final h = _Harness()..sup.start(); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(2)); + async.elapse(const Duration(seconds: 29)); + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(2)); // 2 s now, not 1 s + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(3)); + // The errored stream's stability timer must not reset the count while + // the retry was pending: the next delay is 4 s. + h.opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 3)); + expect(h.opens.controllers, hasLength(3)); + async.elapse(const Duration(seconds: 1)); + expect(h.opens.controllers, hasLength(4)); + }); + }); + + test('pause from onStatus(retrying) stops the retry timer', () { + fakeAsync((async) { + final opens = _Opens(); + late final StreamSupervisor sup; + sup = StreamSupervisor( + open: opens.open, + onData: (_) {}, + onStatus: (s, e) { + if (s == SupervisorStatus.retrying) sup.pause(); + }, + policy: ReconnectPolicy(jitter: 0), + ); + sup.start(); + opens.controllers.last.addError(_net); + async.flushMicrotasks(); + async.elapse(const Duration(seconds: 10)); + expect(opens.controllers, hasLength(1)); + expect(sup.status, SupervisorStatus.paused); + }); + }); + + test('dispose from onStatus(streaming) never listens to the opened stream', () { + fakeAsync((async) { + final opens = _Opens(); + late final StreamSupervisor sup; + sup = StreamSupervisor( + open: opens.open, + onData: (_) {}, + onStatus: (s, e) { + if (s == SupervisorStatus.streaming) sup.dispose(); + }, + policy: ReconnectPolicy(jitter: 0), + ); + sup.start(); + async.flushMicrotasks(); + expect(opens.controllers, hasLength(1)); + expect(opens.controllers.last.hasListener, isFalse); + expect(async.pendingTimers, isEmpty); + }); + }); +} diff --git a/app/test/support/fake_session.dart b/app/test/support/fake_session.dart new file mode 100644 index 0000000..b3a9923 --- /dev/null +++ b/app/test/support/fake_session.dart @@ -0,0 +1,159 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/widgets.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/session/events_hub.dart'; +import 'package:docker_mobile/src/session/lifecycle_source.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; +import 'package:docker_mobile/src/session/transport_factory.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/transport/ssh/ssh_connection.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; + +import 'fake_transport.dart'; + +/// A lifecycle source the test drives; delivery is synchronous. +class ManualLifecycleSource implements LifecycleSource { + final _controller = StreamController.broadcast(sync: true); + + @override + Stream get changes => _controller.stream; + + void emit(AppLifecycleState state) => _controller.add(state); +} + +/// A policy with zero delays, for tests that do not care about timing. +ReconnectPolicy immediatePolicy({int maxAttempts = 5}) => + ReconnectPolicy(base: Duration.zero, cap: Duration.zero, jitter: 0, maxAttempts: maxAttempts); + +/// An SSH connection that presents [fingerprint] and fails with +/// [connectError] (after the host-key check) when set. +class FakeSshConnection implements SshConnection { + final String fingerprint; + final Object? connectError; + bool closed = false; + FakeSshConnection(this.fingerprint, {this.connectError}); + + @override + Future connect({required HostKeyVerifier verifyHostKey}) async { + if (!verifyHostKey(fingerprint)) throw Exception('host key rejected'); + final e = connectError; + if (e != null) throw e; + } + + @override + Future openChannel() async => Duplex(input: const Stream.empty(), add: (_) {}, close: () async {}); + + @override + Future close() async => closed = true; +} + +/// Hands out queued results in order. A result is a [Transport], a +/// [BuiltTransport], a Future of either, or anything else to throw. +class FakeTransportFactory implements TransportFactory { + FakeTransportFactory(List results) : _results = List.of(results); + final List _results; + final pinOverrides = []; + final profiles = []; + int builds = 0; + + void enqueue(Object result) => _results.add(result); + + @override + Future build(ConnectionProfile profile, {String? pinOverride}) async { + builds++; + pinOverrides.add(pinOverride); + profiles.add(profile); + if (_results.isEmpty) throw StateError('FakeTransportFactory: no result queued for build #$builds'); + final r = _results.removeAt(0); + final Object? v = r is Future ? await r : r; + if (v == null) throw StateError('FakeTransportFactory: queued result completed with null'); + if (v is BuiltTransport) return v; + if (v is Transport) return BuiltTransport(v); + throw v; + } +} + +/// A daemon behind a [FakeTransport]: answers /_ping and /version, and opens +/// a fresh controllable events stream on every subscription. +class FakeDaemon { + FakeDaemon({String apiVersion = '1.46', int pingStatus = 200}) { + transport + ..onGet('/_ping', (_) => http.Response(pingStatus == 200 ? 'OK' : '{"message":"ping failed"}', pingStatus)) + ..onGet('/version', (_) => http.Response(jsonEncode({'Version': '27.0', 'ApiVersion': apiVersion}), 200)) + ..onStream(RegExp(r'/events$'), (_) { + final c = StreamController>( + onListen: () => activeEventStreams++, + onCancel: () => activeEventStreams--, + ); + eventStreams.add(c); + return c.stream; + }); + } + + final transport = FakeTransport(); + final eventStreams = >>[]; + int activeEventStreams = 0; + + /// The most recently opened events stream. + StreamController> get events => eventStreams.last; + + List get eventOpens => + transport.calls.where((c) => c.method == 'STREAM' && c.path.endsWith('/events')).toList(); +} + +/// A [FakeDaemon] that also has container `a`, a TTY (so its log bytes are +/// sent unframed): the inspect answers, and every logs or stats open gets a +/// stream that stays open. The test writes log bytes to [logs]. +class FakeContainerDaemon extends FakeDaemon { + FakeContainerDaemon() { + transport + ..onGet(RegExp(r'/containers/a/json$'), (_) => http.Response( + '{"Id":"a","Name":"/web","Config":{"Image":"nginx","Tty":true},"State":{"Status":"running"}}', + 200, + )) + ..onStream(RegExp(r'/containers/a/logs$'), (_) => (logs = StreamController>()).stream) + ..onStream(RegExp(r'/containers/a/stats$'), (_) => StreamController>().stream); + } + + /// The most recently opened logs stream. + late StreamController> logs; + + List get logOpens => _opens('logs'); + + List get statsOpens => _opens('stats'); + + List _opens(String stream) => + transport.calls.where((c) => c.method == 'STREAM' && c.path.endsWith('/containers/a/$stream')).toList(); +} + +/// Two log timestamps one nanosecond apart, in the daemon's format. +const firstLogStamp = '2026-01-02T03:04:05.000000001Z'; +const secondLogStamp = '2026-01-02T03:04:05.000000002Z'; + +/// One NDJSON line of a Docker event. +String eventLine({String type = 'container', String action = 'start', String id = 'c1', int? timeNano}) => + '${jsonEncode({ + 'Type': type, + 'Action': action, + 'Actor': {'ID': id, 'Attributes': {'name': 'web'}}, + 'timeNano': ?timeNano, + })}\n'; + +/// Records invalidations as strings: `list:`, `detail::`, `dashboard`, `all`. +class RecordingInvalidator implements Invalidator { + final calls = []; + + @override + void list(EventCategory category) => calls.add('list:${category.name}'); + + @override + void detail(EventCategory category, String id) => calls.add('detail:${category.name}:$id'); + + @override + void dashboard() => calls.add('dashboard'); + + @override + void all() => calls.add('all'); +} diff --git a/app/test/support/held_transport.dart b/app/test/support/held_transport.dart new file mode 100644 index 0000000..9c2345c --- /dev/null +++ b/app/test/support/held_transport.dart @@ -0,0 +1,52 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; + +import 'fake_transport.dart'; + +/// A [FakeTransport] whose POST and DELETE calls wait for [release] before +/// they answer, so a test can act while a request is in flight. GETs and +/// streams answer at once. +class HeldTransport extends FakeTransport { + final _gate = Completer(); + + /// Lets the held calls, and every later one, answer. + void release() { + if (!_gate.isCompleted) _gate.complete(); + } + + @override + Future post(String path, + {Map? query, Object? body, Map? headers}) async { + await _gate.future; + return super.post(path, query: query, body: body, headers: headers); + } + + @override + Future delete(String path, {Map? query}) async { + await _gate.future; + return super.delete(path, query: query); + } +} + +/// Pumps an app on [transport] whose first route reads 'first' and pushes +/// [screen] over it. Returns the navigator. +Future pumpOverFirstRoute(WidgetTester tester, Transport transport, Widget screen) async { + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => transport)], + child: const MaterialApp(home: Scaffold(body: Text('first'))), + )); + final navigator = tester.state(find.byType(Navigator)); + navigator.push(MaterialPageRoute(builder: (_) => screen)); + await tester.pumpAndSettle(); + return navigator; +} + +/// What the session banner's Disconnect does to the routes: back to the first one. +void popToFirstRoute(WidgetTester tester) => + tester.state(find.byType(Navigator)).popUntil((r) => r.isFirst); diff --git a/app/test/support/stub_session.dart b/app/test/support/stub_session.dart new file mode 100644 index 0000000..c042f83 --- /dev/null +++ b/app/test/support/stub_session.dart @@ -0,0 +1,45 @@ +import 'package:docker_mobile/src/session/docker_session.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; + +import 'fake_session.dart'; + +/// A session whose state the test sets directly; actions are only counted. +class StubSession extends DockerSession { + StubSession(SessionState initial) + : super( + transportFactory: FakeTransportFactory(const []), + policy: immediatePolicy(), + lifecycle: ManualLifecycleSource(), + invalidator: RecordingInvalidator(), + profileStore: InMemoryProfileStore(), + ) { + state = initial; + } + + int retries = 0; + int disconnects = 0; + int acknowledged = 0; + final connects = []; + + void setState(SessionState s) => state = s; + + @override + void retry() => retries++; + + @override + Future disconnect() async => disconnects++; + + @override + void acknowledgeWarning() { + acknowledged++; + state = state.copyWith(clearWarning: true); + } + + /// Only records the profile; a stub never connects. + @override + Future connect(ConnectionProfile profile, {String? pinOverride}) async { + connects.add(profile); + return false; + } +} diff --git a/app/test/transport/agent_transport_stream_test.dart b/app/test/transport/agent_transport_stream_test.dart index 0aba2c6..e3d6313 100644 --- a/app/test/transport/agent_transport_stream_test.dart +++ b/app/test/transport/agent_transport_stream_test.dart @@ -28,6 +28,21 @@ class _SpyClient extends http.BaseClient { } } +class _CountingClient extends http.BaseClient { + final Stream> body; + final void Function() onClose; + _CountingClient(this.body, this.onClose); + + @override + Future send(http.BaseRequest request) async => http.StreamedResponse(body, 200); + + @override + void close() { + onClose(); + super.close(); + } +} + class _HangingClient extends http.BaseClient { @override Future send(http.BaseRequest request) => Completer().future; @@ -153,4 +168,32 @@ void main() { emitsError(isA().having((e) => e.kind, 'kind', DockerErrorKind.network)), ); }); + + test('close() also closes the clients of streams that are still open', () async { + final spy = _SpyClient(StreamController>().stream); + final t = AgentTransport( + baseUri: Uri.parse('http://10.0.0.5:8080'), + token: 'secret', + streamClientFactory: () => spy, + ); + final sub = t.stream('/events').listen((_) {}, onError: (_) {}); + await pumpEventQueue(); + expect(spy.closed, isFalse); + await t.close(); + expect(spy.closed, isTrue); + await sub.cancel(); + }); + + test('a stream that ended normally is not closed twice by close()', () async { + var closes = 0; + final spy = _CountingClient(Stream.value([1]), () => closes++); + final t = AgentTransport( + baseUri: Uri.parse('http://10.0.0.5:8080'), + token: 'secret', + streamClientFactory: () => spy, + ); + await t.stream('/x').toList(); + await t.close(); + expect(closes, 1); + }); } diff --git a/app/test/transport/ssh/ssh_transport_test.dart b/app/test/transport/ssh/ssh_transport_test.dart index 880322f..a456819 100644 --- a/app/test/transport/ssh/ssh_transport_test.dart +++ b/app/test/transport/ssh/ssh_transport_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'package:dartssh2/dartssh2.dart' show SSHStateError; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:docker_mobile/src/api/docker_error.dart'; @@ -110,6 +111,23 @@ void main() { }); }); + test('a stream that gets no headers reports a daemon timeout, in the words of the other transports', () { + fakeAsync((async) { + final conn = Duplex(input: StreamController>().stream, add: (_) {}, close: () async {}); + final t = SshTransport(openDuplex: () async => conn, headerTimeout: const Duration(seconds: 5)); + Object? err; + t.stream('/x').listen((_) {}, onError: (Object e) => err = e); + async.elapse(const Duration(seconds: 6)); + // The SSH connection is up and the request went out: it is the daemon that did not answer. + expect( + err, + isA() + .having((e) => e.kind, 'kind', DockerErrorKind.timeout) + .having((e) => e.message, 'message', 'Timed out waiting for the daemon'), + ); + }); + }); + test('stream times out when the channel never opens', () { fakeAsync((async) { final t = SshTransport(openDuplex: () => Completer().future, headerTimeout: const Duration(seconds: 5)); @@ -234,4 +252,20 @@ void main() { expect(closed, isTrue); }); }); + + test('a dropped SSH connection surfaces as DockerError.network on buffered calls', () async { + final t = SshTransport(openDuplex: () async => throw SSHStateError('Connection closed while waiting for channel open')); + await expectLater( + t.get('/x'), + throwsA(isA().having((e) => e.kind, 'kind', DockerErrorKind.network)), + ); + }); + + test('a dropped SSH connection surfaces as DockerError.network on streams', () async { + final t = SshTransport(openDuplex: () async => throw SSHStateError('Connection closed while waiting for channel open')); + await expectLater( + t.stream('/events'), + emitsError(isA().having((e) => e.kind, 'kind', DockerErrorKind.network)), + ); + }); } diff --git a/app/test/transport/tls_transport_test.dart b/app/test/transport/tls_transport_test.dart index fec9809..623a56f 100644 --- a/app/test/transport/tls_transport_test.dart +++ b/app/test/transport/tls_transport_test.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; +import 'package:http/io_client.dart'; import 'package:docker_mobile/src/api/docker_error.dart'; import 'package:docker_mobile/src/transport/timeouts.dart'; import 'package:docker_mobile/src/transport/tls_transport.dart'; @@ -48,6 +49,54 @@ class _StreamingClient extends http.BaseClient { http.StreamedResponse(body, 200, request: request); } +/// A local server for one request over a real socket. It answers, with the +/// headers of a response that never ends, only when the test calls [answer]. +class _HeldServer { + _HeldServer._(this._server); + + final ServerSocket _server; + Socket? _socket; + final _requested = Completer(); + final _released = Completer(); + + static Future<_HeldServer> start() async { + final held = _HeldServer._(await ServerSocket.bind(InternetAddress.loopbackIPv4, 0)); + held._server.listen(held._serve); + return held; + } + + void _serve(Socket socket) { + _socket = socket; + void gone([Object? _]) { + if (!_released.isCompleted) _released.complete(); + } + + socket.listen((_) { + if (!_requested.isCompleted) _requested.complete(); + }, onDone: gone, onError: gone); + // A write to a connection the client has reset fails here. + socket.done.then(gone, onError: gone); + } + + Uri get uri => Uri.parse('http://${_server.address.host}:${_server.port}'); + + /// Completes once the request has arrived. + Future get requested => _requested.future; + + /// Sends the response headers and the first chunk of the endless body. + void answer() => + _socket!.add(ascii.encode('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n')); + + /// Whether the client closes the connection within [limit]. + Future releasedWithin(Duration limit) => + _released.future.then((_) => true).timeout(limit, onTimeout: () => false); + + Future close() async { + _socket?.destroy(); + await _server.close(); + } +} + void main() { final base = Uri.parse('https://10.0.0.5:2376'); @@ -191,4 +240,43 @@ void main() { expect(err, isA().having((e) => e.kind, 'kind', DockerErrorKind.timeout)); }); }); + + group('over a real connection', () { + late _HeldServer server; + late TlsTransport t; + + /// A transport to a fresh [_HeldServer]; both are closed after the test. + Future connect({Duration streamHeaderTimeout = kStreamHeaderTimeout}) async { + server = await _HeldServer.start(); + t = TlsTransport(baseUri: server.uri, client: IOClient(), streamHeaderTimeout: streamHeaderTimeout); + addTearDown(() async { + await t.close(); + await server.close(); + }); + } + + test('a stream cancelled before its headers arrive lets go of the connection', () async { + await connect(); + final sub = t.stream('/containers/x/logs').listen((_) {}); + await server.requested; // the request is out, its response headers are not + await sub.cancel(); + server.answer(); + + expect(await server.releasedWithin(const Duration(seconds: 3)), isTrue, + reason: 'a response nobody reads must not keep its connection'); + }); + + test('headers that arrive after the header timeout let go of the connection', () async { + await connect(streamHeaderTimeout: const Duration(milliseconds: 200)); + await expectLater( + t.stream('/containers/x/logs'), + emitsError(isA().having((e) => e.kind, 'kind', DockerErrorKind.timeout)), + ); + await server.requested; + server.answer(); // too late: the stream has already failed + + expect(await server.releasedWithin(const Duration(seconds: 3)), isTrue, + reason: 'a response nobody reads must not keep its connection'); + }); + }); } diff --git a/app/test/ui/connection_screen_test.dart b/app/test/ui/connection_screen_test.dart index 21123a4..b4866a7 100644 --- a/app/test/ui/connection_screen_test.dart +++ b/app/test/ui/connection_screen_test.dart @@ -1,15 +1,108 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; import 'package:docker_mobile/src/storage/profile_store.dart'; import 'package:docker_mobile/src/ui/connection_screen.dart'; +import '../support/stub_session.dart'; + Widget _wrap(ProfileStore store) => ProviderScope( overrides: [profileStoreProvider.overrideWithValue(store)], child: const MaterialApp(home: ConnectionScreen()), ); +/// One saved profile of every kind, for the editing tests. +const _existing = { + ConnectionKind.agent: ConnectionProfile(id: 'e', name: 'old', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://10.0.0.9:8080', token: 't')), + ConnectionKind.tls: ConnectionProfile(id: 'e', name: 'old', kind: ConnectionKind.tls, + tls: TlsCredentials(host: '10.0.0.9', port: 2376, clientCertPem: 'cert', clientKeyPem: 'key')), + ConnectionKind.ssh: ConnectionProfile(id: 'e', name: 'old', kind: ConnectionKind.ssh, + ssh: SshCredentials(host: '10.0.0.9', port: 22, username: 'root', authMethod: SshAuthMethod.password, password: 'pw')), +}; + +/// Opens the editor (on [editing], if given) from a host route that keeps +/// whatever the editor returns. +Future<({StubSession stub, List results})> _openFromHost( + WidgetTester tester, ProfileStore store, {ConnectionProfile? editing}) async { + final stub = StubSession(const SessionState()); + final results = []; + await tester.pumpWidget(ProviderScope( + overrides: [ + profileStoreProvider.overrideWithValue(store), + sessionProvider.overrideWith((ref) => stub), + ], + child: MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () async => results.add(await Navigator.of(context) + .push(MaterialPageRoute(builder: (_) => ConnectionScreen(editing: editing)))), + child: const Text('open'), + ), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return (stub: stub, results: results); +} + +/// Picks [kind] in the open editor, fills what its form requires and scrolls +/// [button] into view. +Future _fill(WidgetTester tester, ConnectionKind kind, {required String button}) async { + if (kind != ConnectionKind.agent) { + await tester.tap(find.text(kind == ConnectionKind.tls ? 'TCP+TLS' : 'SSH')); + await tester.pumpAndSettle(); + } + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'box'); + await tester.enterText(find.widgetWithText(TextField, 'Host / IP'), '10.0.0.2'); + switch (kind) { + case ConnectionKind.agent: + break; + case ConnectionKind.tls: + await tester.enterText(find.widgetWithText(TextField, 'Client certificate (PEM)'), 'cert'); + await tester.enterText(find.widgetWithText(TextField, 'Client key (PEM)'), 'key'); + case ConnectionKind.ssh: + await tester.enterText(find.widgetWithText(TextField, 'Username'), 'root'); + await tester.enterText(find.widgetWithText(TextField, 'Password'), 'pw'); + } + final finder = find.widgetWithText(button == 'Save' ? OutlinedButton : FilledButton, button); + await tester.ensureVisible(finder); + await tester.pumpAndSettle(); + return finder; +} + +/// A store that takes a moment to write, like the platform-backed one, so a +/// second tap can land while the first save is still running. +class _SlowStore extends InMemoryProfileStore { + @override + Future add(ConnectionProfile profile) async { + await Future.delayed(const Duration(milliseconds: 50)); + return super.add(profile); + } +} + +/// A store whose first save fails. +class _FailingOnceStore extends InMemoryProfileStore { + bool _failed = false; + + @override + Future add(ConnectionProfile profile) async { + if (!_failed) { + _failed = true; + throw StateError('storage unavailable'); + } + return super.add(profile); + } +} + void main() { testWidgets('Agent is default; selecting TCP+TLS reveals the cert fields', (tester) async { await tester.pumpWidget(_wrap(InMemoryProfileStore())); @@ -41,4 +134,103 @@ void main() { expect(find.textContaining('name'), findsOneWidget); expect(await store.list(), isEmpty); }); + + for (final kind in ConnectionKind.values) { + testWidgets('Save & Connect saves once and returns the profile to the caller (${kind.name})', (tester) async { + final store = _SlowStore(); + final host = await _openFromHost(tester, store); + final button = await _fill(tester, kind, button: 'Save & Connect'); + + await tester.tap(button); + await tester.tap(button); // lands while the first save is still running + await tester.pumpAndSettle(); + + final stored = await store.list(); + expect(stored, hasLength(1)); + expect(stored.single.kind, kind); + expect(find.byType(ConnectionScreen), findsNothing); + expect(find.text('open'), findsOneWidget); // only the editor was popped + expect(host.results.single, same(stored.single)); + expect(host.stub.connects, isEmpty); // connecting is the caller's job + }); + + testWidgets('Save saves once and returns nothing to the caller (${kind.name})', (tester) async { + final store = _SlowStore(); + final host = await _openFromHost(tester, store); + final button = await _fill(tester, kind, button: 'Save'); + + await tester.tap(button); + await tester.tap(button); // lands while the first save is still running + await tester.pumpAndSettle(); + + expect(await store.list(), hasLength(1)); + expect(find.byType(ConnectionScreen), findsNothing); + expect(find.text('open'), findsOneWidget); + expect(host.results.single, isNull); + expect(host.stub.connects, isEmpty); + }); + + for (final label in ['Save', 'Save & Connect']) { + testWidgets('an editor closed underneath a pending $label does not close the screen below (${kind.name})', + (tester) async { + final store = _SlowStore(); + final host = await _openFromHost(tester, store); + final button = await _fill(tester, kind, button: label); + + await tester.tap(button); // the save is now running + // The editor is on its way out, and still mounted until its transition ends. + tester.state(find.byType(Navigator)).popUntil((r) => r.isFirst); + await tester.pumpAndSettle(); + + expect(await store.list(), hasLength(1)); // the save went through + expect(find.text('open'), findsOneWidget); + expect(host.results.single, isNull); // closed, not finished: nothing is handed back + }); + } + + testWidgets('saving an edited profile updates it in place (${kind.name})', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_existing[kind]!); + final host = await _openFromHost(tester, store, editing: _existing[kind]); + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'renamed'); + await tester.pumpAndSettle(); // let the field finish scrolling its caret into view first + final button = find.widgetWithText(FilledButton, 'Save & Connect'); + await tester.ensureVisible(button); + await tester.pumpAndSettle(); + await tester.tap(button); + await tester.pumpAndSettle(); + + final stored = await store.list(); + expect(stored, hasLength(1)); // updated, not added + expect(stored.single.id, 'e'); + expect(stored.single.name, 'renamed'); + expect(stored.single.kind, kind); + expect(host.results.single, same(stored.single)); + }); + + testWidgets('a failed save keeps the editor open and can be tried again (${kind.name})', (tester) async { + final store = _FailingOnceStore(); + final host = await _openFromHost(tester, store); + final button = await _fill(tester, kind, button: 'Save & Connect'); + + // The save error is not handled by the form; catch it here so it does not end the test. + Object? thrown; + await runZonedGuarded(() => tester.tap(button), (e, _) { + thrown = e; + }); + await tester.pumpAndSettle(); + expect(thrown, isStateError); + expect(find.byType(ConnectionScreen), findsOneWidget); + expect(await store.list(), isEmpty); + expect(host.results, isEmpty); + + await tester.tap(button); + await tester.pumpAndSettle(); + final stored = await store.list(); + expect(stored, hasLength(1)); + expect(stored.single.kind, kind); + expect(find.byType(ConnectionScreen), findsNothing); + expect(host.results.single, same(stored.single)); + }); + } } diff --git a/app/test/ui/container_stats_screen_test.dart b/app/test/ui/container_stats_screen_test.dart index 78c12a5..1d18525 100644 --- a/app/test/ui/container_stats_screen_test.dart +++ b/app/test/ui/container_stats_screen_test.dart @@ -1,9 +1,11 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/transport/transport.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/container_stats_screen.dart'; @@ -11,6 +13,7 @@ import 'package:docker_mobile/src/ui/widgets/error_view.dart'; import 'package:docker_mobile/src/ui/widgets/skeletons.dart'; import '../support/fake_transport.dart'; +import '../support/stub_session.dart'; const _sample = '{"cpu_stats":{"cpu_usage":{"total_usage":2000000000},"system_cpu_usage":10000000000,"online_cpus":4},' @@ -65,12 +68,68 @@ void main() { }); testWidgets('a failing stats stream renders an ErrorView with Retry', (tester) async { - await tester.pumpWidget(_wrap(FakeTransport() - ..onStream('/containers/abc/stats', (_) => Stream.error(DockerError.fromResponse(500, '{"message":"boom"}'))))); + final t = FakeTransport() + ..onStream('/containers/abc/stats', (_) => Stream.error(DockerError.fromResponse(404, '{"message":"boom"}'))); + await tester.pumpWidget(_wrap(t)); await tester.pumpAndSettle(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); expect(find.byType(ErrorView), findsOneWidget); expect(find.text('boom'), findsOneWidget); expect(find.text('Retry'), findsOneWidget); + expect(opens(), hasLength(1)); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(opens(), hasLength(2)); // Retry opened the stream again + expect(find.byType(ErrorView), findsOneWidget); // and the same 404 came back + }); + + testWidgets('a reconnecting session shows Reconnecting above the cards and keeps the sample', (tester) async { + final stats = StreamController>(); + final t = FakeTransport()..onStream('/containers/abc/stats', (_) => stats.stream); + final connected = SessionState(status: SessionStatus.connected, transport: t, sessionId: 1); + final stub = StubSession(connected); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: ContainerStatsScreen(containerId: 'abc', containerName: 'web')), + )); + stats.add(utf8.encode('$_sample\n')); + await tester.pumpAndSettle(); + expect(find.text('40.0 %'), findsOneWidget); + expect(find.text('Reconnecting...'), findsNothing); + + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pumpAndSettle(); + expect(find.text('Reconnecting...'), findsOneWidget); + expect(find.text('40.0 %'), findsOneWidget); + expect(tester.getTopLeft(find.text('Reconnecting...')).dy, lessThan(tester.getTopLeft(find.text('CPU')).dy)); + }); + + testWidgets('a session that gave up shows Connection lost above the cards', (tester) async { + final stats = StreamController>(); + final t = FakeTransport()..onStream('/containers/abc/stats', (_) => stats.stream); + final connected = SessionState(status: SessionStatus.connected, transport: t, sessionId: 1); + final stub = StubSession(connected); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: ContainerStatsScreen(containerId: 'abc', containerName: 'web')), + )); + stats.add(utf8.encode('$_sample\n')); + await tester.pumpAndSettle(); + expect(find.text('40.0 %'), findsOneWidget); + + // While the session retries, the note says so. + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pumpAndSettle(); + expect(find.text('Reconnecting...'), findsOneWidget); + expect(find.text('Connection lost'), findsNothing); + + // Once it gives up, nothing is reconnecting any more. + stub.setState(connected.copyWith(status: SessionStatus.failed)); + await tester.pumpAndSettle(); + expect(find.text('Connection lost'), findsOneWidget); + expect(find.text('Reconnecting...'), findsNothing); + expect(find.text('40.0 %'), findsOneWidget); + expect(tester.getTopLeft(find.text('Connection lost')).dy, lessThan(tester.getTopLeft(find.text('CPU')).dy)); }); } diff --git a/app/test/ui/containers_screen_test.dart b/app/test/ui/containers_screen_test.dart index c58a15f..80811a1 100644 --- a/app/test/ui/containers_screen_test.dart +++ b/app/test/ui/containers_screen_test.dart @@ -3,14 +3,20 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; import 'package:docker_mobile/src/api/docker_api_client.dart'; import 'package:docker_mobile/src/api/models/docker_container.dart'; import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/transport/timeouts.dart'; import 'package:docker_mobile/src/ui/containers_screen.dart'; import 'package:docker_mobile/src/ui/widgets/error_view.dart'; import 'package:docker_mobile/src/ui/widgets/resource_widgets.dart'; import 'package:docker_mobile/src/ui/widgets/skeletons.dart'; +import '../support/fake_session.dart'; + void main() { testWidgets('renders container names from the provider', (tester) async { await tester.pumpWidget( @@ -170,4 +176,45 @@ void main() { expect(tester.takeException(), isNull); expect(find.byType(ErrorView), findsOneWidget); }); + + testWidgets('a reconnect keeps the list on screen', (tester) async { + final d1 = FakeDaemon(), d2 = FakeDaemon(); + d1.transport.onGet( + RegExp(r'/containers/json$'), + (_) => http.Response('[{"Id":"a","Names":["/web"],"Image":"nginx","State":"running","Status":"Up"}]', 200), + ); + d2.transport.hangOn('GET', RegExp(r'/containers/json$')); + late ProviderContainer container; + await tester.pumpWidget(ProviderScope( + overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([d1.transport, d2.transport])), + reconnectPolicyProvider.overrideWithValue(immediatePolicy()), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + profileStoreProvider.overrideWithValue(InMemoryProfileStore()), + ], + child: MaterialApp( + home: Builder(builder: (ctx) { + container = ProviderScope.containerOf(ctx); + return const ContainersScreen(); + }), + ), + )); + await container.read(sessionProvider.notifier).connect(const ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://h:1', token: 't'))); + await tester.pumpAndSettle(); + expect(find.text('/web'), findsOneWidget); + + // The events stream breaks and the session reconnects through the second daemon. + d1.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await tester.pump(const Duration(milliseconds: 50)); + // Long enough for a switch to the skeleton to finish, had one started. + await tester.pump(const Duration(milliseconds: 400)); + expect(container.read(transportProvider), same(d2.transport)); + expect(d2.transport.calls.where((c) => c.path.endsWith('/containers/json')), hasLength(1)); // refetch in flight + expect(find.byType(SkeletonList), findsNothing); + expect(find.text('/web'), findsOneWidget); + + // The refetch never answers: let it time out so that no timer outlives the test. + await tester.pump(kRequestTimeout); + }); } diff --git a/app/test/ui/create_container_screen_test.dart b/app/test/ui/create_container_screen_test.dart index 449af94..365894a 100644 --- a/app/test/ui/create_container_screen_test.dart +++ b/app/test/ui/create_container_screen_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -8,10 +9,11 @@ import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/create_container_screen.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; -FakeTransport createFake({int createStatus = 201}) { +FakeTransport createFake({int createStatus = 201, FakeTransport? base}) { var status = createStatus; - return FakeTransport() + return (base ?? FakeTransport()) ..onGet('/networks', (_) => http.Response('[]', 200)) ..onPost('/containers/abc/start', (_) => http.Response('', 204)) ..onPost('/containers/create', (_) { @@ -63,4 +65,54 @@ void main() { // create was attempted twice (404 then 201) expect(t.posts.where((p) => p.path == '/containers/create').length, 2); }); + + testWidgets('a screen closed underneath a pending create does not close the screen below', (tester) async { + final t = HeldTransport(); + await pumpOverFirstRoute(tester, createFake(base: t), const CreateContainerScreen(image: 'nginx')); + await tester.tap(find.widgetWithText(FilledButton, 'Create')); // the create is now in flight + + popToFirstRoute(tester); // the screen is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.map((p) => p.path), contains('/containers/create')); // the create did answer + expect(find.text('first'), findsOneWidget); + }); + + testWidgets('a screen that was closed during the create shows no "Image not found" dialog', (tester) async { + final t = HeldTransport(); + await pumpOverFirstRoute( + tester, createFake(createStatus: 404, base: t), const CreateContainerScreen(image: 'nginx')); + await tester.tap(find.widgetWithText(FilledButton, 'Create')); // the create is now in flight + + popToFirstRoute(tester); + t.release(); // the daemon answers 404: the image is missing + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsNothing); + expect(find.text('Image not found'), findsNothing); + expect(find.text('first'), findsOneWidget); + }); + + testWidgets('a pull dialog closed underneath does not close the screen below when its stream ends', (tester) async { + final pull = StreamController>(); // a pull that stays open + final t = createFake(createStatus: 404)..onPostStream(RegExp(r'/images/create'), (_) => pull.stream); + await pumpOverFirstRoute(tester, t, const CreateContainerScreen(image: 'nginx')); + await tester.tap(find.widgetWithText(FilledButton, 'Create')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Pull')); + // The dialog's spinner never settles: pump its transition by hand. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(find.text('Pulling image'), findsOneWidget); + + popToFirstRoute(tester); // dialog and screen are on their way out, still mounted + unawaited(pull.close()); // the pull ends, as it does when the transport is closed + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + await tester.pumpAndSettle(); + + expect(find.text('Pulling image'), findsNothing); + expect(find.text('first'), findsOneWidget); + }); } diff --git a/app/test/ui/events_screen_test.dart b/app/test/ui/events_screen_test.dart index 4911c8c..fe84a20 100644 --- a/app/test/ui/events_screen_test.dart +++ b/app/test/ui/events_screen_test.dart @@ -1,35 +1,29 @@ -import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'package:docker_mobile/src/api/docker_error.dart'; -import 'package:docker_mobile/src/transport/transport.dart'; +import 'package:docker_mobile/src/api/models/docker_event.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/events_screen.dart'; import 'package:docker_mobile/src/ui/system_screen.dart'; import 'package:docker_mobile/src/ui/widgets/error_view.dart'; import '../support/fake_transport.dart'; - -FakeTransport eventsFake({List? eventsBytes}) => FakeTransport() - ..onStream('/events', (_) => eventsBytes == null ? const Stream.empty() : Stream.value(eventsBytes)) - ..onGet('/info', (_) => http.Response('{"ServerVersion":"27","NCPU":1,"Driver":"overlay2"}', 200)) - ..onGet('/version', (_) => http.Response('{"Version":"27","ApiVersion":"1.46"}', 200)) - ..onGet('/system/df', (_) => http.Response('{"Images":[],"Containers":[],"Volumes":[],"BuildCache":[]}', 200)); - -const _events = - '{"Type":"container","Action":"start","Actor":{"Attributes":{"name":"web"}}}\n' - '{"Type":"image","Action":"pull","Actor":{"Attributes":{"name":"nginx"}}}\n'; - -Widget _wrap(Transport t, Widget child) => ProviderScope( - overrides: [transportProvider.overrideWith((ref) => t)], - child: MaterialApp(home: child), - ); +import '../support/stub_session.dart'; void main() { - testWidgets('renders events; the Containers chip filters the feed', (tester) async { - await tester.pumpWidget(_wrap(eventsFake(eventsBytes: utf8.encode(_events)), const EventsScreen())); + testWidgets('renders the session feed; the Containers chip filters it', (tester) async { + final container = ProviderContainer(); + addTearDown(container.dispose); + container.read(sessionEventsProvider.notifier) + ..add(const DockerEvent(type: 'image', action: 'pull', target: 'nginx')) + ..add(const DockerEvent(type: 'container', action: 'start', target: 'web')); + await tester.pumpWidget(UncontrolledProviderScope( + container: container, + child: const MaterialApp(home: EventsScreen()), + )); await tester.pumpAndSettle(); expect(find.text('web'), findsOneWidget); expect(find.text('nginx'), findsOneWidget); @@ -37,11 +31,32 @@ void main() { await tester.tap(find.widgetWithText(FilterChip, 'Containers')); await tester.pumpAndSettle(); expect(find.text('web'), findsOneWidget); - expect(find.text('nginx'), findsNothing); // image filtered out + expect(find.text('nginx'), findsNothing); + }); + + testWidgets('events added while the screen is open appear live', (tester) async { + final container = ProviderContainer(); + addTearDown(container.dispose); + await tester.pumpWidget(UncontrolledProviderScope( + container: container, + child: const MaterialApp(home: EventsScreen()), + )); + await tester.pumpAndSettle(); + expect(find.textContaining('No events'), findsOneWidget); + container.read(sessionEventsProvider.notifier).add(const DockerEvent(type: 'container', action: 'die', target: 'db')); + await tester.pumpAndSettle(); + expect(find.text('db'), findsOneWidget); }); testWidgets('the System Events action opens the events screen', (tester) async { - await tester.pumpWidget(_wrap(eventsFake(), const SystemScreen())); + final t = FakeTransport() + ..onGet('/info', (_) => http.Response('{"ServerVersion":"27","NCPU":1,"Driver":"overlay2"}', 200)) + ..onGet('/version', (_) => http.Response('{"Version":"27","ApiVersion":"1.46"}', 200)) + ..onGet('/system/df', (_) => http.Response('{"Images":[],"Containers":[],"Volumes":[],"BuildCache":[]}', 200)); + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => t)], + child: const MaterialApp(home: SystemScreen()), + )); await tester.pumpAndSettle(); await tester.tap(find.byIcon(Icons.bolt)); await tester.pumpAndSettle(); @@ -49,14 +64,19 @@ void main() { expect(find.textContaining('No events'), findsOneWidget); }); - testWidgets('a failing event stream renders an ErrorView with Retry', (tester) async { - final t = FakeTransport() - ..onStream('/events', (_) => Stream.error(DockerError.fromResponse(500, '{"message":"boom"}'))); - await tester.pumpWidget(_wrap(t, const EventsScreen())); + testWidgets('a failed session shows an ErrorView whose Retry retries the session', (tester) async { + final stub = StubSession(const SessionState( + status: SessionStatus.failed, + error: DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused'), + )); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: EventsScreen()), + )); await tester.pumpAndSettle(); - expect(find.byType(ErrorView), findsOneWidget); - expect(find.text('boom'), findsOneWidget); - expect(find.text('Retry'), findsOneWidget); + expect(find.text('Cannot reach the daemon: refused'), findsOneWidget); + await tester.tap(find.text('Retry')); + expect(stub.retries, 1); }); } diff --git a/app/test/ui/exec_screen_test.dart b/app/test/ui/exec_screen_test.dart index 715aa66..381e7a6 100644 --- a/app/test/ui/exec_screen_test.dart +++ b/app/test/ui/exec_screen_test.dart @@ -3,10 +3,13 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'package:xterm/xterm.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; import 'package:docker_mobile/src/ui/exec_screen.dart'; import '../support/fake_transport.dart'; +import '../support/stub_session.dart'; void main() { testWidgets('renders the terminal and command bar, then shows session ended', (tester) async { @@ -29,4 +32,181 @@ void main() { await tester.pumpAndSettle(); expect(find.textContaining('ended'), findsOneWidget); }); + + FakeTransport freshExecFake() => FakeTransport() + ..onPost(RegExp(r'/exec$'), (_) => http.Response('{"Id":"e1"}', 201)) + ..onPost(RegExp(r'/resize$'), (_) => http.Response('', 200)) + ..onGet(RegExp(r'/exec/[^/]+/json$'), (_) => http.Response('{"Running":false,"ExitCode":0}', 200)); + + testWidgets('a transport swap ends the terminal; New session starts on the new connection', (tester) async { + final t1 = freshExecFake(); + final t2 = freshExecFake(); + final current = StateProvider((ref) => t1); + late ProviderContainer container; + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => ref.watch(current))], + child: MaterialApp(home: Builder(builder: (ctx) { + container = ProviderScope.containerOf(ctx); + return const ExecScreen(containerId: 'abc', containerName: 'web'); + })), + )); + await tester.pump(const Duration(milliseconds: 100)); + expect(t1.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + + container.read(current.notifier).state = t2; + await tester.pump(const Duration(milliseconds: 100)); + expect(find.textContaining('Session ended'), findsOneWidget); + expect(t1.lastChannel.closed, isTrue); + + await tester.tap(find.text('New session')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t2.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + expect(find.textContaining('Session ended'), findsNothing); + }); + + testWidgets('Run after a transport swap starts on the new connection with the typed command, once', + (tester) async { + final t1 = freshExecFake(); + final t2 = freshExecFake(); + final current = StateProvider((ref) => t1); + late ProviderContainer container; + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => ref.watch(current))], + child: MaterialApp(home: Builder(builder: (ctx) { + container = ProviderScope.containerOf(ctx); + return const ExecScreen(containerId: 'abc', containerName: 'web'); + })), + )); + await tester.pump(const Duration(milliseconds: 100)); + expect(t1.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + + container.read(current.notifier).state = t2; + await tester.pump(const Duration(milliseconds: 100)); + + await tester.enterText(find.byType(TextField), 'top'); + await tester.tap(find.byTooltip('Run')); + await tester.pump(const Duration(milliseconds: 100)); + + final created = t2.posts.where((c) => c.path.endsWith('/exec')).toList(); + expect(created, hasLength(1)); + expect(((created.single.body as Map)['Cmd'] as List).last, 'top'); + expect(t1.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + }); + + testWidgets('Run on the current connection restarts in place', (tester) async { + final t = freshExecFake(); + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => t)], + child: const MaterialApp(home: ExecScreen(containerId: 'abc', containerName: 'web')), + )); + await tester.pump(const Duration(milliseconds: 100)); + final before = tester.widget(find.byType(TerminalView)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + + await tester.enterText(find.byType(TextField), 'top'); + await tester.tap(find.byTooltip('Run')); + await tester.pump(const Duration(milliseconds: 100)); + + final created = t.posts.where((c) => c.path.endsWith('/exec')).toList(); + expect(created, hasLength(2)); + expect((created.last.body as Map)['Cmd'], ['/bin/sh', '-c', 'top']); + expect(t.execChannels.first.closed, isTrue); + // Still the same session's view: no new controller was built. + final after = tester.widget(find.byType(TerminalView)); + expect(after.key, isNotNull); + expect(after.key, before.key); + expect(after.terminal, same(before.terminal)); + }); + + testWidgets('New session gives the terminal view a new key', (tester) async { + final t = freshExecFake(); + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => t)], + child: const MaterialApp(home: ExecScreen(containerId: 'abc', containerName: 'web')), + )); + await tester.pump(const Duration(milliseconds: 100)); + final before = tester.widget(find.byType(TerminalView)).key; + + await t.lastChannel.controller.close(); // the process exits + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('New session')); + await tester.pump(const Duration(milliseconds: 100)); + + final after = tester.widget(find.byType(TerminalView)).key; + expect(after, isNotNull); + expect(after, isNot(before)); + }); + + /// Opens the exec screen on a session the test drives: connected on [t] at first. + Future<({StubSession stub, SessionState connected})> pumpOnSession(WidgetTester tester, FakeTransport t) async { + final connected = SessionState(status: SessionStatus.connected, transport: t, sessionId: 1); + final stub = StubSession(connected); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: ExecScreen(containerId: 'abc', containerName: 'web')), + )); + await tester.pump(const Duration(milliseconds: 100)); + return (stub: stub, connected: connected); + } + + testWidgets('New session waits for a usable session', (tester) async { + final t = freshExecFake(); + final (:stub, :connected) = await pumpOnSession(tester, t); + await t.lastChannel.controller.close(); // the process exits + await tester.pump(const Duration(milliseconds: 100)); + expect(find.textContaining('Session ended'), findsOneWidget); + + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('New session')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); // nothing started on the dead connection + expect(find.textContaining('Session ended'), findsOneWidget); + + stub.setState(connected); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('New session')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(2)); + expect(find.textContaining('Session ended'), findsNothing); + }); + + testWidgets('Run waits for a usable session', (tester) async { + final t = freshExecFake(); + final (:stub, :connected) = await pumpOnSession(tester, t); + await tester.enterText(find.byType(TextField), 'top'); + + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.byTooltip('Run')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + + stub.setState(connected); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.byTooltip('Run')); + await tester.pump(const Duration(milliseconds: 100)); + final created = t.posts.where((c) => c.path.endsWith('/exec')).toList(); + expect(created, hasLength(2)); + expect((created.last.body as Map)['Cmd'], ['/bin/sh', '-c', 'top']); + }); + + testWidgets('Retry waits for a usable session', (tester) async { + final t = FakeTransport() + ..onPost(RegExp(r'/exec$'), (_) => http.Response('{"message":"no such container"}', 404)); + final (:stub, :connected) = await pumpOnSession(tester, t); + expect(find.text('Exec failed'), findsOneWidget); + + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('Retry')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(1)); + + stub.setState(connected); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('Retry')); + await tester.pump(const Duration(milliseconds: 100)); + expect(t.posts.where((c) => c.path.endsWith('/exec')), hasLength(2)); + }); } diff --git a/app/test/ui/home_screen_test.dart b/app/test/ui/home_screen_test.dart index 5ef2528..6bea8c7 100644 --- a/app/test/ui/home_screen_test.dart +++ b/app/test/ui/home_screen_test.dart @@ -2,10 +2,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/home_screen.dart'; +import 'package:docker_mobile/src/ui/widgets/resource_widgets.dart'; +import 'package:docker_mobile/src/ui/widgets/session_banner.dart'; import '../support/fake_transport.dart'; +import '../support/stub_session.dart'; FakeTransport homeFake() => FakeTransport() ..onGet('/containers/json', (_) => http.Response('[]', 200)) @@ -16,6 +20,32 @@ FakeTransport homeFake() => FakeTransport() ..onGet('/version', (_) => http.Response('{}', 200)) ..onGet('/system/df', (_) => http.Response('{}', 200)); +/// How often [t] was asked for each of the dashboard's three endpoints. +Map dashboardCalls(FakeTransport t) => { + for (final path in const ['/info', '/version', '/system/df']) path: t.calls.where((c) => c.path == path).length, + }; + +/// [dashboardCalls] when the dashboard was fetched [times] times. +Map dashboardFetched(int times) => {'/info': times, '/version': times, '/system/df': times}; + +/// Home over a daemon that reports version 27.0.3, with the Containers tab +/// showing. Returns the transport and the container that owns the providers. +Future<(FakeTransport, ProviderContainer)> pumpHome(WidgetTester tester) async { + final t = homeFake()..onGet('/info', (_) => http.Response('{"ServerVersion":"27.0.3"}', 200)); + await tester.pumpWidget(ProviderScope( + overrides: [transportProvider.overrideWith((ref) => t)], + child: const MaterialApp(home: HomeScreen()), + )); + await tester.pumpAndSettle(); + return (t, ProviderScope.containerOf(tester.element(find.byType(HomeScreen)))); +} + +/// Switches Home to the tab whose destination shows [icon]. +Future openTab(WidgetTester tester, IconData icon) async { + await tester.tap(find.byIcon(icon)); + await tester.pumpAndSettle(); +} + void main() { testWidgets('the bottom nav switches the selected tab index', (tester) async { await tester.pumpWidget(ProviderScope( @@ -47,4 +77,86 @@ void main() { await tester.pumpAndSettle(); expect(bar().selectedIndex, 0); }); + + testWidgets('Home hosts no session banner of its own, even while reconnecting', (tester) async { + final stub = StubSession(const SessionState(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pumpWidget(ProviderScope( + overrides: [ + transportProvider.overrideWith((ref) => homeFake()), + sessionProvider.overrideWith((ref) => stub), + ], + child: const MaterialApp(home: HomeScreen()), + )); + await tester.pump(const Duration(milliseconds: 500)); + // The app shell shows it above every route (see SessionBannerHost). + expect(find.byType(SessionBanner), findsNothing); + expect(find.textContaining('Reconnecting'), findsNothing); + }); + + testWidgets('an old-daemon warning shows once and is acknowledged', (tester) async { + final stub = StubSession(const SessionState(status: SessionStatus.connected, warning: 'This daemon speaks Docker API 1.40.')); + await tester.pumpWidget(ProviderScope( + overrides: [ + transportProvider.overrideWith((ref) => homeFake()), + sessionProvider.overrideWith((ref) => stub), + ], + child: const MaterialApp(home: HomeScreen()), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(find.text('This daemon speaks Docker API 1.40.'), findsOneWidget); + expect(stub.acknowledged, 1); + }); + + group('the dashboard', () { + testWidgets('is not fetched while another tab shows, not even when a refresh of it is due', (tester) async { + final (t, container) = await pumpHome(tester); + expect(dashboardCalls(t), dashboardFetched(0)); + expect(find.byType(StatCard, skipOffstage: false), findsNothing); + + // What daemon events and a reconnect do to it. + container.invalidate(systemDashboardProvider); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 3)); + expect(dashboardCalls(t), dashboardFetched(0)); + + // The other tabs do not wake it either. + for (final icon in [Icons.layers, Icons.hub, Icons.storage]) { + await openTab(tester, icon); + expect(dashboardCalls(t), dashboardFetched(0), reason: '$icon'); + } + }); + + testWidgets('is fetched once when the System tab is opened, and shown', (tester) async { + final (t, _) = await pumpHome(tester); + expect(dashboardCalls(t), dashboardFetched(0)); + + await openTab(tester, Icons.monitor_heart); + expect(dashboardCalls(t), dashboardFetched(1)); + expect(find.byType(StatCard), findsNWidgets(4)); + expect(find.text('27.0.3'), findsOneWidget); + }); + + testWidgets('is not refetched by leaving the tab and returning; a refresh that came due meanwhile runs on return', + (tester) async { + final (t, container) = await pumpHome(tester); + await openTab(tester, Icons.monitor_heart); + expect(dashboardCalls(t), dashboardFetched(1)); + + await openTab(tester, Icons.inventory); + await openTab(tester, Icons.monitor_heart); + expect(dashboardCalls(t), dashboardFetched(1)); + expect(find.text('27.0.3'), findsOneWidget); + + await openTab(tester, Icons.inventory); + container.invalidate(systemDashboardProvider); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 3)); + expect(dashboardCalls(t), dashboardFetched(1)); // not while the tab is hidden + + await openTab(tester, Icons.monitor_heart); + expect(dashboardCalls(t), dashboardFetched(2)); + expect(find.text('27.0.3'), findsOneWidget); + }); + }); } diff --git a/app/test/ui/image_detail_screen_test.dart b/app/test/ui/image_detail_screen_test.dart index 3e29d78..8167347 100644 --- a/app/test/ui/image_detail_screen_test.dart +++ b/app/test/ui/image_detail_screen_test.dart @@ -10,8 +10,9 @@ import 'package:docker_mobile/src/ui/image_detail_screen.dart'; import 'package:docker_mobile/src/ui/widgets/error_view.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; -FakeTransport imageFake() => FakeTransport() +FakeTransport imageFake([FakeTransport? base]) => (base ?? FakeTransport()) ..onGet('/images/sha256:abc/json', (_) => http.Response( '{"Id":"sha256:abc","RepoTags":["nginx:latest"],"Architecture":"amd64","Os":"linux","Size":100,"Created":"2026-01-02T03:04:05Z","Config":{"Env":[],"ExposedPorts":{"80/tcp":{}}}}', 200, @@ -70,6 +71,22 @@ void main() { expect(find.text('open'), findsOneWidget); // popped back to the base route }); + testWidgets('a screen closed underneath a pending remove does not close the screen below', (tester) async { + final t = HeldTransport(); + await _open(tester, imageFake(t)); + await tester.tap(find.widgetWithText(ElevatedButton, 'Remove')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Remove')); // dialog confirm; the delete is now in flight + await tester.pumpAndSettle(); + + popToFirstRoute(tester); // the screen is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.calls.where((c) => c.method == 'DELETE'), hasLength(1)); // the remove did answer + expect(find.text('open'), findsOneWidget); + }); + testWidgets('Tag dialog tags the image', (tester) async { final t = imageFake(); await _open(tester, t); diff --git a/app/test/ui/logs_reconnect_test.dart b/app/test/ui/logs_reconnect_test.dart new file mode 100644 index 0000000..e4ad365 --- /dev/null +++ b/app/test/ui/logs_reconnect_test.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/api/timestamps.dart'; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/ui/logs_screen.dart'; + +import '../support/fake_session.dart'; + +Finder _line(String text) => find.textContaining(text, findRichText: true); + +/// Connects a real session through [daemons] (the first one now, the next on +/// every reconnect) and opens the logs screen of container `a`. +Future _openLogs(WidgetTester tester, List daemons) async { + late ProviderContainer container; + await tester.pumpWidget(ProviderScope( + overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([for (final d in daemons) d.transport])), + reconnectPolicyProvider.overrideWithValue(immediatePolicy()), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + profileStoreProvider.overrideWithValue(InMemoryProfileStore()), + ], + child: MaterialApp( + home: Builder(builder: (ctx) { + container = ProviderScope.containerOf(ctx); + return TextButton( + onPressed: () => Navigator.of(ctx).push(MaterialPageRoute( + builder: (_) => const LogsScreen(containerId: 'a', containerName: 'web'))), + child: const Text('open'), + ); + }), + ), + )); + await container.read(sessionProvider.notifier).connect(const ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://h:1', token: 't'))); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + return container; +} + +/// Breaks [daemon]'s events stream, so the session reconnects through the next daemon. +Future _dropConnection(WidgetTester tester, FakeContainerDaemon daemon) async { + daemon.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('every reconnect keeps the lines on screen and resumes after the last one', (tester) async { + final d1 = FakeContainerDaemon(), d2 = FakeContainerDaemon(), d3 = FakeContainerDaemon(); + final container = await _openLogs(tester, [d1, d2, d3]); + + d1.logs.add(utf8.encode('$firstLogStamp first-line\n')); + await tester.pumpAndSettle(); + expect(_line('first-line'), findsOneWidget); + + await _dropConnection(tester, d1); + expect(container.read(transportProvider), same(d2.transport)); + expect(_line('first-line'), findsOneWidget); + expect(d2.logOpens, hasLength(1)); + expect(d2.logOpens.single.query!['since'], rfc3339ToUnixNanos(firstLogStamp)); + + d2.logs.add(utf8.encode('$secondLogStamp second-line\n')); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(_line('second-line')).dy, greaterThan(tester.getTopLeft(_line('first-line')).dy)); + + // Once more: the stream has to move on to the newest transport every time. + await _dropConnection(tester, d2); + expect(container.read(transportProvider), same(d3.transport)); + expect(_line('first-line'), findsOneWidget); + expect(_line('second-line'), findsOneWidget); + expect(d3.logOpens, hasLength(1)); + expect(d3.logOpens.single.query!['since'], rfc3339ToUnixNanos(secondLogStamp)); + expect(d2.logOpens, hasLength(1)); + }); + + testWidgets('a failed inspect refetch after a reconnect keeps the lines', (tester) async { + final d1 = FakeContainerDaemon(), d2 = FakeContainerDaemon(); + d2.transport.onGet(RegExp(r'/containers/a/json$'), (_) => http.Response('{"message":"daemon busy"}', 500)); + final container = await _openLogs(tester, [d1, d2]); + + d1.logs.add(utf8.encode('$firstLogStamp first-line\n')); + await tester.pumpAndSettle(); + expect(_line('first-line'), findsOneWidget); + + await _dropConnection(tester, d1); + expect(container.read(transportProvider), same(d2.transport)); + expect(container.read(containerInspectProvider('a')).hasError, isTrue); // the refetch did fail + + expect(_line('first-line'), findsOneWidget); + expect(find.byType(MaterialBanner), findsNothing); // no inspect error in place of the body + expect(d2.logOpens, hasLength(1)); + expect(d2.logOpens.single.query!['since'], rfc3339ToUnixNanos(firstLogStamp)); + }); +} diff --git a/app/test/ui/logs_screen_test.dart b/app/test/ui/logs_screen_test.dart index 1a17216..e061522 100644 --- a/app/test/ui/logs_screen_test.dart +++ b/app/test/ui/logs_screen_test.dart @@ -1,14 +1,17 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/transport/transport.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/logs_screen.dart'; import '../support/fake_transport.dart'; +import '../support/stub_session.dart'; List frame(int type, List p) { final n = p.length; @@ -63,4 +66,97 @@ void main() { expect(find.byIcon(Icons.arrow_downward), findsOneWidget); }); + + testWidgets('the tail menu refetches with the chosen size, and with All', (tester) async { + final t = logsFake(); + await tester.pumpWidget(_wrap(t)); + await tester.pumpAndSettle(); + List opens() => t.calls.where((c) => c.method == 'STREAM').toList(); + expect(opens(), hasLength(1)); + + await tester.tap(find.byTooltip('Tail')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Tail 100')); + await tester.pumpAndSettle(); + expect(opens(), hasLength(2)); + expect(opens().last.query!['tail'], '100'); + + await tester.tap(find.byTooltip('Tail')); + await tester.pumpAndSettle(); + await tester.tap(find.text('All')); + await tester.pumpAndSettle(); + expect(opens(), hasLength(3)); + expect(opens().last.query!['tail'], 'all'); + }); + + testWidgets('a failed first inspect shows the error banner with Retry', (tester) async { + final t = FakeTransport() + ..onGet('/containers/a/json', (_) => http.Response('{"message":"No such container: a"}', 404)); + await tester.pumpWidget(_wrap(t)); + await tester.pumpAndSettle(); + + expect(find.byType(MaterialBanner), findsOneWidget); + expect(find.text('No such container: a'), findsOneWidget); + expect(t.calls.where((c) => c.method == 'STREAM'), isEmpty); // no body, so no log stream + + await tester.tap(find.widgetWithText(TextButton, 'Retry')); + await tester.pumpAndSettle(); + expect(t.calls.where((c) => c.method == 'GET'), hasLength(2)); // Retry asks the daemon again + expect(find.byType(MaterialBanner), findsOneWidget); + }); + + testWidgets('a reconnecting session shows the reconnecting row and keeps the lines', (tester) async { + late StreamController> logs; // the most recently opened log stream + final t = logsFake()..onStream('/containers/a/logs', (_) => (logs = StreamController>()).stream); + final connected = SessionState(status: SessionStatus.connected, transport: t, sessionId: 1); + final stub = StubSession(connected); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: LogsScreen(containerId: 'a', containerName: 'web')), + )); + await tester.pumpAndSettle(); + logs.add(frame(1, utf8.encode('hello-out\n'))); + await tester.pumpAndSettle(); + expect(find.textContaining('hello-out', findRichText: true), findsOneWidget); + expect(find.text('Reconnecting stream...'), findsNothing); + + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(); + expect(find.text('Reconnecting stream...'), findsOneWidget); + expect(find.textContaining('hello-out', findRichText: true), findsOneWidget); + + stub.setState(connected); + await tester.pumpAndSettle(); + expect(find.text('Reconnecting stream...'), findsNothing); + }); + + testWidgets('a session that gave up shows Connection lost in place of the reconnecting row', (tester) async { + late StreamController> logs; // the most recently opened log stream + final t = logsFake()..onStream('/containers/a/logs', (_) => (logs = StreamController>()).stream); + final connected = SessionState(status: SessionStatus.connected, transport: t, sessionId: 1); + final stub = StubSession(connected); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: LogsScreen(containerId: 'a', containerName: 'web')), + )); + await tester.pumpAndSettle(); + logs.add(frame(1, utf8.encode('hello-out\n'))); + await tester.pumpAndSettle(); + + // While the session retries, the stream waits for it and says so. + stub.setState(connected.copyWith(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(); + expect(find.text('Reconnecting stream...'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + expect(find.text('Connection lost'), findsNothing); + + // Once it gives up, nothing is reconnecting any more. + stub.setState(connected.copyWith(status: SessionStatus.failed)); + await tester.pump(); + expect(find.text('Connection lost'), findsOneWidget); + expect(find.byIcon(Icons.cloud_off), findsOneWidget); + expect(find.text('Reconnecting stream...'), findsNothing); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.textContaining('hello-out', findRichText: true), findsOneWidget); + }); } diff --git a/app/test/ui/network_create_sheet_test.dart b/app/test/ui/network_create_sheet_test.dart index a53eb4d..b501998 100644 --- a/app/test/ui/network_create_sheet_test.dart +++ b/app/test/ui/network_create_sheet_test.dart @@ -6,6 +6,23 @@ import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/network_create_sheet.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; + +/// Opens the sheet over a first route (and a second one, if asked), names the +/// network and taps Create; the create stays in flight until `release()`. +Future _startCreate(WidgetTester tester, {bool overSecondRoute = false}) async { + final t = HeldTransport()..onPost('/networks/create', (_) => http.Response('{"Id":"n9"}', 201)); + final navigator = await pumpOverFirstRoute( + tester, t, overSecondRoute ? const Scaffold(body: Text('second')) : const NetworkCreateSheet()); + if (overSecondRoute) { + navigator.push(MaterialPageRoute(builder: (_) => const NetworkCreateSheet())); + await tester.pumpAndSettle(); + } + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'mynet'); + await tester.pump(); + await tester.tap(find.widgetWithText(FilledButton, 'Create')); + return t; +} void main() { testWidgets('fills the form and creates a network with subnet + label', (tester) async { @@ -73,4 +90,53 @@ void main() { expect(find.textContaining('Failed'), findsOneWidget); }); + + testWidgets('a sheet closed underneath a pending create does not close the screen below', (tester) async { + final t = await _startCreate(tester); + popToFirstRoute(tester); // the sheet is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.single.path, '/networks/create'); // the create did answer + expect(find.text('first'), findsOneWidget); + }); + + testWidgets('backing out of the sheet during a pending create keeps the screen it was opened from', (tester) async { + final t = await _startCreate(tester, overSecondRoute: true); + tester.state(find.byType(Navigator)).pop(); // back + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); // the answer arrives during the exit transition + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.single.path, '/networks/create'); + expect(find.text('second'), findsOneWidget); + }); + + testWidgets('a finished create closes the sheet and the dropdown that is open on top of it', (tester) async { + final t = await _startCreate(tester); + await tester.pump(); + await tester.tap(find.byType(DropdownButton)); // its menu is a route of its own + await tester.pumpAndSettle(); + expect(find.text('overlay'), findsWidgets); // the menu is open + + t.release(); + await tester.pumpAndSettle(); + expect(find.text('overlay', skipOffstage: false), findsNothing); + expect(find.byType(NetworkCreateSheet, skipOffstage: false), findsNothing); + expect(find.text('first'), findsOneWidget); + expect(find.text('Network created'), findsOneWidget); + }); + + testWidgets('a create that answers after the sheet is gone reports no failure', (tester) async { + final t = await _startCreate(tester); + popToFirstRoute(tester); + await tester.pumpAndSettle(); // the sheet is disposed by now + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.single.path, '/networks/create'); + expect(find.textContaining('Failed'), findsNothing); + expect(find.text('first'), findsOneWidget); + }); } diff --git a/app/test/ui/network_detail_screen_test.dart b/app/test/ui/network_detail_screen_test.dart index 617e466..d4ac6c4 100644 --- a/app/test/ui/network_detail_screen_test.dart +++ b/app/test/ui/network_detail_screen_test.dart @@ -7,8 +7,9 @@ import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/network_detail_screen.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; -FakeTransport networkFake() => FakeTransport() +FakeTransport networkFake([FakeTransport? base]) => (base ?? FakeTransport()) ..onGet('/networks/n1', (_) => http.Response( '{"Id":"n1","Name":"mynet","Driver":"bridge","Scope":"local","Internal":true,"IPAM":{"Driver":"default","Config":[{"Subnet":"10.0.0.0/24","Gateway":"10.0.0.1"}]},"Containers":{"abc":{"Name":"web","IPv4Address":"10.0.0.2/24"}},"Labels":{"env":"prod"}}', 200, @@ -34,6 +35,17 @@ Future _open(WidgetTester tester, Transport t) async { await tester.pumpAndSettle(); } +/// Opens the screen and confirms Remove; the delete stays in flight until `release()`. +Future _startRemove(WidgetTester tester) async { + final t = HeldTransport(); + await _open(tester, networkFake(t)); + await tester.tap(find.widgetWithText(ElevatedButton, 'Remove')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Remove')); // confirm + await tester.pumpAndSettle(); + return t; +} + void main() { testWidgets('renders detail + connected containers and removes', (tester) async { final t = networkFake(); @@ -51,4 +63,41 @@ void main() { expect(t.calls.where((c) => c.method == 'DELETE').map((c) => c.path), contains('/networks/n1')); expect(find.text('open'), findsOneWidget); // popped back }); + + testWidgets('a screen closed underneath a pending remove does not close the screen below', (tester) async { + final t = await _startRemove(tester); + popToFirstRoute(tester); // the screen is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.calls.where((c) => c.method == 'DELETE'), hasLength(1)); // the remove did answer + expect(find.text('open'), findsOneWidget); + }); + + testWidgets('a finished remove closes its own screen and what is on top of it', (tester) async { + final t = await _startRemove(tester); + final navigator = tester.state(find.byType(Navigator)); + navigator.push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('on top')))); + await tester.pumpAndSettle(); + expect(find.text('on top'), findsOneWidget); + + t.release(); + await tester.pumpAndSettle(); + expect(find.text('on top', skipOffstage: false), findsNothing); + expect(find.byType(NetworkDetailScreen, skipOffstage: false), findsNothing); + expect(find.text('open'), findsOneWidget); // the screen below is on top again + expect(find.text('Removed'), findsOneWidget); + }); + + testWidgets('a remove that answers after the screen is gone reports no failure', (tester) async { + final t = await _startRemove(tester); + popToFirstRoute(tester); + await tester.pumpAndSettle(); // the screen is disposed by now + t.release(); + await tester.pumpAndSettle(); + + expect(t.calls.where((c) => c.method == 'DELETE'), hasLength(1)); + expect(find.textContaining('Failed'), findsNothing); + expect(find.text('open'), findsOneWidget); + }); } diff --git a/app/test/ui/profiles_screen_test.dart b/app/test/ui/profiles_screen_test.dart index e1ed860..11702db 100644 --- a/app/test/ui/profiles_screen_test.dart +++ b/app/test/ui/profiles_screen_test.dart @@ -1,18 +1,87 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/storage/credential_store.dart'; import 'package:docker_mobile/src/storage/profile_store.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; import 'package:docker_mobile/src/ui/connection_screen.dart'; +import 'package:docker_mobile/src/ui/home_screen.dart'; import 'package:docker_mobile/src/ui/profiles_screen.dart'; import 'package:docker_mobile/src/ui/widgets/resource_widgets.dart'; +import '../support/fake_session.dart'; +import '../support/stub_session.dart'; + Widget _wrap(ProfileStore store) => ProviderScope( overrides: [profileStoreProvider.overrideWithValue(store)], child: const MaterialApp(home: ProfilesScreen()), ); +const _a = ConnectionProfile(id: 'a', name: 'Alpha', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://a:1', token: 't')); +const _b = ConnectionProfile(id: 'b', name: 'Beta', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://b:1', token: 't')); + +Future pumpProfiles( + WidgetTester tester, + SessionState s, { + List profiles = const [_a, _b], +}) async { + final stub = StubSession(s); + await tester.pumpWidget(ProviderScope( + overrides: [ + sessionProvider.overrideWith((ref) => stub), + profilesProvider.overrideWith((ref) async => profiles), + ], + child: const MaterialApp(home: ProfilesScreen()), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + return stub; +} + +/// The list over [store] with a stub session: connects are only recorded. +Future pumpList(WidgetTester tester, ProfileStore store) async { + final stub = StubSession(const SessionState()); + await tester.pumpWidget(ProviderScope( + overrides: [ + profileStoreProvider.overrideWithValue(store), + sessionProvider.overrideWith((ref) => stub), + ], + child: const MaterialApp(home: ProfilesScreen()), + )); + await tester.pumpAndSettle(); + return stub; +} + +/// The list over [store] with a real session whose transports come from [factory]. +Future pumpListWithSession(WidgetTester tester, ProfileStore store, FakeTransportFactory factory) async { + await tester.pumpWidget(ProviderScope( + overrides: [ + profileStoreProvider.overrideWithValue(store), + transportFactoryProvider.overrideWithValue(factory), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + ], + child: const MaterialApp(home: ProfilesScreen()), + )); + await tester.pumpAndSettle(); +} + +/// Names the agent profile in the open editor 'home' and taps [button]. +Future fillEditorAndTap(WidgetTester tester, String button) async { + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'home'); + await tester.enterText(find.widgetWithText(TextField, 'Host / IP'), '10.0.0.2'); + final finder = find.widgetWithText(button == 'Save' ? OutlinedButton : FilledButton, button); + await tester.ensureVisible(finder); + await tester.pumpAndSettle(); + await tester.tap(finder); +} + void main() { testWidgets('empty state, then renders saved profiles', (tester) async { final store = InMemoryProfileStore(); @@ -57,4 +126,369 @@ void main() { expect(await store.list(), isEmpty); expect(find.text('gone'), findsNothing); }); + + testWidgets('the connecting row shows a spinner and every row ignores taps', (tester) async { + final stub = await pumpProfiles(tester, const SessionState(status: SessionStatus.connecting, profile: _a)); + expect( + find.descendant(of: find.widgetWithText(Card, 'Alpha'), matching: find.byType(CircularProgressIndicator)), + findsOneWidget, + ); + expect( + find.descendant(of: find.widgetWithText(Card, 'Beta'), matching: find.byType(CircularProgressIndicator)), + findsNothing, + ); + for (final name in ['Beta', 'Alpha', 'Alpha']) { + await tester.tap(find.text(name)); + await tester.pump(); + } + expect(stub.connects, isEmpty); + expect(stub.disconnects, 0); // not even its own row cancels: that is the bar's Cancel + }); + + testWidgets('a second tap on a connecting profile does not cancel it', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_a); + await store.add(_b); + final held = Completer(); // Alpha's handshake + final daemon = FakeDaemon(); + final factory = FakeTransportFactory([held.future]); + await pumpListWithSession(tester, store, factory); + final container = ProviderScope.containerOf(tester.element(find.byType(ProfilesScreen))); + SessionState session() => container.read(sessionProvider); + + await tester.tap(find.text('Alpha')); + await tester.tap(find.text('Alpha')); // a double tap, before the screen has redrawn + await tester.pump(); + await tester.tap(find.text('Alpha')); // and an impatient one on the row that now shows the spinner + await tester.pump(); + expect(session().status, SessionStatus.connecting); + expect(session().profile!.id, 'a'); + expect(factory.builds, 1); + + // The one attempt is still alive: when its handshake answers it connects and opens Home, once. + held.complete(daemon.transport); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(session().status, SessionStatus.connected); + expect(session().transport, same(daemon.transport)); + expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); + }); + + testWidgets('a connect that succeeds while the add button is still on its way out opens Home', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_a); + final held = Completer(); + await pumpListWithSession(tester, store, FakeTransportFactory([held.future])); + + await tester.tap(find.text('Alpha')); + await tester.pump(); // connecting: the add button starts its 200 ms exit + await tester.pump(const Duration(milliseconds: 50)); + held.complete(FakeDaemon().transport); // the daemon answers before that is over + await tester.pump(); // the button is back and Home is pushed in the same frame + await tester.pump(const Duration(milliseconds: 600)); + + expect(tester.takeException(), isNull); // no two heroes with one tag on the screen being left + expect(find.byType(HomeScreen), findsOneWidget); + }); + + testWidgets('Cancel in the connecting bar cancels the connect', (tester) async { + final stub = await pumpProfiles(tester, const SessionState(status: SessionStatus.connecting, profile: _a)); + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); + await tester.pump(); + expect(stub.disconnects, 1); + expect(stub.connects, isEmpty); + }); + + testWidgets('Cancel in the connecting bar cancels a real connect, and its late handshake changes nothing', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_a); + await store.add(_b); + final held = Completer(); // Alpha's handshake, answered only at the end + final lateDaemon = FakeDaemon(); + final factory = FakeTransportFactory([ + held.future, + const DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused'), + ]); + await pumpListWithSession(tester, store, factory); + final container = ProviderScope.containerOf(tester.element(find.byType(ProfilesScreen))); + SessionState session() => container.read(sessionProvider); + + await tester.tap(find.text('Alpha')); + await tester.pump(); + expect(session().status, SessionStatus.connecting); + + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); + await tester.pump(); + expect(session().status, SessionStatus.disconnected); + expect(session().error, isNull); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.textContaining('Connecting to'), findsNothing); + expect(factory.builds, 1); + + // The rows take taps again. + await tester.tap(find.text('Beta')); + await tester.pumpAndSettle(); + expect(factory.builds, 2); + expect( + find.descendant(of: find.widgetWithText(Card, 'Beta'), matching: find.text('Cannot reach the daemon: refused')), + findsOneWidget, + ); + + // The cancelled handshake answers after all: its transport is closed and nothing else changes. + held.complete(lateDaemon.transport); + await tester.pumpAndSettle(); + expect(lateDaemon.transport.closed, isTrue); + expect(session().status, SessionStatus.disconnected); + expect(session().profile!.id, 'b'); + expect(session().error!.message, 'Cannot reach the daemon: refused'); + expect(find.byType(HomeScreen, skipOffstage: false), findsNothing); + }); + + for (final outcome in ['answers', 'times out']) { + testWidgets('a cancelled connect that $outcome late opens nothing', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_a); + await store.add(_b); + final held = Completer(); // Alpha's handshake + final lateDaemon = FakeDaemon(); + final beta = FakeDaemon(); + await pumpListWithSession(tester, store, FakeTransportFactory([held.future, beta.transport])); + final container = ProviderScope.containerOf(tester.element(find.byType(ProfilesScreen))); + + await tester.tap(find.text('Alpha')); // hangs + await tester.pump(); + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); // cancelled from the bar + await tester.pump(); + await tester.tap(find.text('Beta')); // connects and opens Home + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(find.byType(HomeScreen), findsOneWidget); + + // Alpha's attempt finishes only now, while the session is Beta's. + if (outcome == 'answers') { + held.complete(lateDaemon.transport); + } else { + held.completeError(const DockerError(DockerErrorKind.timeout, 'Timed out waiting for the daemon')); + } + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + + expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); + final session = container.read(sessionProvider); + expect(session.status, SessionStatus.connected); + expect(session.profile!.id, 'b'); + expect(session.transport, same(beta.transport)); + expect(beta.transport.closed, isFalse); + if (outcome == 'answers') expect(lateDaemon.transport.closed, isTrue); + }); + } + + testWidgets('the connecting bar names the profile and the add button is gone while connecting', (tester) async { + final stub = await pumpProfiles(tester, const SessionState(status: SessionStatus.connecting, profile: _a)); + expect(find.text('Connecting to Alpha...'), findsOneWidget); + expect(find.widgetWithText(TextButton, 'Cancel'), findsOneWidget); + expect(find.byType(FloatingActionButton), findsNothing); + expect(find.text('Connecting - tap to cancel'), findsNothing); // the row no longer carries a hint + + // A connect without a profile cannot happen in the session; the bar still reads well. + stub.setState(const SessionState(status: SessionStatus.connecting)); + await tester.pump(); + expect(find.text('Connecting to the daemon...'), findsOneWidget); + + stub.setState(const SessionState()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.textContaining('Connecting to'), findsNothing); + expect(find.widgetWithText(TextButton, 'Cancel'), findsNothing); + expect(find.byType(FloatingActionButton), findsOneWidget); + }); + + testWidgets('the connecting bar stays in view when the connecting row is far down the list', (tester) async { + final many = [ + for (var i = 1; i <= 30; i++) + ConnectionProfile(id: 'p$i', name: 'Host $i', kind: ConnectionKind.agent, + agent: AgentCredentials(baseUri: 'http://h$i:1', token: 't')), + ]; + final stub = await pumpProfiles( + tester, + SessionState(status: SessionStatus.connecting, profile: many.last), + profiles: many, + ); + expect(find.text('Host 1'), findsOneWidget); + expect(find.text('Host 30'), findsNothing); // its row, and the spinner on it, are below the fold + expect(find.text('Connecting to Host 30...').hitTestable(), findsOneWidget); + + await tester.tap(find.widgetWithText(TextButton, 'Cancel')); + await tester.pump(); + expect(stub.disconnects, 1); + }); + + testWidgets('the row menus are off while connecting', (tester) async { + await pumpProfiles(tester, const SessionState(status: SessionStatus.connecting, profile: _a)); + for (final menu in [find.byType(PopupMenuButton).first, find.byType(PopupMenuButton).last]) { + await tester.tap(menu); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text('Edit'), findsNothing); + expect(find.text('Delete'), findsNothing); + } + + // Settings has nothing to do with the connect and stays live. + expect(tester.widget(find.widgetWithIcon(IconButton, Icons.settings)).onPressed, isNotNull); + }); + + testWidgets('the empty-state add button is off while connecting', (tester) async { + final stub = await pumpList(tester, InMemoryProfileStore()); + stub.setState(const SessionState(status: SessionStatus.connecting, profile: _a)); + await tester.pump(); + await tester.tap(find.widgetWithText(FilledButton, 'Add connection')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(ConnectionScreen), findsNothing); + }); + + testWidgets('no inline error while the session is reconnecting or failed', (tester) async { + const error = DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused'); + final stub = await pumpProfiles(tester, const SessionState(profile: _b, error: error)); + expect(find.text(error.message), findsOneWidget); // a failed connect does show it + + for (final status in [SessionStatus.reconnecting, SessionStatus.failed]) { + stub.setState(SessionState(status: status, profile: _b, attempt: 1, error: error)); + await tester.pump(); + expect(find.text(error.message), findsNothing, reason: status.name); + expect(find.text('Beta'), findsOneWidget); + } + }); + + testWidgets('a failed connect shows its error under that profile only', (tester) async { + await pumpProfiles(tester, const SessionState( + profile: _b, + error: DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused'), + )); + expect(find.text('Cannot reach the daemon: refused'), findsOneWidget); + expect( + find.descendant(of: find.widgetWithText(Card, 'Beta'), matching: find.text('Cannot reach the daemon: refused')), + findsOneWidget, + ); + final errorText = tester.widget(find.text('Cannot reach the daemon: refused')); + final scheme = Theme.of(tester.element(find.text('Beta'))).colorScheme; + expect(errorText.style!.color, scheme.error); + }); + + testWidgets('tapping a row connects through the session', (tester) async { + final stub = await pumpProfiles(tester, const SessionState()); + await tester.tap(find.text('Alpha')); + await tester.pump(); + expect(stub.connects.single.id, 'a'); + }); + + testWidgets('the spinner replaces the avatar without shifting the row text sideways', (tester) async { + final stub = await pumpProfiles(tester, const SessionState()); + final row = find.widgetWithText(Card, 'Alpha'); + final host = find.descendant(of: row, matching: find.byType(MonoText)); + final titleX = tester.getTopLeft(find.text('Alpha')).dx; + final hostX = tester.getTopLeft(host).dx; + final width = tester.getSize(row).width; + expect(find.descendant(of: row, matching: find.byType(LeadingAvatar)), findsOneWidget); + + stub.setState(const SessionState(status: SessionStatus.connecting, profile: _a)); + await tester.pump(); + expect(find.descendant(of: row, matching: find.byType(LeadingAvatar)), findsNothing); + expect(find.descendant(of: row, matching: find.byType(CircularProgressIndicator)), findsOneWidget); + expect(tester.getTopLeft(find.text('Alpha')).dx, titleX); + expect(tester.getTopLeft(host).dx, hostX); + expect(tester.getSize(row).width, width); + }); + + testWidgets('Save & Connect from the editor connects on the list', (tester) async { + final store = InMemoryProfileStore(); + final stub = await pumpList(tester, store); + await tester.tap(find.widgetWithIcon(FloatingActionButton, Icons.add)); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save & Connect'); + await tester.pumpAndSettle(); + + expect(find.byType(ConnectionScreen), findsNothing); // back on the list + expect(find.text('home'), findsOneWidget); + expect(stub.connects.single, same((await store.list()).single)); + }); + + testWidgets('Save & Connect from the empty-state editor connects on the list', (tester) async { + final store = InMemoryProfileStore(); + final stub = await pumpList(tester, store); + await tester.tap(find.widgetWithText(FilledButton, 'Add connection')); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save & Connect'); + await tester.pumpAndSettle(); + + expect(find.byType(ConnectionScreen), findsNothing); + expect(stub.connects.single, same((await store.list()).single)); + }); + + testWidgets('Edit, then Save & Connect, connects the edited profile on the list', (tester) async { + final store = InMemoryProfileStore(); + await store.add(_a); + final stub = await pumpList(tester, store); + await tester.tap(find.byType(PopupMenuButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Edit')); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save & Connect'); + await tester.pumpAndSettle(); + + expect(find.byType(ConnectionScreen), findsNothing); + final stored = await store.list(); + expect(stored.single.name, 'home'); // updated in place, not added + expect(stored.single.id, 'a'); + expect(stub.connects.single, same(stored.single)); + }); + + testWidgets('Save still just closes the editor', (tester) async { + final store = InMemoryProfileStore(); + final stub = await pumpList(tester, store); + await tester.tap(find.widgetWithIcon(FloatingActionButton, Icons.add)); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save'); + await tester.pumpAndSettle(); + + expect(find.byType(ConnectionScreen), findsNothing); + expect(find.text('home'), findsOneWidget); + expect(await store.list(), hasLength(1)); + expect(stub.connects, isEmpty); + }); + + testWidgets('a failed Save & Connect shows its error on the list', (tester) async { + final store = InMemoryProfileStore(); + await pumpListWithSession( + tester, + store, + FakeTransportFactory([const DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused')]), + ); + await tester.tap(find.widgetWithIcon(FloatingActionButton, Icons.add)); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save & Connect'); + await tester.pumpAndSettle(); + + expect(find.byType(ConnectionScreen), findsNothing); + expect( + find.descendant(of: find.widgetWithText(Card, 'home'), matching: find.text('Cannot reach the daemon: refused')), + findsOneWidget, + ); + expect(find.byType(HomeScreen), findsNothing); + expect(await store.list(), hasLength(1)); + }); + + testWidgets('Save & Connect to a reachable daemon opens Home over the list, not over the editor', (tester) async { + final d = FakeDaemon(); + await pumpListWithSession(tester, InMemoryProfileStore(), FakeTransportFactory([d.transport])); + await tester.tap(find.widgetWithIcon(FloatingActionButton, Icons.add)); + await tester.pumpAndSettle(); + await fillEditorAndTap(tester, 'Save & Connect'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 700)); // both route transitions + + expect(find.byType(HomeScreen), findsOneWidget); + expect(find.byType(ConnectionScreen, skipOffstage: false), findsNothing); + expect(find.byType(ProfilesScreen, skipOffstage: false), findsOneWidget); + }); } diff --git a/app/test/ui/route_is_open_test.dart b/app/test/ui/route_is_open_test.dart new file mode 100644 index 0000000..178c65c --- /dev/null +++ b/app/test/ui/route_is_open_test.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:docker_mobile/src/ui/route_is_open.dart'; + +/// The context of the pushed screen, kept for the test. +late BuildContext _screen; + +/// Pumps a first route and pushes a screen over it. What the screen's route +/// completes with ends up in [results]. +Future _pumpScreen(WidgetTester tester, List results) async { + await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('first')))); + final navigator = tester.state(find.byType(Navigator)); + navigator + .push(MaterialPageRoute(builder: (context) { + _screen = context; + return const Scaffold(body: Text('screen')); + })) + .then(results.add); + await tester.pumpAndSettle(); + return navigator; +} + +void main() { + testWidgets('routeIsOpen turns false in the call that pops the route, while its widgets are still mounted', (tester) async { + final navigator = await _pumpScreen(tester, []); + expect(routeIsOpen(_screen), isTrue); + + navigator.pop(); + expect(_screen.mounted, isTrue); + expect(routeIsOpen(_screen), isFalse); + await tester.pumpAndSettle(); + }); + + testWidgets('closeRoute closes its route and hands the result to whoever pushed it', (tester) async { + final results = []; + await _pumpScreen(tester, results); + + closeRoute(_screen, 'done'); + await tester.pumpAndSettle(); + expect(find.text('screen'), findsNothing); + expect(find.text('first'), findsOneWidget); + expect(results, ['done']); + }); + + testWidgets('closeRoute also closes what was pushed on top of its route', (tester) async { + final results = []; + final navigator = await _pumpScreen(tester, results); + navigator.push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('on top')))); + navigator.push(DialogRoute(context: navigator.context, builder: (_) => const AlertDialog(title: Text('and a dialog')))); + await tester.pumpAndSettle(); + expect(find.text('and a dialog'), findsOneWidget); + + closeRoute(_screen, 7); + await tester.pumpAndSettle(); + expect(find.text('and a dialog'), findsNothing); + expect(find.text('on top'), findsNothing); + expect(find.text('screen'), findsNothing); + expect(find.text('first'), findsOneWidget); + expect(results, [7]); + }); + + testWidgets('closeRoute leaves the routes alone when its own was closed already', (tester) async { + final results = []; + final navigator = await _pumpScreen(tester, results); + + navigator.pop(); // closed underneath; the screen is still mounted until its transition ends + closeRoute(_screen, 'late'); + await tester.pumpAndSettle(); + expect(find.text('first'), findsOneWidget); + expect(results, [null]); + }); + + testWidgets('closeRoute does nothing for a screen that is gone', (tester) async { + final results = []; + final navigator = await _pumpScreen(tester, results); + navigator.pop(); + await tester.pumpAndSettle(); + expect(_screen.mounted, isFalse); + + closeRoute(_screen, 'late'); + await tester.pumpAndSettle(); + expect(find.text('first'), findsOneWidget); + expect(results, [null]); + }); +} diff --git a/app/test/ui/system_screen_test.dart b/app/test/ui/system_screen_test.dart index 65e3d48..3259c95 100644 --- a/app/test/ui/system_screen_test.dart +++ b/app/test/ui/system_screen_test.dart @@ -1,11 +1,17 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; +import 'package:docker_mobile/src/storage/profile_store.dart'; import 'package:docker_mobile/src/ui/system_screen.dart'; import 'package:docker_mobile/src/ui/widgets/resource_widgets.dart'; +import '../support/fake_session.dart'; import '../support/fake_transport.dart'; FakeTransport systemFake() => FakeTransport() @@ -66,10 +72,15 @@ void main() { }); testWidgets('Disconnect action confirms then nulls the transport', (tester) async { - final t = systemFake(); + final t = systemFake() + ..onGet('/_ping', (_) => http.Response('OK', 200)) + ..onStream(RegExp(r'/events$'), (_) => StreamController>().stream); late ProviderContainer container; await tester.pumpWidget(ProviderScope( - overrides: [transportProvider.overrideWith((ref) => t)], + overrides: [ + transportFactoryProvider.overrideWithValue(FakeTransportFactory([t])), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + ], child: MaterialApp( home: Builder(builder: (ctx) { container = ProviderScope.containerOf(ctx); @@ -83,6 +94,9 @@ void main() { }), ), )); + await container.read(sessionProvider.notifier).connect(const ConnectionProfile( + id: '1', name: 'A', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://h:1', token: 't'))); + expect(container.read(transportProvider), same(t)); await tester.tap(find.text('open')); await tester.pumpAndSettle(); @@ -92,7 +106,9 @@ void main() { await tester.tap(find.widgetWithText(TextButton, 'Disconnect')); await tester.pumpAndSettle(); + expect(container.read(sessionProvider).status, SessionStatus.disconnected); expect(container.read(transportProvider), isNull); + expect(t.closed, isTrue); expect(find.text('open'), findsOneWidget); // popped back }); } diff --git a/app/test/ui/volume_create_sheet_test.dart b/app/test/ui/volume_create_sheet_test.dart index dbc451d..5b33d68 100644 --- a/app/test/ui/volume_create_sheet_test.dart +++ b/app/test/ui/volume_create_sheet_test.dart @@ -7,12 +7,25 @@ import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/volume_create_sheet.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; Widget _wrap(Transport t) => ProviderScope( overrides: [transportProvider.overrideWith((ref) => t)], child: const MaterialApp(home: VolumeCreateSheet()), ); +/// Opens the sheet over a first route, names the volume and taps Create; the +/// create stays in flight until `release()`. +Future _startCreate(WidgetTester tester) async { + final t = HeldTransport() + ..onPost('/volumes/create', (_) => http.Response('{"Name":"data","Driver":"local"}', 201)); + await pumpOverFirstRoute(tester, t, const VolumeCreateSheet()); + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'data'); + await tester.pump(); + await tester.tap(find.widgetWithText(FilledButton, 'Create')); + return t; +} + void main() { testWidgets('fills the form and creates a volume with a label', (tester) async { Map? createBody; @@ -59,4 +72,26 @@ void main() { await tester.pumpAndSettle(); expect(find.textContaining('Failed'), findsOneWidget); }); + + testWidgets('a sheet closed underneath a pending create does not close the screen below', (tester) async { + final t = await _startCreate(tester); + popToFirstRoute(tester); // the sheet is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.single.path, '/volumes/create'); // the create did answer + expect(find.text('first'), findsOneWidget); + }); + + testWidgets('a create that answers after the sheet is gone reports no failure', (tester) async { + final t = await _startCreate(tester); + popToFirstRoute(tester); + await tester.pumpAndSettle(); // the sheet is disposed by now + t.release(); + await tester.pumpAndSettle(); + + expect(t.posts.single.path, '/volumes/create'); + expect(find.textContaining('Failed'), findsNothing); + expect(find.text('first'), findsOneWidget); + }); } diff --git a/app/test/ui/volume_detail_screen_test.dart b/app/test/ui/volume_detail_screen_test.dart index 42b25bf..d9434e0 100644 --- a/app/test/ui/volume_detail_screen_test.dart +++ b/app/test/ui/volume_detail_screen_test.dart @@ -7,8 +7,9 @@ import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/ui/volume_detail_screen.dart'; import '../support/fake_transport.dart'; +import '../support/held_transport.dart'; -FakeTransport volumeFake() => FakeTransport() +FakeTransport volumeFake([FakeTransport? base]) => (base ?? FakeTransport()) ..onGet('/volumes/data', (_) => http.Response( '{"Name":"data","Driver":"local","Mountpoint":"/var/lib/docker/volumes/data/_data","Scope":"local","Labels":{"env":"prod"}}', 200, @@ -34,6 +35,17 @@ Future _open(WidgetTester tester, Transport t) async { await tester.pumpAndSettle(); } +/// Opens the screen and confirms Remove; the delete stays in flight until `release()`. +Future _startRemove(WidgetTester tester) async { + final t = HeldTransport(); + await _open(tester, volumeFake(t)); + await tester.tap(find.widgetWithText(ElevatedButton, 'Remove')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(TextButton, 'Remove')); // confirm + await tester.pumpAndSettle(); + return t; +} + void main() { testWidgets('renders detail and removes', (tester) async { final t = volumeFake(); @@ -64,4 +76,26 @@ void main() { expect(t.calls.lastWhere((c) => c.method == 'DELETE').query, {'force': 'true'}); }); + + testWidgets('a screen closed underneath a pending remove does not close the screen below', (tester) async { + final t = await _startRemove(tester); + popToFirstRoute(tester); // the screen is on its way out, and still mounted until its transition ends + t.release(); + await tester.pumpAndSettle(); + + expect(t.calls.where((c) => c.method == 'DELETE'), hasLength(1)); // the remove did answer + expect(find.text('open'), findsOneWidget); + }); + + testWidgets('a remove that answers after the screen is gone reports no failure', (tester) async { + final t = await _startRemove(tester); + popToFirstRoute(tester); + await tester.pumpAndSettle(); // the screen is disposed by now + t.release(); + await tester.pumpAndSettle(); + + expect(t.calls.where((c) => c.method == 'DELETE'), hasLength(1)); + expect(find.textContaining('Failed'), findsNothing); + expect(find.text('open'), findsOneWidget); + }); } diff --git a/app/test/ui/widgets/session_banner_test.dart b/app/test/ui/widgets/session_banner_test.dart new file mode 100644 index 0000000..3a11ee3 --- /dev/null +++ b/app/test/ui/widgets/session_banner_test.dart @@ -0,0 +1,226 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; +import 'package:docker_mobile/src/state/providers.dart'; +import 'package:docker_mobile/src/ui/widgets/session_banner.dart'; + +import '../../support/stub_session.dart'; + +Future pumpBanner(WidgetTester tester, SessionState s) async { + final stub = StubSession(s); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: const MaterialApp(home: Scaffold(body: SessionBanner())), + )); + return stub; +} + +/// Runs a route transition to its end. The reconnecting strip's spinner never +/// settles, so `pumpAndSettle` cannot be used while it shows. +Future pumpTransition(WidgetTester tester) async { + await tester.pump(); // the transition starts + await tester.pump(const Duration(milliseconds: 600)); // and ends (the default one takes 450 ms) + await tester.pump(); // the navigator hides or drops the route underneath +} + +void main() { + testWidgets('hidden while connected', (tester) async { + await pumpBanner(tester, const SessionState(status: SessionStatus.connected)); + expect(find.textContaining('Reconnecting'), findsNothing); + expect(find.text('Retry'), findsNothing); + }); + + testWidgets('reconnecting shows the attempt and a spinner', (tester) async { + await pumpBanner(tester, const SessionState(status: SessionStatus.reconnecting, attempt: 2)); + expect(find.text('Reconnecting... (attempt 2 of 5)'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('failed shows the message; Retry and Disconnect reach the session', (tester) async { + final stub = await pumpBanner(tester, const SessionState( + status: SessionStatus.failed, + error: DockerError(DockerErrorKind.unauthorized, 'Host key changed - reconnect from the Connections screen to review it'), + )); + expect(find.textContaining('Host key changed'), findsOneWidget); + await tester.tap(find.text('Retry')); + expect(stub.retries, 1); + await tester.tap(find.text('Disconnect')); + await tester.pumpAndSettle(); + expect(stub.disconnects, 1); + }); + + testWidgets('on a narrow screen a long failure message gets three full-width lines above the buttons', (tester) async { + tester.view.physicalSize = const Size(360, 640); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + final stub = await pumpBanner(tester, const SessionState( + status: SessionStatus.failed, + error: DockerError(DockerErrorKind.network, 'short'), + )); + final lineHeight = tester.getSize(find.text('short')).height; + + final message = 'Cannot reach the daemon: ${'no route to host, ' * 12}giving up'; // longer than any clipped error + stub.setState(SessionState(status: SessionStatus.failed, error: DockerError(DockerErrorKind.network, message))); + await tester.pump(); + final text = tester.getRect(find.text(message)); + final retry = tester.getRect(find.widgetWithText(TextButton, 'Retry')); + final disconnect = tester.getRect(find.widgetWithText(TextButton, 'Disconnect')); + + // The message has the strip's width to itself (icon and paddings aside) and stops after three lines. + expect(text.width, 360 - 16 - 24 - 12 - 8 - 8); + expect(text.height, closeTo(3 * lineHeight, 0.5)); + expect(tester.getRect(find.byIcon(Icons.cloud_off)).top, text.top); + // The buttons sit in a row of their own underneath, at the right edge. + expect(retry.top, greaterThanOrEqualTo(text.bottom)); + expect(disconnect.top, retry.top); + expect(retry.right, lessThanOrEqualTo(disconnect.left)); + expect(disconnect.right, 360 - 8); + expect(tester.getSize(find.byType(SessionBanner)).height, lessThan(150)); + + final scheme = Theme.of(tester.element(find.byType(SessionBanner))).colorScheme; + for (final label in ['Retry', 'Disconnect']) { + final style = tester.widget(find.widgetWithText(TextButton, label)).style!; + expect(style.foregroundColor!.resolve({}), scheme.onErrorContainer, reason: label); + } + // Both actions are on screen and work. + await tester.tap(find.text('Retry')); + expect(stub.retries, 1); + expect(find.text('Disconnect').hitTestable(), findsOneWidget); + }); + + testWidgets('the failed strip without an error reads Connection lost', (tester) async { + await pumpBanner(tester, const SessionState(status: SessionStatus.failed)); + expect(find.text('Connection lost'), findsOneWidget); + }); + + testWidgets('the banner shows nothing while disconnected, connecting or connected', (tester) async { + final stub = await pumpBanner(tester, const SessionState(status: SessionStatus.failed)); + expect(tester.getSize(find.byType(SessionBanner)).height, greaterThan(0)); + for (final status in [SessionStatus.disconnected, SessionStatus.connecting, SessionStatus.connected]) { + stub.setState(SessionState(status: status)); + await tester.pump(); + expect(tester.getSize(find.byType(SessionBanner)), Size.zero, reason: status.name); + expect( + find.descendant(of: find.byType(SessionBanner), matching: find.byType(Text)), + findsNothing, + reason: status.name, + ); + } + }); + + testWidgets('the reconnecting strip offers Disconnect, which reaches the session', (tester) async { + final stub = await pumpBanner(tester, const SessionState(status: SessionStatus.reconnecting, attempt: 1)); + final button = find.widgetWithText(TextButton, 'Disconnect'); + expect(button, findsOneWidget); + expect(find.text('Retry'), findsNothing); // the session is already retrying + final scheme = Theme.of(tester.element(button)).colorScheme; + expect( + tester.widget(button).style!.foregroundColor!.resolve({}), + scheme.onSecondaryContainer, + ); + // The strip is only as tall as the button needs. + expect(tester.getSize(find.byType(SessionBanner)).height, tester.getSize(button).height + 4); + + await tester.tap(button); + await tester.pump(); + expect(stub.disconnects, 1); + expect(stub.retries, 0); + }); + + testWidgets('showsFor says for every status whether the banner draws anything', (tester) async { + final stub = await pumpBanner(tester, const SessionState()); + for (final status in SessionStatus.values) { + stub.setState(SessionState(status: status, attempt: 1)); + await tester.pump(); + final drawn = tester.getSize(find.byType(SessionBanner)).height > 0; + expect(SessionBanner.showsFor(status), drawn, reason: status.name); + } + }); + + testWidgets('the host shows the banner above a pushed route and Disconnect pops to the first route', (tester) async { + final key = GlobalKey(); + final stub = StubSession(const SessionState( + status: SessionStatus.failed, + error: DockerError(DockerErrorKind.network, 'Cannot reach the daemon: refused'), + )); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: MaterialApp( + navigatorKey: key, + builder: (context, child) => SessionBannerHost(navigatorKey: key, child: child!), + home: const Scaffold(body: Text('first')), + ), + )); + key.currentState!.push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('second')))); + await tester.pumpAndSettle(); + expect(find.text('second'), findsOneWidget); + expect(find.text('first'), findsNothing); + + // The banner is not part of any route, so the pushed one cannot cover it. + expect(find.text('Cannot reach the daemon: refused'), findsOneWidget); + expect(find.text('Retry').hitTestable(), findsOneWidget); + expect( + tester.getTopLeft(find.widgetWithText(Scaffold, 'second')).dy, + tester.getBottomLeft(find.byType(SessionBanner)).dy, + ); + + await tester.tap(find.text('Disconnect')); + await tester.pumpAndSettle(); + expect(find.text('first'), findsOneWidget); + expect(find.text('second'), findsNothing); + expect(stub.disconnects, 1); + }); + + testWidgets('through the host the reconnecting strip disconnects from a pushed route too', (tester) async { + final key = GlobalKey(); + final stub = StubSession(const SessionState(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: MaterialApp( + navigatorKey: key, + builder: (context, child) => SessionBannerHost(navigatorKey: key, child: child!), + home: const Scaffold(body: Text('first')), + ), + )); + key.currentState!.push(MaterialPageRoute(builder: (_) => const Scaffold(body: Text('second')))); + await pumpTransition(tester); + expect(find.text('second'), findsOneWidget); + expect(find.text('first'), findsNothing); + + await tester.tap(find.text('Disconnect')); + await pumpTransition(tester); + expect(find.text('first'), findsOneWidget); + expect(find.text('second'), findsNothing); + expect(stub.disconnects, 1); + }); + + testWidgets('routes lose the top inset only while the banner shows', (tester) async { + final key = GlobalKey(); + final stub = StubSession(const SessionState(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pumpWidget(ProviderScope( + overrides: [sessionProvider.overrideWith((ref) => stub)], + child: MaterialApp( + navigatorKey: key, + // A 24 px status bar, reported above the host as the device does. + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 24)), + child: SessionBannerHost(navigatorKey: key, child: child!), + ), + home: Builder( + builder: (context) => Scaffold(body: Text('top inset ${MediaQuery.of(context).padding.top}')), + ), + ), + )); + expect(find.text('top inset 0.0'), findsOneWidget); // the banner already sits under the status bar + + stub.setState(const SessionState(status: SessionStatus.connected)); + await tester.pump(); + expect(find.text('top inset 24.0'), findsOneWidget); + + stub.setState(const SessionState(status: SessionStatus.failed)); + await tester.pump(); + expect(find.text('top inset 0.0'), findsOneWidget); + }); +} diff --git a/app/test/widget_test.dart b/app/test/widget_test.dart index d48ddc1..9a6b5f1 100644 --- a/app/test/widget_test.dart +++ b/app/test/widget_test.dart @@ -1,11 +1,59 @@ +import 'dart:async'; + import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; import 'package:docker_mobile/main.dart'; +import 'package:docker_mobile/src/api/docker_error.dart'; +import 'package:docker_mobile/src/session/reconnect_policy.dart'; +import 'package:docker_mobile/src/session/session_state.dart'; import 'package:docker_mobile/src/state/providers.dart'; import 'package:docker_mobile/src/state/theme_provider.dart'; +import 'package:docker_mobile/src/storage/credential_store.dart'; import 'package:docker_mobile/src/storage/profile_store.dart'; import 'package:docker_mobile/src/storage/settings_store.dart'; +import 'package:docker_mobile/src/transport/transport.dart'; +import 'package:docker_mobile/src/ui/home_screen.dart'; import 'package:docker_mobile/src/ui/profiles_screen.dart'; +import 'package:docker_mobile/src/ui/settings_screen.dart'; +import 'package:docker_mobile/src/ui/widgets/error_view.dart'; +import 'package:docker_mobile/src/ui/widgets/session_banner.dart'; +import 'package:docker_mobile/src/ui/widgets/skeletons.dart'; + +import 'support/fake_session.dart'; +import 'support/stub_session.dart'; + +/// Boots the whole app on in-memory stores (see the boot test), plus +/// [overrides]. The saved connections are those in [profiles], if given. +Future _pumpApp(WidgetTester tester, {ProfileStore? profiles, List overrides = const []}) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + profileStoreProvider.overrideWithValue(profiles ?? InMemoryProfileStore()), + settingsStoreProvider.overrideWithValue(InMemorySettingsStore()), + ...overrides, + ], + child: const DockerMobileApp(), + ), + ); + await tester.pumpAndSettle(); +} + +/// A daemon that answers everything Home asks for and lists [containers] by name. +FakeDaemon _daemon(List containers) { + final list = [ + for (final name in containers) '{"Id":"$name","Names":["/$name"],"Image":"nginx","State":"running","Status":"Up"}', + ].join(','); + final d = FakeDaemon(); + d.transport + ..onGet(RegExp(r'/containers/json$'), (_) => http.Response('[$list]', 200)) + ..onGet(RegExp(r'/images/json$'), (_) => http.Response('[]', 200)) + ..onGet(RegExp(r'/networks$'), (_) => http.Response('[]', 200)) + ..onGet(RegExp(r'/volumes$'), (_) => http.Response('{"Volumes":[]}', 200)) + ..onGet(RegExp(r'/info$'), (_) => http.Response('{}', 200)) + ..onGet(RegExp(r'/system/df$'), (_) => http.Response('{}', 200)); + return d; +} void main() { testWidgets('app boots to the profiles screen', (tester) async { @@ -24,4 +72,136 @@ void main() { await tester.pumpAndSettle(); expect(find.byType(ProfilesScreen), findsOneWidget); }); + + testWidgets('the app puts the session banner host above its routes', (tester) async { + await _pumpApp(tester); + expect(find.byType(SessionBannerHost), findsOneWidget); + // Above the navigator: the first route (and so every route) sits inside it. + expect( + find.ancestor(of: find.byType(ProfilesScreen), matching: find.byType(SessionBannerHost)), + findsOneWidget, + ); + }); + + testWidgets('the app banner disconnects through the app navigator', (tester) async { + final stub = StubSession(const SessionState(status: SessionStatus.failed)); + await _pumpApp(tester, overrides: [sessionProvider.overrideWith((ref) => stub)]); + await tester.tap(find.byTooltip('Settings')); + await tester.pumpAndSettle(); + expect(find.byType(SettingsScreen), findsOneWidget); + expect(find.text('Retry').hitTestable(), findsOneWidget); // still there over a pushed route + + await tester.tap(find.text('Disconnect')); + await tester.pumpAndSettle(); + expect(find.byType(SettingsScreen), findsNothing); + expect(find.byType(ProfilesScreen), findsOneWidget); + expect(stub.disconnects, 1); + }); + + testWidgets('the app banner offers Disconnect while it is still reconnecting', (tester) async { + final stub = StubSession(const SessionState(status: SessionStatus.failed)); + await _pumpApp(tester, overrides: [sessionProvider.overrideWith((ref) => stub)]); + await tester.tap(find.byTooltip('Settings')); + await tester.pumpAndSettle(); + expect(find.byType(SettingsScreen), findsOneWidget); + + // Retry puts the session back to reconnecting; its spinner never settles, so pump by hand from here. + stub.setState(const SessionState(status: SessionStatus.reconnecting, attempt: 1)); + await tester.pump(); + expect(find.text('Retry'), findsNothing); + await tester.tap(find.text('Disconnect')); + await tester.pump(); // the pop starts + await tester.pump(const Duration(milliseconds: 600)); // and ends + await tester.pump(); // the navigator drops the popped route + expect(find.byType(SettingsScreen), findsNothing); + expect(find.byType(ProfilesScreen), findsOneWidget); + expect(stub.disconnects, 1); + }); + + testWidgets('connect, lose the connection, get it back and leave: the whole app over a real session', + (tester) async { + const alpha = ConnectionProfile( + id: 'a', name: 'Alpha', kind: ConnectionKind.agent, agent: AgentCredentials(baseUri: 'http://a:1', token: 't')); + final store = InMemoryProfileStore(); + await store.add(alpha); + final d1 = _daemon(['web']); + final d2 = _daemon(['web', 'db']); // a container was created while the connection was down + final handshake = Completer(); // the reconnect's, answered only when the test says so + final factory = FakeTransportFactory([d1.transport, handshake.future]); + await _pumpApp(tester, profiles: store, overrides: [ + transportFactoryProvider.overrideWithValue(factory), + reconnectPolicyProvider.overrideWithValue(ReconnectPolicy(jitter: 0)), + lifecycleSourceProvider.overrideWithValue(ManualLifecycleSource()), + ]); + final container = ProviderScope.containerOf(tester.element(find.byType(ProfilesScreen))); + SessionState session() => container.read(sessionProvider); + int listFetches(FakeDaemon d) => d.transport.calls.where((c) => c.path.endsWith('/containers/json')).length; + // Home is as it was: the list is up and no tab, shown or not, fell back to a skeleton or an error. + void expectHomeUntouched() { + expect(find.text('/web'), findsOneWidget); + expect(find.byType(SkeletonList, skipOffstage: false), findsNothing); + expect(find.byType(SkeletonCards, skipOffstage: false), findsNothing); + expect(find.byType(ErrorView, skipOffstage: false), findsNothing); + } + + await tester.tap(find.text('Alpha')); + await tester.pumpAndSettle(); + expect(find.byType(HomeScreen), findsOneWidget); + expect(session().status, SessionStatus.connected); + expectHomeUntouched(); + expect(find.text('/db'), findsNothing); + + // The connection drops. The reconnect banner shows over Home, which stays as it is. + d1.events.addError(const DockerError(DockerErrorKind.network, 'reset')); + await tester.pump(); // the session notices + await tester.pump(); // and the banner is drawn + expect(session().status, SessionStatus.reconnecting); + expect(find.text('Reconnecting... (attempt 1 of 5)'), findsOneWidget); + expectHomeUntouched(); + + // The first attempt starts after a second, and its handshake does not answer yet. + await tester.pump(const Duration(seconds: 1)); + await tester.pump(const Duration(milliseconds: 400)); // long enough for a switch to a skeleton, had one started + expect(factory.builds, 2); + expect(find.text('Reconnecting... (attempt 1 of 5)'), findsOneWidget); + expectHomeUntouched(); + expect(listFetches(d1), 1); // nothing was asked of the dead connection + + // The handshake answers: the banner goes and the list is refreshed over the new transport. + handshake.complete(d2.transport); + await tester.pump(); + await tester.pumpAndSettle(); + expect(session().status, SessionStatus.connected); + expect(session().transport, same(d2.transport)); + expect(d1.transport.closed, isTrue); + expect(find.textContaining('Reconnecting'), findsNothing); + expect(find.text('/db'), findsOneWidget); + expectHomeUntouched(); + expect(listFetches(d1), 1); + // What the reconnect cost: the probe, the events stream and one fetch of each list. The + // dashboard, whose tab is hidden, was not asked for. + expect( + d2.transport.calls.map((c) => '${c.method} ${c.path}'), + unorderedEquals([ + 'GET /_ping', + 'GET /version', + 'STREAM /v1.45/events', + 'GET /v1.45/containers/json', + 'GET /v1.45/images/json', + 'GET /v1.45/networks', + 'GET /v1.45/volumes', + ]), + ); + + // Back: the Connections list shows again and the session is over. + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byType(HomeScreen), findsNothing); + expect(find.byType(ProfilesScreen), findsOneWidget); + expect(find.text('Alpha'), findsOneWidget); + expect(session().status, SessionStatus.disconnected); + expect(session().error, isNull); + expect(d2.transport.closed, isTrue); + expect(d2.activeEventStreams, 0); + }); }