merge: sync and project position fixes (V-9, V-10, V-21, V-29, CD-2)

Merge branch fix2/sync-positions 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:
Claude committed 2026-10-12 17:10:58 +00:00
commit 51acc7f91b
32 files changed
+1843 -153

No files matched your search

+4 -3
View File
@@ -103,14 +103,15 @@ public sealed class ArchiveIndexer
/// </summary>
internal async Task SyncAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
(string Before, string Moved)? positions = null;
PositionMove? positions = null;
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over.
var existing = await tx.Sequences.GetForUpdateAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
if (existing is not null)
{
positions = await ProjectPositions.MoveAsync(tx, existing, manifest, cancellationToken).ConfigureAwait(false);
if (positions is { } project) existing = existing with { SettingsJson = project.Moved };
if (positions is not null) existing = positions.ApplyTo(existing);
}
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
await tx.Frames.SyncSequenceAsync(manifest.Id, SequenceMapping.ToFrames(manifest, sequence), cancellationToken).ConfigureAwait(false);
+13 -3
View File
@@ -195,7 +195,8 @@ public sealed class ArchiveIngest : IArchiveIngest
{
if (row.SettingsJson is { } settings) AtomicFile.WriteAllText(sequence.ProjectPath, settings);
await using var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await tx.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
// Locked, so an edit of the new sequence committed meanwhile is not written back over.
var current = await tx.Sequences.GetForUpdateAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidOperationException($"Sequence {sequenceId} was deleted before its first frame.");
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, current), cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -457,7 +458,8 @@ public sealed class ArchiveIngest : IArchiveIngest
/// <summary>
/// Appends the new rows when the index was in step with the sidecar; otherwise (or when frames were repaired, whose
/// flags change) resyncs the whole sequence, which also moves the project's frame positions after an insertion.
/// flags change) resyncs the whole sequence, which also moves the project's frame positions after an insertion. A
/// project waiting for photos taken from another copy's settings places those that arrived either way.
/// </summary>
private async Task IndexAsync(Archive archive, SequencePaths sequence, SequenceManifest manifest, int before, List<SidecarFrame> appended,
bool repaired, CancellationToken cancellationToken)
@@ -469,13 +471,21 @@ public sealed class ArchiveIngest : IArchiveIngest
await _indexer.SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
return;
}
PositionMove? placed = null;
await using (var tx = await _db.BeginAsync(cancellationToken).ConfigureAwait(false))
{
var existing = await tx.Sequences.GetAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
// Locked: a settings edit committed after this read (the server's PATCH takes no lease) would be written back over.
var existing = await tx.Sequences.GetForUpdateAsync(manifest.Id, cancellationToken).ConfigureAwait(false);
if (existing is not null && ProjectPositions.Place(existing, manifest) is { } positions)
{
placed = positions;
existing = positions.ApplyTo(existing);
}
await tx.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, sequence, existing), cancellationToken).ConfigureAwait(false);
await tx.Frames.BulkInsertAsync(appended.Select(f => SequenceMapping.ToFrame(f, manifest.Id, sequence)), cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (placed is not null) ProjectPositions.WriteProject(sequence, placed.Before, placed.Moved);
await _indexer.RecordStampsAsync(archive, sequence, manifest.Id, cancellationToken).ConfigureAwait(false);
}
+60 -9
View File
@@ -14,17 +14,19 @@ namespace Titano.Data.Archiving;
/// scan found, a sync download, a journalled batch completed after a crash. Positions name the frames in the indexed
/// order (what editors, renders and the API read), so the old order comes from the index rows. Only an insertion is
/// followed: when an indexed frame is no longer in the sidecar, positions cannot be mapped and stay as they are. The move
/// is part of the frames change, not a settings edit, so the settings version stays and a synced copy receiving the
/// same frames makes the same move.
/// is part of the frames change, not a settings edit, so the settings version stays. Settings synced from another copy
/// arrive translated to this copy's frames (<see cref="ProjectSettings.TranslateFramePositions"/>); their positions on
/// photos that were not here yet (<see cref="ProjectSettings.PendingFrames"/>) take their place when the photos arrive,
/// wherever they land.
/// </summary>
internal static class ProjectPositions
{
/// <summary>
/// The index's copy of the project (the one in force) and the same project with its positions moved to the order of
/// <paramref name="manifest"/>; null when nothing moves. A <c>project.json</c> the index has no copy of was written by
/// another process against its own frames, so it is left to that writer.
/// The index's copy of the project (the one in force) with its positions moved to the order of
/// <paramref name="manifest"/> and its pending frames placed; null when nothing changes. A <c>project.json</c> the
/// index has no copy of was written by another process against its own frames, so it is left to that writer.
/// </summary>
public static async Task<(string Before, string Moved)?> MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
public static async Task<PositionMove?> MoveAsync(TitanoRepositories db, Sequence indexed, SequenceManifest manifest,
CancellationToken cancellationToken)
{
// The sidecar's frames are the ones indexed: nothing was inserted.
@@ -33,13 +35,52 @@ internal static class ProjectPositions
var rows = await db.Frames.ListPositionsAsync(indexed.Id, cancellationToken).ConfigureAwait(false);
var now = new Dictionary<Guid, int>(manifest.Frames.Count);
foreach (var frame in manifest.Frames) now[frame.Id] = frame.I;
var moves = new Dictionary<int, int>();
Dictionary<int, int>? moves = [];
foreach (var row in rows)
{
if (!now.TryGetValue(row.FrameId, out var index)) return null;
if (!now.TryGetValue(row.FrameId, out var index))
{
moves = null;
break;
}
if (index != row.Index) moves[row.Index] = index;
}
return ProjectSettings.MoveFramePositions(project, moves) is { } moved ? (project, moved) : null;
return Placed(project, moves is null ? null : ProjectSettings.MoveFramePositions(project, moves), manifest);
}
/// <summary>
/// The index's copy of the project with the pending frames whose photos <paramref name="manifest"/> now holds put in
/// place: frames appended in step with the index, which moves no position. Null when nothing changes.
/// </summary>
public static PositionMove? Place(Sequence indexed, SequenceManifest manifest) =>
indexed.SettingsJson is { } project ? Placed(project, null, manifest) : null;
private static PositionMove? Placed(string before, string? moved, SequenceManifest manifest)
{
var current = moved ?? before;
// Most projects wait for no photo: the sidecar's photos are gathered only for those that do.
var placed = current.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)
? ProjectSettings.TranslateFramePositions(current, null, new FramePhotos(manifest.Frames.Select(f => (f.I, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))))
: null;
if ((placed ?? moved) is not { } after) return null;
// A hero that waited for its photo names a frame the Library shows too.
var hero = placed is not null && HeroOf(current) is null && HeroOf(placed) is { } index ? manifest.Frames.FirstOrDefault(f => f.I == index)?.Id : null;
return new PositionMove(before, after, hero);
}
private static int? HeroOf(string json)
{
try
{
return JsonNode.Parse(json, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is JsonObject project
&& project["heroFrame"] is JsonValue value && value.TryGetValue<int>(out var hero)
? hero
: null;
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
return null;
}
}
/// <summary>
@@ -73,3 +114,13 @@ internal static class ProjectPositions
}
}
}
/// <summary>
/// A project whose positions followed its frames: the index's copy before and after, and the frame a hero that waited
/// for its photo now names (the index's hero frame follows it); null when the hero frame stays.
/// </summary>
internal sealed record PositionMove(string Before, string Moved, Guid? HeroFrameId)
{
/// <summary>The index row with the moved project.</summary>
public Sequence ApplyTo(Sequence row) => row with { SettingsJson = Moved, HeroFrameId = HeroFrameId ?? row.HeroFrameId };
}
@@ -167,6 +167,14 @@ public sealed class SequenceRepository
public Task<Sequence?> GetAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken);
/// <summary>
/// <see cref="GetAsync"/> inside a transaction, the row locked until it ends (PostgreSQL; SQLite's write lock already
/// serialises writers): a transaction that writes the whole row back from this read cannot undo an edit that another
/// one commits meanwhile, as <see cref="EditAsync(Guid, SequenceEdit, int?, int?, CancellationToken)"/> takes the same lock.
/// </summary>
public Task<Sequence?> GetForUpdateAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.SingleAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken);
/// <summary>Deletes the sequence with its frames, renders and tag links.</summary>
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0;
@@ -233,12 +241,22 @@ public sealed class SequenceRepository
/// changed the sequence first (BRIEF §14.5).
/// </summary>
public Task<SequenceEditResult> EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, CancellationToken cancellationToken = default) =>
EditAsync(id, edit, expectedSettingsVersion, null, cancellationToken);
/// <summary>
/// <see cref="EditAsync(Guid, SequenceEdit, int?, CancellationToken)"/>, also refused when the sequence's frames
/// version is no longer <paramref name="expectedFramesVersion"/>: settings naming frames by position were written
/// against frames that changed since.
/// </summary>
public Task<SequenceEditResult> EditAsync(Guid id, SequenceEdit edit, int? expectedSettingsVersion, int? expectedFramesVersion,
CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken)
.ConfigureAwait(false);
if (current is null) return new SequenceEditResult(SequenceEditOutcome.NotFound, null);
if (expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
if ((expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
|| (expectedFramesVersion is { } frames && frames != current.FramesVersion))
return new SequenceEditResult(SequenceEditOutcome.Conflict, current);
var hero = current.HeroFrameId;
if (edit.HeroFrameId == Guid.Empty) hero = null;
+46 -14
View File
@@ -57,7 +57,12 @@ public sealed class RemoteSequence
}
/// <summary>What the proxy cache keeps next to the files of one server sequence.</summary>
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files);
/// <param name="Kinds">
/// What each file is, in frame order: <see cref="ProxyCache.Proxy"/> or <see cref="ProxyCache.Thumb"/> (a thumbnail standing in
/// while the server has no proxy of the frame); null where no file is cached, and for a cache written before kinds were kept.
/// </param>
internal sealed record ProxyCacheIndex(SequenceDto Sequence, string? SettingsJson, int FramesVersion, IReadOnlyList<FrameDto> Frames, IReadOnlyList<string?> Files,
IReadOnlyList<string?>? Kinds = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(ProxyCacheIndex))]
@@ -70,6 +75,12 @@ internal sealed partial class ProxyCacheJson : JsonSerializerContext;
/// </summary>
internal sealed class ProxyCache(string root)
{
/// <summary>The asset kind of a cached proxy (the server's name for it).</summary>
public const string Proxy = "proxy";
/// <summary>The asset kind of a thumbnail cached in place of a proxy the server did not have.</summary>
public const string Thumb = "thumb";
private const string IndexFile = "remote.json";
public string Folder(string server, Guid remoteId) =>
@@ -82,23 +93,26 @@ internal sealed class ProxyCache(string root)
public void Save(string server, Guid remoteId, ProxyCacheIndex index) =>
AtomicFile.WriteAllText(Path.Combine(Folder(server, remoteId), IndexFile), JsonSerializer.Serialize(index, ProxyCacheJson.Default.ProxyCacheIndex));
/// <summary>
/// What each cached file of a server sequence is, by frame id (<see cref="ProxyCacheIndex.Kinds"/>): none for a frame
/// without a file, null for a file of a cache written before kinds were kept.
/// </summary>
public IReadOnlyDictionary<Guid, string?> Kinds(string server, Guid remoteId)
{
var kinds = new Dictionary<Guid, string?>();
if (ReadIndex(server, remoteId) is not { } index) return kinds;
for (var i = 0; i < index.Frames.Count; i++)
{
if (index.Files[i] is not null) kinds[index.Frames[i].Id] = index.Kinds is { } known && i < known.Count ? known[i] : null;
}
return kinds;
}
/// <summary>The cached sequence, or null when it was never cached or the cache was cleared.</summary>
public RemoteSequence? Load(string server, Guid remoteId)
{
var folder = Folder(server, remoteId);
var path = Path.Combine(folder, IndexFile);
if (!File.Exists(path)) return null;
ProxyCacheIndex? index;
try
{
index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex);
}
catch (Exception ex) when (ex is JsonException or IOException)
{
Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex);
return null;
}
if (index is null || index.Files.Count != index.Frames.Count) return null;
if (ReadIndex(server, remoteId) is not { } index) return null;
var dto = index.Sequence;
var sequence = RenderNodeClient.ToSequence(dto) with
{
@@ -126,6 +140,24 @@ internal sealed class ProxyCache(string root)
return new RemoteSequence(server, sequence, frames, files);
}
/// <summary>The index of a cached sequence; null when there is none or it cannot be read.</summary>
private ProxyCacheIndex? ReadIndex(string server, Guid remoteId)
{
var path = Path.Combine(Folder(server, remoteId), IndexFile);
if (!File.Exists(path)) return null;
ProxyCacheIndex? index;
try
{
index = JsonSerializer.Deserialize(File.ReadAllText(path), ProxyCacheJson.Default.ProxyCacheIndex);
}
catch (Exception ex) when (ex is JsonException or IOException)
{
Log.Warning("sync", $"Proxy cache of {remoteId} is unreadable", ex);
return null;
}
return index is null || index.Files.Count != index.Frames.Count ? null : index;
}
/// <summary>Removes the files of a sequence the server no longer has.</summary>
public void Delete(string server, Guid remoteId)
{
+124
View File
@@ -0,0 +1,124 @@
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Protocol;
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
namespace Titano.Data.Sync;
/// <summary>
/// The frame positions of settings crossing between a local copy and its server sequence (exclusions, hero, camera
/// keyframes; BRIEF §5, §14.5). Each copy numbers its frames in capture order, and the two may hold different photos
/// while originals are still to travel, so settings are translated by photo on the way: the server's are moved to this
/// copy's frames before they are compared or applied, and this copy's to the server's frames as
/// <paramref name="manifest"/> lists them before they are sent. A position on a photo the receiving copy lacks waits
/// there as a pending frame and takes its place when the photo arrives (<see cref="ProjectSettings.TranslateFramePositions"/>).
/// Positions are only ever translated against the frames they name: this copy's row is read with its frames as one
/// state (frames inserted here move the row's positions in the same step), and a manifest whose frames mix two orders
/// is not translated at all.
/// </summary>
internal sealed class SyncPositions(TitanoDatabase db, ISyncRemote remote, Guid localId, SequenceManifest manifest)
{
/// <summary>Times this copy's frames are listed again when an insertion lands while they are read.</summary>
private const int Attempts = 3;
/// <summary>The manifest's frames by hash, and with their capture times once fetched.</summary>
private FramePhotos? _hashed, _timed;
/// <summary>The server's frames version the translation to the server's frames is made against.</summary>
public int ServerFrames => manifest.FramesVersion;
/// <summary>
/// The server's settings with their positions on this copy's frames as they are now, with this copy's row at those
/// frames; null when that row is no longer at <paramref name="settingsVersion"/> (an edit was saved here since), or
/// either copy's frames cannot be read as one state now (the next comparison translates again).
/// </summary>
public async Task<TranslatedSettings?> ToLocalAsync(string? settingsJson, int settingsVersion, CancellationToken cancellationToken)
{
if (!ProjectSettings.NamesFrames(settingsJson))
return await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is { } row && row.SettingsVersion == settingsVersion
? new TranslatedSettings(row, settingsJson)
: null;
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
return new TranslatedSettings(local.Row, ProjectSettings.TranslateFramePositions(settingsJson!, server, local.Frames) ?? settingsJson);
}
/// <summary>
/// This copy's settings at <paramref name="settingsVersion"/> with their positions on the server's frames, with the
/// row they were taken from: frames inserted here since the copy was read moved its positions without a new settings
/// version, so the row is read again with its frames. Null when the row is at another settings version (an edit was
/// saved since), or either copy's frames cannot be read as one state now.
/// </summary>
public async Task<TranslatedSettings?> ToServerAsync(int settingsVersion, CancellationToken cancellationToken)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } row || row.SettingsVersion != settingsVersion) return null;
// Positions cannot appear in a project that names no frame: an insertion only moves those it has.
if (!ProjectSettings.NamesFrames(row.SettingsJson)) return new TranslatedSettings(row, row.SettingsJson);
if (await LocalAsync(cancellationToken).ConfigureAwait(false) is not { } local || local.Row.SettingsVersion != settingsVersion) return null;
if (await ServerAsync(local.Frames, cancellationToken).ConfigureAwait(false) is not { } server) return null;
var settings = local.Row.SettingsJson;
return new TranslatedSettings(local.Row, settings is null ? null : ProjectSettings.TranslateFramePositions(settings, local.Frames, server) ?? settings);
}
/// <summary>
/// This copy's row and 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). Null when the sequence is gone or an insertion lands during every attempt.
/// </summary>
private async Task<LocalState?> LocalAsync(CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < Attempts; attempt++)
{
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } before) return null;
var frames = await SequenceFrames.ListAsync(db, localId, cancellationToken).ConfigureAwait(false);
if (await db.Sequences.GetAsync(localId, cancellationToken).ConfigureAwait(false) is not { } after) return null;
if (after.FramesVersion == before.FramesVersion)
return new LocalState(after, new FramePhotos(frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, f.CapturedAt)))));
}
return null;
}
/// <summary>
/// The server's frames from the manifest; null when they do not read as one frame list (an index given twice, or
/// not the indices 0…n-1: pages read across an insertion). Their capture times are fetched unless both copies hold
/// the same hashed photos at the same places: a frame is matched by size and capture time when either side has not
/// hashed it, and a position parked on a server photo always names its capture time, so the same project reads the
/// same whichever side hashed what.
/// </summary>
private async Task<FramePhotos?> ServerAsync(FramePhotos local, CancellationToken cancellationToken)
{
if (_hashed is null)
{
if (!OneList(manifest.Frames)) return null;
_hashed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, null))));
}
if (_hashed.SameAs(local)) return _hashed;
if (_timed is null)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
_timed = new FramePhotos(manifest.Frames.Select(f => (f.Index, new FramePhoto(f.Sha256, f.Size, captured.GetValueOrDefault(f.Id)))));
}
return _timed;
}
/// <summary>Each frame once, at the indices 0…n-1 a sequence's frames always take.</summary>
private static bool OneList(IReadOnlyList<ManifestFrame> frames)
{
var seen = new bool[frames.Count];
var ids = new HashSet<Guid>();
foreach (var frame in frames)
{
if ((uint)frame.Index >= (uint)seen.Length || seen[frame.Index] || !ids.Add(frame.Id)) return false;
seen[frame.Index] = true;
}
return true;
}
private sealed record LocalState(Sequence Row, FramePhotos Frames);
}
/// <summary>
/// Settings translated by <see cref="SyncPositions"/>, with this copy's row at the frames their positions were
/// translated to or from (its own settings may have been moved since it was first read).
/// </summary>
internal sealed record TranslatedSettings(Sequence Local, string? SettingsJson);
+8 -3
View File
@@ -20,14 +20,17 @@ public interface ISyncRemote : IDisposable
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Every frame row of a sequence, in index order.</summary>
/// <summary>Every frame row of a sequence, each once, in index order.</summary>
Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken);
/// <summary>The first frame row of a sequence (its thumbnail stands for a sequence without a hero frame); null when it has none yet.</summary>
async Task<FrameDto?> FirstFrameAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await ListFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false)).FirstOrDefault();
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
/// <summary>
/// A 409 <see cref="TitanoApiException"/> means the settings version moved on the server, or its frames did since
/// <see cref="UpdateSequenceRequest.ExpectedFramesVersion"/>.
/// </summary>
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
/// <summary>
@@ -98,11 +101,13 @@ public sealed class TitanoSyncRemote(TitanoClient client, bool ownsClient) : ISy
public async Task<IReadOnlyList<FrameDto>> ListFramesAsync(Guid sequenceId, CancellationToken cancellationToken)
{
var all = new List<FrameDto>();
// Pages follow the frame index: frames inserted while they are read list a frame again, which is kept once.
var seen = new HashSet<Guid>();
string? cursor = null;
do
{
var page = await client.ListFramesAsync(sequenceId, cursor, FramePage, cancellationToken).ConfigureAwait(false);
all.AddRange(page.Items);
all.AddRange(page.Items.Where(f => seen.Add(f.Id)));
cursor = page.NextCursor;
}
while (cursor is not null);
+76 -16
View File
@@ -26,9 +26,13 @@ public sealed record SyncPayload(string? Title, IReadOnlyList<string> Tags, int
public bool SameAs(SyncPayload other) => SameMetadata(other) && SyncRules.SameSettings(SettingsJson, other.SettingsJson);
/// <summary>The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form.</summary>
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion) =>
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion);
/// <summary>
/// The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form, with the
/// server frames version their frame positions name when they were translated to the server's frames.
/// </summary>
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion, int? expectedFramesVersion = null) =>
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion,
ExpectedFramesVersion: expectedFramesVersion);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
@@ -119,31 +123,71 @@ public static class SyncRules
}
/// <summary>
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict). Local frames not hashed yet
/// (adopted, not verified) are assumed to match server frames that no hash matched.
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict), from their SHA-256 alone (an
/// empty or null one: not hashed yet). See <see cref="CompareOriginals(IReadOnlyCollection{FramePhoto}, IReadOnlyCollection{FramePhoto})"/>.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> remoteHashes)
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<string?> localHashes, IReadOnlyCollection<string> remoteHashes) =>
CompareOriginals([.. localHashes.Select(h => new FramePhoto(h, 0, null))], [.. remoteHashes.Select(h => new FramePhoto(h, 0, null))]);
/// <summary>
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict): the same SHA-256 where both
/// sides hashed them, else the same size and capture time (<see cref="FramePhoto.Matches"/>; a folder adopted on
/// either side and not verified yet). A photo is there when any photo of the other side matches it, as downloads and
/// uploads find them (<see cref="FramePhotos.IndexOf"/>): two copies of one photo in a folder the server adopted are
/// both held by the one original this PC keeps. Local frames not hashed yet that nothing matched are assumed to match
/// server frames that nothing matched.
/// </summary>
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection<FramePhoto> local, IReadOnlyCollection<FramePhoto> remote)
{
var remote = remoteHashes.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var hashed = localHashes.Where(h => !string.IsNullOrEmpty(h)).Select(h => h!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var unhashed = localHashes.Count(string.IsNullOrEmpty);
var matched = hashed.Count(remote.Contains);
var unmatchedRemote = remote.Count - matched;
return (hashed.Count - matched + Math.Max(0, unhashed - unmatchedRemote), Math.Max(0, unmatchedRemote - unhashed));
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(remote);
var remoteHashes = remote.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var localHashes = local.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
// What no hash matched: each content once, each frame not hashed on its own.
var localLeft = Unmatched(local, remoteHashes);
var remoteLeft = Unmatched(remote, localHashes);
var localPhotos = new FramePhotos(localLeft.Select((p, i) => (i, p)));
var remotePhotos = new FramePhotos(remoteLeft.Select((p, i) => (i, p)));
var remoteUnmatched = remoteLeft.Count(p => localPhotos.IndexOf(p) is null);
int localHashedLeft = 0, localUnhashedLeft = 0;
foreach (var photo in localLeft.Where(p => remotePhotos.IndexOf(p) is null))
{
if (photo.IsHashed) localHashedLeft++;
else localUnhashedLeft++;
}
return (localHashedLeft + Math.Max(0, localUnhashedLeft - remoteUnmatched), Math.Max(0, remoteUnmatched - localUnhashedLeft));
static List<FramePhoto> Unmatched(IEnumerable<FramePhoto> side, HashSet<string> other) =>
[
.. side.Where(p => p.IsHashed && !other.Contains(p.Sha256!.ToLowerInvariant())).DistinctBy(p => p.Sha256!.ToLowerInvariant()),
.. side.Where(p => !p.IsHashed),
];
}
/// <summary>
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
/// <paramref name="decoder"/> reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
/// and not verified) stands for a wanted frame of its size that no hash matched (by size, not name: the server names
/// its copy by its own template); the upload hashes it before making the proxy.
/// its copy by its own template); the upload hashes it before making the proxy. A wanted frame the server has not
/// hashed is the local original of its size and capture time (<paramref name="captured"/>, by server frame id), as
/// <see cref="ProxyOriginal"/> finds it for the upload.
/// </summary>
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection<Frame> local, ImageDecoder decoder)
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection<Frame> local, ImageDecoder decoder,
IReadOnlyDictionary<Guid, DateTime?>? captured = null)
{
ArgumentNullException.ThrowIfNull(manifest);
var hashed = local.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var unhashed = local.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f)).GroupBy(f => f.Size).ToDictionary(g => g.Key, g => g.Count());
IReadOnlyList<Frame> frames = [.. local];
var photos = Photos(frames);
var count = 0;
// The originals of frames the server has not hashed first: they are no longer free to stand for others by size.
var taken = new HashSet<Guid>();
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length == 0))
{
if (ProxyOriginal(frame, captured?.GetValueOrDefault(frame.Id), frames, photos) is { } original && taken.Add(original.Id) && Readable(original)) count++;
}
var hashed = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var unhashed = frames.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f) && !taken.Contains(f.Id)).GroupBy(f => f.Size)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length > 0))
{
var sha = frame.Sha256.ToLowerInvariant();
@@ -162,6 +206,22 @@ public static class SyncRules
bool Readable(Frame frame) => !ArchiveImages.NeedsProxy(decoder, frame.Format);
}
/// <summary>
/// The local original of a wanted frame the server has not hashed yet (adopted there, not verified): the one of its
/// size and capture time (<paramref name="capturedAt"/>, from the server's frame row); null when none is, or the time
/// is unknown. <paramref name="photos"/> are <see cref="Photos"/> of <paramref name="local"/>.
/// </summary>
public static Frame? ProxyOriginal(ManifestFrame wanted, DateTime? capturedAt, IReadOnlyList<Frame> local, FramePhotos photos)
{
ArgumentNullException.ThrowIfNull(wanted);
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(photos);
return capturedAt is not null && photos.IndexOf(new FramePhoto(null, wanted.Size, capturedAt)) is { } at ? local[at] : null;
}
/// <summary>The photos of <paramref name="local"/>'s frames, by their place in the list.</summary>
public static FramePhotos Photos(IReadOnlyList<Frame> local) => new(local.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
/// <summary>
/// Whether <paramref name="local"/> holds originals a server cannot decode (it asks for their proxies, BRIEF §2.3,
/// §4.2: managed decoders only) that this PC's <paramref name="decoder"/> reads, so it can make those proxies.
+101 -28
View File
@@ -8,6 +8,7 @@ using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
@@ -40,7 +41,8 @@ public sealed record SyncOptions
/// and, when frame counters or render counts moved, the manifest: originals are matched by SHA-256 and never conflict;
/// renders by id. Settings, title, tags, rating and notes travel together under the settings version, so a change on
/// one side is sent or taken (automatically or on request) and a change on both sides with different content is a
/// conflict the user settles with <see cref="ResolveAsync"/>, against the versions the user was shown. Uploads and
/// conflict the user settles with <see cref="ResolveAsync"/>, against the versions the user was shown. The settings'
/// frame positions are translated by photo to the frames of the copy they go to (<see cref="SyncPositions"/>). Uploads and
/// downloads run as jobs (<see cref="CreateJobHandlers"/>): uploads use the chunked, hash-verified, resumable protocol;
/// downloaded originals are verified and committed through the archive ingest, so sidecars stay right; proxies go to a
/// cache and open as a <see cref="RemoteSequence"/>; renders travel on request. Thumbnails never travel upward, and
@@ -185,7 +187,7 @@ public sealed class SyncService
try
{
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
if (link is not { ConflictRemote: { } theirs, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
if (link is not { ConflictRemote: not null, ConflictLocalSettings: { } seenLocal, ConflictRemoteSettings: { } seenRemote }
|| local.SettingsVersion != seenLocal)
{
changed = true;
@@ -194,8 +196,17 @@ public sealed class SyncService
{
try
{
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(seenRemote), cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
// Edited here since it was shown, or frames that kept changing while they were read: compared again.
if (await RequestAsync(remote, local, manifest, seenRemote, cancellationToken).ConfigureAwait(false) is not { } request)
{
changed = true;
}
else
{
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
link = Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
@@ -204,15 +215,18 @@ public sealed class SyncService
}
else
{
// The server's version as it is now: the one shown, with its positions on the server's current frames.
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
if (dto.SettingsVersion != seenRemote)
var manifest = dto.SettingsVersion == seenRemote ? await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false) : null;
if (manifest?.SettingsVersion != seenRemote)
{
changed = true;
}
else
{
if (resolution == SyncResolution.SaveBoth) saved = await SaveCopyAsync(local, cancellationToken).ConfigureAwait(false);
if (await ApplyLocallyAsync(local, theirs, cancellationToken).ConfigureAwait(false) is { } applied)
var theirs = SyncPayload.Of(dto, manifest!.SettingsJson);
if (await ApplyLocallyAsync(local, theirs, Positions(remote, local, manifest), cancellationToken).ConfigureAwait(false) is { } applied)
{
link = Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, seenRemote);
}
@@ -339,11 +353,17 @@ public sealed class SyncService
var (link, local) = await LinkedAsync(remote.Server, remoteId, cancellationToken).ConfigureAwait(false);
for (var attempt = 1; ; attempt++)
{
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
try
{
var updated = await remote.UpdateSequenceAsync(remoteId, SyncPayload.Of(local).ToRequest(dto.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
if (await RequestAsync(remote, local, manifest, manifest.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } request)
{
// An edit saved here meanwhile goes instead; frames that keep changing here leave it to the next comparison.
if (attempt >= 3 || await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is not { } fresh) return;
local = fresh;
continue;
}
var updated = await remote.UpdateSequenceAsync(remoteId, request, cancellationToken).ConfigureAwait(false);
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, updated), local.SettingsVersion, updated.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
return;
@@ -370,7 +390,8 @@ public sealed class SyncService
var dto = await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);
var manifest = await remote.GetManifestAsync(remoteId, cancellationToken).ConfigureAwait(false);
// Edited on this PC meanwhile: nothing is agreed yet, so the next comparison settles both sides' content.
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false) is not { } applied) return;
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
.ConfigureAwait(false) is not { } applied) return;
await _links.UpsertAsync(Agreed(Observe(link, remote.Server, dto), applied.SettingsVersion, manifest.SettingsVersion), cancellationToken)
.ConfigureAwait(false);
}
@@ -399,14 +420,18 @@ public sealed class SyncService
await RefreshSequencesAsync(remote, [remoteId], CompareOnly, cancellationToken).ConfigureAwait(false);
}
/// <summary>Records what the proxy cache holds for a server sequence.</summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int framesVersion, CancellationToken cancellationToken)
/// <summary>
/// Records what the proxy cache holds for a server sequence. Thumbnails standing in for proxies the server did not
/// have leave the cache stale: it is filled again once the server has its proxies.
/// </summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int thumbnails, int framesVersion, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var link = Observe(await _links.GetAsync(server, dto.Id, cancellationToken).ConfigureAwait(false), server, dto);
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = framesVersion }, cancellationToken).ConfigureAwait(false);
int? filledAt = thumbnails > 0 && !link.ServerHasProxies ? null : framesVersion;
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = filledAt }, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -497,9 +522,14 @@ public sealed class SyncService
var frames = await SequenceFrames.ListAsync(_db, local.Id, cancellationToken).ConfigureAwait(false);
// A frame flagged missing here counts as absent: downloading the originals restores it from the server.
var present = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => f.Sha256)], [.. manifest.Frames.Select(f => f.Sha256)]);
// A frame either side has not hashed yet (a folder adopted, not verified) is told apart by size and capture time.
var captured = manifest.Frames.Any(f => f.Sha256.Length == 0) || present.Any(f => f.Sha256 is null)
? (await remote.ListFramesAsync(link.RemoteId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt)
: null;
var (missingRemote, missingLocal) = SyncRules.CompareOriginals([.. present.Select(f => new FramePhoto(f.Sha256, f.Size, f.CapturedAt))],
[.. manifest.Frames.Select(f => new FramePhoto(f.Sha256, f.Size, captured?.GetValueOrDefault(f.Id)))]);
// Proxies the server asks for that this PC can make from its originals travel with an upload too (BRIEF §2.3).
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder) : 0;
var proxies = policy.CanEdit && manifest.Proxies is not null ? SyncRules.ProxiesToSend(manifest, present, Options.Archive.Decoder, captured) : 0;
// Those change without the server's frame counters moving: while some may be made here, the server's next
// change of the sequence brings a new comparison.
var watch = policy.CanEdit && (proxies > 0 || SyncRules.MakesProxiesFor(present, Options.Archive.Decoder));
@@ -543,14 +573,22 @@ public sealed class SyncService
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
if (!localChanged && !remoteChanged) return (link, local);
// Frames inserted here since the copy was listed moved its positions without a new settings version.
if (await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false) is { } current && current.SettingsVersion == local.SettingsVersion)
local = current;
if (localChanged && remoteChanged)
{
if (link.ConflictLocalSettings == local.SettingsVersion && link.ConflictRemoteSettings == link.RemoteSettingsVersion) return (link, local);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
// The listing and the manifest disagree: the server changed during the comparison; settle it next time.
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
// Compared (and shown) with its positions on this copy's frames, against this copy as it is at those frames: the
// same photos are the same settings. Edited here meanwhile, or frames that kept changing: compared next time.
if (await Positions(remote, local, manifest).ToLocalAsync(manifest.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false)
is not { } translated) return (link, local);
local = translated.Local;
var mine = SyncPayload.Of(local);
var theirs = SyncPayload.Of(dto, manifest.SettingsJson);
var theirs = SyncPayload.Of(dto, translated.SettingsJson);
if (mine.SameAs(theirs)) return (Agreed(link, local.SettingsVersion, manifest.SettingsVersion), local);
// Last writer wins only when one side changed; both changed differently is the user's choice (BRIEF §14.5).
return (link with
@@ -562,10 +600,15 @@ public sealed class SyncService
}
if (!policy.AutoSyncSettings) return (link, local);
if (localChanged)
return (policy.CanEdit ? await PushAsync(remote, link, local, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false) : link, local);
{
if (!policy.CanEdit) return (link, local);
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
return (await PushAsync(remote, link, local, manifest, link.BaseRemoteSettings, cancellationToken).ConfigureAwait(false), local);
}
manifest ??= await remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
if (manifest.SettingsVersion != dto.SettingsVersion) return (link, local);
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), cancellationToken).ConfigureAwait(false) is { } pulled)
if (await ApplyLocallyAsync(local, SyncPayload.Of(dto, manifest.SettingsJson), Positions(remote, local, manifest), cancellationToken)
.ConfigureAwait(false) is { } pulled)
return (Agreed(link, pulled.SettingsVersion, manifest.SettingsVersion), pulled);
// The local copy was read when the comparison began and an edit was saved on this PC since: both sides changed,
// so the server's version must not replace it unseen (BRIEF §14.5).
@@ -574,12 +617,17 @@ public sealed class SyncService
return await SettleSettingsAsync(remote, link, dto, fresh, manifest, policy, cancellationToken).ConfigureAwait(false);
}
/// <summary>Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next.</summary>
private static async Task<SyncLink> PushAsync(ISyncRemote remote, SyncLink link, Sequence local, int? expected, CancellationToken cancellationToken)
/// <summary>
/// Sends this PC's payload unless the server moved past <paramref name="expected"/>, which shows up as a conflict next,
/// or either copy's frames changed since they were read (the positions are translated again next time).
/// </summary>
private async Task<SyncLink> PushAsync(ISyncRemote remote, SyncLink link, Sequence local, SequenceManifest manifest, int? expected,
CancellationToken cancellationToken)
{
try
{
var updated = await remote.UpdateSequenceAsync(link.RemoteId, SyncPayload.Of(local).ToRequest(expected), cancellationToken).ConfigureAwait(false);
if (await RequestAsync(remote, local, manifest, expected, cancellationToken).ConfigureAwait(false) is not { } request) return link;
var updated = await remote.UpdateSequenceAsync(link.RemoteId, request, cancellationToken).ConfigureAwait(false);
return Agreed(Observe(link, link.Server, updated), local.SettingsVersion, updated.SettingsVersion);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
@@ -588,6 +636,23 @@ public sealed class SyncService
}
}
/// <summary>
/// The PATCH that makes the server's copy equal to this copy at <paramref name="local"/>'s settings version (read again
/// with its frames, which may have moved its positions since), its frame positions moved to the server's frames as
/// <paramref name="manifest"/> lists them; the server refuses it when its frames changed since. Null when this copy
/// was edited since <paramref name="local"/> was read, or either copy's frames cannot be read as one state now.
/// </summary>
private async Task<UpdateSequenceRequest?> RequestAsync(ISyncRemote remote, Sequence local, SequenceManifest manifest, int? expected,
CancellationToken cancellationToken)
{
var positions = Positions(remote, local, manifest);
if (await positions.ToServerAsync(local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } translated) return null;
var frames = ProjectSettings.NamesFrames(translated.Local.SettingsJson) ? positions.ServerFrames : (int?)null;
return (SyncPayload.Of(translated.Local) with { SettingsJson = translated.SettingsJson }).ToRequest(expected, frames);
}
private SyncPositions Positions(ISyncRemote remote, Sequence local, SequenceManifest manifest) => new(_db, remote, local.Id, manifest);
/// <summary>
/// Links local copies and server sequences that hold the same originals but no link joins (an Uploader upload of
/// the same card, a link lost with an old index): candidates start at the same second with the same camera, and
@@ -648,12 +713,19 @@ public sealed class SyncService
private static bool SameMoment(DateTimeOffset a, DateTimeOffset b) => a.UtcTicks / 10 == b.UtcTicks / 10;
/// <summary>
/// Writes a payload into the local index, project and sidecar in one step (settings version + 1) under the sequence's
/// lease, which the editor's saves take too, and only while the local copy is still at the settings version
/// <paramref name="local"/> was read at. Null when an edit was saved on this PC since: nothing is written then.
/// Writes the server's payload into the local index, project and sidecar in one step (settings version + 1) under the
/// sequence's lease, which the editor's saves and the archive's frame commits take too, and only while the local copy
/// is still at the settings version <paramref name="local"/> was read at. The settings' frame positions are moved to
/// this copy's frames as they are under the lease (<paramref name="positions"/>). Null when an edit was saved on this
/// PC since, or the frames of either copy could not be read as one state: nothing is written then. A payload the local
/// copy already holds writes nothing, so it needs neither a writable archive nor the lease.
/// </summary>
private async Task<Sequence?> ApplyLocallyAsync(Sequence local, SyncPayload payload, CancellationToken cancellationToken)
private async Task<Sequence?> ApplyLocallyAsync(Sequence local, SyncPayload payload, SyncPositions positions, CancellationToken cancellationToken)
{
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } stored) return null;
// Settled as it is: an archive that is offline or read-only does not keep the link from being agreed.
if ((payload with { SettingsJson = stored.SettingsJson }).SameAs(SyncPayload.Of(stored.Local))) return stored.Local;
var archive = await _db.Archives.GetAsync(local.ArchiveId, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Archive {local.ArchiveId} is not indexed.");
var paths = new ArchivePaths(archive.RootPath);
@@ -661,9 +733,10 @@ public sealed class SyncService
var folder = paths.Sequence(local.Folder);
await using (await _writer.LockAsync(paths, local.Id, cancellationToken).ConfigureAwait(false))
{
var row = await _db.Sequences.GetAsync(local.Id, cancellationToken).ConfigureAwait(false)
?? throw new InvalidDataException($"Sequence {local.Id} is not indexed.");
if (row.SettingsVersion != local.SettingsVersion) return null;
// The frames cannot change under the lease: the positions are moved to them as they are now.
if (await positions.ToLocalAsync(payload.SettingsJson, local.SettingsVersion, cancellationToken).ConfigureAwait(false) is not { } current) return null;
var row = current.Local;
payload = payload with { SettingsJson = current.SettingsJson };
var metadata = !payload.SameMetadata(SyncPayload.Of(row));
var settings = !SyncRules.SameSettings(payload.SettingsJson, row.SettingsJson);
if (!metadata && !settings) return row;
+135 -57
View File
@@ -4,6 +4,7 @@ using System.Net;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
@@ -11,6 +12,7 @@ using Titano.Data.Processing;
using Titano.Protocol;
using Titano.Protocol.Client;
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
using SequenceManifest = Titano.Protocol.SequenceManifest;
namespace Titano.Data.Sync;
@@ -19,8 +21,9 @@ namespace Titano.Data.Sync;
/// resumable protocol after hashing it again (an original that no longer matches its archived hash is never sent),
/// creating the server sequence first and sending its settings when the upload made it, then the proxies the server asks
/// for (originals it cannot decode, BRIEF §2.3), made here from this PC's originals. Downloads fetch originals the
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 and commit
/// them through the archive ingest, which names them and writes the sidecar; the first original creates the local
/// local copy lacks into the archive's staging folder (resuming with Range), require the manifest's SHA-256 (or, for an
/// original the server has not hashed yet, its size, and hash it here) and commit them through the archive ingest,
/// which names them and writes the sidecar; the first original creates the local
/// sequence, which then takes the server's settings. Frames of the local copy not hashed yet are hashed first (so the
/// server's copies of them are recognised), and originals flagged missing here are restored to their recorded place.
/// Proxy downloads fill the proxy cache. Renders travel on request: this PC's to the server (hash-verified chunked
@@ -44,10 +47,15 @@ internal sealed class SyncTransfers(SyncService sync)
var (remoteId, created) = await TargetAsync(context, remote, local).ConfigureAwait(false);
var frames = (await SequenceFrames.ListAsync(db, local.Id, ct).ConfigureAwait(false)).Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var present = remoteId is { } known
? (await remote.GetManifestAsync(known, ct).ConfigureAwait(false)).Frames.Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal)
: [];
var pending = new Queue<Frame>(frames.Where(f => f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant())));
var manifest = remoteId is { } known ? await remote.GetManifestAsync(known, ct).ConfigureAwait(false) : null;
var present = manifest?.Frames.Where(f => f.Sha256.Length > 0).Select(f => f.Sha256.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal) ?? [];
// Originals the server holds without a hash (adopted there, not verified) are the ones of their size and capture
// time: the server could not recognise them by content, so they are not sent again.
var adopted = manifest is not null && manifest.Frames.Any(f => f.Sha256.Length == 0)
? await UnhashedAsync(remote, manifest, ct).ConfigureAwait(false)
: new FramePhotos([]);
var pending = new Queue<Frame>(frames.Where(f => (f.Sha256 is null || !present.Contains(f.Sha256.ToLowerInvariant()))
&& adopted.IndexOf(new FramePhoto(f.Sha256, f.Size, f.CapturedAt)) is null));
var progress = new TransferProgress(context, frames.Count, frames.Count - pending.Count);
await progress.ReportAsync().ConfigureAwait(false);
var skipped = 0;
@@ -86,10 +94,18 @@ internal sealed class SyncTransfers(SyncService sync)
if (skipped > 0) throw new InvalidDataException(Loc.Plural("Errors.Sync.Unreadable", skipped));
}
/// <summary>The server's frames it has not hashed yet, by size and capture time, at their indices.</summary>
private static async Task<FramePhotos> UnhashedAsync(ISyncRemote remote, SequenceManifest manifest, CancellationToken cancellationToken)
{
var captured = (await remote.ListFramesAsync(manifest.SequenceId, cancellationToken).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
return new FramePhotos(manifest.Frames.Where(f => f.Sha256.Length == 0).Select(f => (f.Index, new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id)))));
}
/// <summary>
/// The proxies the server asks for (<see cref="ManifestFrame.WantsProxy"/>) that this PC's decoders can make from its
/// originals (by their archived SHA-256, or the one <paramref name="hashes"/> holds for an original the index has none
/// for), made as the server's proxy policy says with the server's capture data, and sent. One the server refuses is
/// for; by size and capture time for a frame the server has not hashed, <see cref="SyncRules.ProxyOriginal"/>), made as
/// the server's proxy policy says with the server's capture data, and sent. One the server refuses is
/// counted in the job log; a server that makes no proxies, or an account that may not send them, ends the pass; a
/// server busy or out of reach fails the job like an original would.
/// </summary>
@@ -106,6 +122,7 @@ internal sealed class SyncTransfers(SyncService sync)
if ((frame.Sha256 ?? hashes.GetValueOrDefault(frame.Id)) is { } sha) originals.TryAdd(sha.ToLowerInvariant(), frame);
}
var records = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id);
var photos = SyncRules.Photos(frames);
var camera = new SidecarCamera { Make = local.CameraMake, Model = local.CameraModel, Serial = local.CameraSerial };
var decoder = sync.Options.Archive.Decoder;
var progress = new TransferProgress(context, wanted.Count, 0);
@@ -116,7 +133,12 @@ internal sealed class SyncTransfers(SyncService sync)
{
await Parallel.ForEachAsync(wanted, Workers(sync.Options.Uploads, refused.Token), async (frame, token) =>
{
var jpeg = originals.TryGetValue(frame.Sha256.ToLowerInvariant(), out var original) && records.TryGetValue(frame.Id, out var record)
records.TryGetValue(frame.Id, out var record);
// A frame the server has not hashed yet is this PC's original of its size and capture time.
var original = frame.Sha256.Length == 0
? SyncRules.ProxyOriginal(frame, record?.CapturedAt, frames, photos)
: originals.GetValueOrDefault(frame.Sha256.ToLowerInvariant());
var jpeg = original is not null && record is not null
? await Task.Run(() => MakeProxy(decoder, paths.FromRelative(original.RelativePath), RenderNodeClient.ToFrame(record), camera, spec, frame.FileName,
token), token).ConfigureAwait(false)
: null;
@@ -182,8 +204,14 @@ internal sealed class SyncTransfers(SyncService sync)
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var captured = (await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false)).ToDictionary(f => f.Id, f => f.CapturedAt);
var (have, restore) = local is null ? ([], []) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
var wanted = manifest.Frames.Where(f => !have.Contains(f.Sha256.ToLowerInvariant())).DistinctBy(f => f.Sha256.ToLowerInvariant()).ToList();
var (have, restore, photos) = local is null ? ([], [], new FramePhotos([])) : await LocalContentAsync(archive, local, ct).ConfigureAwait(false);
// An original the server has not hashed yet (adopted there, not verified) is here when an original of its size and
// capture time is; each one is fetched on its own and hashed here.
var wanted = manifest.Frames
.Where(f => f.Sha256.Length == 0
? photos.IndexOf(new FramePhoto(null, f.Size, captured.GetValueOrDefault(f.Id))) is null
: !have.Contains(f.Sha256.ToLowerInvariant()))
.DistinctBy(f => f.Sha256.Length == 0 ? f.Id.ToString("N") : f.Sha256.ToLowerInvariant()).ToList();
EnsureSpace(paths.Root, wanted.Sum(f => f.Size));
var staging = Path.Combine(paths.StagingDirectory, "sync-" + remoteId.ToString("N"));
@@ -195,7 +223,8 @@ internal sealed class SyncTransfers(SyncService sync)
if (local is null && wanted.Count > 0)
{
// The first original creates the local sequence (grouped by the server id); the others join it.
var first = await CommitAsync(remote, remoteId, archive.Id, null, wanted[0], staging, captured, ct).ConfigureAwait(false);
var (staged, sha) = await FetchOriginalAsync(remote, wanted[0], staging, ct).ConfigureAwait(false);
var first = await CommitAsync(remoteId, archive.Id, null, wanted[0], staged, sha, captured, ct).ConfigureAwait(false);
local = await db.Sequences.GetAsync(first.SequenceId, ct).ConfigureAwait(false)
?? throw new InvalidOperationException(Loc.L("Errors.Sync.LocalMissing"));
await sync.LinkAsync(remote.Server, remoteId, local, ct).ConfigureAwait(false);
@@ -208,14 +237,15 @@ internal sealed class SyncTransfers(SyncService sync)
var restored = 0;
await Parallel.ForEachAsync(rest, Workers(sync.Options.Downloads, ct), async (frame, token) =>
{
if (restore.TryGetValue(frame.Sha256.ToLowerInvariant(), out var place))
var (staged, sha) = await FetchOriginalAsync(remote, frame, staging, token).ConfigureAwait(false);
if (restore.TryGetValue(sha, out var place))
{
await RestoreAsync(remote, frame, staging, place, token).ConfigureAwait(false);
Restore(staged, place);
Interlocked.Increment(ref restored);
}
else
{
await CommitAsync(remote, remoteId, archive.Id, sequenceId, frame, staging, captured, token).ConfigureAwait(false);
await CommitAsync(remoteId, archive.Id, sequenceId, frame, staged, sha, captured, token).ConfigureAwait(false);
}
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
@@ -234,11 +264,12 @@ internal sealed class SyncTransfers(SyncService sync)
}
/// <summary>
/// The originals a local copy holds (lower-case SHA-256) and where each original flagged missing belongs. Frames
/// not hashed yet (an adopted folder never verified) are hashed first through the archive's verify, so the
/// server's copies of them are recognised instead of committed again as duplicates.
/// The originals a local copy holds (lower-case SHA-256, and their photos for server frames not hashed yet) and where
/// each original flagged missing belongs. Frames not hashed yet (an adopted folder never verified) are hashed first
/// through the archive's verify, so the server's copies of them are recognised instead of committed again as duplicates.
/// </summary>
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore)> LocalContentAsync(Archive archive, Sequence local, CancellationToken ct)
private async Task<(HashSet<string> Have, Dictionary<string, string> Restore, FramePhotos Photos)> LocalContentAsync(Archive archive, Sequence local,
CancellationToken ct)
{
var frames = await SequenceFrames.ListAsync(sync.Database, local.Id, ct).ConfigureAwait(false);
if (frames.Any(f => f.Sha256 is null && (f.Flags & FrameFlags.Missing) == 0))
@@ -255,16 +286,16 @@ internal sealed class SyncTransfers(SyncService sync)
var sha = frame.Sha256!.ToLowerInvariant();
if (!have.Contains(sha)) restore.TryAdd(sha, paths.FromRelative(frame.RelativePath));
}
return (have, restore);
var photos = SyncRules.Photos([.. frames.Where(f => (f.Flags & FrameFlags.Missing) == 0)]);
return (have, restore, photos);
}
private Task VerifyAsync(Archive archive, Guid sequenceId, CancellationToken ct) =>
sync.Archives.Verifier.VerifyAsync(archive, [sequenceId], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: ct);
/// <summary>Puts a verified copy of an original flagged missing back where its record says; a file that reappeared meanwhile is kept.</summary>
private static async Task RestoreAsync(ISyncRemote remote, ManifestFrame frame, string staging, string place, CancellationToken cancellationToken)
private static void Restore(string staged, string place)
{
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
if (File.Exists(place))
{
File.Delete(staged);
@@ -397,22 +428,26 @@ internal sealed class SyncTransfers(SyncService sync)
var assets = manifest.Frames.ToDictionary(f => f.Id);
var folder = sync.Proxies.Folder(remote.Server, remoteId);
Directory.CreateDirectory(folder);
var cachedKinds = sync.Proxies.Kinds(remote.Server, remoteId);
ProxyCache.Prune(folder, frames.Select(f => ProxyCache.FileName(f.Id)).ToHashSet(StringComparer.Ordinal));
EnsureSpace(folder, frames.Count(f => !File.Exists(Path.Combine(folder, ProxyCache.FileName(f.Id)))) * ProxyEstimate);
var files = new string?[frames.Count];
var kinds = new string?[frames.Count];
var progress = new TransferProgress(context, frames.Count, 0);
await progress.ReportAsync().ConfigureAwait(false);
await Parallel.ForEachAsync(Enumerable.Range(0, frames.Count), Workers(sync.Options.Downloads, ct), async (i, token) =>
{
IReadOnlyList<string> kinds = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
files[i] = await FetchProxyAsync(remote, frames[i].Id, kinds, folder, token).ConfigureAwait(false);
IReadOnlyList<string> offered = assets.TryGetValue(frames[i].Id, out var asset) ? Kinds(asset) : [];
var fetched = await FetchProxyAsync(remote, frames[i].Id, offered, cachedKinds.GetValueOrDefault(frames[i].Id), folder, token).ConfigureAwait(false);
files[i] = fetched?.Name;
kinds[i] = fetched?.Kind;
await progress.StepAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files));
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files, kinds));
var cached = files.Count(f => f is not null);
await sync.SetProxiesAsync(remote.Server, dto, cached, manifest.FramesVersion, ct).ConfigureAwait(false);
await sync.SetProxiesAsync(remote.Server, dto, cached, kinds.Count(k => k == ProxyCache.Thumb), manifest.FramesVersion, ct).ConfigureAwait(false);
if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
}
@@ -476,13 +511,12 @@ internal sealed class SyncTransfers(SyncService sync)
?? new CompleteUploadResponse(Guid.Empty, sequenceId ?? Guid.Empty, -1);
}
/// <summary>Downloads one original into staging and commits it into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(ISyncRemote remote, Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staging,
/// <summary>Commits one original from staging into the local sequence (created from the server id when null).</summary>
private async Task<IngestResult> CommitAsync(Guid remoteId, Guid archiveId, Guid? sequenceId, ManifestFrame frame, string staged, string sha,
IReadOnlyDictionary<Guid, DateTime?> captured, CancellationToken cancellationToken)
{
var staged = await FetchOriginalAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
var request = new IngestRequest(archiveId, sequenceId, null, sequenceId is null ? SyncService.SessionKey(remoteId) : null, staged, frame.FileName,
frame.Size, frame.Sha256.ToLowerInvariant(), captured.GetValueOrDefault(frame.Id), null);
frame.Size, sha, captured.GetValueOrDefault(frame.Id), null);
var result = await sync.Archives.Ingest.CommitAsync(request, cancellationToken).ConfigureAwait(false);
// A duplicate stays in staging (the sequence already holds that content).
if (result.Duplicate) File.Delete(staged);
@@ -490,71 +524,115 @@ internal sealed class SyncTransfers(SyncService sync)
}
/// <summary>
/// A verified copy in staging: resumed from a partial download, accepted only with the manifest's SHA-256 (two
/// attempts). A part as long as the file (a job stopped while hashing it) is only hashed again; a part the server can
/// no longer resume (416) starts over.
/// A verified copy in staging and its lower-case SHA-256: resumed from a partial download, accepted only with the
/// manifest's SHA-256 (two attempts). A part as long as the file (a job stopped while hashing it) is only hashed again;
/// a part the server can no longer resume (416) starts over.
/// </summary>
private static async Task<string> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging, CancellationToken cancellationToken)
private static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
if (frame.Sha256.Length == 0) return await FetchUnhashedAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
var sha = frame.Sha256.ToLowerInvariant();
if (sha.Length != 64 || !sha.All(char.IsAsciiHexDigitLower)) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
var target = Path.Combine(staging, sha + Path.GetExtension(frame.FileName).ToLowerInvariant());
if (File.Exists(target)) return target;
if (File.Exists(target)) return (target, sha);
var part = target + ".part";
for (var attempt = 1; ; attempt++)
{
if (!File.Exists(part) || new FileInfo(part).Length < frame.Size)
{
try
{
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
{
File.Delete(part);
continue;
}
}
if (!await FetchPartAsync(remote, frame, part, attempt, cancellationToken).ConfigureAwait(false)) continue;
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
{
File.Move(part, target, overwrite: true);
return target;
return (target, sha);
}
File.Delete(part);
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
}
}
/// <summary>The cached proxy's file name, downloading the first asset kind the server has; null when it has none.</summary>
private static async Task<string?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> kinds, string folder, CancellationToken cancellationToken)
/// <summary>
/// An original the server has not hashed yet (a folder it adopted and did not verify): nothing to check it against
/// but its size, so a copy of another size is fetched again once; it is hashed here, and the archive ingest files it
/// by that hash like any other. Kept in staging under the frame's id, as several such originals may share content.
/// </summary>
private static async Task<(string Path, string Sha256)> FetchUnhashedAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
var target = Path.Combine(staging, frame.Id.ToString("N") + Path.GetExtension(frame.FileName).ToLowerInvariant());
var part = target + ".part";
for (var attempt = 1; !File.Exists(target); attempt++)
{
if (!await FetchPartAsync(remote, frame, part, attempt, cancellationToken).ConfigureAwait(false)) continue;
if (new FileInfo(part).Length == frame.Size)
{
File.Move(part, target, overwrite: true);
break;
}
File.Delete(part);
if (attempt == 2) throw new InvalidDataException(Loc.L("Errors.Sync.Hash", frame.FileName));
}
return (target, await TitanoClient.HashFileAsync(target, cancellationToken).ConfigureAwait(false));
}
/// <summary>
/// Downloads an original into <paramref name="part"/>, resuming after what it holds; a part as long as the file is
/// kept as it is. False when the server can no longer resume it (416) on the first attempt: the part is gone and the
/// next attempt starts over.
/// </summary>
private static async Task<bool> FetchPartAsync(ISyncRemote remote, ManifestFrame frame, string part, int attempt, CancellationToken cancellationToken)
{
if (File.Exists(part) && new FileInfo(part).Length >= frame.Size) return true;
try
{
await using (var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frame.Id, "original", file, cancellationToken).ConfigureAwait(false);
return true;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.RequestedRangeNotSatisfiable && attempt == 1)
{
File.Delete(part);
return false;
}
}
/// <summary>
/// The cached file of a frame and what it is, downloading the first asset kind the server has
/// (<paramref name="offered"/>, the proxy first); null when it has none. A cached proxy stays. A cached thumbnail,
/// or a file of a cache that did not record its kind (<paramref name="cachedKind"/> null), stands in only until the
/// server has a proxy of the frame, which then replaces it; until then it stays as the thumbnail.
/// </summary>
private static async Task<(string Name, string Kind)?> FetchProxyAsync(ISyncRemote remote, Guid frameId, IReadOnlyList<string> offered, string? cachedKind,
string folder, CancellationToken cancellationToken)
{
var name = ProxyCache.FileName(frameId);
var path = Path.Combine(folder, name);
if (new FileInfo(path) is { Exists: true, Length: > 0 }) return name;
var cached = new FileInfo(path) is { Exists: true, Length: > 0 };
if (cached && (cachedKind == ProxyCache.Proxy || !offered.Contains(ProxyCache.Proxy))) return (name, cachedKind ?? ProxyCache.Thumb);
var part = path + ".part";
foreach (var kind in kinds)
foreach (var kind in offered)
{
// The cached file is as good as the server's thumbnail.
if (cached && kind == ProxyCache.Thumb) break;
try
{
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
File.Move(part, path, overwrite: true);
return name;
return (name, kind);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
File.Delete(part);
}
}
return null;
return cached ? (name, ProxyCache.Thumb) : null;
}
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => ["proxy", "thumb"],
(true, false) => ["proxy"],
(false, true) => ["thumb"],
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],
(true, false) => [ProxyCache.Proxy],
(false, true) => [ProxyCache.Thumb],
_ => [],
};