merge: review2-p5a-fix-workspace into phase 5a fix round 1 integration
# Conflicts: # src/Chronos.Data/Workspaces/WorkspaceSync.cs
This commit is contained in:
commit
9772c2f934
18 files changed
+958
-93
No files matched your search
@@ -20,7 +20,7 @@ public static class ArchiveFailures
|
||||
// any more (FrameTrash.RestoreAsync). Other IOExceptions and InvalidDataExceptions (a sidecar of another sequence)
|
||||
// carry technical text.
|
||||
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
|
||||
or SequenceInLibraryException or TrashMismatchException => ex.Message,
|
||||
or SequenceInLibraryException or TrashMismatchException or Core.Project.ProjectTooLargeException => ex.Message,
|
||||
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
|
||||
DatabaseException => Loc.L("Archive.Failed.Index"),
|
||||
ArgumentException => Loc.L("Archive.Failed.Gone"),
|
||||
|
||||
@@ -228,7 +228,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's
|
||||
/// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by
|
||||
/// the render) and the project recorded on the render; the version too when the settings are those of the last
|
||||
/// version saved (an unsaved working state renders as it is, without a version).
|
||||
/// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight)
|
||||
{
|
||||
@@ -293,12 +293,16 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last version saved: the newest one not sent yet, else the base; with its content hash.</summary>
|
||||
/// <summary>
|
||||
/// The version a render may name, with its content hash: the base, which the home holds, while no version waits to be
|
||||
/// sent; none otherwise. A version not sent yet may never reach the home under its id (a replay or a save-both sends it
|
||||
/// under another), so a render of it names the project alone.
|
||||
/// </summary>
|
||||
private (Guid? Id, string? Hash) Tip()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_sync.Unpushed(ProjectId) is { Count: > 0 } unsent) return (unsent[^1].Id, unsent[^1].ContentHash);
|
||||
if (_sync.Unpushed(ProjectId).Count > 0) return (null, null);
|
||||
return Project.ReadBundle().Workspace?.Base is { } basis ? (basis.VersionId, basis.ContentHash) : (null, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException)
|
||||
|
||||
@@ -43,7 +43,7 @@ public static class ErrorText
|
||||
private static string? Describe(Exception ex) => ex switch
|
||||
{
|
||||
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
|
||||
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message,
|
||||
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException or Core.Project.ProjectTooLargeException => ex.Message,
|
||||
// A template an archive refused (Settings › Archive, or this PC's templates for a new archive): the rule it breaks.
|
||||
TemplateRuleException rule => Loc.L("Errors.Template." + rule.Rule),
|
||||
// The workspace (owner review 2, R8): its own sentences, a home out of reach, a project the home refused.
|
||||
|
||||
@@ -2,10 +2,19 @@ using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Core.Project;
|
||||
|
||||
/// <summary>A project file that would be larger than <see cref="ProjectBundle.MaxBytes"/>: refused before it is written, with a sentence for the user.</summary>
|
||||
public sealed class ProjectTooLargeException(long bytes)
|
||||
: IOException(Loc.L("Errors.Project.TooLarge", ProjectBundle.MaxBytes >> 20))
|
||||
{
|
||||
/// <summary>The size the file would have had.</summary>
|
||||
public long Bytes { get; } = bytes;
|
||||
}
|
||||
|
||||
/// <summary>The archive a project file's sequence lives in: its id, and its name and folder when the file was saved.</summary>
|
||||
public sealed record BundleArchive(Guid Id, string Name, string? Path);
|
||||
|
||||
@@ -70,8 +79,12 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
|
||||
/// <summary>The settings come from a newer Chronos (<see cref="ProjectSettings.IsNewerFormat"/>): show them, never edit them.</summary>
|
||||
public bool IsReadOnly => Project.IsNewerFormat;
|
||||
|
||||
/// <summary>Project settings take a few kilobytes; a larger file is not a project file.</summary>
|
||||
public const int MaxBytes = 4 << 20;
|
||||
/// <summary>
|
||||
/// The largest project file read or written, one limit for both: a workspace's working state parks every position by
|
||||
/// photo until its media are copied (some 260 bytes each), so a 100,000-frame sequence with every frame excluded takes
|
||||
/// some 26 MB; a larger file is not a project file.
|
||||
/// </summary>
|
||||
public const int MaxBytes = 64 << 20;
|
||||
|
||||
private static readonly JsonWriterOptions Indented = new() { Indented = true };
|
||||
|
||||
@@ -165,8 +178,17 @@ public sealed record ProjectBundle(BundleArchive Archive, BundleSequence Sequenc
|
||||
return Parse(reader.ReadToEnd());
|
||||
}
|
||||
|
||||
/// <summary>Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file.</summary>
|
||||
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
|
||||
/// <summary>
|
||||
/// Writes the file atomically (temp, flush, rename): an interrupted save never leaves half a file. A file larger than
|
||||
/// <see cref="MaxBytes"/> is refused before anything is written, as no read could take it back.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectTooLargeException">The file would be larger than <see cref="MaxBytes"/>.</exception>
|
||||
public void Save(string path)
|
||||
{
|
||||
var bytes = new UTF8Encoding(false).GetBytes(ToJson());
|
||||
if (bytes.Length > MaxBytes) throw new ProjectTooLargeException(bytes.Length);
|
||||
AtomicFile.WriteAllBytes(path, bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings to give the sequence when the file is opened, the sequence having <paramref name="frameCount"/>
|
||||
|
||||
@@ -76,6 +76,9 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
/// <summary>The decoders of this engine's image passes (thumbnails, proxies).</summary>
|
||||
public Core.Imaging.ImageDecoder Decoder => _writer.Options.Decoder;
|
||||
|
||||
/// <summary>How the host measures free space under a folder (<see cref="ArchiveServiceOptions.FreeSpace"/>); null: the folder's drive.</summary>
|
||||
public Func<string, long?>? FreeSpace => _writer.Options.FreeSpace;
|
||||
|
||||
/// <summary>
|
||||
/// The steps this host's <see cref="JobKind.Cleanup"/> jobs can run: the shared ones (<see cref="Housekeeping.CleanupSteps.Shared"/>),
|
||||
/// then the host's (<see cref="ArchiveServiceOptions.CleanupSteps"/>). A schedule host lists their names.
|
||||
|
||||
@@ -22,14 +22,16 @@ public enum JobKindPriority
|
||||
public sealed record JobPriorityQueue
|
||||
{
|
||||
/// <summary>
|
||||
/// The levels a kind has unless the user changed it: renders, imports and downloads first; the long passes that resume
|
||||
/// anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
|
||||
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
|
||||
/// media into the workspace, which Edit waits for (owner review 2, R8); the long passes that resume anywhere, and the
|
||||
/// housekeeping of the schedules (backups, clean-ups), last.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
|
||||
{
|
||||
[JobKind.Render] = JobKindPriority.High,
|
||||
[JobKind.Import] = JobKindPriority.High,
|
||||
[JobKind.Download] = JobKindPriority.High,
|
||||
[JobKind.WorkspaceCopy] = JobKindPriority.High,
|
||||
[JobKind.Verify] = JobKindPriority.Low,
|
||||
[JobKind.Proxies] = JobKindPriority.Low,
|
||||
[JobKind.Backup] = JobKindPriority.Low,
|
||||
|
||||
@@ -53,6 +53,7 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
var aliases = embedded is not null ? await Projects.HomePhotos.AliasesAsync(db, sequence.Id, cancellation).ConfigureAwait(false) : [];
|
||||
var project = (embedded is not null ? ProjectStore.Parse(Placed(embedded, frames, aliases)) : ProjectStore.Read(sequence, folder)) with { Export = export };
|
||||
var settingsJson = project.ToJson();
|
||||
var (projectId, projectVersionId) = await ProvenanceAsync(parameters, sequence, cancellation).ConfigureAwait(false);
|
||||
|
||||
using var names = new OutputNames();
|
||||
var all = Targets(export, parameters.PresetName);
|
||||
@@ -90,8 +91,8 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
{
|
||||
Id = RenderId(context.Job.Id, index),
|
||||
OutputPath = Stored(paths, result.OutputPath),
|
||||
ProjectId = parameters.ProjectId,
|
||||
ProjectVersionId = parameters.ProjectVersionId,
|
||||
ProjectId = projectId,
|
||||
ProjectVersionId = projectVersionId,
|
||||
};
|
||||
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
|
||||
done.Add(index);
|
||||
@@ -137,6 +138,27 @@ internal sealed class RenderJobHandler(ChronosDatabase db, ProcessingOptions opt
|
||||
: throw new InvalidOperationException(Loc.L("Errors.Render.ProjectVersion"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The project and the version a render records (owner review 2, R8: a render never names a version whose settings it
|
||||
/// did not use, nor one the index does not hold): the project when it is one of the sequence's; the version when the index
|
||||
/// holds it, for that project of the sequence, with the content hash of the settings the job embeds. A job naming a
|
||||
/// version the home never received (one saved on a PC and sent later under another id) records the project alone.
|
||||
/// </summary>
|
||||
private async Task<(Guid? Project, Guid? Version)> ProvenanceAsync(Protocol.RenderJobParameters parameters, Sequence sequence, CancellationToken cancellationToken)
|
||||
{
|
||||
Guid? project = parameters.ProjectId is { } id && await db.Projects.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } owner
|
||||
&& owner.SequenceId == sequence.Id
|
||||
? id
|
||||
: null;
|
||||
if (parameters.ProjectVersionId is not { } versionId
|
||||
|| await db.Projects.GetVersionAsync(versionId, cancellationToken).ConfigureAwait(false) is not { } version
|
||||
|| (project is { } named && version.ProjectId != named)
|
||||
|| await db.Projects.GetAsync(version.ProjectId, cancellationToken).ConfigureAwait(false) is not { } of || of.SequenceId != sequence.Id
|
||||
|| (parameters.SettingsJson is { } embedded && !ProjectContent.Verifies(embedded, version.ContentHash)))
|
||||
return (project, null);
|
||||
return (version.ProjectId, versionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings whose positions wait for their photos (a project version's portable form, settings synced from another copy)
|
||||
/// with them placed on the frames rendered, a photo parked on an encoding a conversion replaced since found through
|
||||
|
||||
@@ -11,6 +11,7 @@ using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.Data.Workspaces;
|
||||
|
||||
@@ -47,7 +48,10 @@ public static class WorkspaceJobs
|
||||
/// Frames changed at the home during the copy, or the folder moved (a Reorganize), make it start again (three times at
|
||||
/// most; a folder still moving fails it, to be retried). The working state's positions follow the new frames: by frame
|
||||
/// where a frame stays (one whose file a conversion replaced keeps its positions), by photo where frames came or went.
|
||||
/// Checkpoint: <c>copy:<frame>:<frames version></c>; a run resumed on other frames checks every file again.
|
||||
/// Before each pass and at each checkpoint the workspace's drive must hold what is still to copy plus a reserve, else the
|
||||
/// job stops saying how much is missing (the workspace shares this PC's drive with the index and the logs).
|
||||
/// Checkpoint: <c>copy:<frame>:<frames version>:<folder></c>; a run resumed on other frames or in another folder
|
||||
/// checks every file again, and a pass started again stores that before it reads anything.
|
||||
/// Originals come in phase 5c: asked for, the job fails saying so.
|
||||
/// </summary>
|
||||
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : IJobHandler
|
||||
@@ -57,6 +61,17 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
|
||||
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Bytes left free on the workspace's drive besides the copy, as a download keeps (<see cref="SyncTransfers"/>).</summary>
|
||||
private const long SpaceReserve = 512L << 20;
|
||||
|
||||
/// <summary>A proxy at <see cref="ProxyEstimateEdge"/> px, when the archive has none to measure: some 1.5 MB.</summary>
|
||||
private const long ProxyEstimate = 3L << 19;
|
||||
|
||||
private const int ProxyEstimateEdge = 1920;
|
||||
|
||||
/// <summary>The long edge taken for a full-size proxy of a frame whose size is not known.</summary>
|
||||
private const int UnknownFullSize = 6000;
|
||||
|
||||
public JobKind Kind => JobKind.WorkspaceCopy;
|
||||
|
||||
public async Task RunAsync(JobContext context)
|
||||
@@ -80,20 +95,29 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
// Read only: a read-only archive is copied from like any other.
|
||||
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(archive.RootPath, ArchiveAvailability.Offline);
|
||||
var (copied, checkpointVersion) = Parse(context.Checkpoint);
|
||||
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
|
||||
for (var pass = 1; ; pass++)
|
||||
{
|
||||
var (row, frames) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
|
||||
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy;
|
||||
var folder = paths.Sequence(row.Folder);
|
||||
// Another index moved the sequence away, maybe another one in: its files are not this sequence's photos.
|
||||
if (!SequenceFolders.Holds(folder, sequenceId)) throw new SequenceFolderMovedException();
|
||||
// Files kept from an earlier run are this frames version's only (a conversion keeps a frame's id, not its photo).
|
||||
if (checkpointVersion is { } version && version != row.FramesVersion) copied = 0;
|
||||
// Another index moved the sequence away, maybe another one in: its files are not this sequence's photos. A retry
|
||||
// checks every file again (the files of this run may be of that folder).
|
||||
if (!SequenceFolders.Holds(folder, sequenceId))
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, row.FramesVersion, row.Folder), 0, frames.Count).ConfigureAwait(false);
|
||||
throw new SequenceFolderMovedException();
|
||||
}
|
||||
// Files kept from an earlier run are this frames version's and this folder's only (a conversion keeps a frame's id,
|
||||
// not its photo; a sequence moved meanwhile may have left its photos' names to another sequence's).
|
||||
if ((checkpointVersion is { } version && version != row.FramesVersion) || (checkpointFolder is { } read && read != row.Folder)) copied = 0;
|
||||
var total = (long)frames.Count;
|
||||
var tally = new Tally();
|
||||
var entries = new WorkspaceFrame[frames.Count];
|
||||
Directory.CreateDirectory(project.ProxiesDirectory);
|
||||
// The workspace is on this PC's own drive, with the index, the settings and the logs: the copy never fills it.
|
||||
var remaining = Remaining(project, folder, frames, policy);
|
||||
EnsureSpace(parameters.WorkspaceRoot, remaining[0]);
|
||||
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
@@ -101,7 +125,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
entries[i] = Copy(project, folder, paths, frames[i], policy, done: i < copied, tally, ct);
|
||||
if (clock.Elapsed >= CheckpointEvery)
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion), i + 1, total).ConfigureAwait(false);
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion, row.Folder), i + 1, total).ConfigureAwait(false);
|
||||
// Another program may take the space meanwhile.
|
||||
EnsureSpace(parameters.WorkspaceRoot, remaining[i + 1]);
|
||||
clock.Restart();
|
||||
}
|
||||
else
|
||||
@@ -114,15 +140,21 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
var moved = after.Folder != row.Folder || !SequenceFolders.Holds(paths.Sequence(after.Folder), sequenceId) || Renamed(frames, now, entries);
|
||||
if (after.FramesVersion != row.FramesVersion || moved)
|
||||
{
|
||||
// The files read may be of other frames, or missing where a Reorganize took them: read them again.
|
||||
// The files read may be of other frames, or missing where a Reorganize took them: read them again, and so
|
||||
// does a run resumed after a crash in the next pass (the checkpoint stored says so).
|
||||
if (pass < Passes)
|
||||
{
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceFramesChanged", row.DisplayTitle));
|
||||
(copied, checkpointVersion) = (0, null);
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, after.FramesVersion, after.Folder), 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); a folder still moving is not.
|
||||
if (moved) throw new SequenceFolderMovedException();
|
||||
if (moved)
|
||||
{
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, after.FramesVersion, after.Folder), 0, total).ConfigureAwait(false);
|
||||
throw new SequenceFolderMovedException();
|
||||
}
|
||||
}
|
||||
var aliases = await HomePhotos.AliasesAsync(db, sequenceId, ct).ConfigureAwait(false);
|
||||
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, row.FramesVersion, entries,
|
||||
@@ -134,7 +166,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
RemoveStale(project, media);
|
||||
}
|
||||
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, row.FramesVersion), total, total).ConfigureAwait(false);
|
||||
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, row.FramesVersion, row.Folder), total, total).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -205,6 +237,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
}
|
||||
if (bytes is null)
|
||||
{
|
||||
// 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.
|
||||
if (File.Exists(target)) TryDelete(target);
|
||||
tally.Missing++;
|
||||
return WorkspaceFrame.Of(frame, null, null, 0);
|
||||
}
|
||||
@@ -292,15 +327,81 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
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"))
|
||||
{
|
||||
if (listed.Contains(Path.GetFileName(file))) continue;
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{file} could not be removed", ex);
|
||||
}
|
||||
if (!listed.Contains(Path.GetFileName(file))) TryDelete(file);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDelete(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"{file} could not be removed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bytes the copy 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 (kept, or replaced by one of about its size), the archive's
|
||||
/// proxy's size where it has one, else an estimate at the proxy size the copy makes (<see cref="Estimate"/>).
|
||||
/// </summary>
|
||||
private static long[] Remaining(WorkspaceProject project, SequencePaths folder, List<Frame> frames, ProxyPolicy policy)
|
||||
{
|
||||
var held = Directory.Exists(project.ProxiesDirectory)
|
||||
? Directory.EnumerateFiles(project.ProxiesDirectory).Select(Path.GetFileName).ToHashSet(StringComparer.OrdinalIgnoreCase)
|
||||
: [];
|
||||
var proxies = Directory.Exists(folder.Proxies)
|
||||
? new DirectoryInfo(folder.Proxies).EnumerateFiles().ToDictionary(f => f.Name, f => f.Length, StringComparer.OrdinalIgnoreCase)
|
||||
: [];
|
||||
var remaining = new long[frames.Count + 1];
|
||||
for (var i = frames.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var frame = frames[i];
|
||||
var bytes = held.Contains(ProxyCache.FileName(frame.Id)) ? 0
|
||||
: proxies.TryGetValue(ArchiveLayout.ProxyFileName(frame.Index), out var length) ? length
|
||||
: (frame.Flags & FrameFlags.Missing) != 0 ? 0
|
||||
: Estimate(frame, policy);
|
||||
remaining[i] = remaining[i + 1] + bytes;
|
||||
}
|
||||
return remaining;
|
||||
}
|
||||
|
||||
/// <summary>A proxy's size when the archive has none to measure: some 1.5 MB at 1920 px, scaled by the area at the copy's long edge.</summary>
|
||||
private static long Estimate(Frame frame, ProxyPolicy policy)
|
||||
{
|
||||
var edge = policy.LongEdge == ProxyPolicy.Disabled ? new ProxyPolicy().LongEdge : policy.LongEdge;
|
||||
var longest = Math.Max(frame.Width, frame.Height);
|
||||
var side = edge == ProxyPolicy.FullSize ? (longest > 0 ? longest : UnknownFullSize) : longest > 0 ? Math.Min(edge, longest) : edge;
|
||||
return (long)(ProxyEstimate * Math.Pow(side / (double)ProxyEstimateEdge, 2));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses to go on while the workspace's drive lacks <paramref name="bytes"/> besides <see cref="SpaceReserve"/>, with the
|
||||
/// gigabytes missing; a drive that cannot be measured (a network share) is not refused, the copy itself then says so.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">The drive lacks the space (<c>Errors.Workspace.DiskFull</c>).</exception>
|
||||
private void EnsureSpace(string root, long bytes)
|
||||
{
|
||||
if (bytes <= 0 || FreeBytes(root) is not { } free || free >= bytes + SpaceReserve) return;
|
||||
throw new IOException(Loc.L("Errors.Workspace.DiskFull", ((bytes + SpaceReserve - free) / 1e9).ToString("0.0", Loc.Culture)));
|
||||
}
|
||||
|
||||
/// <summary>Free bytes on the volume of <paramref name="folder"/>, as the host measures them (<see cref="ArchiveService.FreeSpace"/>), else its drive's.</summary>
|
||||
private long? FreeBytes(string folder)
|
||||
{
|
||||
if (archives.FreeSpace is { } measure) return measure(folder);
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(folder);
|
||||
// Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on.
|
||||
return new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,22 +462,23 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
|
||||
Done,
|
||||
}
|
||||
|
||||
private static string Checkpoint(Stage stage, int frame, int framesVersion) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{stage.ToString().ToLowerInvariant()}:{frame}:{framesVersion}");
|
||||
private static string Checkpoint(Stage stage, int frame, int framesVersion, string folder) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{stage.ToString().ToLowerInvariant()}:{frame}:{framesVersion}:{folder}");
|
||||
|
||||
/// <summary>
|
||||
/// The frames copied by an earlier run (<c>copy:<frame>[:<frames version>]</c>) and the frames version they
|
||||
/// were of (null when the checkpoint does not say); nothing for a finished run, or another stage (an earlier build's
|
||||
/// archive proxy pass), whose files the copy checks again.
|
||||
/// The frames copied by an earlier run (<c>copy:<frame>[:<frames version>[:<folder>]]</c>, the folder
|
||||
/// last as it may hold a colon), the frames version and the sequence's folder they were of (null when the checkpoint does
|
||||
/// not say); nothing for a finished run, or another stage (an earlier build's archive proxy pass), whose files the copy
|
||||
/// checks again.
|
||||
/// </summary>
|
||||
private static (int Copied, int? FramesVersion) Parse(string? checkpoint)
|
||||
private static (int Copied, int? FramesVersion, string? Folder) Parse(string? checkpoint)
|
||||
{
|
||||
var parts = checkpoint?.Split(':');
|
||||
if (parts is not ([_, _] or [_, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage != Stage.Copy
|
||||
var parts = checkpoint?.Split(':', 4);
|
||||
if (parts is not ([_, _] or [_, _, _] or [_, _, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage != Stage.Copy
|
||||
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var next))
|
||||
return (0, null);
|
||||
int? version = parts.Length == 3 && int.TryParse(parts[2], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : null;
|
||||
return (next, version);
|
||||
return (0, null, null);
|
||||
int? version = parts.Length >= 3 && int.TryParse(parts[2], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : null;
|
||||
return (next, version, parts.Length == 4 ? parts[3] : null);
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
|
||||
@@ -13,14 +13,41 @@ namespace Chronos.Data.Workspaces;
|
||||
/// <summary>The manifest of a workspace folder (<c>workspace.json</c>).</summary>
|
||||
public sealed record WorkspaceManifest(string Format, int FormatVersion, Guid Id, DateTimeOffset Created);
|
||||
|
||||
/// <summary>A workspace's sync state of one project besides its versions (<c>sync.json</c>): a restore to record, a conflict to settle.</summary>
|
||||
/// <summary>
|
||||
/// A workspace's sync state of one project besides its versions (<c>sync.json</c>): a restore to record, a conflict to
|
||||
/// settle, and the journal of a replay or a save-both under way, which the next sync finishes or undoes after a crash.
|
||||
/// </summary>
|
||||
/// <param name="RestoredFrom">The version a restore brought back; the next commit is a "restore" of it.</param>
|
||||
/// <param name="Conflict">The conflict a pull or push stopped at, until the user settles it.</param>
|
||||
public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? Conflict)
|
||||
/// <param name="Replay">A replay (or a base moved onto local commits the home holds) written in steps; null when none is under way.</param>
|
||||
/// <param name="SaveBoth">A save-both that made its copy at the home and has not finished; null when none is under way.</param>
|
||||
public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? Conflict, WorkspaceReplay? Replay = null, WorkspaceSaveBoth? SaveBoth = null)
|
||||
{
|
||||
public static WorkspaceSyncState None { get; } = new(null, null);
|
||||
|
||||
/// <summary>Nothing to keep: the file can go.</summary>
|
||||
[JsonIgnore]
|
||||
public bool IsEmpty => RestoredFrom is null && Conflict is null && Replay is null && SaveBoth is null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The journal of a replay (<see cref="WorkspaceSync"/>): the base it moves the project onto, the local versions it
|
||||
/// replaces, the replayed ones it writes and the local versions the home already holds (their answer lost), whose files
|
||||
/// take the home's copy. The bundle's base is the commit point: once it is <see cref="OntoBase"/> the replay is finished
|
||||
/// (the replaced set aside, the held ones adopted), before it the replayed ones are set aside and nothing else moved.
|
||||
/// </summary>
|
||||
public sealed record WorkspaceReplay(Guid OntoBase, IReadOnlyList<Guid> Replaced, IReadOnlyList<Guid> Replayed, IReadOnlyList<Guid> Adopted);
|
||||
|
||||
/// <summary>
|
||||
/// A save-both under way (<see cref="WorkspaceSync"/>): the copy made at the home and its first version (the base the
|
||||
/// local versions are sent on top of), the base this project had when it started, and the id each local version is sent
|
||||
/// under, so a retry sends to the same copy what it lacks and the home answers "already stored" for the rest.
|
||||
/// </summary>
|
||||
public sealed record WorkspaceSaveBoth(Guid CopyId, Guid CopyBaseId, int CopyBaseNumber, Guid? FromBase, IReadOnlyList<WorkspaceMove> Moves);
|
||||
|
||||
/// <summary>A local version (<paramref name="LocalId"/>) and the id it is sent under to a save-both's copy.</summary>
|
||||
public sealed record WorkspaceMove(Guid LocalId, Guid CopyVersionId);
|
||||
|
||||
/// <summary>
|
||||
/// A pull or push that met real conflicts (owner review 2, R8): the home's head it met, the version the local commits were
|
||||
/// made from, the local commits (oldest first) and the members both sides changed (mine, theirs). Settled by keeping mine,
|
||||
@@ -67,7 +94,11 @@ public sealed class WorkspaceStore
|
||||
/// <summary>The folder name of the workspace inside the program's data folder.</summary>
|
||||
public const string DefaultFolderName = "workspace";
|
||||
|
||||
/// <summary>Opens the workspace at <paramref name="root"/>, making the folder and its manifest when there is none.</summary>
|
||||
/// <summary>
|
||||
/// Opens the workspace at <paramref name="root"/>, making the folder and its manifest when there is none. The manifest
|
||||
/// is written whole to a temporary file and moved into place, so a crash never leaves half of one; a manifest left
|
||||
/// empty, or unreadable in a folder that holds no project yet (an earlier build's interrupted first write), is made again.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidDataException">The folder's <c>workspace.json</c> is not a workspace manifest, or a newer one.</exception>
|
||||
/// <exception cref="IOException">The folder cannot be made or read.</exception>
|
||||
public WorkspaceStore(string root)
|
||||
@@ -76,20 +107,8 @@ public sealed class WorkspaceStore
|
||||
Root = LongPath.Normalize(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)));
|
||||
Directory.CreateDirectory(Root);
|
||||
var path = Path.Combine(Root, ManifestFile);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
var manifest = new WorkspaceManifest(FormatName, FormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow);
|
||||
// Another program opening the same folder at the same moment: the first manifest wins.
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
JsonSerializer.Serialize(stream, manifest, WorkspaceJson.Default.WorkspaceManifest);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
catch (IOException) when (File.Exists(path))
|
||||
{
|
||||
}
|
||||
}
|
||||
if (!File.Exists(path)) Create(path, replace: false);
|
||||
else if (Unfinished(path)) Create(path, replace: true);
|
||||
Manifest = Read(path);
|
||||
}
|
||||
|
||||
@@ -139,6 +158,70 @@ public sealed class WorkspaceStore
|
||||
return bundles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a new manifest. Without <paramref name="replace"/> another program opening the same folder at the same moment
|
||||
/// may have made one first: that one wins (the move never replaces a file).
|
||||
/// </summary>
|
||||
private static void Create(string path, bool replace)
|
||||
{
|
||||
var manifest = new WorkspaceManifest(FormatName, FormatVersion, Guid.CreateVersion7(), DateTimeOffset.UtcNow);
|
||||
var text = JsonSerializer.Serialize(manifest, WorkspaceJson.Default.WorkspaceManifest);
|
||||
if (replace)
|
||||
{
|
||||
Log.Warning("workspace", $"{path} was left unfinished; a new manifest is written");
|
||||
AtomicFile.WriteAllText(path, text);
|
||||
return;
|
||||
}
|
||||
var temp = AtomicFile.TempPathFor(path);
|
||||
try
|
||||
{
|
||||
using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
stream.Write(System.Text.Encoding.UTF8.GetBytes(text));
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
try
|
||||
{
|
||||
File.Move(temp, path, overwrite: false);
|
||||
}
|
||||
catch (IOException) when (File.Exists(path))
|
||||
{
|
||||
// Another program's manifest came first.
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temp)) File.Delete(temp);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A manifest an interrupted first write left (an earlier build wrote it in place): empty, or not JSON in a folder that
|
||||
/// holds no project yet. A readable manifest, or any in a folder with projects, is never written over.
|
||||
/// </summary>
|
||||
private bool Unfinished(string path)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
text = AtomicFile.ReadAllText(path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(text.Trim('\0'))) return true;
|
||||
try
|
||||
{
|
||||
using var _ = JsonDocument.Parse(text);
|
||||
return false;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return List().Count == 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static WorkspaceManifest Read(string path)
|
||||
{
|
||||
WorkspaceManifest? manifest;
|
||||
@@ -283,7 +366,10 @@ public sealed class WorkspaceProject
|
||||
|
||||
internal void WriteVersion(ProjectVersion version, bool replace = false) => ProjectSidecars.WriteVersion(VersionPath(version), version, replace);
|
||||
|
||||
/// <summary>Moves a version file aside into <c>versions/.replaced</c> (a local commit replayed under another id).</summary>
|
||||
/// <summary>
|
||||
/// Moves a version file aside into <c>versions/.replaced</c> (a local commit replayed under another id), trying again
|
||||
/// for a moment while another program (an indexer, an antivirus) holds it open.
|
||||
/// </summary>
|
||||
internal void SetAside(ProjectVersion version)
|
||||
{
|
||||
var path = VersionPath(version);
|
||||
@@ -292,9 +378,23 @@ public sealed class WorkspaceProject
|
||||
Directory.CreateDirectory(aside);
|
||||
var target = Path.Combine(aside, Path.GetFileName(path));
|
||||
if (File.Exists(target)) target += "." + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
File.Move(path, target);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(path, target);
|
||||
return;
|
||||
}
|
||||
catch (IOException) when (attempt < SetAsideAttempts && File.Exists(path) && !File.Exists(target))
|
||||
{
|
||||
Thread.Sleep(10 * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Moves tried, some 1 s in all, before a version file held open fails to move aside.</summary>
|
||||
private const int SetAsideAttempts = 15;
|
||||
|
||||
public WorkspaceSyncState ReadSync()
|
||||
{
|
||||
if (!File.Exists(SyncPath)) return WorkspaceSyncState.None;
|
||||
@@ -310,7 +410,8 @@ public sealed class WorkspaceProject
|
||||
|
||||
internal void WriteSync(WorkspaceSyncState state)
|
||||
{
|
||||
if (state == WorkspaceSyncState.None || state is { RestoredFrom: null, Conflict: null })
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
if (state.IsEmpty)
|
||||
{
|
||||
if (File.Exists(SyncPath)) File.Delete(SyncPath);
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Projects;
|
||||
@@ -88,6 +89,11 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
|
||||
/// moves onto them read-only, any other waits on a conflict of format that only Save both settles
|
||||
/// (<see cref="WorkspaceConflict.NewerFormat"/>). Every operation holds the project's lease; nothing is ever deleted: a
|
||||
/// restore or save-both first saves uncommitted changes as a version.
|
||||
/// Every write sequence survives a cut at any step: the working state's base is the commit point. A push moves the base
|
||||
/// before its local file reads as sent; a replay journals itself in <c>sync.json</c> (<see cref="WorkspaceReplay"/>), writes
|
||||
/// the replayed versions, then the base, and only then sets the old ones aside; a save-both journals its copy and the ids
|
||||
/// it sends under (<see cref="WorkspaceSaveBoth"/>). The next push, pull or resolve finishes or undoes what a cut left
|
||||
/// (<see cref="SettleAsync"/>).
|
||||
/// </summary>
|
||||
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
@@ -104,6 +110,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// <summary>How long an operation waits for the project's lease (another program working on it).</summary>
|
||||
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>For tests: called with a step's name between the writes of a sync, where it may throw as a crash would.</summary>
|
||||
internal Action<string>? Cut { get; init; }
|
||||
|
||||
private void Step(string name) => Cut?.Invoke(name);
|
||||
|
||||
/// <summary>
|
||||
/// The project <paramref name="projectId"/> of <paramref name="home"/> brought into the workspace: its folder, the home's
|
||||
/// head as the base and the working state (positions waiting for the media, which a
|
||||
@@ -130,30 +141,41 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {projectId}.");
|
||||
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
Verify(head);
|
||||
project.WriteVersion(head, replace: true);
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
var bundle = new ProjectBundle(sequence.Archive, sequence.Sequence, ProjectSettings.FromJson(head.SettingsJson, allowNewer: true), DateTimeOffset.UtcNow)
|
||||
{
|
||||
Workspace = new BundleWorkspace(projectId, listed.Name, listed.IsMain, sequence.Home, Base(head), new BundleMedia(media, 0)),
|
||||
};
|
||||
// The working state first: one larger than a project file holds is refused before anything is written
|
||||
// (ProjectTooLargeException), never left as a file no later open could read. Its base is fetched again if a cut
|
||||
// comes before the version's own file.
|
||||
project.WriteBundle(bundle);
|
||||
project.WriteVersion(head, replace: true);
|
||||
Directory.CreateDirectory(project.ExportsDirectory);
|
||||
return project;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The working state for the editor: its settings placed on the media's frames, and the media's sequence.</summary>
|
||||
/// <summary>
|
||||
/// The working state for the editor: its settings placed on the media's frames, and the media's sequence. Both files are
|
||||
/// read under the project's lease, as one state: a copy committing new media rewrites them in turn.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The project is not in the workspace.</exception>
|
||||
public Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default) =>
|
||||
Task.Run(() =>
|
||||
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than <see cref="LockWait"/>.</exception>
|
||||
public async Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
ProjectBundle bundle;
|
||||
WorkspaceMedia? media;
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
(bundle, media) = await Task.Run(() => (project.ReadBundle(), project.ReadMedia()), cancellationToken).ConfigureAwait(false);
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var bundle = project.ReadBundle();
|
||||
var media = project.ReadMedia();
|
||||
var working = bundle.Project;
|
||||
if (media is not null && !working.IsNewerFormat)
|
||||
working = ProjectSettings.FromJson(ProjectContent.Place(working.ToJson(), media.Photos), allowNewer: true);
|
||||
return new WorkspaceSession(project, bundle, working, media, media is null ? null : SequenceOf(project, bundle, media));
|
||||
}, cancellationToken);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Stores the working state (the editor's settings, positions on the media's frames); no version is made.</summary>
|
||||
/// <exception cref="InvalidOperationException">The project is read-only (a newer Chronos's settings) or not in the workspace.</exception>
|
||||
@@ -196,6 +218,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var pushed = new List<ProjectVersion>();
|
||||
var pulled = new List<ProjectVersion>();
|
||||
for (var attempt = 0; attempt < PushAttempts; attempt++)
|
||||
@@ -210,10 +233,13 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
{
|
||||
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
|
||||
Verify(stored);
|
||||
if (stored.Number != local.Number) project.SetAside(local);
|
||||
project.WriteVersion(stored, replace: true);
|
||||
// The base moves first: cut after it, the local file still reads as unsent and the next sync
|
||||
// adopts it; cut before it, the home answers "already stored" next time. Marked sent first, it
|
||||
// would leave the chain from the old base and take the versions after it along.
|
||||
bundle = WithBase(bundle, stored);
|
||||
project.WriteBundle(bundle);
|
||||
Step("push.base");
|
||||
Adopt(project, local, stored);
|
||||
pushed.Add(stored);
|
||||
continue;
|
||||
case PushOutcome.Diverged:
|
||||
@@ -244,6 +270,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
IReadOnlyList<ProjectVersion> pulled = [];
|
||||
if (project.ReadSync().Conflict is null)
|
||||
{
|
||||
@@ -271,6 +298,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
var project = Existing(projectId);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var bundle = project.ReadBundle();
|
||||
var sync = project.ReadSync();
|
||||
if (sync.Conflict is null) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
|
||||
@@ -332,15 +360,19 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
/// <summary>
|
||||
/// Pulls the home's versions after the base and replays the local ones and the working state on its head. With
|
||||
/// <paramref name="takeTheirs"/> null a conflict is recorded and nothing else moves (the versions pulled are kept as
|
||||
/// files); with a choice the conflicts are settled by it.
|
||||
/// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it.
|
||||
/// Written in steps a cut can stop at any point (<see cref="WorkspaceReplay"/>): the journal, the replayed versions, the
|
||||
/// base with the merged working state (the commit point), then the old versions set aside and the held ones adopted.
|
||||
/// </summary>
|
||||
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> ReplayAsync(WorkspaceProject project,
|
||||
ProjectBundle bundle, IProjectHome home, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken)
|
||||
{
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
// Read before the home's versions are written over them: a local commit the home stored although its answer was lost
|
||||
// comes back among them, and the commits after it were made on it.
|
||||
// A local commit the home stored although its answer was lost comes back among the home's versions, and the commits
|
||||
// after it were made on it. Its file keeps reading as unsent until the base has moved onto it or past it: written
|
||||
// over now, it would leave the chain from the base, and the commits after it with it.
|
||||
var locals = Unpushed(project, bundle);
|
||||
var unsent = project.Versions().Where(v => v.StoredAt is null).Select(v => v.Id).ToHashSet();
|
||||
var theirs = new List<ProjectVersion>();
|
||||
for (var after = basis?.Number ?? 0; ;)
|
||||
{
|
||||
@@ -348,13 +380,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
foreach (var version in page)
|
||||
{
|
||||
Verify(version);
|
||||
project.WriteVersion(version, replace: true);
|
||||
if (!unsent.Contains(version.Id)) project.WriteVersion(version, replace: true);
|
||||
}
|
||||
theirs.AddRange(page);
|
||||
if (page.Count < PullPage) break;
|
||||
after = page[^1].Number;
|
||||
}
|
||||
if (theirs.Count == 0) return (bundle, null, theirs);
|
||||
var held = theirs.Where(v => unsent.Contains(v.Id)).ToList();
|
||||
var head = theirs[^1];
|
||||
var atHome = theirs.Select(v => v.Id).ToHashSet();
|
||||
var ours = locals.TakeWhile(v => atHome.Contains(v.Id)).ToList();
|
||||
@@ -364,7 +397,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
// The media first learn how the home names its photos now (hashed or converted there since the copy).
|
||||
var media = await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false);
|
||||
var photos = media?.Photos ?? NoFrames;
|
||||
if (IsNewer(head) || IsNewer(basis)) return NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
|
||||
if (IsNewer(head) || IsNewer(basis))
|
||||
{
|
||||
var newer = NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
|
||||
// Moved onto the head: the local files of versions the home held take its copies, as after a replay.
|
||||
if (newer.Conflict is null && held.Count > 0)
|
||||
await FinishReplayAsync(project, new WorkspaceReplay(head.Id, [], [], [.. held.Select(v => v.Id)]), held, home, cancellationToken).ConfigureAwait(false);
|
||||
return newer;
|
||||
}
|
||||
// Each side names a photo as the frames held it when it was saved: named as the media hold it now (a conversion or a
|
||||
// hash since), the same photo merges as one.
|
||||
var basisSettings = basis is null ? new ProjectSettings() : ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos));
|
||||
@@ -383,15 +423,28 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
if (differences.Count > 0 && takeTheirs is null)
|
||||
{
|
||||
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict });
|
||||
if (ours.Count > 0)
|
||||
{
|
||||
// The conflict is met past local commits the home holds: the base moves onto the last of them (their files
|
||||
// adopted once it has), so the commits after them stay in the chain and the conflict is settled against it.
|
||||
var onto = new WorkspaceReplay(basis!.Id, [], [], [.. held.Select(v => v.Id)]);
|
||||
project.WriteSync(project.ReadSync() with { Replay = onto });
|
||||
Step("replay.journal");
|
||||
bundle = WithBase(bundle, basis);
|
||||
project.WriteBundle(bundle);
|
||||
Step("replay.base");
|
||||
await FinishReplayAsync(project, onto, held, home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
project.WriteSync(project.ReadSync() with { Conflict = conflict, Replay = null });
|
||||
return (bundle, conflict, theirs);
|
||||
}
|
||||
var parent = head;
|
||||
var rebased = new List<ProjectVersion>(locals.Count);
|
||||
ProjectVersion parent = head;
|
||||
for (var i = 0; i < locals.Count; i++)
|
||||
{
|
||||
var local = locals[i];
|
||||
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
|
||||
var rebased = local with
|
||||
parent = local with
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
ParentId = parent.Id,
|
||||
@@ -402,13 +455,23 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
SettingsFormat = ProjectContent.FormatOf(portable),
|
||||
StoredAt = null,
|
||||
};
|
||||
project.SetAside(local);
|
||||
project.WriteVersion(rebased);
|
||||
parent = rebased;
|
||||
rebased.Add(parent);
|
||||
}
|
||||
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(merge.Merged.ToJson()), photos), allowNewer: true);
|
||||
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
|
||||
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)]);
|
||||
project.WriteSync(project.ReadSync() with { Replay = journal });
|
||||
Step("replay.journal");
|
||||
foreach (var version in rebased)
|
||||
{
|
||||
project.WriteVersion(version);
|
||||
Step("replay.version");
|
||||
}
|
||||
// The commit point: before it the old chain hangs from the old base, after it the replayed one from the head.
|
||||
project.WriteBundle(moved);
|
||||
Step("replay.base");
|
||||
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
|
||||
project.WriteSync(project.ReadSync() with { Replay = null });
|
||||
return (moved, null, theirs);
|
||||
}
|
||||
|
||||
@@ -461,38 +524,142 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
|
||||
return (bundle, conflict, theirs);
|
||||
}
|
||||
|
||||
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
|
||||
/// <summary>
|
||||
/// Finishes a replay whose base moved (<see cref="WorkspaceReplay.OntoBase"/>): each local version the home holds takes
|
||||
/// its copy (from <paramref name="known"/>, a file of the workspace, else the home), the replaced ones are set aside.
|
||||
/// </summary>
|
||||
private static async Task FinishReplayAsync(WorkspaceProject project, WorkspaceReplay replay, IReadOnlyList<ProjectVersion> known, IProjectHome home,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var id in replay.Adopted)
|
||||
{
|
||||
var locals = project.Versions().Where(v => v.Id == id && v.StoredAt is null).ToList();
|
||||
if (locals.Count == 0) continue;
|
||||
if ((known.FirstOrDefault(v => v.Id == id) ?? await StoredCopyAsync(project, id, home, cancellationToken).ConfigureAwait(false)) is not { } stored) continue;
|
||||
foreach (var local in locals) Adopt(project, local, stored);
|
||||
}
|
||||
foreach (var id in replay.Replaced) SetAsideUnsent(project, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finishes or undoes what a cut left (see the class remarks), before anything reads the chain: a replay's journal is
|
||||
/// finished once the base is its target, else its replayed versions are set aside (the old chain still hangs from the
|
||||
/// base); a save-both whose project moved onto the home's head sets its sent versions aside and clears its conflict; a
|
||||
/// local file of the version the base names (a push cut after it moved the base) takes the home's copy.
|
||||
/// </summary>
|
||||
private static async Task SettleAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
var sync = project.ReadSync();
|
||||
var basis = project.ReadBundle().Workspace!.Base;
|
||||
if (sync.Replay is { } replay)
|
||||
{
|
||||
if (basis?.VersionId == replay.OntoBase) await FinishReplayAsync(project, replay, [], home, cancellationToken).ConfigureAwait(false);
|
||||
else foreach (var id in replay.Replayed) SetAsideUnsent(project, id);
|
||||
sync = sync with { Replay = null };
|
||||
project.WriteSync(sync);
|
||||
Log.Info("workspace", $"A sync of project {project.ProjectId} cut short was {(basis?.VersionId == replay.OntoBase ? "finished" : "undone")}");
|
||||
}
|
||||
if (sync.SaveBoth is { } both && basis?.VersionId != both.FromBase)
|
||||
{
|
||||
foreach (var move in both.Moves) SetAsideUnsent(project, move.LocalId);
|
||||
var settled = sync.Conflict is { } conflict && conflict.BaseVersionId == (both.FromBase ?? Guid.Empty);
|
||||
sync = sync with { SaveBoth = null, Conflict = settled ? null : sync.Conflict };
|
||||
project.WriteSync(sync);
|
||||
Log.Info("workspace", $"A save-both of project {project.ProjectId} cut short was finished");
|
||||
}
|
||||
if (basis is not null && project.Versions().Where(v => v.Id == basis.VersionId && v.StoredAt is null).ToList() is { Count: > 0 } lingering
|
||||
&& await StoredCopyAsync(project, basis.VersionId, home, cancellationToken).ConfigureAwait(false) is { } stored)
|
||||
{
|
||||
foreach (var local in lingering) Adopt(project, local, stored);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The home's copy of version <paramref name="id"/>: a file of the workspace marked sent, else asked from the home (kept as a file); null when the home has none.</summary>
|
||||
private static async Task<ProjectVersion?> StoredCopyAsync(WorkspaceProject project, Guid id, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
if (project.Versions().FirstOrDefault(v => v.Id == id && v.StoredAt is not null) is { } file) return file;
|
||||
if (await home.GetVersionAsync(project.ProjectId, id, cancellationToken).ConfigureAwait(false) is not { StoredAt: not null } fetched) return null;
|
||||
Verify(fetched);
|
||||
return fetched;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The local file of a version the home holds takes the home's copy (sent, maybe under another number). Called only once
|
||||
/// the base names the version or one after it: before, the copy would take it out of the chain of unsent versions.
|
||||
/// </summary>
|
||||
private static void Adopt(WorkspaceProject project, ProjectVersion local, ProjectVersion stored)
|
||||
{
|
||||
project.WriteVersion(stored, replace: true);
|
||||
if (stored.Number != local.Number) project.SetAside(local);
|
||||
}
|
||||
|
||||
/// <summary>Sets aside the unsent local files of version <paramref name="id"/>.</summary>
|
||||
private static void SetAsideUnsent(WorkspaceProject project, Guid id)
|
||||
{
|
||||
foreach (var version in project.Versions().Where(v => v.Id == id && v.StoredAt is null)) project.SetAside(version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head. The copy
|
||||
/// and the ids its versions are sent under are journaled before the first is sent (<see cref="WorkspaceSaveBoth"/>): a
|
||||
/// retry after a cut sends to the same copy what it lacks (the home answers "already stored" for the rest), whatever name
|
||||
/// it is asked for, and the base moving onto the home's head is the commit point.
|
||||
/// </summary>
|
||||
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
|
||||
{
|
||||
var workspace = bundle.Workspace!;
|
||||
if (!bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
|
||||
bundle = project.ReadBundle();
|
||||
var locals = Unpushed(project, bundle);
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
var sync = project.ReadSync();
|
||||
var pending = sync.SaveBoth;
|
||||
SequenceProject? copy = null;
|
||||
if (pending is not null)
|
||||
{
|
||||
copy = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == pending.CopyId);
|
||||
// A copy deleted at the home meanwhile: a new one is made.
|
||||
if (copy is null) pending = null;
|
||||
}
|
||||
var pushed = new List<ProjectVersion>();
|
||||
if (locals.Count > 0)
|
||||
{
|
||||
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
|
||||
var parent = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (pending is null)
|
||||
{
|
||||
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
|
||||
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
|
||||
var first = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
|
||||
pending = new WorkspaceSaveBoth(copy.Id, first.Id, first.Number, workspace.Base?.VersionId, []);
|
||||
}
|
||||
var known = pending.Moves.Select(m => m.LocalId).ToHashSet();
|
||||
if (locals.Any(l => !known.Contains(l.Id)) || !ReferenceEquals(pending, sync.SaveBoth))
|
||||
{
|
||||
pending = pending with { Moves = [.. pending.Moves, .. locals.Where(l => !known.Contains(l.Id)).Select(l => new WorkspaceMove(l.Id, Guid.CreateVersion7()))] };
|
||||
project.WriteSync(sync with { SaveBoth = pending });
|
||||
}
|
||||
Step("saveboth.journal");
|
||||
var ids = pending.Moves.ToDictionary(m => m.LocalId, m => m.CopyVersionId);
|
||||
var (parentId, parentNumber) = (pending.CopyBaseId, pending.CopyBaseNumber);
|
||||
foreach (var local in locals)
|
||||
{
|
||||
var moved = local with { Id = Guid.CreateVersion7(), ProjectId = copy.Id, ParentId = parent.Id, Number = parent.Number + 1, StoredAt = null };
|
||||
var moved = local with { Id = ids[local.Id], ProjectId = copy!.Id, ParentId = parentId, Number = parentNumber + 1, StoredAt = null };
|
||||
var result = await home.PushAsync(copy.Id, moved, cancellationToken).ConfigureAwait(false);
|
||||
if (result is not { Outcome: PushOutcome.Stored or PushOutcome.AlreadyStored, Version: { } stored })
|
||||
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} saved as project '{copy.Name}': {result.Outcome}.");
|
||||
pushed.Add(stored);
|
||||
parent = stored;
|
||||
(parentId, parentNumber) = (stored.Id, stored.Number);
|
||||
Step("saveboth.pushed");
|
||||
}
|
||||
}
|
||||
// This project takes the home's head: the local versions now live in the copy (and their files in versions/.replaced).
|
||||
var head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
|
||||
Verify(head);
|
||||
project.WriteVersion(head, replace: true);
|
||||
foreach (var local in locals) project.SetAside(local);
|
||||
var media = project.ReadMedia();
|
||||
var working = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
|
||||
project.WriteBundle(WithBase(bundle, head) with { Project = working, Saved = DateTimeOffset.UtcNow });
|
||||
Step("saveboth.base");
|
||||
foreach (var local in locals) project.SetAside(local);
|
||||
foreach (var move in pending?.Moves ?? []) SetAsideUnsent(project, move.LocalId);
|
||||
project.WriteSync(WorkspaceSyncState.None);
|
||||
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user