E2: motore delle copie esterne (porta, destinazioni, piano, copia)

Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data:

- porta del lavoro lungo: importazione, copia e ricostruzione mai insieme;
- radice /esporta in Docker con mountinfo, controllo delle cartelle con
  il file di prova, destinazioni con «Esporta questo account» acceso se
  Alberto non ha mai scelto (decisione del 27/11/2026);
- filtro «Copie», segni delle tessere e conteggi dell'account sui soli
  file dovuti (D3);
- percorsi «Come la libreria», segmento dell'account nella cartella
  generale, 240 caratteri, storia in evidenza;
- piano di «Copia in…», un lavoro per destinazione, copia in .part con
  SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione
  per percorso, pausa della destinazione su prova, spazio e FAT32,
  attesa fuori dalle sessioni del motore, ripresa e recupero;
- .part rimossi solo nelle cartelle degli elementi di lavori non finiti;
- «Tolto» e «Superato» (agganci in importazione, scaricamenti,
  doppioni e ricostruzione), mai ricopiati da soli;
- rapporti e testi in italiano, prove del lavoro di copia.

Interfaccia, API e composizione restano alla parte successiva.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 10:55:29 +01:00
1 parent 213b89a618
commit a112c92893
41 files changed
+5370 -27

No files matched your search

@@ -1,5 +1,6 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library;
@@ -174,6 +175,11 @@ public sealed class DownloadDuplicateReview(
if (ok)
{
removed++;
if (decision == DuplicateDecision.KeepLarger && loser == item.Existing && item.Candidate.Sha256 is { } larger)
{
// «Tieni il più grande» replaced the file already there: its copies in external folders are «Superato».
await ExportSupersession.FileChangedAsync(storage, item.Existing.AccountId, item.Existing.Sha256, larger, clock.Now, CancellationToken.None).ConfigureAwait(false);
}
}
else if (problem is not null)
{
+5
View File
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library;
@@ -319,6 +320,10 @@ public sealed class LibraryIngest(
throw new EntryDeletedException();
}
// A slot that had other bytes (a rebuild left the journal's SHA-256 on a file to download again, an import
// filled it): the copies of the old file in external folders are now «Superato» (spec §4.10).
await ExportSupersession.FileChangedAsync(storage, account.Id, media.Sha256, saved.Sha256, now, CancellationToken.None).ConfigureAwait(false);
var pairs = new List<DuplicatePair>();
if (hash is { } h && hashIndex is not null)
{
+13
View File
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
namespace Febe.Core.Library;
@@ -202,6 +203,14 @@ public sealed class LibraryRebuilder(
}
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
foreach (var (old, now) in report.Changed)
{
await ExportSupersession.FileChangedAsync(storage, account.Id, old, now, clock.Now, CancellationToken.None).ConfigureAwait(false);
}
report.Changed.Clear();
CountUntracked(folder, allItems, report);
}
@@ -554,6 +563,7 @@ public sealed class LibraryRebuilder(
report.FilesVerified++;
if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal))
{
report.Changed.Add((media.Sha256, check.Sha256));
report.HashMismatches++;
report.Note($"Contenuto diverso da quello registrato: {file.Path}");
}
@@ -738,6 +748,9 @@ public sealed class LibraryRebuilder(
public int InvalidLines { get; set; }
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
public List<(string Old, string New)> Changed { get; } = [];
public void Note(string note)
{
if (_notes.Count < MaxNotes)
+114
View File
@@ -0,0 +1,114 @@
namespace Febe.Core.Library;
/// <summary>
/// One line of <c>/proc/self/mountinfo</c> (proc(5)): unlike <c>/proc/self/mounts</c> it says which folder of its file
/// system a mount shows (<see cref="Root"/>: <c>/</c> when the mount is the root of that file system) and gives the exact
/// mount point, which the export needs for <c>/esporta</c> (spec §4.10, §11).
/// </summary>
/// <param name="Id">Mount id.</param>
/// <param name="ParentId">Id of the parent mount.</param>
/// <param name="Root">Folder of the file system shown at the mount point (<c>/</c>: its root).</param>
/// <param name="MountPoint">Where it is mounted, unescaped.</param>
/// <param name="Options">Per-mount options (<c>rw</c>, <c>ro</c>, <c>noatime</c>…).</param>
/// <param name="FileSystemType">File system type (<c>ext4</c>, <c>vfat</c>, <c>cifs</c>…).</param>
/// <param name="Source">Mount source (<c>/dev/sdb1</c>, <c>//server/share</c>…), unescaped.</param>
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source)
{
/// <summary>The mount is read-only (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>).</summary>
public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal);
}
/// <summary>Reads <c>/proc/self/mountinfo</c>.</summary>
public static class MountInfoTable
{
private const string MountInfoPath = "/proc/self/mountinfo";
/// <summary>
/// Parses the content of <c>/proc/self/mountinfo</c>: fields 0-5, then optional fields up to the separator «-», then
/// file system type and source. Malformed lines are skipped; nothing throws.
/// </summary>
public static IReadOnlyList<MountInfoEntry> Parse(string content)
{
ArgumentNullException.ThrowIfNull(content);
var entries = new List<MountInfoEntry>();
foreach (var raw in content.Split('\n'))
{
var fields = raw.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length < 9
|| !int.TryParse(fields[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id)
|| !int.TryParse(fields[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parent))
{
continue;
}
var separator = Array.IndexOf(fields, "-", 6);
if (separator < 0 || separator + 2 >= fields.Length)
{
continue;
}
var root = MountTable.Unescape(fields[3]);
var point = MountTable.Unescape(fields[4]);
if (!root.StartsWith('/') || !point.StartsWith('/'))
{
continue;
}
entries.Add(new MountInfoEntry(
id,
parent,
root,
point,
fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries),
fields[separator + 1],
MountTable.Unescape(fields[separator + 2])));
}
return entries;
}
/// <summary>
/// The mount that holds a path: the longest mount point that is the path itself or one of its parents (ordinal
/// comparison; a later mount over the same point wins, as the kernel shows the last one). Null when none matches.
/// </summary>
public static MountInfoEntry? FindContaining(IReadOnlyList<MountInfoEntry> mounts, string fullPath)
{
ArgumentNullException.ThrowIfNull(mounts);
ArgumentNullException.ThrowIfNull(fullPath);
var path = fullPath.Length > 1 ? fullPath.TrimEnd('/') : fullPath;
MountInfoEntry? best = null;
var bestLength = -1;
foreach (var mount in mounts)
{
var point = mount.MountPoint.Length > 1 ? mount.MountPoint.TrimEnd('/') : mount.MountPoint;
var contains = point == "/"
|| string.Equals(path, point, StringComparison.Ordinal)
|| path.StartsWith(point + "/", StringComparison.Ordinal);
if (contains && point.Length >= bestLength)
{
best = mount;
bestLength = point.Length;
}
}
return best;
}
/// <summary>The content of <c>/proc/self/mountinfo</c> on Linux; null elsewhere or when it cannot be read.</summary>
public static string? ReadProcSelf()
{
if (!OperatingSystem.IsLinux())
{
return null;
}
try
{
return File.Exists(MountInfoPath) ? File.ReadAllText(MountInfoPath) : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
+58
View File
@@ -27,6 +27,21 @@ public sealed record SafeWriteOptions
/// <summary>Bytes written so far.</summary>
public IProgress<long>? Progress { get; init; }
/// <summary>
/// The root folder must already exist: <see cref="ExportRootMissingException"/> before anything is created (spec §4.10
/// «La radice di una destinazione non si crea mai»: a missing disk or share must not become a local folder).
/// Subfolders are still created. The root could vanish between the check and the creation of a subfolder: on Windows
/// a missing drive or share throws anyway, and in Docker a mount cannot vanish inside a running container.
/// </summary>
public bool RequireExistingRoot { get; init; }
/// <summary>
/// After the flush, read the temporary file back from the disk and compare its SHA-256 with the one computed while
/// writing, before the final name is decided (copies to external disks, spec §4.10). On a mismatch the temporary file
/// is removed and an <see cref="IOException"/> says so.
/// </summary>
public bool VerifyFromDisk { get; init; }
}
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
@@ -47,6 +62,24 @@ public sealed class FileTooLargeException : IOException
}
}
/// <summary>The root folder of a write with <see cref="SafeWriteOptions.RequireExistingRoot"/> does not exist; nothing was created.</summary>
public sealed class ExportRootMissingException : DirectoryNotFoundException
{
public ExportRootMissingException()
{
}
public ExportRootMissingException(string message)
: base(message)
{
}
public ExportRootMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary>
/// Writes library files safely (spec §6.5 point 4, rule 12):
/// <list type="number">
@@ -136,6 +169,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
options ??= new SafeWriteOptions();
var root = Path.GetFullPath(rootFolder);
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
if (options.RequireExistingRoot && !Directory.Exists(root))
{
throw new ExportRootMissingException($"La cartella {root} non c'è: Febe non la crea, perché un disco o una condivisione assente non deve diventare una cartella locale.");
}
Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
using var reservation = ReserveTemporaryFile(tempPath);
@@ -144,6 +182,10 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
{
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
if (options.VerifyFromDisk)
{
await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false);
}
var desired = await decide(digest, ct).ConfigureAwait(false);
if (desired is null)
@@ -247,6 +289,22 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
}
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
{
string onDisk;
await using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
onDisk = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
if (!string.Equals(onDisk, digest.Sha256, StringComparison.Ordinal))
{
TryDelete(tempPath); // our own temporary file: the caller's finally would remove it too
throw new IOException("La copia scritta sul disco non corrisponde: il disco potrebbe avere problemi.");
}
}
/// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary>
private static List<string> Segments(string relativePath)
{