using System.Text.Json; using System.Text.Json.Serialization; using Chronos.Core.Archiving; using Chronos.Core.IO; using Chronos.Data.Copies; using Chronos.Data.Sync; namespace Chronos.Data.Archiving; /// The stages of a merge, in the order they run (design §5d). internal enum MergeStage { Copy, Renders, Verify, Replace, Details, Projects, Links, Trash, Done, } /// A photo of the dropped sequence a merge copies into the kept one: its key, the drop's frame, name, size and recorded SHA-256. internal sealed record MergeCopy(string Key, PhotoAction Action, Guid DropFrameId, string FileName, long Bytes, string? Sha256); /// A losing version of the kept sequence that goes to its photo trash once the winner (the drop's version) is in place. internal sealed record MergeReplace(string Key, Guid KeepFrameId, string FileName, string WinnerSha256); /// A drop original the verify found in the kept sequence: its SHA-256 now and the keep frame that holds it. internal sealed record MergeVerified(string Sha256, Guid KeepFrameId); /// /// What a merge's links stage changes, read before it: the session keys each manifest held, the other's archive, and the /// rows moves (). /// internal sealed record MergeLinksUndo(List KeepKeysBefore, List DropKeysBefore, Guid DropArchiveId, MoveUndo Moved); /// /// The journal of a merge (owner review 6, #73; design §5d): <keep archive>/.chronos/journal/merge-<job:N>.json, /// written atomically (temp + rename) after each step. It keeps what the confirmed plan decided (a resumed run never plans /// again: its own steps moved the versions) and how far each stage came, so every stage resumes and nothing is done twice. /// internal sealed class MergeJournal { public Guid JobId { get; set; } public Guid CopyId { get; set; } public Guid KeepId { get; set; } public Guid DropId { get; set; } public string Fingerprint { get; set; } = string.Empty; public MergeStage Stage { get; set; } /// The kept sequence's settings version the plan read (the details are written only at it). public int KeepSettingsVersion { get; set; } /// The dropped sequence's frames version the plan read (checked before each photo and at the verify). public int DropFramesVersion { get; set; } /// /// The dropped sequence's settings version the plan read: the trash refuses another (work sent home to the other since /// the plan, its Main settings or details, would go to the trash unmerged). Null in a journal written before it was kept. /// public int? DropSettingsVersion { get; set; } /// The kept sequence's statuses before the merge (what its follow-ups make again). public int KeepStatus { get; set; } public List Copies { get; set; } = []; public List Replaces { get; set; } = []; /// Raw SHA-256 of drop originals the plan leaves out of the kept sequence (last copies, losers, tombstoned in keep, converted). public List Absent { get; set; } = []; public List Renders { get; set; } = []; public SyncPayload? Payload { get; set; } public List Projects { get; set; } = []; public List SessionKeys { get; set; } = []; /// Drop frame → the keep frame it was filed as (or that already held it). public Dictionary Committed { get; set; } = []; /// Render → its archive-relative path in the kept sequence, written before the copy. public Dictionary RenderTargets { get; set; } = []; public List RendersMoved { get; set; } = []; /// Drop frame → its SHA-256 as hashed by the verify and the keep frame that holds it. public Dictionary Verified { get; set; } = []; /// Drop frames the verify found to be another photo than keep's (unhashed, same size and time) and filed as a second version. public List SecondVersions { get; set; } = []; /// Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds. public List Settled { get; set; } = []; /// /// Raw SHA-256 of the drop photos the verify settled because a third sequence held them: asked again under the kept /// sequence's lease before the trash (that sequence may have gone since). Those settled through the /// user confirmed as last copies and are not asked again. /// public List SettledElsewhere { get; set; } = []; /// The dropped sequence's frames version the verify read: the trash refuses another. public int? VerifiedDropFramesVersion { get; set; } /// /// The dropped sequence's frames flagged Missing or Corrupt whose file was there at the verify, each hashed then and /// settled (held by the kept sequence, a last copy, or held elsewhere): one flagged since keeps the trash from running. /// public List FlaggedVerified { get; set; } = []; public List Replaced { get; set; } = []; /// Keys of losing versions a refused trash step kept (reported at the end). public List KeptLosers { get; set; } = []; public bool DetailsDone { get; set; } public Dictionary ProjectSteps { get; set; } = []; public List ProjectsDone { get; set; } = []; public bool KeepKeysWritten { get; set; } public bool DropKeysRemoved { get; set; } public bool LinksMoved { get; set; } /// /// What the links stage takes from the other sequence, read before its first change: a merge abandoned after it (a check /// before the trash fails, a cancel) gives it back, so the other keeps its keys, links and pairs. Null before the stage. /// public MergeLinksUndo? LinksUndo { get; set; } /// The journal of job in the archive at . public static string PathFor(ArchivePaths paths, Guid jobId) => Path.Combine(paths.JournalDirectory, $"merge-{jobId:N}.json"); /// Where the job stages the files it copies. public static string StagingFor(ArchivePaths paths, Guid jobId) => Path.Combine(paths.StagingDirectory, $"merge-{jobId:N}"); /// The journal of job ; null when there is none (a first run), or it cannot be read. /// The journal is damaged: the merge stops rather than start again over half a merge. public static MergeJournal? Read(ArchivePaths paths, Guid jobId) { var path = PathFor(paths, jobId); if (!File.Exists(path)) return null; try { return JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), MergeJournalJson.Default.MergeJournal); } catch (JsonException ex) { throw new InvalidDataException($"The merge journal {path} is damaged.", ex); } } /// Writes the journal atomically. public void Save(ArchivePaths paths) { Directory.CreateDirectory(paths.JournalDirectory); AtomicFile.WriteAllText(PathFor(paths, JobId), JsonSerializer.Serialize(this, MergeJournalJson.Default.MergeJournal)); } /// Deletes the journal and the staging folder of job . public static void Delete(ArchivePaths paths, Guid jobId) { var staging = StagingFor(paths, jobId); if (Directory.Exists(staging)) Directory.Delete(staging, recursive: true); File.Delete(PathFor(paths, jobId)); } } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(MergeJournal))] internal sealed partial class MergeJournalJson : JsonSerializerContext;