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

Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #68.
This commit is contained in:
Alby96 authored and Alby96 committed 2026-11-15 18:11:43 +01:00
1 parent 988068ee8e
commit 20d64af4a4
793 files changed
+23882 -2096

No files matched your search

+29 -6
View File
@@ -69,11 +69,15 @@ internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJso
internal sealed partial class ProxyCacheJson : JsonSerializerContext;
/// <summary>
/// Proxies of server sequences on this PC: <c>&lt;root&gt;/&lt;server hash&gt;/&lt;sequence id&gt;/</c> with one JPEG per
/// frame (named by frame id, so renumbering never mixes them up) and <c>remote.json</c>. Everything here can be
/// downloaded again, so the folder lives in the client's cache.
/// Proxies of server sequences on this PC, one folder per sequence with one JPEG per frame (named by frame id, so
/// renumbering never mixes them up) and <c>remote.json</c>. With a servers root (owner review 5, #66) a sequence's folder is
/// <c>&lt;servers&gt;/&lt;home folder&gt;/proxies/&lt;sequence id&gt;/</c> (<see cref="HomeFolders.ServerFolder"/> of the
/// server's canonical key); a folder still where an earlier layout put it (<c>&lt;root&gt;/&lt;address hash&gt;/&lt;sequence
/// id&gt;/</c>, 1.0; or the home folder of one of the server's aliases) is used where it is until it is moved, so a sequence
/// always has one folder. Without a servers root the 1.0 layout stays. Everything here can be downloaded again, so the
/// folder lives in the client's cache.
/// </summary>
internal sealed class ProxyCache(string root)
internal sealed class ProxyCache(string root, string? servers = null, Func<ServerIdentity>? identity = null)
{
/// <summary>The asset kind of a cached proxy (the server's name for it).</summary>
public const string Proxy = "proxy";
@@ -83,8 +87,27 @@ internal sealed class ProxyCache(string root)
private const string IndexFile = "remote.json";
public string Folder(string server, Guid remoteId) =>
Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..16], remoteId.ToString("N"));
/// <summary>The 1.0 folder of a server sequence's proxies: <c>&lt;root&gt;/&lt;address hash&gt;/&lt;sequence id&gt;</c>.</summary>
internal static string LegacyFolder(string root, string server, Guid remoteId) =>
Path.Combine(root, Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(server)))[..HomeFolders.HashLength], remoteId.ToString("N"));
/// <summary>The folder of a server sequence's proxies: where it is now, or where a new one goes (see the class).</summary>
public string Folder(string server, Guid remoteId)
{
if (servers is null) return LegacyFolder(root, server, remoteId);
var known = identity?.Invoke() ?? ServerIdentity.None;
var name = remoteId.ToString("N");
var target = Path.Combine(servers, known.FolderName(server), HomeFolders.Proxies, name);
if (Directory.Exists(target)) return target;
foreach (var key in known.KeysOf(server))
{
var home = Path.Combine(servers, HomeFolders.ServerFolder(key), HomeFolders.Proxies, name);
if (Directory.Exists(home)) return home;
var legacy = LegacyFolder(root, key, remoteId);
if (Directory.Exists(legacy)) return legacy;
}
return target;
}
public static string FileName(Guid frameId) => frameId.ToString("N") + ".jpg";
+121
View File
@@ -0,0 +1,121 @@
using Chronos.Core.IO;
using Chronos.Protocol;
namespace Chronos.Data.Sync;
/// <summary>A server known by its stable id, with the address keys it was reached under (<see cref="SyncService.ServerKey"/>).</summary>
/// <param name="Id">The server's id (<see cref="ServerInfo.ServerId"/>).</param>
/// <param name="Aliases">The legacy address keys this id was reached under, in any case.</param>
public sealed record KnownServerKey(Guid Id, IReadOnlyCollection<string> Aliases);
/// <summary>
/// How the desktop names a server (owner review 5, #66). A server that announces its stable id
/// (<see cref="ServerInfo.ServerId"/>) is keyed <c>id:&lt;N&gt;</c> (<see cref="Key(Guid?, Uri)"/>), the same whatever
/// address it is reached by; an older one keeps its address key (<see cref="SyncService.ServerKey"/>, the 1.0 key, here the
/// <see cref="LegacyKey"/>). An instance holds the alias table: the address keys each known id was reached under, which
/// projects, links and jobs made before the id was known still carry. <see cref="Canonical"/> turns an alias into its id
/// key, <see cref="Same"/> compares two keys through it, and <see cref="FolderName"/> is the home's folder
/// (<see cref="HomeFolders.ServerFolder"/>) of the canonical key. Keys compare ignoring case, as address keys always did.
/// </summary>
public sealed class ServerIdentity
{
private readonly Dictionary<string, string> _canonical = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<string>> _aliases = new(StringComparer.OrdinalIgnoreCase);
/// <summary>No server known by id: every key is its own.</summary>
public static ServerIdentity None { get; } = new([]);
public ServerIdentity(IEnumerable<KnownServerKey> servers)
{
ArgumentNullException.ThrowIfNull(servers);
var known = new List<KnownServerKey>();
foreach (var server in servers)
{
if (server.Id == Guid.Empty) continue;
var idKey = HomeFolders.IdKey(server.Id);
if (!_aliases.TryGetValue(idKey, out var list))
{
list = [];
_aliases[idKey] = list;
}
foreach (var alias in server.Aliases ?? [])
{
if (string.IsNullOrWhiteSpace(alias) || string.Equals(alias, idKey, StringComparison.OrdinalIgnoreCase)) continue;
// An address that two ids claim (a server replaced at the same address) stays with the first one listed.
if (!_canonical.TryAdd(alias, idKey)) continue;
list.Add(alias);
}
known.Add(server);
}
Servers = known;
}
/// <summary>The servers this table knows, as it was given them.</summary>
public IReadOnlyList<KnownServerKey> Servers { get; }
/// <summary>The key of a server reached at <paramref name="address"/>: its id key when <paramref name="info"/> announces an id, else its address key.</summary>
public static string Key(ServerInfo? info, Uri address) => Key(info?.ServerId, address);
/// <summary>The key of a server reached at <paramref name="address"/>: <c>id:&lt;N&gt;</c> for an id, else its address key.</summary>
public static string Key(Guid? serverId, Uri address)
{
ArgumentNullException.ThrowIfNull(address);
return serverId is { } id && id != Guid.Empty ? HomeFolders.IdKey(id) : LegacyKey(address);
}
/// <summary>The key of a server known by its id.</summary>
public static string IdKey(Guid serverId) => HomeFolders.IdKey(serverId);
/// <summary>The address key (<see cref="SyncService.ServerKey"/>): how 1.0 named every server, and how an older server is still named.</summary>
public static string LegacyKey(Uri address) => SyncService.ServerKey(address);
/// <summary>The id of an id key; null for an address key.</summary>
public static Guid? IdOf(string? key) => HomeFolders.IdOfKey(key);
/// <summary>The key names the server by its id.</summary>
public static bool IsIdKey(string? key) => IdOf(key) is not null;
/// <summary>The id key an alias stands for; any other key as it is.</summary>
public string Canonical(string key)
{
ArgumentNullException.ThrowIfNull(key);
if (IdOf(key) is { } id) return HomeFolders.IdKey(id);
return _canonical.TryGetValue(key, out var idKey) ? idKey : key;
}
/// <summary>Both keys name one server: equal ignoring case, or one an alias of the other's id (null equals only null).</summary>
public bool Same(string? a, string? b)
{
if (a is null || b is null) return a is null && b is null;
return string.Equals(Canonical(a), Canonical(b), StringComparison.OrdinalIgnoreCase);
}
/// <summary>Every key that names the server of <paramref name="key"/>: its canonical key first, then its aliases.</summary>
public IReadOnlyList<string> KeysOf(string key)
{
var canonical = Canonical(key);
var keys = new List<string> { canonical };
if (_aliases.TryGetValue(canonical, out var aliases)) keys.AddRange(aliases);
if (!keys.Contains(key, StringComparer.OrdinalIgnoreCase)) keys.Add(key);
return keys;
}
/// <summary>The aliases of a server id (its legacy address keys); empty when none is known.</summary>
public IReadOnlyList<string> AliasesOf(Guid serverId) =>
_aliases.TryGetValue(HomeFolders.IdKey(serverId), out var aliases) ? aliases : [];
/// <summary>The folder of the home of <paramref name="key"/> (<see cref="HomeFolders.ServerFolder"/> of its canonical key).</summary>
public string FolderName(string key) => HomeFolders.ServerFolder(Canonical(key));
/// <summary>This table with <paramref name="alias"/> added to the aliases of <paramref name="serverId"/> (an address it was reached under).</summary>
public ServerIdentity With(Guid serverId, string alias)
{
ArgumentException.ThrowIfNullOrWhiteSpace(alias);
var servers = Servers.ToList();
var index = servers.FindIndex(s => s.Id == serverId);
if (index < 0) servers.Add(new KnownServerKey(serverId, [alias]));
else if (!servers[index].Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase)) servers[index] = servers[index] with { Aliases = [.. servers[index].Aliases, alias] };
else return this;
return new ServerIdentity(servers);
}
}
+47
View File
@@ -43,6 +43,53 @@ internal sealed class SyncLinkStore(ChronosDatabase db)
public Task DeleteAsync(string server, Guid remoteId, CancellationToken cancellationToken) =>
_db.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [server, remoteId], cancellationToken);
/// <summary>
/// Moves every link of <paramref name="from"/> to <paramref name="to"/> in one transaction (owner review 5, #66: an address
/// key becomes the server's id key). Where <paramref name="to"/> already links the same server sequence, or the same local
/// copy, the row compared last (<see cref="SyncLink.SyncedAt"/>, never compared counting oldest) is kept and the other
/// deleted: link rows are recomputed by the next comparison, so nothing is lost.
/// </summary>
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
if (string.Equals(from, to, StringComparison.Ordinal)) return (0, 0);
return await _db.InTransactionAsync(async session =>
{
var inner = new DbAccess(session);
var old = await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [from], Map, cancellationToken)
.ConfigureAwait(false);
if (old.Count == 0) return (0, 0);
var current = (await inner.ListAsync($"SELECT {Columns} FROM sync_links WHERE server = $1 ORDER BY remote_id", [to], Map, cancellationToken)
.ConfigureAwait(false)).ToList();
var (moved, dropped) = (0, 0);
foreach (var link in old)
{
var clashes = current.Where(c => c.RemoteId == link.RemoteId || (link.LocalId is { } local && c.LocalId == local)).ToList();
if (clashes.Any(c => Newer(c, link)))
{
await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [from, link.RemoteId], cancellationToken).ConfigureAwait(false);
dropped++;
continue;
}
foreach (var clash in clashes)
{
await inner.ExecuteAsync("DELETE FROM sync_links WHERE server = $1 AND remote_id = $2", [to, clash.RemoteId], cancellationToken).ConfigureAwait(false);
current.Remove(clash);
dropped++;
}
await inner.ExecuteAsync("UPDATE sync_links SET server = $3 WHERE server = $1 AND remote_id = $2", [from, link.RemoteId, to], cancellationToken)
.ConfigureAwait(false);
current.Add(link with { Server = to });
moved++;
}
return (moved, dropped);
}, cancellationToken).ConfigureAwait(false);
// The row already under the new key stays on a tie: it is the one the signed-in session works with.
static bool Newer(SyncLink kept, SyncLink other) => (kept.SyncedAt ?? DateTimeOffset.MinValue) >= (other.SyncedAt ?? DateTimeOffset.MinValue);
}
/// <summary>Records where a local sequence stands for the Library; touches neither its versions nor its update time.</summary>
public Task SetLocalStateAsync(Guid localId, SyncState state, CancellationToken cancellationToken) =>
_db.ExecuteAsync("UPDATE sequences SET sync_state = $2 WHERE id = $1 AND sync_state <> $2", [localId, (int)state], cancellationToken);
+6 -2
View File
@@ -115,7 +115,11 @@ public interface ISyncConnector
}
/// <summary><see cref="ISyncRemote"/> over a signed-in <see cref="ChronosClient"/>, which it disposes when it owns it.</summary>
public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : ISyncRemote
/// <param name="server">
/// The key links and homes name the server by (<see cref="ServerIdentity.Key(Guid?, Uri)"/>: its id key once it announced
/// one, owner review 5); null takes the client's address key (<see cref="SyncService.ServerKey"/>).
/// </param>
public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient, string? server = null) : ISyncRemote
{
private const int SequencePage = 500;
private const int FramePage = 1000;
@@ -137,7 +141,7 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
/// <summary>The settings format the server announced, and when it was read (a <see cref="System.Diagnostics.Stopwatch"/> timestamp).</summary>
private sealed record KnownFormat(int Format, long Read);
public string Server { get; } = SyncService.ServerKey(client.BaseAddress);
public string Server { get; } = string.IsNullOrWhiteSpace(server) ? SyncService.ServerKey(client.BaseAddress) : server;
public async Task<IReadOnlyList<SequenceDto>> ListSequencesAsync(CancellationToken cancellationToken)
{
+35 -3
View File
@@ -26,9 +26,23 @@ public sealed record SyncOptions
/// <summary>Decoders, lease owner and lease timing for sidecar and project writes (shared with the archive engine).</summary>
public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Folder of the proxy cache of server sequences (inside the client's cache).</summary>
/// <summary>
/// Folder of the proxy cache of server sequences as 1.0 laid it out (<c>&lt;cache&gt;\proxies\&lt;address hash&gt;</c>):
/// where proxies go without <see cref="ServersDirectory"/>, and where a sequence's proxies are still read from, with it,
/// until they are moved into their server's home.
/// </summary>
public required string ProxyCacheDirectory { get; init; }
/// <summary>
/// The servers' homes in the client's cache (<c>&lt;cache&gt;\servers</c>, owner review 5, #66): with it, a server's
/// proxies go to <c>&lt;servers&gt;\&lt;home folder&gt;\proxies\&lt;sequence id&gt;</c>
/// (<see cref="Core.IO.HomeFolders.ServerFolder"/>). Null keeps the 1.0 layout under <see cref="ProxyCacheDirectory"/>.
/// </summary>
public string? ServersDirectory { get; init; }
/// <summary>The alias table the cache finds a server's home by (<see cref="ServerIdentity"/>); null: every key is its own.</summary>
public Func<ServerIdentity>? Identity { get; init; }
/// <summary>Concurrent frame downloads of one job.</summary>
public int Downloads { get; init; } = 4;
@@ -74,7 +88,7 @@ public sealed class SyncService
Options = options;
_links = new SyncLinkStore(db);
_writer = new SequenceWriter(options.Archive);
Proxies = new ProxyCache(options.ProxyCacheDirectory);
Proxies = new ProxyCache(options.ProxyCacheDirectory, options.ServersDirectory, options.Identity);
}
public SyncOptions Options { get; }
@@ -90,9 +104,27 @@ public sealed class SyncService
internal ArchiveService Archives { get; }
/// <summary>"https://nas.local:8443": the key links are stored under (scheme, lower-case host, port, path).</summary>
/// <summary>
/// "https://nas.local:8443": the address key (scheme, lower-case host, port, path), the key every server had in 1.0 and an
/// older server, which announces no id, still has. A server that announces one is keyed by it
/// (<see cref="ServerIdentity.Key(Guid?, Uri)"/>), its address keys kept as aliases.
/// </summary>
public static string ServerKey(Uri address) => address.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant();
/// <summary>
/// Moves the links of <paramref name="from"/> (an address key the server was reached under) to <paramref name="to"/> (its
/// id key, owner review 5, #66) in one transaction. A link both keys hold for one server sequence, or for one local copy,
/// keeps the row compared last (<see cref="SyncLink.SyncedAt"/>); the other row goes, which loses nothing: the next
/// comparison makes links again. Nothing happens when the keys are the same.
/// </summary>
/// <returns>The links moved, and those dropped for a newer one.</returns>
public async Task<(int Moved, int Dropped)> RekeyAsync(string from, string to, CancellationToken cancellationToken)
{
var result = await _links.RekeyAsync(from, to, cancellationToken).ConfigureAwait(false);
if (result.Moved + result.Dropped > 0) Changed?.Invoke(to);
return result;
}
/// <summary>What an upload or download job moves; null for any other job.</summary>
public static SyncTransferKind? TransferKind(Job job) => SyncJobParameters.Read(job)?.Kind(job.Kind);
+22 -10
View File
@@ -60,7 +60,7 @@ internal sealed class SyncTransfers(SyncService sync)
: new FramePhotos([]);
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || (!present.Contains(tombstones.Canonical(f.Sha256)!) && !tombstones.DeletedRemotely(f.Sha256)))
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count, new JobDetail(JobStep.Upload, local.DisplayTitle));
await progress.ReportAsync().ConfigureAwait(false);
var skipped = 0;
// The SHA-256 of each original the index has none for (a folder adopted and not verified), as its upload computes
@@ -135,7 +135,7 @@ internal sealed class SyncTransfers(SyncService sync)
var photos = SyncRules.Photos(frames);
var camera = new SidecarCamera { Make = local.CameraMake, Model = local.CameraModel, Serial = local.CameraSerial };
var decoder = sync.Options.Archive.Decoder;
var progress = new TransferProgress(context, wanted.Count, 0);
var progress = new TransferProgress(context, wanted.Count, 0, new JobDetail(JobStep.Upload, local.DisplayTitle));
await progress.ReportAsync().ConfigureAwait(false);
int sent = 0, unsent = 0;
using var refused = CancellationTokenSource.CreateLinkedTokenSource(ct);
@@ -241,7 +241,8 @@ internal sealed class SyncTransfers(SyncService sync)
var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
Directory.CreateDirectory(staging);
var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count);
var progress = new TransferProgress(context, manifest.Frames.Count, manifest.Frames.Count - wanted.Count,
new JobDetail(JobStep.Download, local?.DisplayTitle ?? context.Job.TargetLabel));
await progress.ReportAsync().ConfigureAwait(false);
var created = false;
var rest = wanted;
@@ -457,12 +458,13 @@ internal sealed class SyncTransfers(SyncService sync)
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotLinked"));
var there = (await remote.GetManifestAsync(link.RemoteId, ct).ConfigureAwait(false)).Renders.Select(r => r.Id).ToHashSet();
var renders = (await db.Renders.ListBySequenceAsync(local.Id, ct).ConfigureAwait(false)).Where(r => !there.Contains(r.Id)).ToList();
var progress = new TransferProgress(context, renders.Count, 0);
var progress = new TransferProgress(context, renders.Count, 0, new JobDetail(JobStep.Upload, local.DisplayTitle), items: false);
await progress.ReportAsync().ConfigureAwait(false);
var gone = 0;
foreach (var render in renders)
{
var file = SyncService.RenderFile(archive, render);
await progress.PartAsync(Path.GetFileName(file)).ConfigureAwait(false);
if (File.Exists(file))
{
var sha = await ChronosClient.HashFileAsync(file, ct).ConfigureAwait(false);
@@ -495,10 +497,11 @@ internal sealed class SyncTransfers(SyncService sync)
var staging = Path.Combine(paths.StagingDirectory, "exports-" + remoteId.ToString("N"));
Directory.CreateDirectory(staging);
var progress = new TransferProgress(context, wanted.Count, 0);
var progress = new TransferProgress(context, wanted.Count, 0, new JobDetail(JobStep.Download, local.DisplayTitle), items: false);
await progress.ReportAsync().ConfigureAwait(false);
foreach (var render in wanted)
{
await progress.PartAsync(render.PresetName).ConfigureAwait(false);
var (part, name, sha) = await FetchRenderAsync(remote, render, staging, ct).ConfigureAwait(false);
var filed = await FileRenderAsync(sync.Archives, db, local, paths, part, name, new Render
{
@@ -630,7 +633,7 @@ internal sealed class SyncTransfers(SyncService sync)
var files = new string?[frames.Count];
var kinds = new string?[frames.Count];
var progress = new TransferProgress(context, frames.Count, 0);
var progress = new TransferProgress(context, frames.Count, 0, new JobDetail(JobStep.Download, context.Job.TargetLabel));
await progress.ReportAsync().ConfigureAwait(false);
await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
{
@@ -906,8 +909,12 @@ internal sealed class SyncTransfers(SyncService sync)
private static ParallelOptions Workers(int degree, CancellationToken cancellationToken) =>
new() { MaxDegreeOfParallelism = Math.Max(1, degree), CancellationToken = cancellationToken };
/// <summary>Files done out of the total, reported in order from parallel workers.</summary>
private sealed class TransferProgress(JobContext context, long total, long done)
/// <summary>
/// Files done out of the total, reported in order from parallel workers, with what moves (<paramref name="detail"/>: up or
/// down, the sequence): photo x of y of the transfer when <paramref name="items"/>, else the file being moved, video n of m
/// (<see cref="PartAsync"/>).
/// </summary>
private sealed class TransferProgress(JobContext context, long total, long done, JobDetail detail, bool items = true)
{
private readonly SemaphoreSlim _gate = new(1, 1);
@@ -917,7 +924,8 @@ internal sealed class SyncTransfers(SyncService sync)
try
{
done++;
await context.ReportAsync(done, total).ConfigureAwait(false);
if (items) await context.ReportItemAsync(done, total, done, total).ConfigureAwait(false);
else await context.ReportAsync(done, total).ConfigureAwait(false);
}
finally
{
@@ -927,7 +935,11 @@ internal sealed class SyncTransfers(SyncService sync)
public long Done => done;
public ValueTask ReportAsync() => context.ReportAsync(done, total);
public ValueTask ReportAsync() => context.ReportAsync(done, total, items ? detail with { ItemDone = done, ItemTotal = total } : detail);
/// <summary>The next video starts moving: its file name, video n of m.</summary>
public ValueTask PartAsync(string? file) =>
context.ReportAsync(done, total, detail with { Item = file, Part = (int)Math.Min(done + 1, total), Parts = (int)total, PartUnit = JobPartUnit.Render });
}
}