fix(app): exit without waiting for the UI thread, close the editor with the shell, cancel sign-in safely
DESK-1: SyncHost's dispose, session switch and stop now continue on the thread pool (ConfigureAwait(false)) and keep the running agent in one reference. A signed-in user whose archive is not polled no longer waits 10 s at every exit, after which the job engine and the index were never closed. DESK-7: ShellViewModel.Dispose disposes the Sequence section first, so the open editor stops its runners and closes its source before the engine and the index go. DESK-8: Cancel stays available while the server answers a sign-in. It now cancels the request; an answer that still arrives changes nothing (the connection flow ignores answers for a client it dropped), and a sign-in that completed just before the cancel was handled is signed out again. The form no longer sets a result after it closed, and an unexpected failure shows inline instead of escaping async void. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
8 files changed
+345
-35
No files matched your search
@@ -131,23 +131,28 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
|
|||||||
return await IdentifyAsync(ct);
|
return await IdentifyAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Sends the credentials; only possible once the server is identified and trusted.</summary>
|
/// <summary>
|
||||||
|
/// Sends the credentials; only possible once the server is identified and trusted. An answer that arrives after the
|
||||||
|
/// flow moved on (disconnected, or connecting elsewhere) changes nothing.
|
||||||
|
/// </summary>
|
||||||
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
|
public async Task<ConnectStep> SignInAsync(string username, string password, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) return Step;
|
if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is not { } api) return Step;
|
||||||
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
|
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
|
||||||
Set(ConnectStep.SigningIn, ConnectError.None);
|
Set(ConnectStep.SigningIn, ConnectError.None);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var login = await _api.LoginAsync(username.Trim(), password, ct);
|
var login = await api.LoginAsync(username.Trim(), password, ct);
|
||||||
|
if (!ReferenceEquals(api, _api)) return Step;
|
||||||
if (login.Token is null) return Retry(ConnectError.BadCredentials);
|
if (login.Token is null) return Retry(ConnectError.BadCredentials);
|
||||||
// TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
|
// TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
|
||||||
_api.Token = login.Token;
|
api.Token = login.Token;
|
||||||
User = login.User;
|
User = login.User;
|
||||||
return Set(ConnectStep.Connected, ConnectError.None);
|
return Set(ConnectStep.Connected, ConnectError.None);
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
catch (Exception ex) when (Classify(ex, ct) is { } error)
|
||||||
{
|
{
|
||||||
|
if (!ReferenceEquals(api, _api)) return Step;
|
||||||
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
|
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,17 +144,23 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
|
|||||||
if (step != ConnectStep.AwaitingCredentials) return false;
|
if (step != ConnectStep.AwaitingCredentials) return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The form may be cancelled while the server is still answering: that answer must not sign this PC in.
|
||||||
|
using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
|
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
|
||||||
{
|
{
|
||||||
var result = await _flow.SignInAsync(user, password, ct);
|
var result = await _flow.SignInAsync(user, password, attempt.Token);
|
||||||
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
|
// An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own.
|
||||||
|
return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error);
|
||||||
});
|
});
|
||||||
if (signedIn && IsConnected)
|
if (signedIn && IsConnected)
|
||||||
{
|
{
|
||||||
Remember();
|
Remember();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _flow.Disconnect();
|
await attempt.CancelAsync();
|
||||||
|
// Signed in just before the cancel was handled: the session the user turned down ends on the server too.
|
||||||
|
if (IsConnected) await _flow.SignOutAsync();
|
||||||
|
else if (_flow.Step is ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) _flow.Disconnect();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
|
|
||||||
private Task _switch = Task.CompletedTask;
|
private Task _switch = Task.CompletedTask;
|
||||||
private Credentials? _credentials;
|
private Credentials? _credentials;
|
||||||
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
|
private Running? _running;
|
||||||
private JobEngine? _renders;
|
private JobEngine? _renders;
|
||||||
|
|
||||||
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
||||||
@@ -44,10 +44,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
public SyncService? Service { get; private set; }
|
public SyncService? Service { get; private set; }
|
||||||
|
|
||||||
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
|
/// <summary>The background comparison of the signed-in server; null while signed out.</summary>
|
||||||
public SyncAgent? Agent => _running?.Agent;
|
public SyncAgent? Agent => Volatile.Read(ref _running)?.Agent;
|
||||||
|
|
||||||
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
||||||
public ISyncRemote? Remote => _running?.Remote;
|
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
|
||||||
|
|
||||||
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
|
/// <summary>Key of the signed-in server (<see cref="SyncService.ServerKey"/>); null while signed out.</summary>
|
||||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
||||||
@@ -103,8 +103,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
||||||
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
|
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await _switch;
|
await _switch.ConfigureAwait(false);
|
||||||
return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
|
return Agent is { } agent ? await agent.RefreshAsync(ct).ConfigureAwait(false) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
|
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
|
||||||
@@ -135,13 +135,17 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stops the agent once the session switch in progress settled. The app's exit waits for this on the UI thread, so
|
||||||
|
/// nothing here, in the switch or in the stop continues on it.
|
||||||
|
/// </summary>
|
||||||
public async ValueTask DisposeAsync()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
Volatile.Write(ref _credentials, null);
|
Volatile.Write(ref _credentials, null);
|
||||||
Uploads.Dispose();
|
Uploads.Dispose();
|
||||||
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
||||||
await _switch;
|
await _switch.ConfigureAwait(false);
|
||||||
await StopAsync();
|
await StopAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
|
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
|
||||||
@@ -183,11 +187,16 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
|
||||||
|
/// the old agent when the app exits must not need the UI thread its exit blocks.
|
||||||
|
/// </summary>
|
||||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||||
{
|
{
|
||||||
await previous;
|
await previous.ConfigureAwait(false);
|
||||||
if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
|
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
|
||||||
await StopAsync();
|
return;
|
||||||
|
await StopAsync().ConfigureAwait(false);
|
||||||
if (wanted is not { } start || Service is not { } service)
|
if (wanted is not { } start || Service is not { } service)
|
||||||
{
|
{
|
||||||
Changed?.Invoke();
|
Changed?.Invoke();
|
||||||
@@ -197,19 +206,21 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
|||||||
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
|
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
|
||||||
agent.Changed += () => Changed?.Invoke();
|
agent.Changed += () => Changed?.Invoke();
|
||||||
agent.Start();
|
agent.Start();
|
||||||
_running = (agent, remote, start);
|
Volatile.Write(ref _running, new Running(agent, remote, start));
|
||||||
Log.Info("sync", $"Comparing with {remote.Server}");
|
Log.Info("sync", $"Comparing with {remote.Server}");
|
||||||
Changed?.Invoke();
|
Changed?.Invoke();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task StopAsync()
|
private async Task StopAsync()
|
||||||
{
|
{
|
||||||
if (_running is not { } running) return;
|
if (Interlocked.Exchange(ref _running, null) is not { } running) return;
|
||||||
_running = null;
|
await running.Agent.DisposeAsync().ConfigureAwait(false);
|
||||||
await running.Agent.DisposeAsync();
|
|
||||||
running.Remote.Dispose();
|
running.Remote.Dispose();
|
||||||
Changed?.Invoke();
|
Changed?.Invoke();
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
||||||
|
|
||||||
|
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
|
||||||
|
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Automation;
|
using System.Windows.Automation;
|
||||||
using System.Windows.Automation.Peers;
|
using System.Windows.Automation.Peers;
|
||||||
|
using Titano.Core.Diagnostics;
|
||||||
using Titano.Ui.Controls;
|
using Titano.Ui.Controls;
|
||||||
|
|
||||||
namespace Titano.App.Shell;
|
namespace Titano.App.Shell;
|
||||||
@@ -9,16 +10,20 @@ namespace Titano.App.Shell;
|
|||||||
/// The login form (BRIEF §12.7). It calls back the connection with the credentials and stays open with the
|
/// The login form (BRIEF §12.7). It calls back the connection with the credentials and stays open with the
|
||||||
/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
|
/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
|
||||||
/// except for that call. A failed sign-in is announced to screen readers and marks the password box (error border,
|
/// except for that call. A failed sign-in is announced to screen readers and marks the password box (error border,
|
||||||
/// sentence as its help text) until the next attempt.
|
/// sentence as its help text) until the next attempt. Cancel stays available while the server answers: the form
|
||||||
|
/// closes at once and the connection drops the answer.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed partial class LoginDialog : TitanoWindow
|
public sealed partial class LoginDialog : TitanoWindow
|
||||||
{
|
{
|
||||||
private readonly Func<string, string, Task<string?>> _signIn;
|
private readonly Func<string, string, Task<string?>> _signIn;
|
||||||
|
private bool _pending;
|
||||||
|
private bool _closed;
|
||||||
|
|
||||||
private LoginDialog(string server, string? username, Func<string, string, Task<string?>> signIn)
|
private LoginDialog(string server, string? username, Func<string, string, Task<string?>> signIn)
|
||||||
{
|
{
|
||||||
_signIn = signIn;
|
_signIn = signIn;
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
Closed += (_, _) => _closed = true;
|
||||||
ServerText.Text = server;
|
ServerText.Text = server;
|
||||||
User.Text = username ?? string.Empty;
|
User.Text = username ?? string.Empty;
|
||||||
Loaded += (_, _) =>
|
Loaded += (_, _) =>
|
||||||
@@ -41,28 +46,41 @@ public sealed partial class LoginDialog : TitanoWindow
|
|||||||
|
|
||||||
private async void OnSignIn(object sender, RoutedEventArgs e)
|
private async void OnSignIn(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
|
if (_pending) return;
|
||||||
|
_pending = true;
|
||||||
SignIn.IsEnabled = false;
|
SignIn.IsEnabled = false;
|
||||||
Error.Visibility = Visibility.Collapsed;
|
Error.Visibility = Visibility.Collapsed;
|
||||||
Field.SetError(Password, null);
|
Field.SetError(Password, null);
|
||||||
|
string? error;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var error = await _signIn(User.Text, Password.Password);
|
error = await _signIn(User.Text, Password.Password);
|
||||||
if (error is null)
|
}
|
||||||
{
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
DialogResult = true;
|
{
|
||||||
return;
|
// Cancel ended the request: nobody waits for this answer any more.
|
||||||
}
|
if (_closed && ex is OperationCanceledException) return;
|
||||||
Error.Text = error;
|
Log.Warning("server", "Sign-in failed", ex);
|
||||||
Error.Visibility = Visibility.Visible;
|
error = ErrorText.For(ex);
|
||||||
Field.SetError(Password, error);
|
|
||||||
Password.Clear();
|
|
||||||
Password.Focus();
|
|
||||||
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
|
|
||||||
AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
|
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
_pending = false;
|
||||||
SignIn.IsEnabled = true;
|
SignIn.IsEnabled = true;
|
||||||
}
|
}
|
||||||
|
// The form was cancelled or closed while the server answered: a result can no longer be set on it.
|
||||||
|
if (_closed) return;
|
||||||
|
if (error is null)
|
||||||
|
{
|
||||||
|
DialogResult = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Error.Text = error;
|
||||||
|
Error.Visibility = Visibility.Visible;
|
||||||
|
Field.SetError(Password, error);
|
||||||
|
Password.Clear();
|
||||||
|
Password.Focus();
|
||||||
|
UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
|
||||||
|
AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -292,6 +292,8 @@ public sealed class ShellViewModel : LocalizedViewModel
|
|||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
|
// The editor first: it stops its runners and closes its source before the engine and the index under it go.
|
||||||
|
Sequence.Dispose();
|
||||||
Jobs.Dispose();
|
Jobs.Dispose();
|
||||||
Library.Dispose();
|
Library.Dispose();
|
||||||
Import.Dispose();
|
Import.Dispose();
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Titano.App.Infrastructure;
|
||||||
|
using Titano.App.Server;
|
||||||
|
using Titano.Protocol;
|
||||||
|
using Titano.Protocol.Client;
|
||||||
|
using Titano.Testing;
|
||||||
|
|
||||||
|
namespace Titano.App.Tests.Server;
|
||||||
|
|
||||||
|
/// <summary>The login form cancelled while the server is still answering (DESK-8): nothing signs this PC in afterwards.</summary>
|
||||||
|
public sealed class ServerSessionSignInTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task CancelEndsTheSignInStillWaitingForTheServer()
|
||||||
|
{
|
||||||
|
var server = new GatedServer { HonoursCancellation = true };
|
||||||
|
var settings = new AppSettings();
|
||||||
|
using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
|
||||||
|
Task<string?>? pending = null;
|
||||||
|
var dialogs = new Dialogs((_, _, signIn) =>
|
||||||
|
{
|
||||||
|
pending = signIn("alberto", "secret");
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
|
||||||
|
// The request the form left behind was cancelled, and the session dropped the connection it belonged to.
|
||||||
|
await Assert.ThrowsAsync<OperationCanceledException>(() => pending!);
|
||||||
|
Assert.False(session.IsConnected);
|
||||||
|
Assert.Equal(ConnectStep.Idle, session.Flow.Step);
|
||||||
|
Assert.Null(settings.ProtectedToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AnAnswerArrivingAfterCancelSignsNothingIn()
|
||||||
|
{
|
||||||
|
var server = new GatedServer { HonoursCancellation = false };
|
||||||
|
var settings = new AppSettings();
|
||||||
|
using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
|
||||||
|
Task<string?>? pending = null;
|
||||||
|
var dialogs = new Dialogs((_, _, signIn) =>
|
||||||
|
{
|
||||||
|
pending = signIn("alberto", "secret");
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
|
||||||
|
// The server accepts the password only now: the answer belongs to a connection that is gone.
|
||||||
|
server.Answer();
|
||||||
|
Assert.NotNull(await pending!);
|
||||||
|
Assert.False(session.IsConnected);
|
||||||
|
Assert.Equal(ConnectStep.Idle, session.Flow.Step);
|
||||||
|
Assert.Null(session.Flow.Token);
|
||||||
|
Assert.Null(settings.ProtectedToken);
|
||||||
|
Assert.Null(settings.ServerUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SignedInJustBeforeTheCancelSignsOutAgain()
|
||||||
|
{
|
||||||
|
var server = new GatedServer { HonoursCancellation = false };
|
||||||
|
server.Answer();
|
||||||
|
var settings = new AppSettings();
|
||||||
|
using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
|
||||||
|
var dialogs = new Dialogs((_, _, signIn) =>
|
||||||
|
{
|
||||||
|
// The server's answer was handled first, then the click on Cancel closed the form.
|
||||||
|
Assert.Null(signIn("alberto", "secret").GetAwaiter().GetResult());
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
|
||||||
|
Assert.False(session.IsConnected);
|
||||||
|
Assert.Equal(1, server.Logouts);
|
||||||
|
Assert.Null(settings.ProtectedToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ASignInTheFormConfirmsIsRemembered()
|
||||||
|
{
|
||||||
|
var server = new GatedServer { HonoursCancellation = true };
|
||||||
|
server.Answer();
|
||||||
|
var settings = new AppSettings();
|
||||||
|
using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
|
||||||
|
var dialogs = new Dialogs((_, _, signIn) => signIn("alberto", "secret").GetAwaiter().GetResult() is null);
|
||||||
|
|
||||||
|
Assert.True(await session.ConnectAsync("nas.local:8443", dialogs));
|
||||||
|
Assert.True(session.IsConnected);
|
||||||
|
Assert.Equal("token-1", settings.ProtectedToken);
|
||||||
|
Assert.Equal(0, server.Logouts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Dialogs(Func<string, string?, Func<string, string, Task<string?>>, bool> signIn) : IAppDialogs
|
||||||
|
{
|
||||||
|
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||||
|
public string? PickJsonFile(string title) => null;
|
||||||
|
public bool Confirm(ConfirmRequest request) => true;
|
||||||
|
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> callback) => signIn(server, username, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class PlainProtector : ITokenProtector
|
||||||
|
{
|
||||||
|
public string Protect(string token) => token;
|
||||||
|
public string? Unprotect(string protectedToken) => protectedToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A server whose login answers only when the test says so.</summary>
|
||||||
|
private sealed class GatedServer : IServerApiFactory
|
||||||
|
{
|
||||||
|
private readonly TaskCompletionSource _answer = new();
|
||||||
|
|
||||||
|
/// <summary>The request ends when its token is cancelled (as over HTTP); otherwise the answer is already on its way.</summary>
|
||||||
|
public bool HonoursCancellation { get; init; }
|
||||||
|
|
||||||
|
public int Logins { get; private set; }
|
||||||
|
public int Logouts { get; private set; }
|
||||||
|
|
||||||
|
public void Answer() => _answer.TrySetResult();
|
||||||
|
|
||||||
|
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new Client(this, baseAddress);
|
||||||
|
|
||||||
|
private sealed class Client(GatedServer server, Uri baseAddress) : IServerApi
|
||||||
|
{
|
||||||
|
public Uri BaseAddress { get; } = baseAddress;
|
||||||
|
public string? Token { get; set; }
|
||||||
|
|
||||||
|
public Task<ServerInfo> GetInfoAsync(CancellationToken ct) =>
|
||||||
|
Task.FromResult(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0)));
|
||||||
|
|
||||||
|
public async Task<LoginResponse> LoginAsync(string username, string password, CancellationToken ct)
|
||||||
|
{
|
||||||
|
server.Logins++;
|
||||||
|
await (server.HonoursCancellation ? server._answer.Task.WaitAsync(ct) : server._answer.Task);
|
||||||
|
if (password != "secret") throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("bad_credentials", "Wrong"));
|
||||||
|
return new LoginResponse("token-" + server.Logins, User(username), false, DateTimeOffset.UtcNow.AddDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<UserDto> MeAsync(CancellationToken ct) => Task.FromResult(User("alberto"));
|
||||||
|
|
||||||
|
public Task LogoutAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
server.Logouts++;
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
private static UserDto User(string name) =>
|
||||||
|
new(Guid.Empty, name, null, "editor", 0, 5_000_000_000_000, 0, false, false, DateTimeOffset.UtcNow, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using Titano.App.DesignTime;
|
||||||
|
using Titano.App.Infrastructure;
|
||||||
|
using Titano.App.Tests.Uploader;
|
||||||
|
using Titano.Testing;
|
||||||
|
|
||||||
|
namespace Titano.App.Tests.Server;
|
||||||
|
|
||||||
|
public sealed class SyncHostTests
|
||||||
|
{
|
||||||
|
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
|
||||||
|
private sealed class NoDialogs : IAppDialogs
|
||||||
|
{
|
||||||
|
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||||
|
public string? PickJsonFile(string title) => null;
|
||||||
|
public bool Confirm(ConfirmRequest request) => false;
|
||||||
|
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DESK-1: a signed-in user whose archive is not polled (no archive, or offline at start) exits. Nothing before the
|
||||||
|
/// sync agent's stop leaves the UI thread, and the agent stops asynchronously: its continuation must not need the UI
|
||||||
|
/// thread that App.OnExit blocks, or the exit waits 10 s and never closes the engine and the index.
|
||||||
|
/// </summary>
|
||||||
|
[Test]
|
||||||
|
[WindowsOnly]
|
||||||
|
public void ExitWithASignedInSessionAndNoPollingDoesNotWaitForTheUiThread()
|
||||||
|
{
|
||||||
|
var environment = AppEnvironment.ForCapture();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SingleThreadedContext.Run(async () =>
|
||||||
|
{
|
||||||
|
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
|
||||||
|
var sample = SampleData.Configure(services);
|
||||||
|
// An index without the archive poller (OpenAsync never ran) and a saved session, as for a server-only user.
|
||||||
|
await sample.OpenEmptyAsync();
|
||||||
|
await sample.FillAsync();
|
||||||
|
services.Settings.RenderNodeOptIn = false;
|
||||||
|
await services.Server.RestoreAsync();
|
||||||
|
Assert.True(services.Server.IsConnected, "session restored");
|
||||||
|
var until = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||||
|
while (services.Sync.Agent is null)
|
||||||
|
{
|
||||||
|
Assert.True(DateTime.UtcNow < until, "sync agent not started");
|
||||||
|
await Task.Delay(20);
|
||||||
|
}
|
||||||
|
|
||||||
|
// App.OnExit blocks the UI thread until the services stop.
|
||||||
|
var clock = Stopwatch.StartNew();
|
||||||
|
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
|
||||||
|
Assert.Less(clock.Elapsed.TotalSeconds, 5, "the exit waited for the UI thread");
|
||||||
|
Assert.Null(services.Sync.Agent);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
environment.DeleteCaptureData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using Titano.App.DesignTime;
|
||||||
|
using Titano.App.Infrastructure;
|
||||||
|
using Titano.App.Shell;
|
||||||
|
using Titano.Testing;
|
||||||
|
using Titano.Ui.Theming;
|
||||||
|
|
||||||
|
namespace Titano.App.Tests.Windows;
|
||||||
|
|
||||||
|
/// <summary>What the shell stops when the app exits (App.OnExit disposes it before the services).</summary>
|
||||||
|
[WindowsOnly]
|
||||||
|
[Serial]
|
||||||
|
[Timeout(120_000)]
|
||||||
|
public sealed class ShellLifetimeTests
|
||||||
|
{
|
||||||
|
private sealed class NoDialogs : IAppDialogs
|
||||||
|
{
|
||||||
|
public string? PickFolder(string title, string? initialFolder = null) => null;
|
||||||
|
public string? PickJsonFile(string title) => null;
|
||||||
|
public bool Confirm(ConfirmRequest request) => false;
|
||||||
|
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>DESK-7: the open editor goes with the shell, before the engine and the index under it.</summary>
|
||||||
|
[Test]
|
||||||
|
public Task DisposingTheShellClosesTheOpenEditor() => ScreenHost.RunAsync(async () =>
|
||||||
|
{
|
||||||
|
var environment = AppEnvironment.ForCapture();
|
||||||
|
UiLanguage.Apply("en");
|
||||||
|
ThemeManager.Apply(AppTheme.Dark);
|
||||||
|
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var sample = SampleData.Configure(services);
|
||||||
|
var shell = new ShellViewModel(services);
|
||||||
|
await sample.OpenEmptyAsync();
|
||||||
|
await shell.StartAsync();
|
||||||
|
var id = await sample.FillEditorAsync();
|
||||||
|
shell.OpenSequence(id);
|
||||||
|
await shell.Sequence.OpenAsync(id);
|
||||||
|
var editor = Assert.NotNull(shell.Sequence.Editor);
|
||||||
|
editor.PlayCommand.Execute(null);
|
||||||
|
Assert.True(editor.IsPlaying, "the editor plays");
|
||||||
|
|
||||||
|
shell.Dispose();
|
||||||
|
Assert.False(editor.IsPlaying, "the editor's player stopped with the shell");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await services.DisposeAsync();
|
||||||
|
environment.DeleteCaptureData();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user