merge: third-pass sync and editor fixes (W-2, W-3, W-4, W-16)
Merge branch fix3/sync-editor into the verification branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
21 files changed
+1038
-79
No files matched your search
@@ -13,12 +13,17 @@ namespace Titano.App.Editor;
|
||||
/// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render
|
||||
/// jobs. Every change is saved shortly after it is made (<see cref="ProjectSaver"/>); a change stored meanwhile by
|
||||
/// someone else (an analysis job, another client) is merged in. On a server sequence, settings both sides changed to
|
||||
/// different values wait for the user's choice (<see cref="Conflict"/>). Call from one thread (the UI thread).
|
||||
/// different values wait for the user's choice (<see cref="Conflict"/>). Frames inserted under the editor (a sync
|
||||
/// download, an import of earlier photos, a scan) are read again before the next save or render, and the project's frame
|
||||
/// positions, its undo steps included, move with their frames as the stored ones did. Call from one thread (the UI thread).
|
||||
/// </summary>
|
||||
public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
/// <summary>Times a save reads the frames again when frames keep changing under it.</summary>
|
||||
private const int FollowAttempts = 3;
|
||||
|
||||
/// <summary>Sections "Optimise all" walks through, in panel order.</summary>
|
||||
public static IReadOnlyList<AdvisorSection> OptimisedSections { get; } =
|
||||
[AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export];
|
||||
@@ -27,6 +32,12 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
private readonly ProjectSaver _saver;
|
||||
private ProjectSettings _basis;
|
||||
|
||||
/// <summary>
|
||||
/// The sequence being read again (<see cref="BeginReadAsync"/>) until its content is taken: saves and other reads wait
|
||||
/// for it.
|
||||
/// </summary>
|
||||
private Task _reading = Task.CompletedTask;
|
||||
|
||||
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList<EncoderCapability> codecs, TimeSpan? saveDelay = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
@@ -201,19 +212,46 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
|
||||
|
||||
/// <summary>Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one.</summary>
|
||||
/// <summary>
|
||||
/// Makes the project's frame positions name the sequence's frames as they are now, before the project is taken along
|
||||
/// (a render embeds it): frames inserted since the last read (a sync download, an import of earlier photos, a scan)
|
||||
/// are read again and the positions follow them (<see cref="ReloadAsync"/>). A server sequence whose frames changed
|
||||
/// becomes outdated instead (<see cref="ISequenceSource.IsOutdated"/>: read-only, its renders refused).
|
||||
/// </summary>
|
||||
public async Task EnsureFramesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
var current = await Source.FramesCurrentAsync(cancellationToken);
|
||||
// A read that began meanwhile (a save that met the new frames) may have taken them already: it ends first.
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
if (!current && !IsRemote) await ReloadAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
|
||||
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
|
||||
/// and a read waits for the one under way, so each follows the frames the one before it took.
|
||||
/// </summary>
|
||||
public async Task ReloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _saver.FlushAsync();
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
||||
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
|
||||
// retry meets them and asks (Conflict).
|
||||
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
|
||||
var taken = await BeginReadAsync();
|
||||
try
|
||||
{
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
History.Replace(merged);
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
Follow(content);
|
||||
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
|
||||
// retry meets them and asks (Conflict).
|
||||
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
|
||||
{
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
History.Replace(merged);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
taken.SetResult();
|
||||
}
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
@@ -233,6 +271,42 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
await Source.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes <paramref name="content"/> as the sequence. Frames inserted or removed since the last read (a sync download,
|
||||
/// an import of earlier photos, a scan) moved the stored project's frame positions with their frames: the editor's
|
||||
/// project, its undo and redo steps and its basis move the same way (<see cref="ProjectSettings.FollowFrames"/>), so
|
||||
/// they keep naming the frames the user chose. Call while the read is under way (<see cref="BeginReadAsync"/>).
|
||||
/// </summary>
|
||||
private void Follow(SequenceContent content)
|
||||
{
|
||||
var before = Content.Frames.Select(f => f.Id).ToList();
|
||||
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
||||
if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return;
|
||||
var after = content.Frames;
|
||||
Log.Info("editor", $"The frames of {content.Sequence.DisplayTitle} changed while it was open; its frame positions follow them");
|
||||
_basis = Move(_basis);
|
||||
History.Remap(Move);
|
||||
|
||||
ProjectSettings Move(ProjectSettings project) =>
|
||||
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
|
||||
/// one under way until the returned source is completed.
|
||||
/// </summary>
|
||||
private async Task<TaskCompletionSource> BeginReadAsync()
|
||||
{
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_reading = taken.Task;
|
||||
return taken;
|
||||
}
|
||||
|
||||
/// <summary>Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.</summary>
|
||||
private static bool NamesFrames(ProjectSettings project) =>
|
||||
project.ExcludedFrames.Count > 0 || project.HeroFrame is not null || project.Camera.Keyframes.Count > 0 || project.PendingFrames is { Count: > 0 };
|
||||
|
||||
private static (SequenceContent, SequenceContext, AdvisorResult, IReadOnlyList<SequencePreset>) Analyse(SequenceContent content,
|
||||
IReadOnlyList<EncoderCapability> codecs)
|
||||
{
|
||||
@@ -271,21 +345,49 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
private async Task SaveAsync(ProjectSettings project)
|
||||
{
|
||||
ProjectSettings stored;
|
||||
try
|
||||
if (!_reading.IsCompleted)
|
||||
{
|
||||
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
// A read under way decides the frames the project's positions name. Once it is taken, the project as it is
|
||||
// then contains this change (projects are whole snapshots), with its positions on those frames.
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
project = Project;
|
||||
}
|
||||
catch (ProjectConflictException ex)
|
||||
ProjectSettings stored;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var found = Conflict is null;
|
||||
Conflict = ex;
|
||||
if (found)
|
||||
try
|
||||
{
|
||||
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
|
||||
ConflictFound?.Invoke(ex);
|
||||
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
break;
|
||||
}
|
||||
catch (FramesChangedException) when (attempt < FollowAttempts)
|
||||
{
|
||||
// Frames were inserted under the editor and the stored positions moved with them: the frames are read
|
||||
// again (after a read under way, whose move this edit's snapshot missed), the project's positions follow
|
||||
// them, and the project as it is then, which contains this edit, is saved in the new order.
|
||||
var taken = await BeginReadAsync();
|
||||
try
|
||||
{
|
||||
Follow(await Source.LoadAsync(CancellationToken.None));
|
||||
}
|
||||
finally
|
||||
{
|
||||
taken.SetResult();
|
||||
}
|
||||
project = Project;
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
catch (ProjectConflictException ex)
|
||||
{
|
||||
var found = Conflict is null;
|
||||
Conflict = ex;
|
||||
if (found)
|
||||
{
|
||||
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
|
||||
ConflictFound?.Invoke(ex);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
throw;
|
||||
}
|
||||
Conflict = null;
|
||||
_basis = stored;
|
||||
|
||||
@@ -48,6 +48,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
private readonly AsyncRelayCommand _cancelServerJob;
|
||||
private PreviewRenderer _renderer;
|
||||
private int _currentIndex;
|
||||
|
||||
/// <summary>The frame on screen: it stays on screen when frames are inserted or removed before it.</summary>
|
||||
private Guid _currentFrameId;
|
||||
private EditorTab _selectedTab;
|
||||
private ImageSource? _previewImage;
|
||||
private ImageSource? _originalImage;
|
||||
@@ -111,6 +114,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
|
||||
_selectedTab = Exposure;
|
||||
_currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0;
|
||||
_currentFrameId = FrameId(_currentIndex);
|
||||
// Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders.
|
||||
_syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut;
|
||||
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
|
||||
@@ -233,6 +237,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
set
|
||||
{
|
||||
var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1);
|
||||
_currentFrameId = FrameId(clamped);
|
||||
if (!Set(ref _currentIndex, clamped)) return;
|
||||
foreach (var tab in Tabs) tab.OnCurrentFrameChanged();
|
||||
UpdateInfo();
|
||||
@@ -515,6 +520,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
/// </summary>
|
||||
public async Task RenderAsync(JobPriority priority, bool batch)
|
||||
{
|
||||
// The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server
|
||||
// sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies.
|
||||
await Session.EnsureFramesAsync();
|
||||
if (IsOutdated) return;
|
||||
var export = batch ? RenderExport : RenderExport with { Batch = [] };
|
||||
var requests = Session.RenderRequests(export);
|
||||
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
|
||||
@@ -801,6 +810,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
|
||||
private void OnContentChanged()
|
||||
{
|
||||
// The frame on screen stays on screen, wherever frames inserted or removed before it put it (the tabs that reload
|
||||
// below may seek meanwhile).
|
||||
var shown = IndexOfFrame(_currentFrameId) ?? int.Min(CurrentIndex, int.Max(0, FrameCount - 1));
|
||||
_renderer = new PreviewRenderer(Session.Content, Session.Source);
|
||||
Planner = new ExportPlanner(Session.Content, _encoders, _host);
|
||||
if (Thumbnails.Count != FrameCount) Thumbnails = new EditorThumbnails(Session.Source, FrameCount);
|
||||
@@ -808,13 +820,27 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
foreach (var tab in Tabs) tab.OnContentChanged();
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
OnPropertyChanged(nameof(FrameCount));
|
||||
CurrentIndex = int.Min(CurrentIndex, int.Max(0, FrameCount - 1));
|
||||
CurrentIndex = shown;
|
||||
UpdateMarkers();
|
||||
RequestCorrections();
|
||||
RequestPlan();
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
|
||||
/// <summary>The id of frame <paramref name="index"/>; empty when there is none.</summary>
|
||||
private Guid FrameId(int index) => (uint)index < (uint)FrameCount ? Session.Content.Frames[index].Id : Guid.Empty;
|
||||
|
||||
/// <summary>Where frame <paramref name="id"/> is now; null when the sequence no longer has it.</summary>
|
||||
private int? IndexOfFrame(Guid id)
|
||||
{
|
||||
var frames = Session.Content.Frames;
|
||||
for (var i = 0; i < frames.Count; i++)
|
||||
{
|
||||
if (frames[i].Id == id) return i;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The UI language changed: what the tabs keep in objects (chart legends and summaries, the Auto chips of the
|
||||
/// settings), the timeline markers and the preview's info line are made again in the new language.
|
||||
|
||||
@@ -44,6 +44,14 @@ public interface ISequenceSource : IAsyncDisposable
|
||||
/// <exception cref="EditorException">The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano).</exception>
|
||||
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the frames <see cref="LoadAsync"/> read last are still the sequence's, in the same order: frames inserted
|
||||
/// or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's positions. A
|
||||
/// server sequence whose frames changed becomes <see cref="IsOutdated"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="EditorException">The sequence is gone.</exception>
|
||||
Task<bool> FramesCurrentAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Frame <paramref name="index"/> in linear light, oriented, long edge at most <paramref name="maxLongEdge"/>; null
|
||||
/// when the frame cannot be read. The caller owns the buffer.
|
||||
|
||||
@@ -23,7 +23,10 @@ namespace Titano.App.Editor;
|
||||
/// project in <c>.titano/project.json</c> mirrored in the index's settings column (with its hero frame, which the
|
||||
/// Library shows), jobs on this PC's engine. Project writes follow the archive engine's protocol: under the sequence's
|
||||
/// lease file (so the server and the job engine wait for it), file first (atomically), then the index with its settings
|
||||
/// version as an optimistic check.
|
||||
/// version as an optimistic check. Project settings name frames by position, and frames inserted while the sequence is
|
||||
/// open (a sync download, an import of earlier photos, a scan) move the stored positions with their frames: a save made
|
||||
/// against the frames read earlier is refused (<see cref="FramesChangedException"/>) until the editor has read them again
|
||||
/// and moved its own positions the same way (<see cref="EditorSession"/>).
|
||||
/// </summary>
|
||||
public sealed class LocalSequenceSource : ISequenceSource
|
||||
{
|
||||
@@ -31,6 +34,9 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
private const int SaveAttempts = 3;
|
||||
private const int JobsListed = 200;
|
||||
|
||||
/// <summary>Times the frames are listed again when an insertion lands while they are read.</summary>
|
||||
private const int ReadAttempts = 3;
|
||||
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly Guid _sequenceId;
|
||||
private readonly ImageDecoder _decoder;
|
||||
@@ -41,6 +47,10 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
/// <summary>The JPEG of each GPR frame that an import keeps in another sequence (<see cref="GprCompanions"/>), by position.</summary>
|
||||
private string?[] _companions = [];
|
||||
private Guid[] _frameIds = [];
|
||||
|
||||
/// <summary>The frames version of the frames last read (<see cref="LoadAsync"/>), whose order the project's positions follow.</summary>
|
||||
private int _framesVersion = -1;
|
||||
|
||||
private ArchivePaths? _paths;
|
||||
private SequencePaths? _folder;
|
||||
|
||||
@@ -74,15 +84,8 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
var (sequence, frames) = await ReadFramesAsync(cancellationToken);
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing();
|
||||
var frames = new List<Frame>();
|
||||
while (true)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(_sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < PageSize) break;
|
||||
}
|
||||
var renders = await _db.Renders.ListBySequenceAsync(_sequenceId, cancellationToken);
|
||||
var companions = await GprCompanions.FindAsync(_db, archive, frames, cancellationToken);
|
||||
return await Task.Run(() =>
|
||||
@@ -95,13 +98,21 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath);
|
||||
}
|
||||
_companions = [.. frames.Select(f => companions.GetValueOrDefault(f.Id))];
|
||||
(_paths, _folder, _files, _frameIds) = (paths, folder, files, [.. frames.Select(f => f.Id)]);
|
||||
(_paths, _folder, _files, _frameIds, _framesVersion) = (paths, folder, files, [.. frames.Select(f => f.Id)], sequence.FramesVersion);
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), ReadReport(folder, frames.Count),
|
||||
context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)], SavedCopies.List(folder.MetaDirectory));
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <remarks>An insertion bumps the row's frames version in the transaction that renumbers the frames.</remarks>
|
||||
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var framesVersion = _framesVersion;
|
||||
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
return row.FramesVersion == framesVersion;
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null;
|
||||
@@ -127,7 +138,7 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var (paths, folder, frameIds) = (_paths, _folder, _frameIds);
|
||||
var (paths, folder, frameIds, framesVersion) = (_paths, _folder, _frameIds, _framesVersion);
|
||||
if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first.");
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
@@ -137,13 +148,16 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
// Frames were inserted or removed since the editor read them, so its positions name the old order. Insertions
|
||||
// hold this lease, so the frames do not change again before this save ends.
|
||||
if (row.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Editor.Error.FramesArriving"));
|
||||
var stored = ReadProject(row, folder);
|
||||
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
|
||||
var json = merged.ToJson();
|
||||
if (json == stored.ToJson()) return merged;
|
||||
AtomicFile.WriteAllText(folder.ProjectPath, json);
|
||||
var edit = new SequenceEdit { SettingsJson = json, HeroFrameId = merged.HeroFrame == stored.HeroFrame ? null : HeroFrameId(merged, frameIds) };
|
||||
var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, cancellationToken);
|
||||
var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, framesVersion, cancellationToken);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.Updated:
|
||||
@@ -151,7 +165,8 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
return merged;
|
||||
case SequenceEditOutcome.NotFound:
|
||||
throw Missing();
|
||||
// The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write.
|
||||
// The settings moved in the index meanwhile (server API): merge again on top of them, or find the frames that
|
||||
// moved; the file follows the next write.
|
||||
case SequenceEditOutcome.Conflict when attempt == SaveAttempts:
|
||||
throw new EditorException(Loc.L("Editor.Error.SaveConflict"));
|
||||
}
|
||||
@@ -181,6 +196,30 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence row with its frames as one state: the frames are listed between two reads of the row that find the
|
||||
/// same frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and
|
||||
/// bumps the version), so the project's positions name these frames.
|
||||
/// </summary>
|
||||
/// <exception cref="EditorException">The sequence is gone, or an insertion landed during every attempt.</exception>
|
||||
private async Task<(Sequence Row, List<Frame> Frames)> ReadFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 0; attempt < ReadAttempts; attempt++)
|
||||
{
|
||||
var before = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
var frames = new List<Frame>();
|
||||
while (true)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(_sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < PageSize) break;
|
||||
}
|
||||
var after = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
if (after.FramesVersion == before.FramesVersion) return (after, frames);
|
||||
}
|
||||
throw new EditorException(Loc.L("Editor.Error.FramesArriving"));
|
||||
}
|
||||
|
||||
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
|
||||
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
|
||||
internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder)
|
||||
@@ -221,3 +260,9 @@ public sealed class LocalSequenceSource : ISequenceSource
|
||||
|
||||
private static EditorException Missing() => new(Loc.L("Editor.Error.Missing"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames of a sequence of this PC changed since the editor read them (frames inserted or removed): nothing was
|
||||
/// saved. The editor reads them again, moves its positions as the index moved the stored ones, and saves again.
|
||||
/// </summary>
|
||||
public sealed class FramesChangedException(string message) : EditorException(message);
|
||||
@@ -78,6 +78,25 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the project and every undo and redo snapshot with <paramref name="remap"/>, without an undo step: a change
|
||||
/// of what the values mean rather than of the values (frame positions following frames inserted under the editor), so
|
||||
/// undo and redo keep naming the same frames.
|
||||
/// </summary>
|
||||
public void Remap(Func<ProjectSettings, ProjectSettings> remap)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remap);
|
||||
foreach (var steps in new[] { _undo, _redo })
|
||||
{
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = remap(node.Value);
|
||||
}
|
||||
var current = remap(Current);
|
||||
if (ProjectMerge.SameValues(current, Current)) return;
|
||||
_runKey = null;
|
||||
Current = current;
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private static void Rebase(LinkedList<ProjectSettings> steps, ProjectMerge.Rebase rebase)
|
||||
{
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
|
||||
|
||||
@@ -31,7 +31,8 @@ namespace Titano.App.Editor;
|
||||
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
|
||||
/// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames
|
||||
/// throws <see cref="ProxiesOutdatedException"/>, and frames that change on the server while the sequence is open make
|
||||
/// it <see cref="IsOutdated"/> (read-only, nothing saved or rendered).
|
||||
/// it <see cref="IsOutdated"/> (read-only, nothing saved or rendered). Saves name the frames version the editor's frames
|
||||
/// are at, so the server refuses one made against frames it no longer has even before its event arrives.
|
||||
/// </summary>
|
||||
public sealed class RemoteSequenceSource : ISequenceSource
|
||||
{
|
||||
@@ -129,6 +130,13 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <remarks>Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated.</remarks>
|
||||
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (IsOutdated) return false;
|
||||
return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken)));
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_remote.Frames.Count) return null;
|
||||
@@ -150,19 +158,24 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
|
||||
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
|
||||
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
|
||||
// The positions name the frames this editor holds: the server refuses them (409 frames_conflict) once its
|
||||
// frames changed, also before its event says so. A server that predates the check ignores it.
|
||||
var request = new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero, Volatile.Read(ref _framesVersion));
|
||||
try
|
||||
{
|
||||
var updated = await Call(() => _api.UpdateSequenceAsync(Id, new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero),
|
||||
cancellationToken));
|
||||
var updated = await Call(() => _api.UpdateSequenceAsync(Id, request, cancellationToken));
|
||||
Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion));
|
||||
return merged;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
// Changed on the server since this editor read it: merge again on top of the server's settings.
|
||||
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
|
||||
// Changed on the server since this editor read it, its settings or its frames: other frames make the
|
||||
// editor outdated (its proxies are not the server's), otherwise the edit merges again on top of the
|
||||
// server's settings, at the frames version they are at.
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
if (!SameFrames(manifest)) throw Outdated();
|
||||
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
|
||||
}
|
||||
}
|
||||
@@ -219,7 +232,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
|
||||
/// <summary>
|
||||
/// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile
|
||||
/// are read back from the jobs). Nothing that fails on the way ends it.
|
||||
/// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it.
|
||||
/// </summary>
|
||||
private async Task ListenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -244,6 +257,8 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
|
||||
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
|
||||
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
|
||||
// A frames change announced while the socket was down is found now rather than at the next save.
|
||||
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
@@ -297,9 +312,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
{
|
||||
try
|
||||
{
|
||||
var manifest = await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false);
|
||||
if (SameFrames(manifest)) Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
else MarkOutdated();
|
||||
Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
@@ -336,6 +349,21 @@ public sealed class RemoteSequenceSource : ISequenceSource
|
||||
JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
|
||||
/// (saves name it), outdated otherwise. Returns whether they are.
|
||||
/// </summary>
|
||||
private bool Compare(SequenceManifest manifest)
|
||||
{
|
||||
if (!SameFrames(manifest))
|
||||
{
|
||||
MarkOutdated();
|
||||
return false;
|
||||
}
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames).</summary>
|
||||
private bool SameFrames(SequenceManifest manifest) =>
|
||||
manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id));
|
||||
|
||||
@@ -26,12 +26,13 @@ public sealed record FramePhoto(string? Sha256, long Size, DateTime? CapturedAt)
|
||||
|
||||
/// <summary>
|
||||
/// The photos of one copy's frames by frame index (positions in capture order, BRIEF §5), and where a photo is among
|
||||
/// them. Immutable once built, so parallel workers may share it.
|
||||
/// them. A copy may hold one photo more than once (a folder adopted with 'IMG_0001.JPG' and 'IMG_0001 (1).JPG'); those
|
||||
/// frames are told apart by their order (<see cref="Occurrence"/>). Immutable once built, so parallel workers may share it.
|
||||
/// </summary>
|
||||
public sealed class FramePhotos
|
||||
{
|
||||
private readonly FramePhoto?[] _byIndex;
|
||||
private readonly Dictionary<string, int> _bySha = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, List<int>> _bySha = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<(long Size, long Time), List<int>> _bySizeAndTime = [];
|
||||
|
||||
/// <param name="frames">Each frame's index and photo, in any order.</param>
|
||||
@@ -44,7 +45,12 @@ public sealed class FramePhotos
|
||||
for (var i = 0; i < _byIndex.Length; i++)
|
||||
{
|
||||
if (_byIndex[i] is not { } photo) continue;
|
||||
if (photo.IsHashed) _bySha.TryAdd(photo.Sha256!.ToLowerInvariant(), i);
|
||||
if (photo.IsHashed)
|
||||
{
|
||||
var sha = photo.Sha256!.ToLowerInvariant();
|
||||
if (!_bySha.TryGetValue(sha, out var copies)) _bySha[sha] = copies = [];
|
||||
copies.Add(i);
|
||||
}
|
||||
if (photo.CapturedAt is not { } time) continue;
|
||||
var key = (photo.Size, FramePhoto.Millisecond(time));
|
||||
if (!_bySizeAndTime.TryGetValue(key, out var same)) _bySizeAndTime[key] = same = [];
|
||||
@@ -60,17 +66,39 @@ public sealed class FramePhotos
|
||||
/// <summary>Some frame is not hashed yet: matching it needs capture times.</summary>
|
||||
public bool HasUnhashed => _byIndex.Any(p => p is { IsHashed: false });
|
||||
|
||||
/// <summary>The index of the first frame holding <paramref name="photo"/> (<see cref="FramePhoto.Matches"/>); null when none does.</summary>
|
||||
public int? IndexOf(FramePhoto photo)
|
||||
/// <summary>
|
||||
/// The index of the first frame holding <paramref name="photo"/> (<see cref="FramePhoto.Matches"/>), or with
|
||||
/// <paramref name="occurrence"/> n of the (n+1)-th in index order; null when fewer frames hold it.
|
||||
/// </summary>
|
||||
public int? IndexOf(FramePhoto photo, int occurrence = 0)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photo);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(occurrence);
|
||||
var holding = Holding(photo);
|
||||
return occurrence < holding.Count ? holding[occurrence] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which of the frames holding the photo at <paramref name="index"/> it is, in index order: 0 for the first (and for
|
||||
/// a photo held once), 1 for the second, … A position translated to another copy names the same one there.
|
||||
/// </summary>
|
||||
public int Occurrence(int index) => this[index] is { } photo ? Math.Max(Holding(photo).BinarySearch(index), 0) : 0;
|
||||
|
||||
/// <summary>
|
||||
/// The indices of the frames holding <paramref name="photo"/>, ascending. A hashed photo is the frames with its SHA-256
|
||||
/// when there are any: a frame not hashed yet with the same size and capture time may be another photo (a RAW of
|
||||
/// constant size in a burst without sub-second times), so it counts only when no frame has the hash.
|
||||
/// </summary>
|
||||
private List<int> Holding(FramePhoto photo)
|
||||
{
|
||||
if (photo.IsHashed && _bySha.TryGetValue(photo.Sha256!.ToLowerInvariant(), out var hashed)) return hashed;
|
||||
if (photo.CapturedAt is not { } time || !_bySizeAndTime.TryGetValue((photo.Size, FramePhoto.Millisecond(time)), out var candidates)) return null;
|
||||
var holding = new List<int>(1);
|
||||
if (photo.CapturedAt is not { } time || !_bySizeAndTime.TryGetValue((photo.Size, FramePhoto.Millisecond(time)), out var candidates)) return holding;
|
||||
foreach (var index in candidates)
|
||||
{
|
||||
if (_byIndex[index]!.Matches(photo)) return index;
|
||||
if (_byIndex[index]!.Matches(photo)) holding.Add(index);
|
||||
}
|
||||
return null;
|
||||
return holding;
|
||||
}
|
||||
|
||||
/// <summary>Both lists hold the same photos at the same indices: a position names the same photo on both.</summary>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.Core.Project;
|
||||
|
||||
@@ -59,6 +60,13 @@ public sealed record PendingFrame
|
||||
public long Size { get; init; }
|
||||
public DateTime? CapturedAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Which of the frames holding the photo it names, in capture order, when a copy holds the photo more than once
|
||||
/// (<see cref="FramePhotos.Occurrence"/>): 0, the first, is not written.
|
||||
/// </summary>
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
|
||||
public int Occurrence { get; init; }
|
||||
|
||||
/// <summary>The photo is excluded from renders.</summary>
|
||||
public bool Excluded { get; init; }
|
||||
|
||||
@@ -317,6 +325,39 @@ public sealed record ProjectSettings
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A project written against the frames <paramref name="before"/> (frame ids, by index) moved to the frames
|
||||
/// <paramref name="after"/> (in index order) the way the archive index moves its own copy when it takes them
|
||||
/// (ProjectPositions in Titano.Data): while every frame of <paramref name="before"/> is still there, its positions
|
||||
/// move with their frames (<see cref="MoveFramePositions"/>), otherwise they stay; either way pending frames whose
|
||||
/// photos are now there take their place (<see cref="TranslateFramePositions"/>). An editor that read the frames
|
||||
/// before frames were inserted saves its edit in the new order this way. Null when nothing changes.
|
||||
/// </summary>
|
||||
public static string? FollowFrames(string json, IReadOnlyList<Guid> before, IReadOnlyList<Frame> after)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(before);
|
||||
ArgumentNullException.ThrowIfNull(after);
|
||||
var now = new Dictionary<Guid, int>(after.Count);
|
||||
for (var i = 0; i < after.Count; i++) now[after[i].Id] = i;
|
||||
Dictionary<int, int>? moves = [];
|
||||
for (var i = 0; i < before.Count; i++)
|
||||
{
|
||||
if (!now.TryGetValue(before[i], out var index))
|
||||
{
|
||||
moves = null;
|
||||
break;
|
||||
}
|
||||
if (index != i) moves[i] = index;
|
||||
}
|
||||
var moved = moves is null ? null : MoveFramePositions(json, moves);
|
||||
var current = moved ?? json;
|
||||
// Most projects wait for no photo: the frames' photos are gathered only for those that do.
|
||||
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
|
||||
? TranslateFramePositions(current, null, new FramePhotos(after.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
|
||||
: null;
|
||||
return placed ?? moved;
|
||||
}
|
||||
|
||||
private static bool Move(JsonNode? position, Action<JsonNode> replace, IReadOnlyDictionary<int, int> moves)
|
||||
{
|
||||
if (position is not JsonValue value || !value.TryGetValue<int>(out var old) || !moves.TryGetValue(old, out var now) || now == old) return false;
|
||||
@@ -347,7 +388,9 @@ public sealed record ProjectSettings
|
||||
/// Translates the frame positions of a project written against the frames of another copy of the sequence
|
||||
/// (<paramref name="from"/>; a server sequence and a PC's copy hold the same photos, though not always all of them,
|
||||
/// BRIEF §14.5) to the frames of <paramref name="to"/>, by photo: each exclusion, the hero and each camera keyframe
|
||||
/// moves to the frame of <paramref name="to"/> holding its photo. One whose photo <paramref name="to"/> lacks becomes
|
||||
/// moves to the frame of <paramref name="to"/> holding its photo, and a position on the n-th frame holding a photo
|
||||
/// <paramref name="from"/> holds more than once to the n-th such frame (<see cref="FramePhotos.Occurrence"/>), so
|
||||
/// duplicates stay apart. One whose photo (or that copy of it) <paramref name="to"/> lacks becomes
|
||||
/// a <see cref="PendingFrame"/>, and pending frames whose photo <paramref name="to"/> holds become positions again; a
|
||||
/// pending hero only while no other hero is chosen (a hero chosen since one was left pending is newer, so that one no
|
||||
/// longer waits even when the chosen one must wait in turn), a pending keyframe only where no keyframe is. With
|
||||
@@ -370,7 +413,7 @@ public sealed record ProjectSettings
|
||||
foreach (var node in stored)
|
||||
{
|
||||
// An entry naming no photo is not this Titano's to place: it stays as it is.
|
||||
if (node is JsonObject entry && PhotoOf(entry) is { } photo) pending.Add(new Parked(photo, entry.DeepClone().AsObject()));
|
||||
if (node is JsonObject entry && PhotoOf(entry) is { } photo) pending.Add(new Parked(photo, OccurrenceOf(entry), entry.DeepClone().AsObject()));
|
||||
else unreadable.Add(node?.DeepClone());
|
||||
}
|
||||
}
|
||||
@@ -409,14 +452,14 @@ public sealed record ProjectSettings
|
||||
{
|
||||
if (!IsPosition(node, out var at)) kept.Add(node?.DeepClone());
|
||||
else if (from[at] is not { } photo) changed = true;
|
||||
else if (to.IndexOf(photo) is { } now)
|
||||
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
|
||||
{
|
||||
kept.Add(JsonValue.Create(now));
|
||||
changed |= now != at;
|
||||
}
|
||||
else
|
||||
{
|
||||
Park(pending, photo).Entry["excluded"] = true;
|
||||
Park(pending, photo, from.Occurrence(at)).Entry["excluded"] = true;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -425,8 +468,8 @@ public sealed record ProjectSettings
|
||||
if (project["heroFrame"] is JsonValue hero && hero.TryGetValue<int>(out var heroAt))
|
||||
{
|
||||
var photo = from[heroAt];
|
||||
var now = photo is null ? null : to.IndexOf(photo);
|
||||
if (photo is not null && now is null) Park(pending, photo).Entry["hero"] = true;
|
||||
var now = photo is null ? null : to.IndexOf(photo, from.Occurrence(heroAt));
|
||||
if (photo is not null && now is null) Park(pending, photo, from.Occurrence(heroAt)).Entry["hero"] = true;
|
||||
if (now != heroAt)
|
||||
{
|
||||
project["heroFrame"] = now;
|
||||
@@ -448,7 +491,7 @@ public sealed record ProjectSettings
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
else if (to.IndexOf(photo) is { } now)
|
||||
else if (to.IndexOf(photo, from.Occurrence(at)) is { } now)
|
||||
{
|
||||
copy["frame"] = now;
|
||||
kept.Add(copy);
|
||||
@@ -456,7 +499,7 @@ public sealed record ProjectSettings
|
||||
}
|
||||
else
|
||||
{
|
||||
var parked = Park(pending, photo).Entry;
|
||||
var parked = Park(pending, photo, from.Occurrence(at)).Entry;
|
||||
if (parked["keyframes"] is not JsonArray keys) parked["keyframes"] = keys = new JsonArray();
|
||||
keys.Add(copy);
|
||||
changed = true;
|
||||
@@ -473,7 +516,7 @@ public sealed record ProjectSettings
|
||||
var changed = false;
|
||||
foreach (var parked in pending)
|
||||
{
|
||||
if (to.IndexOf(parked.Photo) is not { } at) continue;
|
||||
if (to.IndexOf(parked.Photo, parked.Occurrence) is not { } at) continue;
|
||||
parked.Placed = changed = true;
|
||||
if (Flag(parked.Entry, "excluded"))
|
||||
{
|
||||
@@ -523,18 +566,19 @@ public sealed record ProjectSettings
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The pending entry of <paramref name="photo"/>, added when there is none.</summary>
|
||||
private static Parked Park(List<Parked> pending, FramePhoto photo)
|
||||
/// <summary>The pending entry of <paramref name="photo"/> (the copy of it <paramref name="occurrence"/> names), added when there is none.</summary>
|
||||
private static Parked Park(List<Parked> pending, FramePhoto photo, int occurrence)
|
||||
{
|
||||
if (pending.FirstOrDefault(p => p.Photo.Matches(photo)) is { } known) return known;
|
||||
if (pending.FirstOrDefault(p => p.Occurrence == occurrence && p.Photo.Matches(photo)) is { } known) return known;
|
||||
var entry = new JsonObject();
|
||||
if (photo.IsHashed) entry["sha256"] = photo.Sha256!.ToLowerInvariant();
|
||||
entry["size"] = photo.Size;
|
||||
if (photo.CapturedAt is { } captured) entry["capturedAt"] = captured;
|
||||
if (occurrence > 0) entry["occurrence"] = occurrence;
|
||||
entry["excluded"] = false;
|
||||
entry["hero"] = false;
|
||||
entry["keyframes"] = new JsonArray();
|
||||
var parked = new Parked(photo, entry);
|
||||
var parked = new Parked(photo, occurrence, entry);
|
||||
pending.Add(parked);
|
||||
return parked;
|
||||
}
|
||||
@@ -548,6 +592,9 @@ public sealed record ProjectSettings
|
||||
return string.IsNullOrEmpty(sha) && (captured is null || size < 0) ? null : new FramePhoto(sha, size, captured);
|
||||
}
|
||||
|
||||
/// <summary>Which copy of its photo a pending entry names; the first when it says nothing (or nothing readable).</summary>
|
||||
private static int OccurrenceOf(JsonObject entry) => entry["occurrence"] is JsonValue o && o.TryGetValue<int>(out var occurrence) && occurrence > 0 ? occurrence : 0;
|
||||
|
||||
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
|
||||
|
||||
/// <summary>A pending entry still has a position to give its photo.</summary>
|
||||
@@ -566,10 +613,11 @@ public sealed record ProjectSettings
|
||||
foreach (var node in copy) array.Add(node);
|
||||
}
|
||||
|
||||
/// <summary>A pending entry being edited: its photo, its JSON, and whether its photo took its place.</summary>
|
||||
private sealed class Parked(FramePhoto photo, JsonObject entry)
|
||||
/// <summary>A pending entry being edited: its photo (and which copy of it), its JSON, and whether its photo took its place.</summary>
|
||||
private sealed class Parked(FramePhoto photo, int occurrence, JsonObject entry)
|
||||
{
|
||||
public FramePhoto Photo { get; } = photo;
|
||||
public int Occurrence { get; } = occurrence;
|
||||
public JsonObject Entry { get; } = entry;
|
||||
public bool Placed { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.Data.Sync;
|
||||
|
||||
@@ -48,6 +50,10 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
private readonly Dictionary<Guid, Guid> _proxyJobs = [];
|
||||
|
||||
private readonly Dictionary<Guid, (int Failures, DateTime NotBefore)> _proxyFailures = [];
|
||||
|
||||
/// <summary>The server's update time at which a cache holding thumbnails in place of proxies was last compared with its manifest.</summary>
|
||||
private readonly Dictionary<Guid, DateTimeOffset> _standInsCompared = [];
|
||||
|
||||
private readonly SemaphoreSlim _refreshing = new(1, 1);
|
||||
private Task _running = Task.CompletedTask;
|
||||
private SyncSnapshot? _snapshot;
|
||||
@@ -220,7 +226,9 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Queues (background priority) the proxies of server sequences this PC keeps proxies of, without local originals,
|
||||
/// whose cache is stale; a sequence whose last download failed waits for its backoff.
|
||||
/// whose cache is stale: frames changed on a server that has the sequence's proxies, or the server now offers the
|
||||
/// proxy of a frame the cache holds a thumbnail for (<see cref="OffersProxiesAsync"/>). A sequence whose last
|
||||
/// download failed waits for its backoff.
|
||||
/// </summary>
|
||||
private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -229,6 +237,9 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
var job = await _sync.Database.Jobs.GetAsync(jobId, cancellationToken).ConfigureAwait(false);
|
||||
if (job?.State is JobState.Queued or JobState.Running or JobState.Paused) continue;
|
||||
_proxyJobs.Remove(remoteId);
|
||||
// A download of stand-ins' proxies that did not finish compares the cache with the manifest again (after its
|
||||
// backoff when it failed): the server's sequence may never change again to ask for it.
|
||||
if (job?.State != JobState.Done) _standInsCompared.Remove(remoteId);
|
||||
if (job?.State == JobState.Failed)
|
||||
{
|
||||
var failures = _proxyFailures.GetValueOrDefault(remoteId).Failures + 1;
|
||||
@@ -241,14 +252,47 @@ public sealed class SyncAgent : IAsyncDisposable
|
||||
}
|
||||
foreach (var entry in snapshot.Entries)
|
||||
{
|
||||
if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ServerHasProxies: true, ProxiesStale: true } link }) continue;
|
||||
if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ProxiesStale: true } link }) continue;
|
||||
if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue;
|
||||
if (!link.ServerHasProxies && !await OffersProxiesAsync(link, cancellationToken).ConfigureAwait(false)) continue;
|
||||
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
_proxyJobs[link.RemoteId] = job.Id;
|
||||
// Compared at this update time once the download that brings what the server offers is queued.
|
||||
if (!link.ServerHasProxies) _standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the server now offers the proxy of a frame whose cached file only stands in for one (a thumbnail, a file
|
||||
/// of a cache that did not record its kind) or that has no cached file. The sequence's proxy flag cannot say: it waits
|
||||
/// for every frame, a missing or damaged one never gets a proxy, and clients and render nodes send the other frames'
|
||||
/// proxies one by one. The manifest is read once per change of the server's sequence, since a proxy that arrives
|
||||
/// leaves a new update time (the proxy pass it queues records the sequence's state). A comparison that offers nothing
|
||||
/// is recorded here; one that offers proxies is recorded when their download is queued, and dropped when that
|
||||
/// download does not finish (<see cref="QueueProxiesAsync"/>).
|
||||
/// </summary>
|
||||
private async Task<bool> OffersProxiesAsync(SyncLink link, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_standInsCompared.TryGetValue(link.RemoteId, out var compared) && SyncService.SameMoment(compared, link.RemoteUpdatedAt)) return false;
|
||||
SequenceManifest manifest;
|
||||
try
|
||||
{
|
||||
manifest = await _remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
// Compared again at the next refresh; the other sequences go on.
|
||||
Log.Info(LogCategory, $"The proxies of {link.Title} on {Server} could not be compared: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
var cached = _sync.Proxies.Kinds(Server, link.RemoteId);
|
||||
if (manifest.Frames.Any(f => f.HasProxy && cached.GetValueOrDefault(f.Id) != ProxyCache.Proxy)) return true;
|
||||
_standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Waits for a wake-up or the delay; false when stopping.</summary>
|
||||
private static async Task<bool> WaitAsync(ChannelReader<bool> wake, TimeSpan delay, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -710,7 +710,7 @@ public sealed class SyncService
|
||||
private static DateTime Second(DateTime time) => new(time.Ticks - time.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
|
||||
|
||||
/// <summary>The same instant as databases keep it (to the microsecond).</summary>
|
||||
private static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
|
||||
internal static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the server's payload into the local index, project and sidecar in one step (settings version + 1) under the
|
||||
|
||||
Reference in new issue
Block a user