M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione

Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 16:06:15 +00:00
1 parent c803bd98b5
commit 3aeaa17da7
69 files changed
+12472

No files matched your search

+292
View File
@@ -0,0 +1,292 @@
using System.Buffers;
using System.Globalization;
using System.Security.Cryptography;
namespace Febe.Core.Library;
/// <summary>Size and SHA-256 of a file written by <see cref="SafeFileWriter"/>.</summary>
public readonly record struct FileDigest(long Bytes, string Sha256);
/// <summary>A file safely written to its final name.</summary>
/// <param name="RelativePath">Path relative to the root folder, '/' separated (may differ from the one asked: never overwrites).</param>
/// <param name="FullPath">Full path on disk.</param>
/// <param name="Bytes">Size.</param>
/// <param name="Sha256">Lowercase hex SHA-256, computed while writing.</param>
/// <param name="LastWriteTimeSet">The modification time was set as asked.</param>
public sealed record SavedFile(string RelativePath, string FullPath, long Bytes, string Sha256, bool LastWriteTimeSet);
/// <summary>Options of a safe write.</summary>
public sealed record SafeWriteOptions
{
/// <summary>Set the file modification time to this instant (publication time, spec §4.7). Null leaves it.</summary>
public DateTimeOffset? LastWriteTime { get; init; }
/// <summary>Abort with <see cref="FileTooLargeException"/> beyond this size (e.g. «Salta i video oltre»).</summary>
public long? MaxBytes { get; init; }
/// <summary>Bytes written so far.</summary>
public IProgress<long>? Progress { get; init; }
}
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
public sealed class FileTooLargeException : IOException
{
public FileTooLargeException()
{
}
public FileTooLargeException(string message)
: base(message)
{
}
public FileTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Writes library files safely (spec §6.5 point 4, rule 12):
/// <list type="number">
/// <item>the content goes to a temporary name (<c>.febe-*.part</c>) in the destination folder;</item>
/// <item>SHA-256 is computed while writing, then the data is flushed to disk;</item>
/// <item>the file is renamed to its final name; an existing file is never overwritten — a free name
/// («nome (2).jpg») is chosen instead;</item>
/// <item>if anything goes wrong or the operation is cancelled, the temporary file is removed: an interrupted
/// download never leaves a file with the final name.</item>
/// </list>
/// </summary>
public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathLength)
{
/// <summary>Prefix of temporary files.</summary>
public const string TempPrefix = ".febe-";
/// <summary>Suffix of temporary files.</summary>
public const string TempSuffix = ".part";
private const int BufferSize = 128 * 1024;
private const int MaxNameAttempts = 10_000;
/// <summary>Serializes «is the name free? then rename» across all writers of the process.</summary>
private static readonly Lock MoveGate = new();
/// <summary>Writes <paramref name="source"/> to <paramref name="relativePath"/> inside <paramref name="rootFolder"/>.</summary>
public Task<SavedFile> SaveAsync(Stream source, string rootFolder, string relativePath, SafeWriteOptions? options = null, CancellationToken ct = default)
{
var segments = Segments(relativePath);
var directory = string.Join('/', segments.Take(segments.Count - 1));
var sanitized = string.Join('/', segments);
return SaveAsync(source, rootFolder, directory, _ => sanitized, options, ct);
}
/// <summary>
/// Writes <paramref name="source"/> and decides the final name only after hashing (e.g. profile pictures, named after
/// their SHA-256). The temporary file is written in <paramref name="tempDirectory"/> (relative to the root, '/'
/// separated; use the destination folder when known).
/// </summary>
public async Task<SavedFile> SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func<FileDigest, string> relativePathFor,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(relativePathFor);
var saved = await SaveAsync(source, rootFolder, tempDirectory, (d, _) => ValueTask.FromResult<string?>(relativePathFor(d)), options, ct)
.ConfigureAwait(false);
return saved!;
}
/// <summary>
/// Writes <paramref name="source"/> to a temporary file, then asks <paramref name="decide"/> — knowing size and
/// SHA-256 — for the final relative path. When <paramref name="decide"/> returns null the content is discarded
/// (e.g. identical to a file already in the account, spec §9.5): nothing is left on disk and the result is null.
/// </summary>
public async Task<SavedFile?> SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
ArgumentNullException.ThrowIfNull(decide);
options ??= new SafeWriteOptions();
var root = Path.GetFullPath(rootFolder);
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
try
{
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
var desired = await decide(digest, ct).ConfigureAwait(false);
if (desired is null)
{
return null;
}
ct.ThrowIfCancellationRequested();
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative);
var timeSet = true;
if (options.LastWriteTime is { } time)
{
try
{
File.SetLastWriteTimeUtc(finalPath, time.UtcDateTime);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentOutOfRangeException)
{
timeSet = false; // some shares refuse it: the file is still good
}
}
return new SavedFile(relative, finalPath, digest.Bytes, digest.Sha256, timeSet);
}
finally
{
TryDelete(tempPath); // no-op after a successful move
}
}
/// <summary>
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>).
/// Returns how many were removed.
/// </summary>
public static int CleanupTemporaryFiles(string folder, bool recursive = true)
{
if (!Directory.Exists(folder))
{
return 0;
}
var removed = 0;
var files = Directory.EnumerateFiles(
folder,
TempPrefix + "*" + TempSuffix,
new EnumerationOptions { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = 0 });
foreach (var file in files)
{
if (TryDelete(file))
{
removed++;
}
}
return removed;
}
/// <summary>True for a temporary file name of the safe writer.</summary>
public static bool IsTemporaryFile(string path)
{
var name = Path.GetFileName(path);
return name.StartsWith(TempPrefix, StringComparison.Ordinal) && name.EndsWith(TempSuffix, StringComparison.Ordinal);
}
private static async Task<FileDigest> WriteTempAsync(Stream source, string tempPath, SafeWriteOptions options, CancellationToken ct)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
long total = 0;
try
{
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
int read;
while ((read = await source.ReadAsync(buffer.AsMemory(0, BufferSize), ct).ConfigureAwait(false)) > 0)
{
total += read;
if (options.MaxBytes is { } max && total > max)
{
throw new FileTooLargeException(
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
}
hash.AppendData(buffer, 0, read);
await target.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
options.Progress?.Report(total);
}
await target.FlushAsync(ct).ConfigureAwait(false);
target.Flush(flushToDisk: true);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
}
/// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary>
private static List<string> Segments(string relativePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var segments = LibraryLayout.ToStored(relativePath)
.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(WindowsFileNames.SanitizeSegment)
.ToList();
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
}
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative)
{
var segments = Segments(desiredRelativePath);
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
for (var attempt = 1; attempt <= MaxNameAttempts; attempt++)
{
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength);
relative = string.Join('/', fitted);
var finalPath = LibraryLayout.FullPath(root, relative);
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
// On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces:
// two writers of this process could overwrite each other. The check and the rename are therefore done under
// one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name.
lock (MoveGate)
{
if (File.Exists(finalPath) || Directory.Exists(finalPath))
{
continue;
}
try
{
File.Move(tempPath, finalPath, overwrite: false);
return finalPath;
}
catch (IOException) when (File.Exists(finalPath))
{
// Another program took the name in the meantime: try the next one.
}
}
}
throw new IOException($"Nessun nome libero per {desiredRelativePath} dopo {MaxNameAttempts} tentativi.");
}
private static bool TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
return true;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: a leftover temporary file is removed at the next start-up.
}
return false;
}
}