feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
1 parent
988068ee8e
commit
20d64af4a4
793 files changed
+23882
-2096
No files matched your search
@@ -1,10 +1,14 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Editor;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Homes;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
@@ -13,8 +17,14 @@ using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Server;
|
||||
|
||||
/// <summary>Makes the sync connection of a signed-in session.</summary>
|
||||
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
/// <summary>Makes the sync connection of a signed-in session; <paramref name="server"/> is the key it names the server by (<see cref="SyncHost.Server"/>).</summary>
|
||||
public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints, string server);
|
||||
|
||||
/// <summary>
|
||||
/// Where Download originals puts a server sequence's photos (<see cref="SyncHost.OriginalsArchiveAsync"/>): the archive's id,
|
||||
/// and its root when it was made just now (the first download from that server); a null id when there is none to use.
|
||||
/// </summary>
|
||||
public sealed record OriginalsTarget(Guid? ArchiveId, string? Created = null);
|
||||
|
||||
/// <summary>
|
||||
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
|
||||
@@ -24,25 +34,37 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
|
||||
/// (<see cref="ConnectEditor"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
|
||||
/// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) and the Export "Sync" of finished renders
|
||||
/// (<see cref="ExportSync"/>). Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
|
||||
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
|
||||
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>. A server that announces
|
||||
/// its stable id (owner review 5, #66) is keyed by it (<see cref="Server"/>) and recorded in
|
||||
/// <see cref="AppSettings.KnownServers"/> with the address keys it was reached under, which match it all the same
|
||||
/// (<see cref="Identity"/>); at a sign-in that tells its id, what this PC keeps under those addresses moves to its id
|
||||
/// (<see cref="HomeLayoutMigration.RekeyAsync"/>) before the agent starts.
|
||||
/// </summary>
|
||||
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
|
||||
{
|
||||
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
|
||||
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>Jobs that write into the workspace or the servers' homes in the cache: the move of the folders to a server's id waits for them.</summary>
|
||||
private static readonly JobKind[] RekeyHeldBy =
|
||||
[JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove, JobKind.Download, JobKind.UploadCommit, JobKind.VideoCopy];
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private Task _switch = Task.CompletedTask;
|
||||
private Credentials? _credentials;
|
||||
private Running? _running;
|
||||
private JobEngine? _renders;
|
||||
|
||||
/// <summary>The alias table of <see cref="AppSettings.KnownServers"/>, made again whenever a sign-in records a server.</summary>
|
||||
private ServerIdentity _identity = services.Settings.KnownIdentity();
|
||||
|
||||
/// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary>
|
||||
private SharedClient? _projects;
|
||||
|
||||
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted, server) =>
|
||||
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true,
|
||||
server);
|
||||
|
||||
/// <summary>Connections of editors of server sequences over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
|
||||
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
|
||||
@@ -61,8 +83,28 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <summary>The agent's connection, for the table's own calls (conflict resolution); null while signed out.</summary>
|
||||
public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
|
||||
|
||||
/// <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;
|
||||
/// <summary>
|
||||
/// Key of the signed-in server: its id key when it announced its id (<see cref="ServerIdentity.Key(Guid?, Uri)"/>), else
|
||||
/// its address key (<see cref="SyncService.ServerKey"/>); null while signed out.
|
||||
/// </summary>
|
||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? c.Key : null;
|
||||
|
||||
/// <summary>The servers known by id and the address keys each was reached under (any thread).</summary>
|
||||
public ServerIdentity Identity => Volatile.Read(ref _identity);
|
||||
|
||||
/// <summary>
|
||||
/// A known server id came back with another TLS certificate and another name (owner review 5: a copied server database,
|
||||
/// two servers sharing one id): the server's name now, and the name it had (UI thread).
|
||||
/// </summary>
|
||||
public event Action<string, string>? IdentityClash;
|
||||
|
||||
/// <summary>The key a server reached at <paramref name="address"/> goes by: the signed-in one's when it is that server, else its address key mapped through the aliases.</summary>
|
||||
public string KeyOf(Uri address)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
if (Volatile.Read(ref _credentials) is { } c && c.Address == address) return c.Key;
|
||||
return Identity.Canonical(SyncService.ServerKey(address));
|
||||
}
|
||||
|
||||
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
|
||||
@@ -97,15 +139,15 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <summary>
|
||||
/// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's
|
||||
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
|
||||
/// shows the project offline and its work waits.
|
||||
/// shows the project offline and its work waits. A home named by an address the signed-in server was reached under before
|
||||
/// it told its id is that server's all the same (owner review 5).
|
||||
/// </summary>
|
||||
public IProjectHome? ProjectHome(BundleHome home)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
|
||||
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
|
||||
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials || !Identity.Same(home.Server, credentials.Key))
|
||||
return null;
|
||||
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat);
|
||||
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName, SettingsFormat, credentials.Key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -121,14 +163,23 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
/// <summary>Creates the engine over the open index; the proxy cache lives in the client's cache folder.</summary>
|
||||
/// <summary>
|
||||
/// Creates the engine over the open index; the proxy cache lives in the client's cache folder, one home per server
|
||||
/// (<c><cache>\servers\<folder>\proxies</c>, owner review 5), read where 1.0 put it until it is moved.
|
||||
/// </summary>
|
||||
public SyncService Open(ChronosDatabase database, Chronos.Data.Archiving.ArchiveService archives, Chronos.Data.Archiving.ArchiveServiceOptions options)
|
||||
{
|
||||
var cache = CacheStore.Folder(services.Environment, services.Settings);
|
||||
Service = new SyncService(database, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = Path.Combine(cache, "proxies") });
|
||||
Service = new SyncService(database, archives, new SyncOptions
|
||||
{
|
||||
Archive = options,
|
||||
ProxyCacheDirectory = Path.Combine(cache, HomeLayoutMigration.LegacyProxies),
|
||||
ServersDirectory = CacheStore.ServersFolder(cache),
|
||||
Identity = () => Identity,
|
||||
});
|
||||
Service.Changed += server =>
|
||||
{
|
||||
if (server == Server) Changed?.Invoke();
|
||||
if (Server is { } signedIn && Identity.Same(server, signedIn)) Changed?.Invoke();
|
||||
};
|
||||
return Service;
|
||||
}
|
||||
@@ -138,8 +189,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
{
|
||||
var session = services.Server;
|
||||
Credentials? wanted = session.IsConnected && session.Flow is { Address: { } address, Token: { } token }
|
||||
? new Credentials(address, token, session.Fingerprints)
|
||||
? new Credentials(address, token, session.Fingerprints, session.Flow.Info?.ServerId is { } id && id != Guid.Empty ? id : null)
|
||||
: null;
|
||||
if (wanted is { ServerId: { } serverId } && session.Flow.Info is { } info) Remember(serverId, wanted.Address, info);
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is not { } engine) return;
|
||||
@@ -150,6 +202,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
/// <summary>The servers known by id were changed elsewhere (Settings › Server › Forget, an import): the alias table follows (UI thread).</summary>
|
||||
public void KnownServersChanged() => Volatile.Write(ref _identity, services.Settings.KnownIdentity());
|
||||
|
||||
/// <summary>The sign-in <see cref="ConnectEditor"/> uses now (another object once signed in anew); null while signed out.</summary>
|
||||
public object? Session => Volatile.Read(ref _credentials);
|
||||
|
||||
@@ -167,18 +222,73 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
/// <summary>Compares again soon (an option changed, an edit on this PC).</summary>
|
||||
public void RequestRefresh() => Agent?.RequestRefresh();
|
||||
|
||||
/// <summary>The archive downloaded originals go to when a sequence has no local copy: the one this PC works with.</summary>
|
||||
/// <summary>This PC's archive: the one at Settings › Archive's folder, else the only one that is not a server's originals archive.</summary>
|
||||
public async Task<Archive?> CurrentArchiveAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (services.Database is not { } db) return null;
|
||||
var archives = await db.Archives.ListAsync(ct);
|
||||
if (services.Settings.LastArchivePath is { Length: > 0 } root)
|
||||
if (services.Settings.LastArchivePath is { Length: > 0 } root && CurrentArchive.At(archives, root) is { } current) return current;
|
||||
var originals = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
|
||||
var own = archives.Where(a => !originals.Contains(a.Id)).ToList();
|
||||
return own.Count == 1 ? own[0] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where Download originals puts the photos of a server sequence (owner review 5, Q1; UI thread): the archive of its local
|
||||
/// copy when it has one (a copy keeps receiving where it is), else the signed-in server's own originals archive
|
||||
/// (<see cref="KnownServer.OriginalsArchiveId"/>), made at the first download beside this PC's archive
|
||||
/// (<see cref="HomeFolders.OriginalsArchiveRoot"/>: <c>D:\ChronosArchive - Studio NAS</c>, named "Studio NAS (server)").
|
||||
/// A server that announces no id (an older one) has no home of its own: its originals go to this PC's archive, as in 1.0.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The originals archive's folder cannot be made.</exception>
|
||||
public async Task<OriginalsTarget> OriginalsArchiveAsync(Sequence? local, CancellationToken ct = default)
|
||||
{
|
||||
if (local?.ArchiveId is { } held) return new OriginalsTarget(held);
|
||||
if (services.Database is not { } db || services.Archives is not { } archives) return new OriginalsTarget(null);
|
||||
if (Volatile.Read(ref _credentials) is not { ServerId: { } id } || services.Settings.FindKnownServer(id) is not { } known)
|
||||
return new OriginalsTarget((await CurrentArchiveAsync(ct))?.Id);
|
||||
var listed = await db.Archives.ListAsync(ct);
|
||||
if (known.OriginalsArchiveId is { } chosen && listed.Any(a => a.Id == chosen)) return new OriginalsTarget(chosen);
|
||||
var name = known.Name is { Length: > 0 } n ? n : services.Server.ServerName ?? known.LastAddress ?? id.ToString("N");
|
||||
var mine = await CurrentArchiveAsync(ct);
|
||||
var root = HomeFolders.OriginalsArchiveRoot(mine?.RootPath ?? services.Settings.LastArchivePath, name, ArchiveLocations.SuggestRoot(),
|
||||
path => Directory.Exists(path) || File.Exists(path) || CurrentArchive.At(listed, path) is not null);
|
||||
var made = await archives.CreateAsync(root, Loc.L("Archive.Name.ServerOriginals", name), cancellationToken: ct);
|
||||
known.OriginalsArchiveId = made.Id;
|
||||
services.SavePreferences();
|
||||
Log.Info("sync", $"The originals of {name} ({id}) go to their own archive {made.RootPath}");
|
||||
return new OriginalsTarget(made.Id, made.RootPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The archive Download originals puts a sequence's photos in (<see cref="OriginalsArchiveAsync"/>; UI thread), with what
|
||||
/// the user is told: where a new originals archive went, or why there is none (<paramref name="notify"/>: title, message, is error).
|
||||
/// </summary>
|
||||
public async Task<Guid?> OriginalsForDownloadAsync(Sequence? local, Action<string, string?, bool> notify)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(notify);
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
|
||||
if (archives.FirstOrDefault(a => string.Equals(Path.GetFullPath(a.RootPath).TrimEnd(Path.DirectorySeparatorChar), full, StringComparison.OrdinalIgnoreCase))
|
||||
is { } current) return current;
|
||||
var target = await OriginalsArchiveAsync(local);
|
||||
if (target.ArchiveId is null) notify(Loc.L("Errors.Sync.NoArchive"), null, true);
|
||||
else if (target.Created is { } made) notify(Loc.L("Shell.Homes.Originals"), AppEnvironment.Shown(made), false);
|
||||
return target.ArchiveId;
|
||||
}
|
||||
return archives.Count == 1 ? archives[0] : null;
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or DatabaseException)
|
||||
{
|
||||
Log.Warning("sync", "The originals archive of the signed-in server could not be made", ex);
|
||||
notify(Loc.L("Errors.Sync.NoOriginalsFolder", services.Server.ServerName ?? Server ?? string.Empty), null, true);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The archives of the known servers' downloaded originals that the index holds (the scan schedule scans them too).</summary>
|
||||
public async Task<IReadOnlyList<Archive>> OriginalsArchivesAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (services.Database is not { } db) return [];
|
||||
var ids = services.Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
|
||||
if (ids.Count == 0) return [];
|
||||
return [.. (await db.Archives.ListAsync(ct).ConfigureAwait(false)).Where(a => ids.Contains(a.Id))];
|
||||
}
|
||||
|
||||
public async ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
|
||||
@@ -187,9 +297,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
var until = DateTime.UtcNow + RestoreWait;
|
||||
while (Volatile.Read(ref _credentials) is null && services.Settings.ProtectedToken is not null && DateTime.UtcNow < until)
|
||||
await Task.Delay(500, cancellationToken);
|
||||
if (Volatile.Read(ref _credentials) is not { } c || SyncService.ServerKey(c.Address) != server) return null;
|
||||
// A job queued under an address the server was reached under before it told its id reaches it all the same.
|
||||
if (Volatile.Read(ref _credentials) is not { } c || !Identity.Same(c.Key, server)) return null;
|
||||
CacheStore.Prepare(CacheStore.Folder(services.Environment, services.Settings));
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
|
||||
return RemoteFactory(c.Address, c.Token, c.Fingerprints, c.Key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -240,9 +351,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
|
||||
}
|
||||
|
||||
/// <summary>Key of the server of the saved session (Disconnect keeps it); null without one.</summary>
|
||||
/// <summary>The key of the server this PC is signed in to, else of the saved session's; null without either.</summary>
|
||||
public string? LastServer => Server ?? SavedServer();
|
||||
|
||||
/// <summary>Key of the server of the saved session (Disconnect keeps it), its id key when it is known by id; null without one.</summary>
|
||||
private string? SavedServer() =>
|
||||
services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null;
|
||||
services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? Identity.Canonical(SyncService.ServerKey(address)) : null;
|
||||
|
||||
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
|
||||
{
|
||||
@@ -265,6 +379,92 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the signed-in server in <see cref="AppSettings.KnownServers"/> (UI thread): its id, name, address, certificate,
|
||||
/// and the address key it was reached by as an alias; the settings are written only when something changed. A known id
|
||||
/// presented with another certificate and another name is told (<see cref="IdentityClash"/>).
|
||||
/// </summary>
|
||||
private void Remember(Guid id, Uri address, ServerInfo info)
|
||||
{
|
||||
var settings = services.Settings;
|
||||
var alias = SyncService.ServerKey(address);
|
||||
var shown = ServerAddress.Display(address);
|
||||
var known = settings.FindKnownServer(id);
|
||||
var changed = false;
|
||||
if (known is null)
|
||||
{
|
||||
known = new KnownServer { Id = id, Name = info.Name, LastAddress = shown, Fingerprint = info.TlsFingerprint };
|
||||
settings.KnownServers.Add(known);
|
||||
changed = true;
|
||||
Log.Info("sync", $"Server {info.Name} is known by its id {id} from now on (reached at {shown})");
|
||||
}
|
||||
else if (known.Fingerprint is { Length: > 0 } before && info.TlsFingerprint is { Length: > 0 } now
|
||||
&& !string.Equals(before, now, StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.Equals(known.Name, info.Name, StringComparison.Ordinal))
|
||||
{
|
||||
Log.Warning("sync", $"Server id {id} was {known.Name} with another certificate; it is {info.Name} now: two servers may share one copied database");
|
||||
IdentityClash?.Invoke(info.Name, known.Name ?? shown);
|
||||
}
|
||||
if (!known.Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
known.Aliases.Add(alias);
|
||||
changed = true;
|
||||
}
|
||||
if (!string.Equals(known.Name, info.Name, StringComparison.Ordinal) || !string.Equals(known.LastAddress, shown, StringComparison.OrdinalIgnoreCase)
|
||||
|| (info.TlsFingerprint is { Length: > 0 } fingerprint
|
||||
&& !string.Equals(known.Fingerprint, fingerprint, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
(known.Name, known.LastAddress, known.Fingerprint) = (info.Name, shown, info.TlsFingerprint ?? known.Fingerprint);
|
||||
changed = true;
|
||||
}
|
||||
if (DateTimeOffset.UtcNow - known.LastSeen > TimeSpan.FromHours(1))
|
||||
{
|
||||
known.LastSeen = DateTimeOffset.UtcNow;
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
Volatile.Write(ref _identity, settings.KnownIdentity());
|
||||
services.SavePreferences();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whatever this PC keeps under the address keys the server of <paramref name="credentials"/> was reached by moves to its
|
||||
/// id (owner review 5, #66: <see cref="HomeLayoutMigration.RekeyAsync"/>), before the agent starts. The links move at
|
||||
/// once (<see cref="HomeLayoutMigration.RekeyLinksAsync"/>): the jobs resumed under the id key look them up by it. The
|
||||
/// folders wait while a job writes into the workspace or the cache, a project is open in the editor, or the workspace
|
||||
/// is being moved: a later sign-in moves them, and the aliases match meanwhile. A failure is logged: nothing is lost,
|
||||
/// and the next sign-in goes on.
|
||||
/// </summary>
|
||||
private async Task RekeyAsync(Credentials credentials)
|
||||
{
|
||||
if (credentials.ServerId is not { } id || services.Database is not { } db) return;
|
||||
var aliases = Identity.AliasesOf(id);
|
||||
if (aliases.Count == 0) return;
|
||||
try
|
||||
{
|
||||
var workspace = services.Workspace;
|
||||
var migration = new HomeLayoutMigration(new HomeLayoutOptions
|
||||
{
|
||||
DataDirectory = services.Environment.DataDirectory,
|
||||
WorkspaceRoot = workspace.IsEnabled && !workspace.IsMoving ? workspace.Root : null,
|
||||
CacheRoot = CacheStore.Folder(services.Environment, services.Settings),
|
||||
Identity = Identity,
|
||||
Database = db,
|
||||
});
|
||||
await migration.RekeyLinksAsync(id, aliases).ConfigureAwait(false);
|
||||
if (workspace.HasProjectsInEditor || await db.Jobs.HasPendingAsync(RekeyHeldBy).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("sync", $"Server {id}: its folders on this PC move from its addresses to its id at a later sign-in (jobs are under way or a project is open)");
|
||||
return;
|
||||
}
|
||||
await migration.RekeyAsync(id, aliases).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
|
||||
{
|
||||
Log.Warning("sync", $"What this PC keeps under the addresses of server {id} could not all move to its id; the next sign-in goes on", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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.
|
||||
@@ -272,7 +472,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
await previous.ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
|
||||
if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token
|
||||
&& running.Credentials.ServerId == same.ServerId)
|
||||
return;
|
||||
var stopped = Volatile.Read(ref _running)?.Remote.Server;
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
@@ -283,7 +484,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
Changed?.Invoke();
|
||||
return;
|
||||
}
|
||||
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
|
||||
await RekeyAsync(start).ConfigureAwait(false);
|
||||
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints, start.Key);
|
||||
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
|
||||
agent.Changed += () => Changed?.Invoke();
|
||||
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
|
||||
@@ -302,7 +504,12 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
|
||||
/// <param name="ServerId">The id the server announced (owner review 5); null for an older server.</param>
|
||||
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints, Guid? ServerId)
|
||||
{
|
||||
/// <summary>The key the server goes by (<see cref="ServerIdentity.Key(Guid?, Uri)"/>).</summary>
|
||||
public string Key => ServerIdentity.Key(ServerId, Address);
|
||||
}
|
||||
|
||||
/// <summary>The client project homes share, and the session it was made for.</summary>
|
||||
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
|
||||
|
||||
Reference in new issue
Block a user