diff --git a/src/SharpClient.App/MauiProgram.cs b/src/SharpClient.App/MauiProgram.cs index 8613fab..8fb52fa 100644 --- a/src/SharpClient.App/MauiProgram.cs +++ b/src/SharpClient.App/MauiProgram.cs @@ -115,7 +115,8 @@ public static MauiApp CreateMauiApp() // Eagerly resolve the coordinator so it begins observing session/connection activity at // startup (DI singletons are otherwise lazily constructed on first request). - app.Services.GetRequiredService(); + var keepAlive = app.Services.GetRequiredService(); + NetworkChangeSignal.Changed += keepAlive.ReconnectAll; return app; } diff --git a/src/SharpClient.App/Platforms/Android/AndroidConnectionKeepAlive.cs b/src/SharpClient.App/Platforms/Android/AndroidConnectionKeepAlive.cs index b2f786f..3f4bcfb 100644 --- a/src/SharpClient.App/Platforms/Android/AndroidConnectionKeepAlive.cs +++ b/src/SharpClient.App/Platforms/Android/AndroidConnectionKeepAlive.cs @@ -16,9 +16,20 @@ internal sealed class AndroidConnectionKeepAlive : IConnectionKeepAlive // service's android26.0 SupportedOSPlatform requirement. internal const string ExtraStatus = "extra_status_text"; + private bool _started; + public void Start(string statusText) { - var ctx = Android.App.Application.Context; + var ctx = Android.App.Application.Context; + + // Android 12+ refuses StartForegroundService while the app is in the background (screen + // locked), so once the service runs a status change only re-posts its notification. + if (_started && OperatingSystem.IsAndroidVersionAtLeast(26)) + { + ConnectionKeepAliveService.UpdateStatus(ctx, statusText); + return; + } + var intent = new Intent(ctx, typeof(ConnectionKeepAliveService)) .PutExtra(ExtraStatus, statusText); @@ -31,10 +42,13 @@ public void Start(string statusText) { ctx.StartService(intent); } + + _started = true; } public void Halt() { + _started = false; var ctx = Android.App.Application.Context; ctx.StopService(new Intent(ctx, typeof(ConnectionKeepAliveService))); } diff --git a/src/SharpClient.App/Platforms/Android/ConnectionKeepAliveService.cs b/src/SharpClient.App/Platforms/Android/ConnectionKeepAliveService.cs index 3bd401a..9ac1fc6 100644 --- a/src/SharpClient.App/Platforms/Android/ConnectionKeepAliveService.cs +++ b/src/SharpClient.App/Platforms/Android/ConnectionKeepAliveService.cs @@ -28,6 +28,9 @@ internal sealed class ConnectionKeepAliveService : Service private const int NotificationId = 1_001; private const string WakeLockTag = "SharpClient::KeepAlive"; + // The text on the notification, kept so a network change can re-post it unchanged. + private static string s_status = "Connected"; + private PowerManager.WakeLock? _wakeLock; private ConnectivityManager? _connectivity; private ConnectivityManager.NetworkCallback? _networkCallback; @@ -39,9 +42,9 @@ internal sealed class ConnectionKeepAliveService : Service [return: GeneratedEnum] public override StartCommandResult OnStartCommand(Intent? intent, [GeneratedEnum] StartCommandFlags flags, int startId) { - EnsureNotificationChannel(); - var status = intent?.GetStringExtra(AndroidConnectionKeepAlive.ExtraStatus) ?? "Connected"; - var notification = BuildNotification(status); + EnsureNotificationChannel(this); + s_status = intent?.GetStringExtra(AndroidConnectionKeepAlive.ExtraStatus) ?? s_status; + var notification = BuildNotification(this, s_status); // On API 29+ supply the foreground service type declared in AndroidManifest.xml. // TypeConnectedDevice = FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE (connectedDevice; API 29+). @@ -157,8 +160,7 @@ private void OnNetworkAvailable(Network network) } _haveSeenNetwork = true; - var nm = (NotificationManager?)GetSystemService(NotificationService); - nm?.Notify(NotificationId, BuildNotification("Connected")); + UpdateStatus(this, s_status); } private void OnNetworkLost(Network network) @@ -171,18 +173,29 @@ private void OnNetworkLost(Network network) } } - private void EnsureNotificationChannel() + /// + /// Changes the text on the running service's notification. Unlike another + /// StartForegroundService, this is allowed while the app is in the background. + /// + internal static void UpdateStatus(Context context, string statusText) + { + s_status = statusText; + var nm = (NotificationManager?)context.GetSystemService(NotificationService); + nm?.Notify(NotificationId, BuildNotification(context, statusText)); + } + + private static void EnsureNotificationChannel(Context context) { var channel = new NotificationChannel(ChannelId, ChannelName, NotificationImportance.Low) { Description = "Keeps the MUSH TCP connection alive while the app is in the background.", }; - var nm = (NotificationManager?)GetSystemService(NotificationService); + var nm = (NotificationManager?)context.GetSystemService(NotificationService); nm?.CreateNotificationChannel(channel); } - private Notification BuildNotification(string statusText) => - new Notification.Builder(this, ChannelId) + private static Notification BuildNotification(Context context, string statusText) => + new Notification.Builder(context, ChannelId) .SetContentTitle("SharpClient") .SetContentText(statusText) .SetSmallIcon(Resource.Drawable.ic_stat_keepalive) diff --git a/src/SharpClient.App/Services/ConnectionKeepAliveCoordinator.cs b/src/SharpClient.App/Services/ConnectionKeepAliveCoordinator.cs deleted file mode 100644 index 2d7fc5d..0000000 --- a/src/SharpClient.App/Services/ConnectionKeepAliveCoordinator.cs +++ /dev/null @@ -1,105 +0,0 @@ -using SharpClient.Core.Connection; -using SharpClient.Core.Sessions; - -namespace SharpClient.App.Services; - -/// -/// App-level glue that starts the platform while at least one -/// telnet session is connected and halts it once none remain. Observes the -/// and each session's so the -/// keep-alive tracks real connection activity without touching Core session logic. -/// -internal sealed class ConnectionKeepAliveCoordinator : IDisposable -{ - private readonly ISessionManager _sessions; - private readonly IConnectionKeepAlive _keepAlive; - private readonly HashSet _tracked = []; - private readonly object _gate = new(); - private bool _running; - - public ConnectionKeepAliveCoordinator(ISessionManager sessions, IConnectionKeepAlive keepAlive) - { - _sessions = sessions; - _keepAlive = keepAlive; - _sessions.Changed += OnSessionsChanged; - NetworkChangeSignal.Changed += OnNetworkChanged; - OnSessionsChanged(); - } - - // The device's default network changed (raised on Android by the keep-alive service). Every - // session's socket is now dead, so force each one to reconnect immediately rather than waiting - // out the Core backoff. ForceReconnectAsync is a no-op for intentionally-disconnected sessions. - private void OnNetworkChanged() - { - foreach (var session in _sessions.Sessions) - { - _ = session.ForceReconnectAsync(); - } - } - - private void OnSessionsChanged() - { - lock (_gate) - { - var current = _sessions.Sessions; - - foreach (var session in current) - { - if (_tracked.Add(session)) - { - session.StateChanged += OnStateChanged; - } - } - - foreach (var session in _tracked.Where(t => !current.Contains(t)).ToList()) - { - session.StateChanged -= OnStateChanged; - _tracked.Remove(session); - } - - Evaluate(); - } - } - - private void OnStateChanged(ConnectionState _) - { - lock (_gate) - { - Evaluate(); - } - } - - private void Evaluate() - { - var connected = _sessions.Sessions.Count(s => s.State == ConnectionState.Connected); - - if (connected > 0) - { - var status = connected == 1 - ? "1 connection active" - : $"{connected} connections active"; - _keepAlive.Start(status); - _running = true; - } - else if (_running) - { - _keepAlive.Halt(); - _running = false; - } - } - - public void Dispose() - { - NetworkChangeSignal.Changed -= OnNetworkChanged; - lock (_gate) - { - _sessions.Changed -= OnSessionsChanged; - foreach (var session in _tracked) - { - session.StateChanged -= OnStateChanged; - } - - _tracked.Clear(); - } - } -} diff --git a/src/SharpClient.App/Services/NetworkChangeSignal.cs b/src/SharpClient.App/Services/NetworkChangeSignal.cs index 3805dcf..ebf12e7 100644 --- a/src/SharpClient.App/Services/NetworkChangeSignal.cs +++ b/src/SharpClient.App/Services/NetworkChangeSignal.cs @@ -3,9 +3,9 @@ namespace SharpClient.App.Services; /// /// Process-wide bridge for "the device's default network changed" events. The Android /// keep-alive service (which owns the connectivity callback but has no session references) -/// raises it; (which has the sessions but is -/// platform-agnostic) listens and forces a reconnect. Keeping it here — not in the Android -/// service type — lets the coordinator subscribe without referencing any Android-only API. +/// raises it; MauiProgram routes it to , +/// which has the sessions. Keeping it here, not in the Android service type, lets that wiring +/// avoid any Android-only API. /// On platforms that never raise it, subscribers simply never fire. /// internal static class NetworkChangeSignal diff --git a/src/SharpClient.Core/Connection/ConnectionKeepAliveCoordinator.cs b/src/SharpClient.Core/Connection/ConnectionKeepAliveCoordinator.cs new file mode 100644 index 0000000..1b18a19 --- /dev/null +++ b/src/SharpClient.Core/Connection/ConnectionKeepAliveCoordinator.cs @@ -0,0 +1,255 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using SharpClient.Core.Sessions; + +namespace SharpClient.Core.Connection; + +/// +/// Runs the platform while any session is connected or on its way +/// back to connected, and halts it a grace period after none are. +/// +/// +/// On Android the keep-alive is a foreground service, and Android 12+ refuses to start one while the +/// app is in the background (screen locked, say). So it must not stop during a reconnect: a session +/// that drops while the phone is locked passes through Reconnecting, or briefly Disconnected on a +/// network-change reconnect, and a keep-alive halted there cannot be started again until the user +/// opens the app. Without it the process loses its wake lock and is frozen, and the session dies. +/// +public sealed partial class ConnectionKeepAliveCoordinator : IDisposable +{ + /// How long the keep-alive outlives the last active session. + public static readonly TimeSpan DefaultHaltGrace = TimeSpan.FromSeconds(15); + + private readonly ISessionManager _sessions; + private readonly IConnectionKeepAlive _keepAlive; + private readonly Func _haltDelay; + private readonly ILogger _logger; + private readonly HashSet _tracked = []; + private readonly object _gate = new(); + private string? _status; + private CancellationTokenSource? _pendingHalt; + private bool _disposed; + + public ConnectionKeepAliveCoordinator( + ISessionManager sessions, + IConnectionKeepAlive keepAlive, + ILogger? logger = null) + : this(sessions, keepAlive, token => Task.Delay(DefaultHaltGrace, token), logger) + { + } + + /// Waits out the grace period before a halt; cancelled when a session becomes active again. + internal ConnectionKeepAliveCoordinator( + ISessionManager sessions, + IConnectionKeepAlive keepAlive, + Func haltDelay, + ILogger? logger = null) + { + _sessions = sessions; + _keepAlive = keepAlive; + _haltDelay = haltDelay; + _logger = logger ?? NullLogger.Instance; + _sessions.Changed += OnSessionsChanged; + OnSessionsChanged(); + } + + /// Whether the keep-alive is running, as far as this coordinator knows. + public bool IsRunning + { + get + { + lock (_gate) + { + return _status is not null; + } + } + } + + /// + /// The device's network changed, so every socket is dead: reconnect each session now instead of + /// waiting out the backoff. A no-op for a session the user disconnected. + /// + public void ReconnectAll() + { + foreach (var session in _sessions.Sessions.ToList()) + { + _ = ReconnectQuietlyAsync(session); + } + } + + private async Task ReconnectQuietlyAsync(ISession session) + { + try + { + await session.ForceReconnectAsync(); + } + catch (Exception ex) + { + LogReconnectFailed(_logger, session.WorldName, ex); + } + } + + private void OnSessionsChanged() + { + lock (_gate) + { + var current = _sessions.Sessions; + + foreach (var session in current) + { + if (_tracked.Add(session)) + { + session.StateChanged += OnStateChanged; + } + } + + foreach (var session in _tracked.Where(t => !current.Contains(t)).ToList()) + { + session.StateChanged -= OnStateChanged; + _tracked.Remove(session); + } + + Evaluate(); + } + } + + // Runs inside the connection's state change. Nothing here may throw: an exception would surface + // in TelnetConnection.SetState and fail the connect or reconnect that raised it. + private void OnStateChanged(ConnectionState _) + { + lock (_gate) + { + Evaluate(); + } + } + + private void Evaluate() + { + if (_disposed) + { + return; + } + + var sessions = _sessions.Sessions; + var connected = sessions.Count(s => s.State == ConnectionState.Connected); + var pending = sessions.Count(s => s.State is ConnectionState.Connecting or ConnectionState.Reconnecting); + + if (connected + pending == 0) + { + ScheduleHalt(); + return; + } + + CancelPendingHalt(); + + var status = connected switch + { + 0 => "Reconnecting…", + 1 => "1 connection active", + _ => $"{connected} connections active", + }; + + if (status == _status) + { + return; + } + + try + { + _keepAlive.Start(status); + _status = status; + } + catch (Exception ex) + { + // Android: ForegroundServiceStartNotAllowedException when this is the first start and the + // app is in the background. The next state change tries again. + LogStartFailed(_logger, ex); + } + } + + private void ScheduleHalt() + { + if (_status is null || _pendingHalt is not null) + { + return; + } + + var cts = new CancellationTokenSource(); + _pendingHalt = cts; + _ = HaltAfterGraceAsync(cts); + } + + private async Task HaltAfterGraceAsync(CancellationTokenSource cts) + { + try + { + await _haltDelay(cts.Token); + } + catch (OperationCanceledException) + { + return; + } + + lock (_gate) + { + if (!ReferenceEquals(_pendingHalt, cts)) + { + return; + } + + _pendingHalt = null; + cts.Dispose(); + Halt(); + } + } + + private void CancelPendingHalt() + { + if (_pendingHalt is null) + { + return; + } + + _pendingHalt.Cancel(); + _pendingHalt.Dispose(); + _pendingHalt = null; + } + + private void Halt() + { + _status = null; + try + { + _keepAlive.Halt(); + } + catch (Exception ex) + { + LogHaltFailed(_logger, ex); + } + } + + public void Dispose() + { + lock (_gate) + { + _disposed = true; + CancelPendingHalt(); + _sessions.Changed -= OnSessionsChanged; + foreach (var session in _tracked) + { + session.StateChanged -= OnStateChanged; + } + + _tracked.Clear(); + } + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Reconnect after a network change failed for {World}")] + private static partial void LogReconnectFailed(ILogger logger, string world, Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not start the connection keep-alive")] + private static partial void LogStartFailed(ILogger logger, Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not stop the connection keep-alive")] + private static partial void LogHaltFailed(ILogger logger, Exception exception); +} diff --git a/src/SharpClient.Core/Connection/IConnectionKeepAlive.cs b/src/SharpClient.Core/Connection/IConnectionKeepAlive.cs index 946be5a..1a21c5b 100644 --- a/src/SharpClient.Core/Connection/IConnectionKeepAlive.cs +++ b/src/SharpClient.Core/Connection/IConnectionKeepAlive.cs @@ -7,7 +7,7 @@ namespace SharpClient.Core.Connection; /// /// /// Registered in DI in the App head (Android: a foreground service proxy; other platforms: a no-op) -/// and driven by ConnectionKeepAliveCoordinator off the session lifecycle. Socket-level SO_KEEPALIVE +/// and driven by off the session lifecycle. Socket-level SO_KEEPALIVE /// and telnet-NOP keepalive remain owned by the Core connection layer. /// public interface IConnectionKeepAlive diff --git a/tests/SharpClient.Tests/Connection/ConnectionKeepAliveCoordinatorTests.cs b/tests/SharpClient.Tests/Connection/ConnectionKeepAliveCoordinatorTests.cs new file mode 100644 index 0000000..ccb91ab --- /dev/null +++ b/tests/SharpClient.Tests/Connection/ConnectionKeepAliveCoordinatorTests.cs @@ -0,0 +1,172 @@ +using SharpClient.Core.Connection; +using SharpClient.Core.Sessions; +using SharpClient.Tests.Sessions; + +namespace SharpClient.Tests.Connection; + +public sealed class ConnectionKeepAliveCoordinatorTests +{ + private sealed class FakeKeepAlive : IConnectionKeepAlive + { + public List Starts { get; } = []; + public int Halts { get; private set; } + public Exception? StartFailure { get; set; } + + public void Start(string statusText) + { + if (StartFailure is { } ex) + { + throw ex; + } + + Starts.Add(statusText); + } + + public void Halt() => Halts++; + } + + // Stands in for the grace period: a halt waits until the test calls Elapse. + private sealed class ManualDelay + { + private TaskCompletionSource _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public int Waits { get; private set; } + + public Task WaitAsync(CancellationToken token) + { + Waits++; + _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + token.Register(() => _tcs.TrySetCanceled(token)); + return _tcs.Task; + } + + public void Elapse() => _tcs.TrySetResult(); + } + + private static (SessionManager Sessions, FakeKeepAlive KeepAlive, ManualDelay Delay, ConnectionKeepAliveCoordinator Coordinator) Create() + { + var sessions = new SessionManager(); + var keepAlive = new FakeKeepAlive(); + var delay = new ManualDelay(); + var coordinator = new ConnectionKeepAliveCoordinator(sessions, keepAlive, delay.WaitAsync); + return (sessions, keepAlive, delay, coordinator); + } + + private static async Task WaitUntilAsync(Func condition) + { + for (var i = 0; i < 200 && !condition(); i++) + { + await Task.Delay(10); + } + } + + [Test] + public async Task StartsWhenASessionConnects() + { + var (sessions, keepAlive, _, coordinator) = Create(); + + sessions.Add(new FakeSession { State = ConnectionState.Connected }); + + await Assert.That(keepAlive.Starts).IsEquivalentTo(["1 connection active"]); + await Assert.That(coordinator.IsRunning).IsTrue(); + } + + [Test] + public async Task KeepsRunningWhileASessionReconnects() + { + var (sessions, keepAlive, delay, _) = Create(); + var session = new FakeSession { State = ConnectionState.Connected }; + sessions.Add(session); + + session.RaiseState(ConnectionState.Reconnecting); + session.RaiseState(ConnectionState.Connected); + + await Assert.That(keepAlive.Halts).IsEqualTo(0); + await Assert.That(delay.Waits).IsEqualTo(0); + await Assert.That(keepAlive.Starts).IsEquivalentTo(["1 connection active", "Reconnecting…", "1 connection active"]); + } + + [Test] + public async Task NetworkChangeReconnectPassingThroughDisconnectedDoesNotHalt() + { + // ForceReconnectAsync tears the old socket down first, so the session is briefly Disconnected. + var (sessions, keepAlive, delay, _) = Create(); + var session = new FakeSession { State = ConnectionState.Connected }; + sessions.Add(session); + + session.RaiseState(ConnectionState.Disconnected); + session.RaiseState(ConnectionState.Connecting); + session.RaiseState(ConnectionState.Connected); + delay.Elapse(); + await Task.Delay(50); + + await Assert.That(keepAlive.Halts).IsEqualTo(0); + await Assert.That(keepAlive.Starts[^1]).IsEqualTo("1 connection active"); + } + + [Test] + public async Task HaltsOnceTheGracePeriodPassesWithNothingActive() + { + var (sessions, keepAlive, delay, coordinator) = Create(); + var session = new FakeSession { State = ConnectionState.Connected }; + sessions.Add(session); + + session.RaiseState(ConnectionState.Disconnected); + await Assert.That(keepAlive.Halts).IsEqualTo(0); + + delay.Elapse(); + await WaitUntilAsync(() => keepAlive.Halts > 0); + + await Assert.That(keepAlive.Halts).IsEqualTo(1); + await Assert.That(coordinator.IsRunning).IsFalse(); + } + + [Test] + public async Task DoesNotRestartForAnUnchangedStatus() + { + var (sessions, keepAlive, _, _) = Create(); + var session = new FakeSession { State = ConnectionState.Connected }; + sessions.Add(session); + + sessions.Add(new FakeSession { State = ConnectionState.Disconnected }); + session.RaiseState(ConnectionState.Connected); + + await Assert.That(keepAlive.Starts).IsEquivalentTo(["1 connection active"]); + } + + [Test] + public async Task AStartThatThrowsDoesNotReachTheConnection() + { + // Android refuses a foreground-service start from the background; that must not fail the + // reconnect whose state change asked for it. + var (sessions, keepAlive, _, coordinator) = Create(); + var session = new FakeSession { State = ConnectionState.Disconnected }; + sessions.Add(session); + keepAlive.StartFailure = new InvalidOperationException("ForegroundServiceStartNotAllowed"); + + session.RaiseState(ConnectionState.Connected); + + await Assert.That(coordinator.IsRunning).IsFalse(); + + keepAlive.StartFailure = null; + session.RaiseState(ConnectionState.Reconnecting); + + await Assert.That(keepAlive.Starts).IsEquivalentTo(["Reconnecting…"]); + } + + [Test] + public async Task ReconnectAllForcesEverySessionAndSwallowsFailures() + { + var (sessions, _, _, coordinator) = Create(); + var a = new FakeSession { ForceReconnectFailure = new IOException("network unreachable") }; + var b = new FakeSession(); + sessions.Add(a); + sessions.Add(b); + + coordinator.ReconnectAll(); + await Task.Delay(20); + + await Assert.That(a.ForceReconnects).IsEqualTo(1); + await Assert.That(b.ForceReconnects).IsEqualTo(1); + } +} diff --git a/tests/SharpClient.Tests/Sessions/FakeSession.cs b/tests/SharpClient.Tests/Sessions/FakeSession.cs index 1482e0f..56b627d 100644 --- a/tests/SharpClient.Tests/Sessions/FakeSession.cs +++ b/tests/SharpClient.Tests/Sessions/FakeSession.cs @@ -32,6 +32,16 @@ public Task SendWindowSizeAsync(int cols, int rows) return Task.CompletedTask; } + public int ForceReconnects { get; private set; } + + public Exception? ForceReconnectFailure { get; set; } + + public Task ForceReconnectAsync() + { + ForceReconnects++; + return ForceReconnectFailure is { } ex ? Task.FromException(ex) : Task.CompletedTask; + } + public void RaiseState(ConnectionState state) { State = state;