using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.IO;
namespace Titano.Core.Archiving;
///
/// .titano/index-snapshot.bin (BRIEF ยง7): every sidecar of the archive in one file, so a rebuild reads one file
/// sequentially instead of thousands of small ones over a share. Optional and never authoritative: an entry is used
/// only when its sidecar still has the recorded size and time, and a file whose trailing SHA-256 does not match is
/// ignored entirely.
///
/// Layout: "TISN", version (u16), reserved (u16), then per sidecar: folder length (u16), UTF-8 folder,
/// size (i64), modified UTC ticks (i64), length (i32), sidecar bytes; finally the SHA-256 of everything before it.
public sealed class IndexSnapshot
{
private const ushort Version = 1;
private static ReadOnlySpan Magic => "TISN"u8;
private readonly Dictionary _entries;
private IndexSnapshot(Dictionary entries) => _entries = entries;
public int Count => _entries.Count;
/// The snapshot at , or null when it is absent, damaged or of another version.
public static IndexSnapshot? TryLoad(string path)
{
byte[] data;
try
{
if (!File.Exists(path)) return null;
data = AtomicFile.ReadAllBytes(path);
}
catch (IOException)
{
return null;
}
if (data.Length < 8 + 32 || !data.AsSpan(0, 4).SequenceEqual(Magic) || BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(4)) != Version)
return null;
var body = data.AsSpan(0, data.Length - 32);
if (!SHA256.HashData(body).AsSpan().SequenceEqual(data.AsSpan(data.Length - 32))) return null;
var entries = new Dictionary(StringComparer.Ordinal);
var position = 8;
while (position < body.Length)
{
if (position + 2 > body.Length) return null;
var folderLength = BinaryPrimitives.ReadUInt16LittleEndian(body[position..]);
position += 2;
if (position + folderLength + 20 > body.Length) return null;
var folder = Encoding.UTF8.GetString(body.Slice(position, folderLength));
position += folderLength;
var size = BinaryPrimitives.ReadInt64LittleEndian(body[position..]);
var ticks = BinaryPrimitives.ReadInt64LittleEndian(body[(position + 8)..]);
var length = BinaryPrimitives.ReadInt32LittleEndian(body[(position + 16)..]);
position += 20;
if (length < 0 || ticks < 0 || ticks > DateTime.MaxValue.Ticks || position + length > body.Length) return null;
entries[folder] = (new FileStamp(size, new DateTime(ticks, DateTimeKind.Utc)), body.Slice(position, length).ToArray());
position += length;
}
return new IndexSnapshot(entries);
}
/// The recorded sidecar bytes of when its current stamp still matches.
public byte[]? TryGet(string folder, FileStamp current) =>
_entries.TryGetValue(folder, out var entry) && entry.Stamp == current ? entry.Bytes : null;
/// Streams a new snapshot to a temporary file; replaces the old one atomically.
public sealed class Writer : IDisposable
{
private readonly string _path;
private readonly string _temp;
private readonly FileStream _stream;
private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
private bool _committed;
public Writer(string path)
{
_path = path;
_temp = AtomicFile.TempPathFor(path);
_stream = new FileStream(_temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16);
Span header = stackalloc byte[8];
header.Clear();
Magic.CopyTo(header);
BinaryPrimitives.WriteUInt16LittleEndian(header[4..], Version);
Write(header);
}
public void Add(string folder, FileStamp stamp, ReadOnlySpan sidecar)
{
var name = Encoding.UTF8.GetBytes(folder);
Span head = stackalloc byte[2];
BinaryPrimitives.WriteUInt16LittleEndian(head, checked((ushort)name.Length));
Write(head);
Write(name);
Span fields = stackalloc byte[20];
BinaryPrimitives.WriteInt64LittleEndian(fields, stamp.Size);
BinaryPrimitives.WriteInt64LittleEndian(fields[8..], stamp.ModifiedUtc.Ticks);
BinaryPrimitives.WriteInt32LittleEndian(fields[16..], sidecar.Length);
Write(fields);
Write(sidecar);
}
public void Commit()
{
_stream.Write(_hash.GetHashAndReset());
_stream.Dispose();
AtomicFile.Commit(_temp, _path);
_committed = true;
}
public void Dispose()
{
_stream.Dispose();
_hash.Dispose();
if (!_committed && File.Exists(_temp)) File.Delete(_temp);
}
private void Write(ReadOnlySpan data)
{
_hash.AppendData(data);
_stream.Write(data);
}
}
}