feat: found copies foundation (contracts, migration 0012, store, wire, trash and job hooks, keys)

Owner review 6 asks Chronos to recognise the same time-lapse held under different ids on the
server and on this PC, compare the copies, and keep them apart or integrate and sync them. This
lays the shared foundation the later parcels build on, without any UI or detection yet.

- Migration 0012 adds found_copies (local-server and local-local pairs with evidence, scores,
  answer, policy and the 404 record) and copy_probes; every existing link with a local sequence
  becomes a Linked pair, so a server deletion and the per-link policy have a place.
- FoundCopyStore keeps the pairs: upserts that never touch the answer, a compare-and-set of the
  state with an Integrating backstop (a failed or cancelled job reads as the previous state),
  link promotion and demotion, the once-per-refresh 404 count, the merge's links stage
  (session keys, links reset, pairs moved, refused when both are linked on one server), the
  local overlap queries and the probes. SyncLinkStore.RekeyAsync moves pairs and probes with
  the links in the same transaction.
- Contracts for detection, review, plans, the Integrate and MergeSequences jobs (kinds 25/26,
  High level, new detail steps) and the Upload all rule that keeps suspected, kept-apart,
  deleted, busy and server-born sequences here.
- Wire: POST photos/lookup, uploads into a target (IntoTarget/Copied, trailing and optional),
  frames/delete on the client, capabilities photo-lookup and upload-into, cached per remote.
- The trash plans and deletes accept the job that holds the sequence (its own hold is not
  Busy) and a frames version checked under the lease; a Background job never interrupts a
  running one.
- Settings for linking, the photo policy and projects; the en and it keys of design section 9.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 19:39:04 +01:00
1 parent 43719bb5c5
commit 283d04d9cd
57 files changed
+3302 -26

No files matched your search

@@ -59,6 +59,134 @@ internal sealed class FakeSyncRemote : ISyncRemote
public Task<int> SettingsFormatAsync(CancellationToken cancellationToken) => Task.FromResult(SettingsFormat);
/// <summary>
/// The capabilities the server announces (<see cref="ServerCapabilities"/>): none by default, an older server's path
/// (owner review 6, #73); tests of the lookup and of uploads into a target opt in.
/// </summary>
public HashSet<string> Capabilities { get; } = new(StringComparer.Ordinal);
public Task<IReadOnlySet<string>> CapabilitiesAsync(CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult<IReadOnlySet<string>>(new HashSet<string>(Capabilities, StringComparer.Ordinal));
}
/// <summary>Lookup requests so far, as received.</summary>
public List<PhotoLookupRequest> Lookups { get; } = [];
/// <summary>Uploads into a target so far (<see cref="UploadFileIntoAsync"/>), and how many the server filed from a copy it held elsewhere.</summary>
public int IntoUploads { get; private set; }
public int CopiedInto { get; private set; }
/// <summary>Frame deletions refused with 403, as for an account that is neither the owner nor an admin.</summary>
public bool ForbidFrameDeletes { get; set; }
/// <summary>Frames moved to the server's trash so far, by sequence.</summary>
public List<(Guid SequenceId, FakeFrame Frame)> Trashed { get; } = [];
/// <summary>Files <paramref name="sequence"/> under <paramref name="sessionKey"/>, as an upload with that key would.</summary>
public void FileUnder(string sessionKey, FakeSequence sequence)
{
lock (_gate) _sessions[sessionKey] = sequence;
}
/// <summary>
/// Like the server (owner review 6, #73): per probe, the sequences holding its hashes in a frame (a sequence it never
/// hashed lists none), tombstoning them (by the photo's or its replacement's SHA-256), holding a frame of its unhashed keys
/// by size and capture millisecond, or filed under its session key. 404 without <see cref="ServerCapabilities.PhotoLookup"/>,
/// 413 beyond the limits.
/// </summary>
public Task<PhotoLookupResponse> LookupPhotosAsync(PhotoLookupRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
if (!Capabilities.Contains(ServerCapabilities.PhotoLookup)) throw new ChronosApiException(HttpStatusCode.NotFound, new ApiError("not_found", "route"));
if (request.Probes.Count > PhotoLookupRequest.MaxProbes || request.CountItems() > PhotoLookupRequest.MaxItems)
throw new ChronosApiException(HttpStatusCode.RequestEntityTooLarge, new ApiError("too_many", "probes"));
Lookups.Add(request);
var results = new List<ProbeResult>();
foreach (var probe in request.Probes)
{
var hashes = probe.Sha256.Select(h => h.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var keys = (probe.Unhashed ?? []).Select(k => (k.Size, Ms(k.CapturedAt))).ToHashSet();
var filed = probe.SessionKey is { } key && _sessions.TryGetValue(key, out var held) ? held : null;
var hits = new List<PhotoLookupHit>();
foreach (var sequence in Sequences.Values)
{
var inFrames = sequence.Unhashed ? 0 : sequence.Frames.Select(f => f.Sha256).Where(hashes.Contains).Distinct(StringComparer.Ordinal).Count();
var removed = hashes.Count(h => sequence.Removed.Any(r => r.Sha256 == h || r.Replacement == h));
var unhashed = keys.Count(k => sequence.Frames.Any(f => f.CapturedAt is { } at && f.Bytes.Length == k.Size && Ms(at) == k.Item2));
var session = ReferenceEquals(filed, sequence);
if (inFrames + removed + unhashed > 0 || session) hits.Add(new PhotoLookupHit(sequence.Id, inFrames, removed, unhashed, session));
}
results.Add(new ProbeResult(probe.Key, hits));
}
return Task.FromResult(new PhotoLookupResponse(results));
}
static long Ms(DateTime at) => at.Ticks / TimeSpan.TicksPerMillisecond;
}
/// <summary>
/// Like the server with <see cref="ServerCapabilities.UploadInto"/>: the photo is filed into the target even when another
/// sequence holds it (a server-side copy, counted in <see cref="CopiedInto"/>); one the target holds answers its frame, one
/// it tombstoned answers none. Without the capability the server ignores the flag: an upload as before.
/// </summary>
public async Task<CompleteUploadResponse?> UploadFileIntoAsync(string path, Guid sequenceId, string sha256, DateTime? capturedAt,
CancellationToken cancellationToken)
{
bool capable;
lock (_gate) capable = Capabilities.Contains(ServerCapabilities.UploadInto);
if (!capable) return await UploadFileAsync(path, sequenceId, null, sha256, capturedAt, cancellationToken);
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
throw new ChronosApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
lock (_gate)
{
IntoUploads++;
var target = Find(sequenceId);
if (target.Removed.Any(r => r.Sha256 == sha256)) return null;
var index = target.Frames.FindIndex(f => f.Sha256 == sha256);
if (index >= 0) return new CompleteUploadResponse(target.Frames[index].Id, target.Id, index);
if (Sequences.Values.Where(s => !s.Unhashed && s != target).SelectMany(s => s.Frames).Any(f => f.Sha256 == sha256)) CopiedInto++;
var frame = target.AddFrame(bytes, Path.GetFileName(path), capturedAt);
return new CompleteUploadResponse(frame.Id, target.Id, target.Frames.IndexOf(frame));
}
}
/// <summary>
/// Like the server's <c>frames/delete</c>: 404 for an unknown sequence, 403 with <see cref="ForbidFrameDeletes"/>, 409
/// <c>frames_conflict</c> when a frame is not there or the frames version moved, 409 <c>would_empty</c>; a dry run answers
/// the plan; else the frames go to the trash, each leaving a tombstone, and the frames version moves.
/// </summary>
public Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
var sequence = Find(sequenceId);
if (ForbidFrameDeletes) throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "delete"));
var wanted = request.FrameIds.ToHashSet();
var frames = sequence.Frames.Where(f => wanted.Contains(f.Id)).ToList();
if (frames.Count != wanted.Count || (request.ExpectedFramesVersion is { } expected && expected != sequence.FramesVersion))
throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "changed"));
if (frames.Count == sequence.Frames.Count) throw new ChronosApiException(HttpStatusCode.Conflict, new ApiError("would_empty", "empty"));
var bytes = frames.Sum(f => (long)f.Bytes.Length);
if (request.DryRun)
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count, null, true));
var at = DateTimeOffset.UtcNow;
foreach (var frame in frames)
{
sequence.Frames.Remove(frame);
Trashed.Add((sequenceId, frame));
if (!sequence.Removed.Any(r => r.Sha256 == frame.Sha256)) sequence.Removed.Add(new RemovedPhotoDto(frame.Sha256, null, "deleted", at));
}
sequence.FramesVersion++;
sequence.UpdatedAt = at;
return Task.FromResult(new FrameDeleteResultDto(sequenceId, frames.Count, bytes, sequence.FramesVersion, sequence.Frames.Count,
$"trash/photos-{Guid.NewGuid():N}", false));
}
}
public FakeSequence Add(string? title, IEnumerable<byte[]> originals, string? settingsJson = null,
SequenceStatus status = SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt)
{