using System.Text.Json; using Chronos.Core.IO; namespace Chronos.Core.Archiving; /// /// Write-ahead record of an ingest batch (.chronos/ingest.pending.json): the frames whose files are about to be /// moved into the sequence folder. Written before the moves and removed once sequence.json lists them, so a /// crash in between is repaired by instead of leaving unindexed originals behind. /// public sealed record IngestJournal(IReadOnlyList Frames) { public static void Write(SequencePaths sequence, IngestJournal journal) { Directory.CreateDirectory(sequence.MetaDirectory); AtomicFile.WriteAllBytes(sequence.IngestJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.IngestJournal)); } public static void Delete(SequencePaths sequence) { if (File.Exists(sequence.IngestJournalPath)) File.Delete(sequence.IngestJournalPath); } /// /// Completes an interrupted batch: frames whose file reached the sequence folder (same size) but are missing from /// are added in capture order. Returns the manifest to write, or null when nothing has /// to change. The journal is left in place; it once the result is written. /// public static SequenceManifest? Recover(SequencePaths sequence, SequenceManifest manifest) { if (!File.Exists(sequence.IngestJournalPath)) return null; IngestJournal? journal; try { journal = JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.IngestJournalPath), ArchiveJson.Default.IngestJournal); } catch (JsonException) { journal = null; // torn while being written: nothing was moved yet } if (journal is null) return null; var known = manifest.Frames.Select(f => f.Id).ToHashSet(); var moved = journal.Frames.Where(f => !known.Contains(f.Id) && FileHasSize(sequence.File(f.File), f.Size)).ToList(); return moved.Count == 0 ? null : SequenceFrames.Insert(manifest, moved); } private static bool FileHasSize(string path, long size) { var info = new FileInfo(path); return info.Exists && info.Length == size; } }