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>
380 lines
16 KiB
C#
380 lines
16 KiB
C#
using System.Buffers;
|
|
using System.Collections.Concurrent;
|
|
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 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>
|
|
public sealed class FileTooLargeException : IOException
|
|
{
|
|
public FileTooLargeException()
|
|
{
|
|
}
|
|
|
|
public FileTooLargeException(string message)
|
|
: base(message)
|
|
{
|
|
}
|
|
|
|
public FileTooLargeException(string message, Exception innerException)
|
|
: base(message, innerException)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <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">
|
|
/// <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>Temporary files this process is writing now: the clean-up of a previous run never touches them.</summary>
|
|
private static readonly ConcurrentDictionary<string, byte> LiveTemporaryFiles =
|
|
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
|
|
|
/// <summary>
|
|
/// Marks a temporary file this process is about to write: <see cref="CleanupTemporaryFiles"/> leaves it alone
|
|
/// until the returned handle is disposed. The clean-up of an interrupted run can still be going through a large
|
|
/// library while the first downloads of this run are written (on Linux a deleted open file would be lost).
|
|
/// </summary>
|
|
public static IDisposable ReserveTemporaryFile(string path)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
|
var key = Path.GetFullPath(path);
|
|
LiveTemporaryFiles[key] = 0;
|
|
return new TemporaryFileReservation(key);
|
|
}
|
|
|
|
/// <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);
|
|
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);
|
|
|
|
try
|
|
{
|
|
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)
|
|
{
|
|
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>), except
|
|
/// those this process is writing (<see cref="ReserveTemporaryFile"/>). 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 (LiveTemporaryFiles.ContainsKey(Path.GetFullPath(file)))
|
|
{
|
|
continue; // being written by this process right now
|
|
}
|
|
|
|
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>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)
|
|
{
|
|
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 sealed class TemporaryFileReservation(string key) : IDisposable
|
|
{
|
|
public void Dispose() => LiveTemporaryFiles.TryRemove(key, out _);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|