feat: owner review 2 phase 5b: the server as a project home (#17)
CI / Build and test (push) Successful in 9m58s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 14m8s
CI / PostgreSQL 16 integration (push) Successful in 8m55s
CI / PostgreSQL 17 integration (push) Successful in 8m50s
CI / Docker image (push) Successful in 57s
Release / Server image (push) Successful in 1m22s

A Chronos Server keeps its sequences' projects, as a PC's archive does: Main and named projects with versions under /api/v1/sequences/{id}/projects, the projects capability and the projectChanged event. The desktop opens a server's sequences in the workspace (proxies downloaded, hash-checked, resumable) with Save version, Sync, conflicts, History, Restore and the project actions against the server. Renders can be of a project version. The admin panel lists a sequence's projects and versions. Strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #17.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 14:58:11 +01:00
1 parent 255e149087
commit 81c303f484
325 files changed
+11477 -516

No files matched your search

+13 -1
View File
@@ -355,14 +355,26 @@ public sealed class ArchiveIndexer
{
if (await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) is not { } row
|| !Directory.Exists(paths.Sequence(row.Folder).ProjectsDirectory)) return;
ProjectChangeSet? changed = null;
try
{
await using (await _writer.LockAsync(paths, sequenceId, cancellationToken).ConfigureAwait(false))
{
var folder = await SequenceWriter.FolderAsync(_db, paths, row, cancellationToken).ConfigureAwait(false);
if (!SequenceFolders.Holds(folder, sequenceId) || !Directory.Exists(folder.ProjectsDirectory)) return;
await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false);
// Projects and versions another program wrote, taken in here, are told as a project call's are: the next call
// finds them in the index already and has nothing to tell.
var before = await ProjectService.WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken).ConfigureAwait(false);
try
{
await _projects.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false);
}
finally
{
if (before is not null) changed = await ProjectService.ChangesAsync(_db, sequenceId, before, settingsChanged: false).ConfigureAwait(false);
}
}
if (changed is not null) await ProjectService.TellAsync(_writer.Options, changed).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
@@ -3,6 +3,7 @@ using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
@@ -348,6 +349,65 @@ public sealed class ArchiveService : IJobHandlerProvider
return await write(await _db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false)).ConfigureAwait(false);
}
/// <summary>
/// Settings a caller writes into the index (<paramref name="edit"/>: the server's <c>PATCH</c>, with its version checks)
/// written into the sequence's <c>project.json</c> too, under its lease, as every other writer of the settings does: so
/// the file never holds settings older than the index's, which the projects would take for the sequence's own when they
/// meet Main (<see cref="ProjectService"/>). <paramref name="settingsJson"/> goes to the file first; when the index then
/// does not take it (a conflict, the sequence gone) or the edit fails, the file is put back as it was. A sequence with no
/// folder yet is edited in the index alone: its first photo writes the file from the index.
/// </summary>
/// <param name="wait">How long the sequence's lease is waited for.</param>
/// <exception cref="ArgumentException">The sequence or its archive is not in the index.</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only: nothing is written.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than <paramref name="wait"/>: nothing is written.</exception>
/// <exception cref="SequenceFolderMovedException">The sequence's folder does not hold it now: nothing is written.</exception>
/// <exception cref="IOException">The file cannot be written: nothing is written.</exception>
public async Task<SequenceEditResult> EditSettingsAsync(Guid sequenceId, string settingsJson, Func<CancellationToken, Task<SequenceEditResult>> edit, TimeSpan wait,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settingsJson);
ArgumentNullException.ThrowIfNull(edit);
var (archive, sequence) = await LoadSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(sequence.Folder)) return await edit(cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw Unknown(sequenceId);
var folder = paths.Sequence(row.Folder);
if (string.IsNullOrEmpty(row.Folder) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
var previous = File.Exists(folder.ProjectPath) ? AtomicFile.ReadAllText(folder.ProjectPath) : null;
Directory.CreateDirectory(folder.MetaDirectory);
AtomicFile.WriteAllText(folder.ProjectPath, settingsJson);
SequenceEditResult result;
try
{
result = await edit(cancellationToken).ConfigureAwait(false);
}
catch
{
PutBack(folder, previous);
throw;
}
if (result.Outcome != SequenceEditOutcome.Updated) PutBack(folder, previous);
return result;
}
static void PutBack(SequencePaths folder, string? previous)
{
try
{
if (previous is not null) AtomicFile.WriteAllText(folder.ProjectPath, previous);
else File.Delete(folder.ProjectPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"The project.json of {folder.RelativeFolder} could not be put back after an edit the index did not take", ex);
}
}
}
public Task<IReadOnlyList<DuplicateGroup>> FindDuplicatesAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
Maintenance.FindDuplicatesAsync(archiveId, cancellationToken);
@@ -26,6 +26,16 @@ public sealed record ArchiveServiceOptions
/// </summary>
public bool ImagesAfterScan { get; init; }
/// <summary>
/// The index may hold settings newer than a sequence's <c>project.json</c>: the server, whose <c>PATCH</c> wrote the
/// settings a client sent into the index alone before owner review 2 phase 5b. When the projects meet a sequence whose two
/// copies differ, the index's is never dropped: Main is born with <c>project.json</c>'s as version 1 and the index's as
/// version 2, in force; a Main the sidecars already hold keeps the index's as a version below the settings in force
/// (<see cref="Projects.ProjectService"/>). The desktop, whose every writer writes the file, takes the file alone: its index
/// can be an old copy (a second PC, a backup).
/// </summary>
public bool IndexSettingsMayLead { get; init; }
/// <summary>
/// Photos a pass works on at once, asked at the start of each sequence (owner review 1, R2: one job runs at a time and
/// the host's parallelism decides how many photos it processes at once; Settings › Rendering › Parallelism on the
@@ -62,6 +72,15 @@ public sealed record ArchiveServiceOptions
/// </summary>
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>
/// Told after a call of <see cref="Projects.ProjectService"/> changed a sequence's projects (owner review 2, R8): a project
/// made, renamed or deleted, a new head (a push, settings another path wrote taken as Main's external version, a merge, the
/// versions another program sharing the archive wrote found in the sidecars), and whether the call wrote Main's head into
/// the sequence's settings. Told once per call, after the sequence's lease is let go. A server tells its connected clients
/// (BRIEF §14.3); a failure is logged and never fails the call.
/// </summary>
public Func<Projects.ProjectChangeSet, CancellationToken, Task>? ProjectsChanged { get; init; }
/// <summary>
/// The free bytes a write under a folder of an archive (its root, its staging folder) may count on, as the host counts
/// them: a server takes the tighter of its space volume (owner review 2, R2) and the folder's own volume, the desktop asks
+2 -2
View File
@@ -7,9 +7,9 @@ namespace Chronos.Data.Projects;
/// <summary>
/// The photos of a sequence's frames at its home as project positions name them (owner review 2, R8), with the encodings
/// a conversion joined (R7): a version parked on a photo before its file was converted, or after a conversion was undone,
/// still finds its frame.
/// still finds its frame. A server builds the same for a sequence it is the home of, and sends its aliases to workspaces.
/// </summary>
internal static class HomePhotos
public static class HomePhotos
{
/// <summary>The links between encodings of the sequence's photos: its tombstones of reason "replaced".</summary>
public static async Task<IReadOnlyList<PhotoAlias>> AliasesAsync(ChronosRepositories db, Guid sequenceId, CancellationToken cancellationToken) =>
+37 -3
View File
@@ -13,11 +13,21 @@ public sealed record HomeSequence(BundleArchive Archive, BundleSequence Sequence
/// <summary>
/// Where a sequence's projects live (owner review 2, R8): the side a workspace pushes to and pulls from, "like git". This
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (phase 5b). Every call may throw
/// <see cref="HomeUnavailableException"/> when the home cannot be reached, and <see cref="ProjectException"/> when it refuses.
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (<see cref="ServerProjectHome"/>, phase
/// 5b). Every call may throw <see cref="HomeUnavailableException"/> when the home cannot be reached, and
/// <see cref="ProjectException"/> when it refuses.
/// </summary>
public interface IProjectHome
{
/// <summary>Gives a project another name (1–60 characters, unique among the sequence's live projects whatever the case).</summary>
/// <exception cref="ProjectException">Unknown project, or the name is invalid or taken.</exception>
Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
throw new NotSupportedException("This home does not rename projects.");
/// <summary>Deletes a project (never Main) into the home's project trash, with all its versions, which stay readable there.</summary>
/// <exception cref="ProjectException">Unknown project, or the Main project.</exception>
Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) => throw new NotSupportedException("This home does not delete projects.");
/// <summary>The sequence and where it is.</summary>
Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken);
@@ -146,13 +156,37 @@ public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projec
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => projects.FramesAsync(sequenceId, cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
});
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
await projects.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
return true;
});
/// <summary>
/// The sequence's frames version (frames added, removed, converted or renamed), with how many of its photos the index has
/// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version)
/// and how many removals it keeps (a conversion's links).
/// </summary>
public async Task<string?> FramesStampAsync(CancellationToken cancellationToken)
public async Task<string?> FramesStampAsync(CancellationToken cancellationToken) =>
await StampOfAsync(db, sequenceId, cancellationToken).ConfigureAwait(false);
/// <summary>
/// The stamp of a sequence's frames as an index holds them (<see cref="FramesStampAsync"/>): what a server answers for
/// its sequences too (<c>GET …/projects/frames/stamp</c>).
/// </summary>
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
public static async Task<string> StampOfAsync(ChronosDatabase db, Guid sequenceId, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(db);
var row = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var (hashed, checksum, removals) = await db.Frames.CountNamedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
+246 -20
View File
@@ -27,6 +27,12 @@ public enum ProjectError
/// <summary>The Main project cannot be deleted: it holds the sequence's own settings.</summary>
MainCannotBeDeleted,
/// <summary>
/// The sequence has no folder in its archive yet (made before its first photo, as a server's new sequence is): it keeps
/// no projects until its first photo places it.
/// </summary>
SequenceEmpty,
}
/// <summary>A project operation was refused; nothing was written.</summary>
@@ -79,6 +85,19 @@ public sealed record PushResult(PushOutcome Outcome, ProjectVersion? Version, Pr
/// </summary>
public sealed record HomeFrames(int FramesVersion, IReadOnlyList<Frame> Frames, FramePhotos Photos);
/// <summary>
/// One project a <see cref="ProjectService"/> call changed: <see cref="Change"/> is one of <see cref="Protocol.ProjectChanges"/>
/// (<c>created</c>, <c>renamed</c>, <c>deleted</c>, <c>pushed</c>: a new head), with the project's head after the call.
/// </summary>
public sealed record ProjectChange(Guid ProjectId, string Change, int HeadNumber, Guid? HeadVersionId);
/// <summary>
/// What one <see cref="ProjectService"/> call changed in a sequence's projects (<see cref="ArchiveServiceOptions.ProjectsChanged"/>):
/// the projects, in index order, and whether it wrote Main's head into the sequence's settings (<see cref="SettingsChanged"/>:
/// the sequence's settings version moved, which the code paths that read the sequence's settings want to know).
/// </summary>
public sealed record ProjectChangeSet(Guid SequenceId, IReadOnlyList<ProjectChange> Changes, bool SettingsChanged);
/// <summary>
/// The projects of the sequences of this PC's archives (owner review 2, R8): the home side of a workspace's push and pull.
/// Every operation runs under the sequence's lease and first catches up: the sidecars into the index
@@ -393,6 +412,7 @@ public sealed class ProjectService
ArgumentNullException.ThrowIfNull(version);
if (await _db.Projects.GetAsync(projectId, cancellationToken).ConfigureAwait(false) is not { DeletedAt: null } project) return false;
var (paths, row) = await LocateAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
if (Unplaced(row)) return false;
if (Availability(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, project.SequenceId)) throw new SequenceFolderMovedException();
@@ -412,6 +432,20 @@ public sealed class ProjectService
return false;
}
/// <summary>
/// Brings the sequence's projects in step now (see the class remarks: the sidecars into the index, Main made, settings
/// another path wrote appended to Main), as every call does first, but saying why when it cannot: what a host runs soon
/// after it wrote a sequence's settings outside the projects, so Main takes them (and is told, <see
/// cref="ArchiveServiceOptions.ProjectsChanged"/>) before anyone asks.
/// </summary>
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another writer held the sequence for longer than a read waits.</exception>
/// <exception cref="SequenceFolderMovedException">The sequence's folder does not hold it.</exception>
/// <exception cref="ProjectsUnreadableException">The index has no Main and a project record cannot be read now (it may be Main's).</exception>
public Task CatchUpAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait);
/// <summary>
/// Catches the sequence's projects up under its lease (see the class remarks) before a read; the index alone answers while
/// the archive is offline, the sequence busy for longer than the lease wait, or a project of it cannot be read now. A
@@ -419,6 +453,8 @@ public sealed class ProjectService
/// </summary>
private async Task ReadAsync(Guid sequenceId, CancellationToken cancellationToken)
{
// A sequence with no folder yet keeps no projects: nothing to catch up, and nothing may be written (its folder would be the archive's root).
if (Unplaced(await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId))) return;
try
{
try
@@ -452,6 +488,8 @@ public sealed class ProjectService
{
var (paths, row) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var folder = paths.Sequence(row.Folder);
// What the sidecars bring into the index, and a Main made in it, are told as any other call's changes.
var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
try
{
if (!SequenceFolders.Holds(folder, sequenceId))
@@ -467,6 +505,11 @@ public sealed class ProjectService
{
Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}");
}
finally
{
if (before is not null && await ChangesAsync(sequenceId, before, settingsChanged: false).ConfigureAwait(false) is { } changed)
await TellAsync(changed).ConfigureAwait(false);
}
}
/// <summary>
@@ -480,17 +523,109 @@ public sealed class ProjectService
private async Task<T> UnderLeaseAsync<T>(Guid sequenceId, Func<LeaseContext, CancellationToken, Task<T>> work, CancellationToken cancellationToken,
TimeSpan? wait = null)
{
var (paths, _) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
var (paths, located) = await LocateAsync(sequenceId, cancellationToken).ConfigureAwait(false);
// Before the lease: the archive's root is no sequence's folder, so nothing of this sequence's projects is read from it or written into it.
if (Unplaced(located))
throw new ProjectException(ProjectError.SequenceEmpty, $"Sequence {sequenceId} has no folder yet: it keeps no projects before its first photo.");
var availability = Availability(paths);
if (availability != ArchiveAvailability.Online) throw new ArchiveOfflineException(paths.Root, availability);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
ProjectChangeSet? changed = null;
try
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
var folder = paths.Sequence(row.Folder);
if (!SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
var context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
return await work(context, cancellationToken).ConfigureAwait(false);
await using (await _writer.LockAsync(paths, sequenceId, wait, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false) ?? throw SequenceMissing(sequenceId);
var folder = paths.Sequence(row.Folder);
if (Unplaced(row) || !SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
// Taken before the reconcile: the versions another program wrote into the sidecars are told too.
var before = await WatchedAsync(sequenceId, cancellationToken).ConfigureAwait(false);
LeaseContext? context = null;
try
{
context = new LeaseContext(folder, row, await _indexer.ReconcileAsync(folder, sequenceId, cancellationToken).ConfigureAwait(false));
await CatchUpAsync(context, cancellationToken).ConfigureAwait(false);
return await work(context, cancellationToken).ConfigureAwait(false);
}
finally
{
// What the reconcile, the catch-up and the work wrote stays written even when the work then refused or failed.
if (before is not null)
changed = await ChangesAsync(sequenceId, before, context is not null && row.SettingsVersion != context.Row.SettingsVersion).ConfigureAwait(false);
}
}
}
finally
{
if (changed is not null) await TellAsync(changed).ConfigureAwait(false);
}
}
/// <summary>The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes; else null.</summary>
private Task<Dictionary<Guid, SequenceProject>?> WatchedAsync(Guid sequenceId, CancellationToken cancellationToken) =>
WatchedAsync(_db, _writer.Options, sequenceId, cancellationToken);
private Task<ProjectChangeSet?> ChangesAsync(Guid sequenceId, Dictionary<Guid, SequenceProject> before, bool settingsChanged) =>
ChangesAsync(_db, sequenceId, before, settingsChanged);
private Task TellAsync(ProjectChangeSet changed) => TellAsync(_writer.Options, changed);
/// <summary>
/// The sequence's projects as the index has them now (deleted ones too), when someone is to be told what changes
/// (<see cref="ArchiveServiceOptions.ProjectsChanged"/>); else null. Shared with the scans that take the sidecars back
/// outside a project call (<see cref="ArchiveIndexer"/>).
/// </summary>
internal static async Task<Dictionary<Guid, SequenceProject>?> WatchedAsync(ChronosDatabase db, ArchiveServiceOptions options, Guid sequenceId,
CancellationToken cancellationToken) =>
options.ProjectsChanged is null
? null
: (await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, cancellationToken).ConfigureAwait(false)).ToDictionary(p => p.Id);
/// <summary>
/// What changed in the sequence's projects since <paramref name="before"/> (a project new or back, deleted, renamed or
/// made Main or no longer Main, or with a new head); null when nothing did. Never throws: it runs after the work,
/// whatever became of it.
/// </summary>
internal static async Task<ProjectChangeSet?> ChangesAsync(ChronosDatabase db, Guid sequenceId, Dictionary<Guid, SequenceProject> before, bool settingsChanged)
{
IReadOnlyList<SequenceProject> after;
try
{
after = await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: true, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("projects", $"The project changes of sequence {sequenceId} cannot be read", ex);
return null;
}
var changes = new List<ProjectChange>();
foreach (var project in after)
{
before.TryGetValue(project.Id, out var was);
var (live, wasLive) = (project.DeletedAt is null, was is { DeletedAt: null });
if (live && !wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Created));
else if (!live && wasLive) changes.Add(Change(project, Protocol.ProjectChanges.Deleted));
else if (live)
{
// Main passed to another project (the sidecars name another one Main): told as a rename, which lists read again for.
if (project.Name != was!.Name || project.IsMain != was.IsMain) changes.Add(Change(project, Protocol.ProjectChanges.Renamed));
if (project.HeadVersionId != was.HeadVersionId) changes.Add(Change(project, Protocol.ProjectChanges.Pushed));
}
}
return changes.Count == 0 && !settingsChanged ? null : new ProjectChangeSet(sequenceId, changes, settingsChanged);
static ProjectChange Change(SequenceProject project, string change) => new(project.Id, change, project.HeadNumber, project.HeadVersionId);
}
/// <summary>Tells the host what a call changed; a failure is logged, never passed on.</summary>
internal static async Task TellAsync(ArchiveServiceOptions options, ProjectChangeSet changed)
{
try
{
await options.ProjectsChanged!(changed, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
Log.Warning("projects", $"The project changes of sequence {changed.SequenceId} were not told", ex);
}
}
@@ -664,9 +799,15 @@ public sealed class ProjectService
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
if (LeadingCopy(context, shared, CurrentPortable(context, photos), photos) is { } copy && !ProjectContent.SameChoices(head.SettingsJson, copy, photos)
&& !await MirroredBeforeAsync(main, head, null, copy, photos, cancellationToken).ConfigureAwait(false))
{
await KeepCopyAsync(context, main, head, shared, copy, photos, cancellationToken).ConfigureAwait(false);
return;
}
if (ProjectContent.SameChoices(head.SettingsJson, shared, photos))
{
if (CurrentPortable(context, photos) is { } copy && ProjectContent.SameChoices(head.SettingsJson, copy, photos))
if (CurrentPortable(context, photos) is { } current && ProjectContent.SameChoices(head.SettingsJson, current, photos))
await MarkMirroredAsync(context, main, head, photos, cancellationToken).ConfigureAwait(false);
else
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
@@ -691,6 +832,58 @@ public sealed class ProjectService
await MirrorAsync(context, main, external, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Main met with no mirror known on a host whose index may hold newer settings than <c>project.json</c>
/// (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>), with this index's copy (<paramref name="copy"/>) none of
/// Main's versions: which of the two is newer cannot be told (an earlier server's <c>PATCH</c> wrote the index alone, an
/// index taken back from a backup is old), so both are kept. The copy becomes an External version on the head, and on
/// it the settings the meeting puts in force as it does elsewhere, from <c>project.json</c>: the head (a mirror cut
/// short, brought back as a Restore), a merge with the versions no mirror wrote, or <c>project.json</c>'s as External.
/// That is mirrored.
/// </summary>
private async Task KeepCopyAsync(LeaseContext context, SequenceProject main, ProjectVersion head, string shared, string copy, FramePhotos photos,
CancellationToken cancellationToken)
{
var recorded = await RecordedMirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
var headMirrored = context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored?.Id == head.Id;
var (inForce, kind) = ProjectContent.SameChoices(head.SettingsJson, shared, photos)
|| (!headMirrored && await MirroredBeforeAsync(main, head, recorded, shared, photos, cancellationToken).ConfigureAwait(false))
? (head.SettingsJson, ProjectVersionKind.Restore)
: recorded is not null && Merged(recorded, head, shared, photos) is { } merged
? (merged, ProjectVersionKind.Merge)
: (shared, ProjectVersionKind.External);
Log.Warning("projects", $"The settings of sequence {context.Row.Id} in the index differ from its project.json and from Main's versions: "
+ $"they are kept as version {head.Number + 1} of Main, and the settings project.json gives on top of it");
var kept = await AppendDerivedAsync(context, main, head, copy, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
var top = kept;
if (!ProjectContent.SameChoices(copy, inForce, photos))
{
var restoredFrom = kind == ProjectVersionKind.Restore ? head.Id : (Guid?)null;
top = NewVersion(main.Id, kept.Id, main.HeadNumber + 1, kind, inForce, context.Row.FramesVersion, DateTimeOffset.UtcNow) with { RestoredFrom = restoredFrom };
main = await AppendAsync(context.Folder, main, top, cancellationToken).ConfigureAwait(false);
}
// project.json's settings are taken in (kept or in force): the mirror writes over them.
await MirrorAsync(context, main, top, cancellationToken, shared).ConfigureAwait(false);
}
/// <summary>
/// <paramref name="theirs"/> merged with <paramref name="head"/> over <paramref name="basis"/> as <see cref="MergeIntoMainAsync"/>
/// merges them (<paramref name="theirs"/> wins where both changed); null when either is of a newer Chronos.
/// </summary>
private static string? Merged(ProjectVersion basis, ProjectVersion head, string theirs, FramePhotos photos)
{
try
{
return ProjectContent.Canonical(ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos)),
ProjectMerge.Read(ProjectContent.Rebind(theirs, photos)), ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, photos))).Merged.ToJson());
}
catch (NewerSettingsException)
{
return null;
}
}
/// <summary>
/// The version Main's record names as mirrored last, when it is one the head descends from (not the head itself) and of
/// a format this Chronos reads; null otherwise (an older record names none).
@@ -863,9 +1056,11 @@ public sealed class ProjectService
/// <summary>
/// The Main project of a sequence that has none: version 1 from the sequence's settings as its <c>project.json</c> holds
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. With the archive
/// read-only it is made in the index only, and nothing is written to the archive: its sidecars are written once the
/// archive takes writes (<see cref="WriteBackAsync"/>).
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. On a host whose index
/// may hold newer settings than the file (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>: the server) and when
/// the two differ, the index's copy is version 2 (External) on top, in force and mirrored: neither is lost. With the
/// archive read-only it is made in the index only, and nothing is written to the archive: its sidecars are written once
/// the archive takes writes (<see cref="WriteBackAsync"/>).
/// </summary>
private async Task MakeMainAsync(LeaseContext context, bool writable, CancellationToken cancellationToken)
{
@@ -884,20 +1079,39 @@ public sealed class ProjectService
UpdatedAt = now,
};
var first = NewVersion(project.Id, null, 1, ProjectVersionKind.Imported, portable, context.Row.FramesVersion, now);
var versions = new List<ProjectVersion> { first };
if (LeadingCopy(context, shared, copy, frames.Photos) is { } leading)
{
Log.Warning("projects", $"The settings of sequence {context.Row.Id} in the index differ from its project.json: Main is made with project.json's as "
+ "version 1 and the index's as version 2, in force");
versions.Add(NewVersion(project.Id, first.Id, 2, ProjectVersionKind.External, leading, context.Row.FramesVersion, now));
}
// Settings this Chronos cannot read (of a newer one) are never written over: the index's copy then stays as it is too.
var inStep = shared is null || copy is null || ProjectContent.SameChoices(portable, copy, frames.Photos);
var inStep = versions.Count == 1 && (shared is null || copy is null || ProjectContent.SameChoices(portable, copy, frames.Photos));
if (inStep) project = project with { MirroredSettingsVersion = context.Row.SettingsVersion, MirroredVersionId = first.Id };
if (!writable)
{
await AddProjectAsync(null, project, first, null, cancellationToken).ConfigureAwait(false);
await AddProjectAsync(null, project, versions, null, cancellationToken).ConfigureAwait(false);
return;
}
var onDisk = shared is not null && File.Exists(context.Folder.ProjectPath);
var made = await AddProjectAsync(context.Folder, project, first, onDisk ? new ProjectHead(first.Id, first.Number) : null, cancellationToken)
var made = await AddProjectAsync(context.Folder, project, versions, onDisk ? new ProjectHead(first.Id, first.Number) : null, cancellationToken)
.ConfigureAwait(false);
if (!inStep) await MirrorAsync(context, made, first, cancellationToken).ConfigureAwait(false);
// project.json holds version 1: what the mirror of version 2 writes over is taken in already.
if (!inStep) await MirrorAsync(context, made, versions[^1], cancellationToken, versions.Count > 1 ? shared : null).ConfigureAwait(false);
}
/// <summary>
/// This index's copy of the sequence's settings when it differs from its <c>project.json</c> on a host whose index may hold
/// the newer ones (<see cref="ArchiveServiceOptions.IndexSettingsMayLead"/>); null otherwise (the desktop, the two the same,
/// either unreadable, or no file: then <paramref name="shared"/> is the copy).
/// </summary>
private string? LeadingCopy(LeaseContext context, string? shared, string? copy, FramePhotos photos) =>
_writer.Options.IndexSettingsMayLead && shared is not null && copy is not null && File.Exists(context.Folder.ProjectPath)
&& !ProjectContent.SameChoices(shared, copy, photos)
? copy
: null;
/// <summary>"Main", or "Main (2)"… when a project of that name exists already (one made before the sequence had its Main).</summary>
private async Task<string> FreeMainNameAsync(Guid sequenceId, CancellationToken cancellationToken)
{
@@ -967,18 +1181,24 @@ public sealed class ProjectService
/// A new project with its first version: sidecars (version, then the record, naming <paramref name="mirrored"/>), then
/// both rows in one transaction; the rows only when <paramref name="folder"/> is null (a read-only archive).
/// </summary>
private async Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, ProjectVersion first, ProjectHead? mirrored,
private Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, ProjectVersion first, ProjectHead? mirrored,
CancellationToken cancellationToken) =>
AddProjectAsync(folder, project, [first], mirrored, cancellationToken);
/// <summary>A new project with its first versions, in order (each the next one's parent): the last is its head.</summary>
private async Task<SequenceProject> AddProjectAsync(SequencePaths? folder, SequenceProject project, IReadOnlyList<ProjectVersion> versions, ProjectHead? mirrored,
CancellationToken cancellationToken)
{
var withHead = project with { HeadVersionId = first.Id, HeadNumber = first.Number };
var head = versions[^1];
var withHead = project with { HeadVersionId = head.Id, HeadNumber = head.Number };
if (folder is not null)
{
ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, first.Number, first.Id), first);
foreach (var version in versions) ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, version.Number, version.Id), version);
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), ProjectRecord.Of(withHead, mirrored));
}
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Projects.InsertAsync(withHead with { HeadVersionId = null, HeadNumber = 0 }, cancellationToken).ConfigureAwait(false);
await tx.Projects.InsertVersionAsync(first, cancellationToken).ConfigureAwait(false);
foreach (var version in versions) await tx.Projects.InsertVersionAsync(version, cancellationToken).ConfigureAwait(false);
await tx.Projects.UpdateAsync(withHead, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
return withHead;
@@ -1222,6 +1442,12 @@ public sealed class ProjectService
? project
: throw new ProjectException(ProjectError.NotFound, $"Project {projectId} was deleted.");
/// <summary>
/// Whether the sequence has no folder in its archive yet (a server's sequence made before its first photo): its folder
/// would read as the archive's root, which every such sequence shares and which is no sequence's.
/// </summary>
private static bool Unplaced(Sequence row) => string.IsNullOrEmpty(row.Folder);
private static ProjectException SequenceMissing(Guid sequenceId) => new(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
/// <summary>The sequence as read under its lease (the mirror moves its settings version), its folder, and what its projects' reconcile met.</summary>
+123
View File
@@ -0,0 +1,123 @@
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Protocol;
namespace Chronos.Data.Projects;
/// <summary>
/// Projects and their versions on the wire (owner review 2, R8): what a server answers from its index, and how a client
/// reads it back into the model a workspace works with, so a server is a project home like this PC's archive; with the
/// wire names of the push outcomes.
/// </summary>
public static class ProjectWire
{
/// <summary>A project as the API shows it; <paramref name="head"/> (its head version) says who changed it last, and when.</summary>
public static ProjectDto ToDto(SequenceProject project, ProjectVersion? head = null)
{
ArgumentNullException.ThrowIfNull(project);
return new ProjectDto(project.Id, project.SequenceId, project.Name, project.IsMain, project.HeadVersionId, project.HeadNumber, project.CreatedBy,
project.CreatedAt, project.UpdatedAt, head is null ? null : ProjectVersionKinds.Name(head.Kind), head?.Author, head?.ClientName, head?.StoredAt);
}
public static ProjectVersionDto ToDto(ProjectVersion version)
{
ArgumentNullException.ThrowIfNull(version);
return new ProjectVersionDto(version.Id, version.ProjectId, version.ParentId, version.Number, ProjectVersionKinds.Name(version.Kind), version.Author,
version.ClientName, version.Note, version.SettingsJson, version.ContentHash, version.SettingsFormat, version.FramesVersion, version.RestoredFrom,
version.CreatedAt, version.StoredAt);
}
/// <summary>A project of a server sequence as the model knows it (the mirror fields stay the server's own).</summary>
public static SequenceProject ToProject(ProjectDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new SequenceProject
{
Id = dto.Id,
SequenceId = dto.SequenceId,
Name = dto.Name,
IsMain = dto.IsMain,
HeadVersionId = dto.HeadVersionId,
HeadNumber = dto.HeadNumber,
CreatedBy = dto.CreatedBy,
CreatedAt = dto.CreatedAt,
UpdatedAt = dto.UpdatedAt,
};
}
/// <summary>A version as the model knows it; a kind this build does not know reads as a commit (<see cref="ProjectVersionKinds.Parse"/>).</summary>
public static ProjectVersion ToVersion(ProjectVersionDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new ProjectVersion
{
Id = dto.Id,
ProjectId = dto.ProjectId,
ParentId = dto.ParentId,
Number = dto.Number,
Kind = ProjectVersionKinds.Parse(dto.Kind),
Author = dto.Author,
ClientName = dto.ClientName,
Note = dto.Note,
SettingsJson = dto.SettingsJson,
ContentHash = dto.ContentHash,
SettingsFormat = dto.SettingsFormat,
FramesVersion = dto.FramesVersion,
RestoredFrom = dto.RestoredFrom,
CreatedAt = dto.CreatedAt,
StoredAt = dto.StoredAt,
};
}
/// <summary>The wire name of <paramref name="outcome"/> (<see cref="ProjectPushOutcomes"/>).</summary>
public static string Outcome(PushOutcome outcome) => outcome switch
{
PushOutcome.Stored => ProjectPushOutcomes.Stored,
PushOutcome.AlreadyStored => ProjectPushOutcomes.AlreadyStored,
PushOutcome.Diverged => ProjectPushOutcomes.Diverged,
PushOutcome.HashMismatch => ProjectPushOutcomes.HashMismatch,
PushOutcome.NewerFormat => ProjectPushOutcomes.NewerFormat,
PushOutcome.TooLarge => ProjectPushOutcomes.TooLarge,
_ => ProjectPushOutcomes.Invalid,
};
/// <summary>The outcome a wire name stands for; one this build does not know is a refusal (<see cref="PushOutcome.Invalid"/>).</summary>
public static PushOutcome ParseOutcome(string? name) => name switch
{
ProjectPushOutcomes.Stored => PushOutcome.Stored,
ProjectPushOutcomes.AlreadyStored => PushOutcome.AlreadyStored,
ProjectPushOutcomes.Diverged => PushOutcome.Diverged,
ProjectPushOutcomes.HashMismatch => PushOutcome.HashMismatch,
ProjectPushOutcomes.NewerFormat => PushOutcome.NewerFormat,
ProjectPushOutcomes.TooLarge => PushOutcome.TooLarge,
_ => PushOutcome.Invalid,
};
/// <summary>A push's answer as <see cref="ProjectService.PushAsync"/> gives it on this PC's archive.</summary>
public static PushResult ToResult(ProjectPushResultDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
return new PushResult(ParseOutcome(dto.Outcome), dto.Version is null ? null : ToVersion(dto.Version), dto.Head is null ? null : ToVersion(dto.Head));
}
/// <summary>
/// The links a server sends with a sequence's frames (<see cref="ProjectFramesDto.Aliases"/>): its tombstones of reason
/// <c>replaced</c> with their replacement.
/// </summary>
public static IReadOnlyList<RemovedPhotoDto> Aliases(IEnumerable<FrameRemoval> removals) =>
Sync.SyncTombstones.ToDto(removals.Where(r => r.Reason == RemovalReason.Replaced && !string.IsNullOrEmpty(r.ReplacementSha256)));
/// <summary>
/// The frames a server sequence's project positions are placed on, as <see cref="ProjectService.FramesAsync"/> gives a
/// sequence of this PC's archive: rows in index order and their photos, with the encodings its conversions joined.
/// </summary>
public static HomeFrames ToHomeFrames(ProjectFramesDto dto)
{
ArgumentNullException.ThrowIfNull(dto);
var frames = dto.Frames.Select(RenderNodeClient.ToFrame).OrderBy(f => f.Index).ToList();
var aliases = (dto.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
return new HomeFrames(dto.FramesVersion, frames, HomePhotos.Of(frames, aliases));
}
}
@@ -0,0 +1,231 @@
using System.Net;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.Data.Projects;
/// <summary>
/// A sequence of a Chronos Server as its projects' home (owner review 2, R8, phase 5b): the server's
/// <c>/api/v1/sequences/{sid}/projects</c> through <see cref="ChronosClient"/>, read into the model a workspace works with
/// (<see cref="ProjectWire"/>), so a workspace pushes to and pulls from a server as it does with this PC's archive. A
/// server out of reach (no answer, a timeout, a certificate it no longer presents, an answer that is not the API's), a
/// sign-in that expired, a sequence the server holds busy or an archive offline there (503), a project file it cannot write
/// for now and a server that keeps no projects are <see cref="HomeUnavailableException"/>s: the workspace shows Offline and
/// its work waits. A sequence, project or version the server does not have, and a name it refuses, are
/// <see cref="ProjectException"/>s as on this PC's archive; anything else (an account without the right, a request the
/// server takes for wrong) keeps its <see cref="ChronosApiException"/>. A push answers its outcome without throwing (a
/// divergence carries the head). The client is the caller's: the home never disposes it, and a client disposed meanwhile
/// (the session ended) is a home out of reach.
/// </summary>
public sealed class ServerProjectHome : IProjectHome
{
/// <summary>The largest page of versions the server answers.</summary>
private const int MaxPage = 200;
/// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress);
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
}
public ChronosClient Client { get; }
/// <summary>The server's sequence.</summary>
public Guid SequenceId { get; }
/// <summary>The server as workspace projects and sync links name it (<see cref="SyncService.ServerKey"/>).</summary>
public string Server { get; }
public string ServerName { get; }
/// <summary>The home of a workspace project of this server's sequence.</summary>
public BundleHome Home => new(BundleHome.ServerKind, SequenceId, null, Server);
/// <remarks>
/// A project file names an archive by id: a server's sequences carry one made from the server's key
/// (<see cref="ArchiveIdOf"/>), with the server's name and no path.
/// </remarks>
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) =>
Reach(async () =>
{
var sequence = await Client.GetSequenceAsync(SequenceId, cancellationToken).ConfigureAwait(false);
return new HomeSequence(new BundleArchive(ArchiveIdOf(Server), ServerName, null), new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle,
sequence.FrameCount), Home);
}, cancellationToken);
/// <summary>
/// The archive id a server's sequences carry in a workspace's project file, which names one: the same for every
/// sequence of <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), made from its key (a version 8 UUID),
/// never one of this PC's archives.
/// </summary>
public static Guid ArchiveIdOf(string server)
{
ArgumentNullException.ThrowIfNull(server);
var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("chronos-server-archive:" + server));
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) =>
Reach<IReadOnlyList<SequenceProject>>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
/// <remarks>The server records the account that makes the project as its maker, whatever <paramref name="author"/> says.</remarks>
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.CreateProjectAsync(SequenceId, new CreateProjectRequest(name, fromVersionId), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToVersion(await Client.GetProjectHeadAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(async () => await Client.GetProjectVersionAsync(SequenceId, projectId, versionId, cancellationToken).ConfigureAwait(false) is { } version
? ProjectWire.ToVersion(version)
: null, cancellationToken);
/// <remarks>
/// The server ends a page early when its versions' settings are large (<see cref="ProjectVersionPageDto.More"/>): the
/// pages are read on until <paramref name="limit"/> versions came or no more follow, so a short answer always means the end.
/// </remarks>
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, last?.Number ?? afterNumber),
limit: Page(limit), ct: cancellationToken)), cancellationToken);
/// <remarks>Read on past a page the server ended early, as <see cref="VersionsAfterAsync"/> is.</remarks>
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => PagesAsync(Page(limit), last => Client.ListProjectVersionsAsync(SequenceId, projectId,
before: last is not null ? last.Number : beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit), ct: cancellationToken)),
cancellationToken);
/// <summary>Up to <paramref name="limit"/> versions, page after page (each read after the last version of the one before) while more follow.</summary>
private static async Task<IReadOnlyList<ProjectVersion>> PagesAsync(int limit, Func<ProjectVersion?, Task<ProjectVersionPageDto>> read)
{
var versions = new List<ProjectVersion>();
while (true)
{
var page = await read(versions.Count > 0 ? versions[^1] : null).ConfigureAwait(false);
versions.AddRange(page.Items.Take(limit - versions.Count).Select(ProjectWire.ToVersion));
if (!page.More || page.Items.Count == 0 || versions.Count >= limit) return versions;
}
}
/// <summary>
/// Read back from the version's file on the server (<c>?stored=true</c>: <see cref="ProjectService.StoredAsync"/> there),
/// never from its index's row: false when the file is missing or damaged, or the project was deleted.
/// </summary>
public Task<bool> HoldsAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () =>
{
if (!ProjectContent.Verifies(version.SettingsJson, version.ContentHash)) return false;
try
{
return await Client.GetStoredProjectVersionAsync(SequenceId, projectId, version.Id, cancellationToken).ConfigureAwait(false) is { } held
&& held.ProjectId == projectId && string.Equals(held.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase);
}
catch (ChronosApiException ex) when (ex is { Status: HttpStatusCode.NotFound, Error.Details: "project" })
{
return false;
}
}, cancellationToken);
}
/// <summary>The server's stamp of the frames (<c>GET …/projects/frames/stamp</c>): the frames are downloaded again only when it moved.</summary>
public Task<string?> FramesStampAsync(CancellationToken cancellationToken) =>
Reach<string?>(async () => (await Client.GetProjectFramesStampAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Stamp, cancellationToken);
/// <remarks>The server numbers the version (head + 1) and records the account that pushed it as its author.</remarks>
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () => ProjectWire.ToResult(await Client.PushProjectVersionAsync(SequenceId, projectId, ProjectWire.ToDto(version), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
}
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToHomeFrames(await Client.GetProjectFramesAsync(SequenceId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.RenameProjectAsync(SequenceId, projectId, name, cancellationToken).ConfigureAwait(false)),
cancellationToken);
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Client.DeleteProjectAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>
/// Whether <paramref name="exception"/> says a server is out of reach for now (see the class remarks), not that it
/// refused: what a workspace waits out.
/// </summary>
public static bool IsUnavailable(Exception exception, CancellationToken cancellationToken = default) => exception switch
{
HomeUnavailableException => true,
// A refusal for good, which is an IOException too.
Workspaces.WorkspaceSyncException => false,
ChronosApiException api => Unavailable(api),
UntrustedCertificateException or HttpRequestException or JsonException or ObjectDisposedException => true,
// A timeout of the client's (not the caller's cancellation).
OperationCanceledException => !cancellationToken.IsCancellationRequested,
IOException => true,
_ => false,
};
private static int Page(int limit) => Math.Clamp(limit, 1, MaxPage);
/// <summary>A refusal of the server as this PC's archive gives it, or a server out of reach.</summary>
private static async Task<T> Reach<T>(Func<Task<T>> call, CancellationToken cancellationToken)
{
try
{
return await call().ConfigureAwait(false);
}
catch (ChronosApiException ex) when (Refusal(ex) is { } refusal)
{
throw refusal;
}
catch (Exception ex) when (ex is not ProjectException && IsUnavailable(ex, cancellationToken))
{
throw new HomeUnavailableException(ex is ChronosApiException { Status: HttpStatusCode.Unauthorized }
? $"The sign-in on the server expired: {ex.Message}"
: $"The server cannot be reached: {ex.Message}", ex);
}
}
/// <summary>The project error a refusal stands for (a sequence, project or version the server does not have, a name it refuses); null for any other.</summary>
private static ProjectException? Refusal(ChronosApiException ex) => (ex.Status, ex.Error.Code, ex.Error.Details) switch
{
(HttpStatusCode.NotFound, _, "sequence") => new ProjectException(ProjectError.SequenceNotFound, ex.Message),
(HttpStatusCode.NotFound, _, "project" or "version") => new ProjectException(ProjectError.NotFound, ex.Message),
(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, _) => new ProjectException(ProjectError.InvalidName, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.NameTaken, _) => new ProjectException(ProjectError.NameTaken, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, _) => new ProjectException(ProjectError.MainCannotBeDeleted, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.SequenceEmpty, _) => new ProjectException(ProjectError.SequenceEmpty, ex.Message),
_ => null,
};
/// <summary>
/// An answer that says the server cannot serve the call for now: busy, its archive offline or its sequence's folder
/// moved (503), a gateway or a timeout, the sign-in expired (401), a project file it cannot write now (409
/// <c>folder_in_use</c>), a server without the projects (404 with nothing named: the API's fallback), or a success
/// that is no answer of the API (a portal's or a proxy's page).
/// </summary>
private static bool Unavailable(ChronosApiException ex) =>
ex.IsTransient
|| ex.Status == HttpStatusCode.Unauthorized
|| (int)ex.Status is >= 200 and < 300
|| ex is { Status: HttpStatusCode.Conflict, Error.Code: "folder_in_use" }
|| ex is { Status: HttpStatusCode.NotFound, Error.Details: null or "" };
}
+53 -1
View File
@@ -59,6 +59,17 @@ public sealed class SyncAgent : IAsyncDisposable
private readonly SemaphoreSlim _refreshing = new(1, 1);
private Task _running = Task.CompletedTask;
/// <summary>
/// Whether project changes may have been missed: <see cref="Missed"/> from the moment the event stream was lost,
/// <see cref="Reopened"/> once it is open again (no change is missed from then on), back to <see cref="InStep"/> when a
/// comparison that started after that reached the server and <see cref="ProjectChanged"/> said so.
/// </summary>
private int _projectsMissed;
private const int InStep = 0;
private const int Missed = 1;
private const int Reopened = 2;
private SyncSnapshot? _snapshot;
private Exception? _lastError;
@@ -84,6 +95,13 @@ public sealed class SyncAgent : IAsyncDisposable
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
public event Action? Changed;
/// <summary>
/// A project of one of the server's sequences changed there (owner review 2, R8: <c>projectChanged</c>, any thread), or,
/// with null, a comparison reached the server again after its event stream was lost, so changes may have been missed:
/// workspace projects whose home is this server read where they stand again.
/// </summary>
public event Action<ProjectChangedEvent?>? ProjectChanged;
/// <summary>Starts the comparison and event loops.</summary>
public void Start()
{
@@ -104,12 +122,16 @@ public sealed class SyncAgent : IAsyncDisposable
await _refreshing.WaitAsync(linked.Token).ConfigureAwait(false);
try
{
// Only a comparison that started once the stream was open again covers every change missed meanwhile: one that
// started before may end while the stream is still down, and a change said then would be missed for good.
var reopened = Volatile.Read(ref _projectsMissed) == Reopened;
var policy = _policy();
var snapshot = await _sync.RefreshAsync(_remote, policy, linked.Token).ConfigureAwait(false);
Volatile.Write(ref _snapshot, snapshot);
Volatile.Write(ref _lastError, null);
if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
Changed?.Invoke();
if (reopened && Interlocked.CompareExchange(ref _projectsMissed, InStep, Reopened) == Reopened) TellProjects(null);
return snapshot;
}
finally
@@ -169,9 +191,14 @@ public sealed class SyncAgent : IAsyncDisposable
{
try
{
await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false))
await foreach (var e in _remote.EventsAsync(Reconnected, cancellationToken).ConfigureAwait(false))
{
failures = 0;
if (e is ProjectChangedEvent project)
{
TellProjects(project);
continue;
}
if (e is not SequenceChangedEvent changed) continue;
_changed[changed.SequenceId] = 0;
_eventWake.Writer.TryWrite(true);
@@ -185,6 +212,9 @@ public sealed class SyncAgent : IAsyncDisposable
{
Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}");
}
// Project changes said meanwhile are missed: the first comparison that reaches the server once the stream is open
// again says so (Reconnected).
Volatile.Write(ref _projectsMissed, Missed);
try
{
await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false);
@@ -197,6 +227,28 @@ public sealed class SyncAgent : IAsyncDisposable
}
}
/// <summary>
/// The event stream is open (again): after a loss, a comparison is asked for now, and the one that starts from here says
/// that project changes may have been missed (<see cref="ProjectChanged"/> with null).
/// </summary>
private void Reconnected()
{
if (Interlocked.CompareExchange(ref _projectsMissed, Reopened, Missed) == Missed) RequestRefresh();
}
/// <summary>Tells <see cref="ProjectChanged"/>; what a listener throws is logged, never ends the event loop.</summary>
private void TellProjects(ProjectChangedEvent? change)
{
try
{
ProjectChanged?.Invoke(change);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning(LogCategory, $"A project change of {Server} was not handled", ex);
}
}
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
private async Task ChangedLoopAsync(CancellationToken cancellationToken)
{
+28
View File
@@ -63,6 +63,28 @@ public interface ISyncRemote : IDisposable
/// <summary>Server events until cancelled or the socket closes.</summary>
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
/// <summary>
/// <see cref="EventsAsync(CancellationToken)"/>, calling <paramref name="connected"/> once the stream is open, before its
/// first event: from then on no event the server sends is missed. A remote that cannot say calls it when the stream is
/// asked for.
/// </summary>
IAsyncEnumerable<ServerEvent> EventsAsync(Action connected, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(connected);
connected();
return EventsAsync(cancellationToken);
}
/// <summary>
/// Every frame of a sequence as of one frames version, with the photo aliases of its conversions (owner review 2, R8:
/// what a workspace copy of a server project holds; servers with the <c>projects</c> capability). A remote without the
/// call (the screenshots' sample server) throws <see cref="NotSupportedException"/>.
/// </summary>
Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <summary>The sequence's deep-analysis report (<c>analysis.json</c>); null when it was never deep-analysed, or the remote has no such call.</summary>
Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
}
/// <summary>Where sync jobs find their server connection.</summary>
@@ -138,6 +160,12 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
public IAsyncEnumerable<ServerEvent> EventsAsync(Action connected, CancellationToken cancellationToken) => client.EventsAsync(connected, cancellationToken);
public Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetProjectFramesAsync(sequenceId, cancellationToken);
public Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(sequenceId, cancellationToken);
public void Dispose()
{
if (ownsClient) client.Dispose();
+96 -9
View File
@@ -774,32 +774,54 @@ internal sealed class SyncTransfers(SyncService sync)
var cached = new FileInfo(path) is { Exists: true, Length: > 0 };
if (cached && (cachedKind == ProxyCache.Proxy || !offered.Contains(ProxyCache.Proxy))) return (name, cachedKind ?? ProxyCache.Thumb);
var part = path + ".part";
foreach (var kind in offered)
// The cached file is as good as the server's thumbnail.
var kind = await DownloadFirstAsync(remote, frameId, offered.TakeWhile(k => !(cached && k == ProxyCache.Thumb)), part, null, cancellationToken)
.ConfigureAwait(false);
if (kind is not null)
{
File.Move(part, path, overwrite: true);
return (name, kind);
}
return cached ? (name, ProxyCache.Thumb) : null;
}
/// <summary>
/// Downloads the first of <paramref name="kinds"/> a frame has on the server (a 404 tries the next) into a fresh
/// <paramref name="part"/> file, written through <paramref name="through"/> when given (a hash of what arrives, which
/// leaves the file open) and flushed to the disk when <paramref name="durable"/>; the kind it got, or null when the server
/// has none of them, no part file left then. The proxy cache and the workspace copy of a server project (owner review 2,
/// R8) download alike.
/// </summary>
internal static async Task<string?> DownloadFirstAsync(ISyncRemote remote, Guid frameId, IEnumerable<string> kinds, string part, Func<Stream, Stream>? through,
CancellationToken cancellationToken, bool durable = false)
{
foreach (var kind in kinds)
{
// The cached file is as good as the server's thumbnail.
if (cached && kind == ProxyCache.Thumb) break;
try
{
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
File.Move(part, path, overwrite: true);
return (name, kind);
{
await remote.DownloadFrameAsync(frameId, kind, through?.Invoke(file) ?? file, cancellationToken).ConfigureAwait(false);
if (durable) file.Flush(flushToDisk: true);
}
return kind;
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
File.Delete(part);
}
}
return cached ? (name, ProxyCache.Thumb) : null;
return null;
}
/// <summary>
/// A frame missing or damaged on the server: its manifest never asks for its proxy and a pass makes none of a missing
/// one, so the thumbnail (or the lack of a file) that stands in for it does not keep the cache stale.
/// </summary>
private static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
internal static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
/// <summary>The kinds of a frame's assets the server offers, the proxy before the thumbnail that stands in while it has none.</summary>
internal static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],
(true, false) => [ProxyCache.Proxy],
@@ -867,3 +889,68 @@ internal sealed class SyncTransfers(SyncService sync)
public ValueTask ReportAsync() => context.ReportAsync(done, total);
}
}
/// <summary>
/// A write-only stream that hashes (SHA-256) what passes through it into <paramref name="inner"/>, which it leaves open: the
/// hash of a download as it arrived, to check the file it was written to against (owner review 2, R8). It cannot seek,
/// so a download through it always starts from the beginning.
/// </summary>
internal sealed class HashingStream(Stream inner) : Stream
{
private readonly System.Security.Cryptography.IncrementalHash _hash = System.Security.Cryptography.IncrementalHash.CreateHash(
System.Security.Cryptography.HashAlgorithmName.SHA256);
private long _written;
/// <summary>The bytes written through.</summary>
public long Written => _written;
/// <summary>The lower-case hex SHA-256 of what was written through (once; it resets the hash).</summary>
public string Sha256() => Convert.ToHexStringLower(_hash.GetHashAndReset());
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
_hash.AppendData(buffer);
_written += buffer.Length;
inner.Write(buffer);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
_hash.AppendData(buffer.Span);
_written += buffer.Length;
return inner.WriteAsync(buffer, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (disposing) _hash.Dispose();
base.Dispose(disposing);
}
}
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
@@ -12,6 +13,9 @@ using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Workspaces;
@@ -31,10 +35,28 @@ public static class WorkspaceJobs
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name).
/// <see cref="JobKind.WorkspaceCopy"/> of a project whose home is a server (phase 5b): the media of workspace project
/// <paramref name="projectId"/> (checked out first) downloaded from sequence <paramref name="sequenceId"/> of
/// <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), into the workspace alone. The job's target is the
/// server's sequence, as for a sync download.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => [new WorkspaceCopyJobHandler(db, archives)];
public static ArchiveJobRequest CopyFromServer(Guid sequenceId, string title, string server, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media, server), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name); copies from a server fail without a connection to it.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => CreateHandlers(db, archives, null);
/// <param name="servers">The connection a copy from a server's sequence downloads through (the desktop's signed-in session).</param>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers) =>
[new WorkspaceCopyJobHandler(db, archives, servers)];
/// <summary>
/// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
@@ -70,14 +92,32 @@ public static class WorkspaceJobs
/// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler
/// runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// Originals come in phase 5c: asked for, the job fails saying so.
/// A project whose home is a server (phase 5b, <see cref="WorkspaceJobs.CopyFromServer"/>) has its media downloaded from
/// the server through the desktop's session (<see cref="ISyncConnector"/>), never through this PC's archive: the frames as
/// of one frames version with the aliases of the server's conversions (<c>GET …/projects/frames</c>), each frame's proxy as
/// the proxy cache fetches it (<see cref="SyncTransfers.DownloadFirstAsync"/>: the proxy, else the thumbnail standing in
/// while the server has none, recorded as such and replaced by a later copy once the server has the proxy), hashed as it
/// arrives and checked against the file written, four at a time; then the server's deep report. A file the editor's media
/// or this run hold of the same photo is hashed again and kept; the editor's file is never written over, as above. The
/// space, the passes, the checkpoint and a cancelled first copy go as for a copy from this PC's archive (the server's
/// folder of the sequence in the checkpoint). Like the sync's downloads it is not held on a metered connection.
/// </summary>
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : ICancelledJobHandler
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers = null) : ICancelledJobHandler
{
private const int PageSize = 1000;
private const int Passes = 3;
/// <summary>Frames downloaded at once from a server (as the sync's downloads).</summary>
private const int Downloads = 4;
/// <summary>Frames downloaded between two looks at the checkpoint clock.</summary>
private const int DownloadBatch = 32;
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
/// <summary>Beside a server's thumbnail downloaded for a frame until the copy commits: what it is, should the run stop first.</summary>
internal const string StandInSuffix = ".thumb";
/// <summary>Bytes left free on the workspace's drive besides the copy, as a download keeps (<see cref="SyncTransfers"/>).</summary>
internal const long SpaceReserve = 512L << 20;
@@ -97,6 +137,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
var parameters = Parameters(context.Job);
if (parameters.Media == BundleMedia.Originals) throw new NotSupportedException(Loc.L("Errors.Workspace.OriginalsLater"));
if (parameters.Media != BundleMedia.Proxies) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Server is { Length: > 0 } server)
{
await RunFromServerAsync(context, parameters, server).ConfigureAwait(false);
return;
}
if (context.Job.TargetIds is not [var sequenceId] || await db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) is not { } sequence
|| await db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false) is not { } archive)
throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", context.Job.TargetIds.FirstOrDefault()));
@@ -336,7 +381,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, row);
Commit(project, project.ReadBundle(), media, row.Folder, row.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
@@ -345,6 +390,293 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
}
}
/// <summary>
/// The copy of a project whose home is a server (see the class remarks): its frames and their files downloaded into the
/// workspace, then the media index and the working state moved onto them as for a copy from this PC's archive.
/// </summary>
private async Task RunFromServerAsync(JobContext context, WorkspaceCopyParameters parameters, string server)
{
var ct = context.Cancellation;
if (context.Job.TargetIds is not [var sequenceId]) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
// Asked before the store is opened, which makes its folder (as for a copy from this PC's archive).
if (await InsideALibraryAsync(parameters.WorkspaceRoot, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
if (project.ReadBundle().Workspace is not { Home: { Kind: BundleHome.ServerKind } home } || home.SequenceId != sequenceId
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
try
{
using (WritingMedia(project))
{
using var remote = (servers is null ? null : await servers.ConnectAsync(server, ct).ConfigureAwait(false))
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
await DownloadAsync(context, project, remote, sequenceId, parameters, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Stopped writing: what a first copy the user cancelled wrote goes (a pause or a shutdown resumes it).
await RemovePartialMediaAsync(context.Job, project).ConfigureAwait(false);
throw;
}
}
private async Task DownloadAsync(JobContext context, WorkspaceProject project, ISyncRemote remote, Guid sequenceId, WorkspaceCopyParameters parameters,
CancellationToken ct)
{
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
// What this run downloaded, pass after pass: kept where a frame still shows the same photo.
var fetched = new Dictionary<Guid, WorkspaceFrame>();
for (var pass = 1; ; pass++)
{
var (sequence, frames, assets, aliases, framesVersion, spec) = await ServerFramesAsync(remote, sequenceId, ct).ConfigureAwait(false);
var folder = sequence.Folder ?? string.Empty;
if ((checkpointVersion is { } version && version != framesVersion) || (checkpointFolder is { } read && read != folder)) copied = 0;
var total = (long)frames.Count;
var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? [];
Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive: the copy never fills it (the server's files estimated at its proxy size).
var remaining = RemainingDownloads(project, frames, assets, spec);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]);
var clock = System.Diagnostics.Stopwatch.StartNew();
var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct };
for (var start = 0; start < frames.Count; start += DownloadBatch)
{
var end = Math.Min(frames.Count, start + DownloadBatch);
var done = copied;
await Parallel.ForEachAsync(Enumerable.Range(start, end - start), options, async (i, token) =>
entries[i] = await DownloadAsync(remote, project, frames[i], assets.GetValueOrDefault(frames[i].Id), i < done, current.GetValueOrDefault(frames[i].Id),
fetched.GetValueOrDefault(frames[i].Id), tally, token).ConfigureAwait(false)).ConfigureAwait(false);
if (clock.Elapsed >= CheckpointEvery || end == frames.Count)
{
await context.CheckpointAsync(Checkpoint(Stage.Copy, end, framesVersion, folder), end, total).ConfigureAwait(false);
// Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[end]);
clock.Restart();
}
else
{
await context.ReportAsync(end, total).ConfigureAwait(false);
}
}
foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry;
var analysis = await CopyServerAnalysisAsync(remote, sequenceId, project, frames.Count, ct).ConfigureAwait(false);
var after = await remote.GetSequenceAsync(sequenceId, ct).ConfigureAwait(false);
if (after.FramesVersion != framesVersion && pass < Passes)
{
// The files read may be of other frames now: the next pass reads the frames again, keeping what still shows them,
// and so does a run resumed after a crash in it (the checkpoint stored says so).
context.Log(Loc.L("Archive.Log.WorkspaceFramesChanged", sequence.DisplayTitle));
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, after.FramesVersion, after.Folder ?? string.Empty), 0, total).ConfigureAwait(false);
(copied, checkpointVersion, checkpointFolder) = (0, null, null);
continue;
}
// Frames still arriving are copied as they were read (Update media takes the rest).
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, framesVersion, entries,
DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null);
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, folder, sequence.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false);
return;
}
}
/// <summary>
/// A server sequence's frames in index order as of one frames version, the assets the server holds of each, the links
/// of its conversions, that frames version and the server's proxy size: the frames read twice around the manifest until
/// both are of the same one.
/// </summary>
private static async Task<(SequenceDto Sequence, List<Frame> Frames, Dictionary<Guid, ManifestFrame> Assets, IReadOnlyList<PhotoAlias> Aliases, int FramesVersion,
ProxySpec? Spec)> ServerFramesAsync(ISyncRemote remote, Guid sequenceId, CancellationToken cancellationToken)
{
for (var attempt = 1; ; attempt++)
{
ProjectFramesDto frames;
SequenceManifest manifest;
SequenceDto sequence;
try
{
sequence = await remote.GetSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
frames = await remote.GetProjectFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
manifest = await remote.GetManifestAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// The sequence is gone, or the server keeps no projects (its API knows no such call).
throw new InvalidOperationException(ex.Error.Details == "sequence" ? Loc.L("Archive.Log.SequenceMissing", sequenceId) : Loc.L("Errors.Workspace.NoProjects"), ex);
}
if (manifest.FramesVersion == frames.FramesVersion || attempt == Passes)
{
var home = ProjectWire.ToHomeFrames(frames);
var aliases = (frames.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
return (sequence, [.. home.Frames], manifest.Frames.ToDictionary(f => f.Id), aliases, frames.FramesVersion, manifest.Proxies);
}
}
}
/// <summary>
/// A frame's file from the server: kept when this run downloaded it before it stopped or in an earlier pass, or the
/// editor's media hold one of the same photo that is no thumbnail standing in for a proxy the server has now (hashed
/// again: a file that no longer matches is fetched anew); else its proxy, or the thumbnail while the server has none,
/// hashed as it arrives and checked against the file written (downloaded once more when they differ, then refused);
/// none for a frame without either, or missing or damaged on the server. The editor's file (<paramref name="current"/>)
/// is never written over: other bytes for it go under a name of their own, as for a copy from this PC's archive.
/// </summary>
private static async Task<WorkspaceFrame> DownloadAsync(ISyncRemote remote, WorkspaceProject project, Frame frame, ManifestFrame? asset, bool done,
WorkspaceFrame? current, WorkspaceFrame? fetched, Tally tally, CancellationToken cancellationToken)
{
var name = WorkspaceProject.ProxyName(frame.Id);
var target = project.MediaFile(name);
var listed = current is not null && string.Equals(current.File, name, StringComparison.OrdinalIgnoreCase);
IReadOnlyList<string> offered = asset is null || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? [] : SyncTransfers.Kinds(asset);
if (done && File.Exists(target))
{
var keptSha = await ContentHash.Sha256Async(target, cancellationToken: cancellationToken).ConfigureAwait(false);
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
// A run stopped before it recorded the file's kind left a marker beside a thumbnail it took for a missing proxy.
var keptKind = KindOf(fetched, keptSha) ?? KindOf(current, keptSha)
?? (File.Exists(StandInMarker(target)) ? ProxyCache.Thumb : offered.FirstOrDefault() ?? ProxyCache.Proxy);
if ((!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame)) && !(keptKind == ProxyCache.Thumb && offered.Contains(ProxyCache.Proxy)))
{
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, new FileInfo(target).Length, keptKind);
}
}
// What this run downloaded in an earlier pass, then the editor's file of the same photo, unless a thumbnail stands in
// there for a proxy the server has now.
foreach (var held in new[] { fetched, current })
{
if (held is not { File: { } file, FileSha256: { } heldSha } || !SamePhoto(held, frame) || (held.IsStandIn && offered.Contains(ProxyCache.Proxy))) continue;
var path = project.MediaFile(file);
if (!File.Exists(path)
|| !string.Equals(await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false), heldSha, StringComparison.OrdinalIgnoreCase))
continue;
tally.Keep();
return WorkspaceFrame.Of(frame, file, heldSha.ToLowerInvariant(), new FileInfo(path).Length, held.FileKind ?? ProxyCache.Proxy);
}
if (offered.Count == 0)
{
// A file an earlier copy left for the frame is never kept as its photo: a regenerable copy, it goes, unless the
// editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var part = target + ".part";
for (var attempt = 1; ; attempt++)
{
HashingStream? hashing = null;
string? kind;
string received;
long bytes;
try
{
kind = await SyncTransfers.DownloadFirstAsync(remote, frame.Id, offered, part, file =>
{
hashing?.Dispose();
return hashing = new HashingStream(file);
}, cancellationToken, durable: true).ConfigureAwait(false);
(received, bytes) = hashing is null ? (string.Empty, 0L) : (hashing.Sha256(), hashing.Written);
}
finally
{
hashing?.Dispose();
}
if (kind is null || bytes == 0)
{
if (File.Exists(part)) File.Delete(part);
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
// Other bytes for the file the editor's media name: under a name of their own, never over the editor's file.
var (file, path) = (name, target);
if (listed && current!.FileSha256 is { } editors && !string.Equals(editors, received, StringComparison.OrdinalIgnoreCase)
&& Holds(target, editors.ToLowerInvariant()))
{
file = WorkspaceProject.ProxyName(frame.Id, received);
path = project.MediaFile(file);
}
// The kind is known on disk before the file is: a run stopped after the move resumes with it.
if (kind == ProxyCache.Thumb) File.WriteAllBytes(StandInMarker(path), []);
else if (File.Exists(StandInMarker(path))) File.Delete(StandInMarker(path));
File.Move(part, path, overwrite: true);
if (await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false) == received)
{
if (kind == ProxyCache.Proxy) tally.Copy();
else tally.Make();
return WorkspaceFrame.Of(frame, file, received, bytes, kind);
}
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", path));
}
static string StandInMarker(string file) => file + StandInSuffix;
static string? KindOf(WorkspaceFrame? entry, string sha) =>
entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null;
}
/// <summary>
/// The bytes a copy from a server still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one more
/// entry, 0): nothing for a frame the workspace holds a file of already or the server has neither proxy nor thumbnail of,
/// else an estimate at the server's proxy size (its manifest gives no file's size).
/// </summary>
private static long[] RemainingDownloads(WorkspaceProject project, List<Frame> frames, Dictionary<Guid, ManifestFrame> assets, ProxySpec? spec)
{
var held = Directory.Exists(project.ProxiesDirectory) ? HeldFrames(Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg")) : [];
var policy = spec is null ? new ProxyPolicy() : new ProxyPolicy { LongEdge = spec.LongEdge, Quality = spec.Quality };
var remaining = new long[frames.Count + 1];
for (var i = frames.Count - 1; i >= 0; i--)
{
var frame = frames[i];
var bytes = held.Contains(frame.Id) || assets.GetValueOrDefault(frame.Id) is not { } asset || SyncTransfers.Kinds(asset).Length == 0 ? 0 : Estimate(frame, policy);
remaining[i] = remaining[i + 1] + bytes;
}
return remaining;
}
/// <summary>The server's deep report into the media folder when it describes these frames; its SHA-256, or null without one.</summary>
private static async Task<string?> CopyServerAnalysisAsync(ISyncRemote remote, Guid sequenceId, WorkspaceProject project, int frameCount,
CancellationToken cancellationToken)
{
string? json;
try
{
json = await remote.GetAnalysisReportAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
json = null;
}
try
{
if (json is null || Core.Analysis.Deep.DeepAnalysisReport.FromJson(json).FrameCount != frameCount)
{
if (File.Exists(project.AnalysisPath)) File.Delete(project.AnalysisPath);
return null;
}
}
catch (Exception ex) when (ex is InvalidDataException or JsonException)
{
Log.Warning("workspace", $"The deep report of server sequence {sequenceId} cannot be read; the workspace takes none", ex);
return null;
}
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var sha = Sha(bytes);
WriteVerified(project.AnalysisPath, bytes, sha);
return sha;
}
/// <summary>Whether <paramref name="folder"/> is an archive's root of this index or lies inside one.</summary>
private async Task<bool> InsideALibraryAsync(string folder, CancellationToken cancellationToken)
{
@@ -397,7 +729,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
if (!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, kept.Length);
}
}
@@ -424,7 +756,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// A file an earlier copy left for the frame (of other frames, or another folder's) is never kept as its photo by a
// resumed run: a regenerable copy, it goes, unless the editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Missing++;
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var sha = Sha(bytes);
@@ -432,12 +764,12 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
if (current?.File is { } held && !string.Equals(held, name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(current.FileSha256, sha, StringComparison.OrdinalIgnoreCase) && Holds(project.MediaFile(held), sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, held, sha, bytes.Length);
}
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
// Other bytes for the file the editor's media name (a conversion since): written under a name of their own, never over
@@ -450,13 +782,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
target = project.MediaFile(name);
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
}
WriteVerified(target, bytes, sha);
if (made) tally.Made++;
else tally.Copied++;
if (made) tally.Make();
else tally.Copy();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
@@ -504,11 +836,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// as the photo they hold for it, so one whose file a conversion replaced (the same frame, another SHA-256) keeps its
/// positions, as the archive's own settings do (<see cref="ProjectPositions"/>).
/// </summary>
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, Sequence row)
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, string folder, string title)
{
var old = TryReadMedia(project);
var workspace = bundle.Workspace! with { Media = new BundleMedia(BundleMedia.Proxies, media.FramesVersion) };
var sequence = bundle.Sequence with { Folder = row.Folder, Title = row.DisplayTitle, Frames = media.Frames.Count };
var sequence = bundle.Sequence with { Folder = folder, Title = title, Frames = media.Frames.Count };
var working = bundle.Project;
// Without the media index the positions were made against, they are taken as naming these frames.
if (!working.IsNewerFormat && old is not null)
@@ -534,14 +866,19 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
held.Size == frame.Size && held.CapturedAt == frame.CapturedAt
&& (string.IsNullOrEmpty(held.Sha256) || string.IsNullOrEmpty(frame.Sha256) || string.Equals(held.Sha256, frame.Sha256, StringComparison.OrdinalIgnoreCase));
/// <summary>Proxies of frames the sequence no longer has: regenerable copies, removed so the media folder holds the frames listed.</summary>
/// <summary>
/// Proxies of frames the sequence no longer has, and downloads a stopped copy from a server left half done: regenerable
/// copies, removed so the media folder holds the frames listed.
/// </summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
{
var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg"))
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg").Concat(Directory.EnumerateFiles(project.ProxiesDirectory, "*.part")))
{
if (!listed.Contains(Path.GetFileName(file))) TryDelete(file);
}
// The media committed record each file's kind: the markers of a run are done with.
foreach (var marker in Directory.EnumerateFiles(project.ProxiesDirectory, "*" + StandInSuffix)) TryDelete(marker);
}
private static void TryDelete(string file)
@@ -718,11 +1055,30 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return (next, version, parts.Length == 4 ? parts[3] : null);
}
/// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary>
private sealed class Tally
{
public int Copied { get; set; }
public int Made { get; set; }
public int Kept { get; set; }
public int Missing { get; set; }
private int _copied;
private int _made;
private int _kept;
private int _missing;
/// <summary>Proxies copied (from the archive) or downloaded (from a server).</summary>
public int Copied => Volatile.Read(ref _copied);
/// <summary>Proxies made from the originals (from the archive), or thumbnails standing in for them (from a server).</summary>
public int Made => Volatile.Read(ref _made);
public int Kept => Volatile.Read(ref _kept);
public int Missing => Volatile.Read(ref _missing);
public void Copy() => Interlocked.Increment(ref _copied);
public void Make() => Interlocked.Increment(ref _made);
public void Keep() => Interlocked.Increment(ref _kept);
public void Miss() => Interlocked.Increment(ref _missing);
}
}
+13 -4
View File
@@ -13,6 +13,10 @@ namespace Chronos.Data.Workspaces;
/// editor read) and the file the workspace holds for it, with its SHA-256 and size as copied.
/// </summary>
/// <param name="File">The file relative to the media folder ("proxies/&lt;frame id&gt;.jpg"); null when the workspace holds none.</param>
/// <param name="FileKind">
/// What the file is when a server sent it (phase 5b): <c>proxy</c>, or <c>thumb</c>, a thumbnail standing in while the server
/// had no proxy of the frame, which a later copy replaces once it has one; null for a proxy (copies from this PC's archive).
/// </param>
public sealed record WorkspaceFrame(
Guid Id,
int Index,
@@ -41,18 +45,23 @@ public sealed record WorkspaceFrame(
FrameFlags Flags,
string? File,
string? FileSha256,
long FileBytes)
long FileBytes,
string? FileKind = null)
{
/// <summary>The record of a home's frame, with the file the workspace holds for it.</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes)
/// <summary>The record of a home's frame, with the file the workspace holds for it (<paramref name="fileKind"/>: what a server sent).</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes, string? fileKind = null)
{
ArgumentNullException.ThrowIfNull(frame);
return new WorkspaceFrame(frame.Id, frame.Index, frame.FileName, frame.OriginalFileName, frame.Size, frame.Sha256, frame.CapturedAt, frame.UtcOffsetMinutes,
frame.TimestampSource, frame.ExposureTime, frame.FNumber, frame.Iso, frame.FocalLength, frame.ExposureBias, frame.WhiteBalance, frame.Orientation,
frame.Width, frame.Height, frame.Format, frame.PreviewWidth, frame.PreviewHeight, frame.MeanLogLuminance, frame.ClipLow, frame.ClipHigh, frame.Flags,
file, fileSha256, fileBytes);
file, fileSha256, fileBytes, fileKind);
}
/// <summary>A thumbnail stands in for the frame's proxy (a server had none when it was copied).</summary>
[JsonIgnore]
public bool IsStandIn => FileKind == Sync.ProxyCache.Thumb;
/// <summary>The frame as the processing engine reads it; flagged missing while the workspace holds no file for it.</summary>
public Frame ToFrame(Guid sequenceId) => new()
{
@@ -93,7 +93,8 @@ public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, G
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>; originals in phase 5c).
/// </summary>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media);
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>, phase 5b); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media, string? Server = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
+42 -1
View File
@@ -50,10 +50,11 @@ public enum WorkspaceState
/// <summary>
/// A workspace project's state (owner review 2, R8): the leading <see cref="State"/> and every fact behind it. Without a
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> false.
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> and <see cref="Gone"/> false.
/// </summary>
/// <param name="Base">The home's version the project was last in step with.</param>
/// <param name="HomeHead">The home's newest version, when it was asked.</param>
/// <param name="Gone">The home was asked and no longer has the project (<see cref="WorkspaceState.Gone"/>).</param>
public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly,
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead)
{
@@ -369,10 +370,50 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
}
if (project.ReadSync().Conflict is null) PruneReplaced(project);
await FollowNameLockedAsync(project, home, cancellationToken).ConfigureAwait(false);
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], pulled);
}
}
/// <summary>
/// The project's name (and whether it is Main) as its home has them now, written to the copy here: a rename made at the
/// home reaches the workspace. True when the copy's name changed; false when it already matched, or the home could not
/// say (unreachable, or no longer listing the project): the next pull or status tells those.
/// </summary>
public async Task<bool> FollowNameAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
return await FollowNameLockedAsync(project, home, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// <see cref="FollowNameAsync"/> under the project's lock. It runs after a pull that succeeded, so it never fails: whatever
/// the home or the copy answers (unreachable, a refusal such as a 403, a file in use) is logged and the name is followed
/// next time; only a cancellation is passed on.
/// </summary>
private static async Task<bool> FollowNameLockedAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
{
try
{
var listed = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == project.ProjectId);
var bundle = project.ReadBundle();
if (listed is null || bundle.Workspace is not { } workspace || (workspace.Name == listed.Name && workspace.IsMain == listed.IsMain)) return false;
project.WriteBundle(bundle with { Workspace = workspace with { Name = listed.Name, IsMain = listed.IsMain } });
return true;
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException)
{
return false;
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
Log.Warning("workspace", $"The name of project {project.ProjectId} could not be followed from its home; tried again at the next pull", ex);
return false;
}
}
/// <summary>
/// Settles the conflict a pull or push stopped at, as the user was shown it (<paramref name="shown"/>, else the one
/// recorded). <see cref="ConflictChoice.KeepMine"/> keeps this workspace's values (but for the members in