using System.Buffers;
using System.Globalization;
using System.Security.Cryptography;
namespace Febe.Core.Library;
/// Size and SHA-256 of a file written by .
public readonly record struct FileDigest(long Bytes, string Sha256);
/// A file safely written to its final name.
/// Path relative to the root folder, '/' separated (may differ from the one asked: never overwrites).
/// Full path on disk.
/// Size.
/// Lowercase hex SHA-256, computed while writing.
/// The modification time was set as asked.
public sealed record SavedFile(string RelativePath, string FullPath, long Bytes, string Sha256, bool LastWriteTimeSet);
/// Options of a safe write.
public sealed record SafeWriteOptions
{
/// Set the file modification time to this instant (publication time, spec §4.7). Null leaves it.
public DateTimeOffset? LastWriteTime { get; init; }
/// Abort with beyond this size (e.g. «Salta i video oltre»).
public long? MaxBytes { get; init; }
/// Bytes written so far.
public IProgress? Progress { get; init; }
}
/// The content exceeded ; nothing was kept.
public sealed class FileTooLargeException : IOException
{
public FileTooLargeException()
{
}
public FileTooLargeException(string message)
: base(message)
{
}
public FileTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
///
/// Writes library files safely (spec §6.5 point 4, rule 12):
///
/// - the content goes to a temporary name (.febe-*.part) in the destination folder;
/// - SHA-256 is computed while writing, then the data is flushed to disk;
/// - the file is renamed to its final name; an existing file is never overwritten — a free name
/// («nome (2).jpg») is chosen instead;
/// - 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.
///
///
public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathLength)
{
/// Prefix of temporary files.
public const string TempPrefix = ".febe-";
/// Suffix of temporary files.
public const string TempSuffix = ".part";
private const int BufferSize = 128 * 1024;
private const int MaxNameAttempts = 10_000;
/// Serializes «is the name free? then rename» across all writers of the process.
private static readonly Lock MoveGate = new();
/// Writes to inside .
public Task 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);
}
///
/// Writes and decides the final name only after hashing (e.g. profile pictures, named after
/// their SHA-256). The temporary file is written in (relative to the root, '/'
/// separated; use the destination folder when known).
///
public async Task SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func relativePathFor,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(relativePathFor);
var saved = await SaveAsync(source, rootFolder, tempDirectory, (d, _) => ValueTask.FromResult(relativePathFor(d)), options, ct)
.ConfigureAwait(false);
return saved!;
}
///
/// Writes to a temporary file, then asks — knowing size and
/// SHA-256 — for the final relative path. When 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.
///
public async Task SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func> 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
}
}
///
/// Removes temporary files left by an interrupted process (never library files: only .febe-*.part).
/// Returns how many were removed.
///
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;
}
/// True for a temporary file name of the safe writer.
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 WriteTempAsync(Stream source, string tempPath, SafeWriteOptions options, CancellationToken ct)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = ArrayPool.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.Shared.Return(buffer);
}
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
}
/// Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.
private static List 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;
}
}