Files
Febe/tests/Febe.Tests/Export/Support/ExportTestBed.cs
T
Alby96andClaude Opus 5.5 309f4d0402 E5: il giro non si ripete a vuoto e le copie automatiche cedono davvero
Il passaggio che segue la ripresa di un giro non rifà il lavoro di
recupero (prova delle cartelle in pausa, ripresa dei lavori fermati da
un errore): un lavoro che si ferma di nuovo aspetta il giro dopo invece
di essere ripreso all'infinito senza dormire. Il giro misura lo spazio
per il lavoro automatico che riprenderebbe, non per una pausa di Alberto,
così una pausa per spazio non va e viene con un evento nuovo ogni volta.
«Annulla» tiene lontane le partenze automatiche finché il lavoro è
annullato; «Esporta questo account» spento ferma subito la copia
automatica; «Cerca i video fermi» chiede di fermarsi a una copia
automatica partita dopo di lei; un file che manca sul disco non crea
più un lavoro automatico a ogni passaggio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:42:27 +01:00

578 lines
21 KiB
C#

using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Export.Support;
/// <summary>
/// A real library (database, account folders, files saved as the collection pipeline saves them) in a temporary
/// folder, two accounts, a real destination folder «usb» next to it and the export service with fakes for the disk,
/// the engine session and the mount table (tappa E2, WP5). Nothing outside the temporary folder is ever touched.
/// </summary>
internal sealed class ExportTestBed : IAsyncDisposable
{
private ExportTestBed(TempFolder temp, TestLibrary library, ExportEnvironment env, Account marta, Account luca, FakeExportDisk disk, FakeSessionState session, LongWorkGate gate)
{
Temp = temp;
Library = library;
Environment = env;
Service = new ExportService(env);
Marta = marta;
Luca = luca;
Disk = disk;
Session = session;
Gate = gate;
}
public TempFolder Temp { get; }
public TestLibrary Library { get; }
public FebeDatabase Db => Library.Db;
public ManualClock Clock => Library.Clock;
public ExportEnvironment Environment { get; }
public ExportService Service { get; }
public Account Marta { get; }
public Account Luca { get; }
public FakeExportDisk Disk { get; }
public FakeSessionState Session { get; }
public LongWorkGate Gate { get; }
/// <summary>The automatic export's signal of this bed: its journal lines and its destinations raise it.</summary>
public AutoExportSignal Signal => Library.AutoExport;
/// <summary>The folder of the general destination (created, empty).</summary>
public string Usb => Temp.Combine("usb");
/// <summary>
/// A new bed. <paramref name="configure"/> changes the environment (a file system seam, a Docker root…) before the
/// service is built.
/// </summary>
public static async Task<ExportTestBed> CreateAsync(Func<ExportEnvironment, ExportEnvironment>? configure = null)
{
var temp = new TempFolder("export");
var library = await TestLibrary.CreateAsync(temp);
var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
Directory.CreateDirectory(temp.Combine("usb"));
var disk = new FakeExportDisk();
var session = new FakeSessionState();
var gate = new LongWorkGate();
var env = new ExportEnvironment
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() },
Disk = disk,
Session = session,
Gate = gate,
AutoSignal = library.AutoExport,
};
return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate);
}
/// <summary>The general folder at <see cref="Usb"/> (or another folder), every type unless told.</summary>
public async Task<ExportDestination> GeneralAsync(ContentTypes types = ContentTypes.All, string? folder = null, string? scheme = null, CancellationToken ct = default) =>
(await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, folder ?? Usb, "Disco USB", types, scheme, null, null), ct)).Destination;
/// <summary>The own folder of an account, created under the temporary folder.</summary>
public async Task<ExportDestination> OwnAsync(Account account, string name, ContentTypes types = ContentTypes.All, CancellationToken ct = default)
{
var folder = Temp.Combine(name);
Directory.CreateDirectory(folder);
return (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.Account, account.Id, folder, null, types, null, null, null), ct)).Destination;
}
/// <summary>A post of the account with small photos (distinct scenes give distinct bytes; the same scene the same bytes).</summary>
public Task<EntryWithMedia> PostAsync(Account account, string code, params int[] scenes) =>
Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [.. scenes.Select((s, i) => Photo(i + 1, s))]);
/// <summary>A small photo (fast to encode).</summary>
public static TestFile Photo(int position, int scene) => TestFile.Photo(position, scene, 96, 120);
/// <summary>«Copia in…» and waits for the job to end.</summary>
public async Task<ExportStart> CopyAsync(ExportJobRequest request, CancellationToken ct = default)
{
var start = await Service.StartAsync(request, ct);
await Service.WaitAsync(ct);
return start;
}
/// <summary>«Copia in…» of every file of an account.</summary>
public Task<ExportStart> CopyAccountAsync(Account account, bool copyAgain = false, CancellationToken ct = default) =>
CopyAsync(new ExportJobRequest(new ExportSelection.Account(account.Id), copyAgain), ct);
public async Task<IReadOnlyList<ExportItem>> ItemsAsync(long runId, CancellationToken ct = default) =>
await Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, Limit = 10_000 }, ct);
public async Task<ExportRun> RunAsync(long runId, CancellationToken ct = default) => (await Db.Exports.GetRunAsync(runId, ct))!;
/// <summary>Where a file of the account goes in the general folder «Come la libreria».</summary>
public string GeneralCopy(Account account, Media media) => Path.Combine(Usb, account.Username, LibraryLayout.ToPlatform(media.RelativePath!));
/// <summary>The library file.</summary>
public string LibraryFile(Account account, Media media) => Library.Layout.FullPath(account, media.RelativePath!);
public Task SetSamePostAsync(SamePostCopies value, CancellationToken ct = default) => (ExportSettings.Default with { SamePost = value }).SaveAsync(Db.Settings, ct);
public async ValueTask DisposeAsync()
{
await Service.DisposeAsync();
await Library.DisposeAsync();
Temp.Dispose();
}
}
/// <summary>A disk with settable free space and largest file (null: not measurable, no limit).</summary>
internal sealed class FakeExportDisk(long? free = null, long? max = null) : IExportDisk
{
public long? Free { get; set; } = free;
public long? Max { get; set; } = max;
public long? FreeBytes(string root) => Free;
public long? MaxFileBytes(string root) => Max;
}
/// <summary>An engine session that the test starts and ends.</summary>
internal sealed class FakeSessionState : IEngineSessionState
{
private volatile bool _inSession;
public bool InSession
{
get => _inSession;
set => _inSession = value;
}
}
/// <summary>A clock whose delays really pass a little (so a waiting loop does not spin) and move the time on.</summary>
internal sealed class WaitingClock(IClock inner) : IClock
{
private long _delays;
public DateTimeOffset Now => inner.Now;
public TimeZoneInfo LocalZone => inner.LocalZone;
/// <summary>How many delays were asked.</summary>
public long Delays => Interlocked.Read(ref _delays);
public async Task Delay(TimeSpan time, CancellationToken ct)
{
Interlocked.Increment(ref _delays);
await inner.Delay(time, ct);
await Task.Delay(5, ct);
}
}
/// <summary>
/// A clock whose delays end only when the test moves the time past them (<see cref="Advance"/>), shared by the worker
/// and the service in the loop tests of the automatic export (tappa E5). The time is the library's manual clock.
/// </summary>
internal sealed class GatedClock(ManualClock inner) : IClock
{
private readonly Lock _gate = new();
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _pending = [];
private long _asked;
public DateTimeOffset Now => inner.Now;
public TimeZoneInfo LocalZone => inner.LocalZone;
/// <summary>How many delays were asked so far.</summary>
public long Asked => Interlocked.Read(ref _asked);
/// <summary>When the delays waiting now end, earliest first.</summary>
public IReadOnlyList<DateTimeOffset> Pending
{
get
{
lock (_gate)
{
return [.. _pending.Select(p => p.Due).Order()];
}
}
}
public Task Delay(TimeSpan time, CancellationToken ct)
{
Interlocked.Increment(ref _asked);
if (time <= TimeSpan.Zero)
{
return Task.CompletedTask;
}
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var entry = (Now + time, done);
lock (_gate)
{
_pending.Add(entry);
}
ct.Register(() =>
{
lock (_gate)
{
_pending.Remove(entry);
}
done.TrySetCanceled(ct);
});
return done.Task;
}
/// <summary>Moves the time on and ends every delay that is due.</summary>
public void Advance(TimeSpan time)
{
List<TaskCompletionSource> due;
lock (_gate)
{
inner.Now += time;
due = [.. _pending.Where(p => p.Due <= inner.Now).Select(p => p.Done)];
_pending.RemoveAll(p => p.Due <= inner.Now);
}
foreach (var done in due)
{
done.TrySetResult();
}
}
/// <summary>Waits (real time, at most 30 s) until more than <paramref name="asked"/> delays were asked and one waits.</summary>
public async Task<DateTimeOffset> WaitForDelayAsync(long asked, CancellationToken ct)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (true)
{
if (Asked > asked && Pending is [var first, ..])
{
return first;
}
if (watch.Elapsed > TimeSpan.FromSeconds(30))
{
Assert.Fail("nessuna attesa sull'orologio");
}
await Task.Delay(5, ct);
}
}
}
/// <summary>
/// The file system of the copies, recording every file opened or hashed while an engine session is under way: the
/// automatic export never reads during a session (tappa E5, §15). Wraps another file system (the real one by default);
/// <c>watched</c> chooses the files that count (the library's, say).
/// </summary>
internal sealed class SessionRecordingFileSystem(IEngineSessionState session, IExportFileSystem? inner = null, Func<string, bool>? watched = null) : IExportFileSystem
{
private readonly IExportFileSystem _inner = inner ?? ExportFileSystem.Instance;
private int _violations;
/// <summary>Files opened or hashed during a session.</summary>
public int Violations => Volatile.Read(ref _violations);
public Stream OpenRead(string path)
{
Check(path);
return _inner.OpenRead(path);
}
public Stream OpenRandomAccess(string path)
{
Check(path);
return _inner.OpenRandomAccess(path);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct)
{
Check(path);
return _inner.ComputeSha256Async(path, ct);
}
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private void Check(string path)
{
if (session.InSession && (watched is null || watched(path)))
{
Interlocked.Increment(ref _violations);
}
}
}
/// <summary>A mount table given by the test, on any platform (the longest mount point that holds the path wins).</summary>
internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts
{
public ExportMount? FindContaining(string fullPath) =>
mounts.Where(m => ExportPaths.IsSameOrInside(fullPath, m.MountPoint)).OrderByDescending(m => ExportPaths.Trim(m.MountPoint).Length).FirstOrDefault();
public IReadOnlyList<ExportMount> All() => mounts;
}
/// <summary>The real file system, but the first read of a blocked file never ends until the job is cancelled.</summary>
internal sealed class GatedExportFileSystem(Func<string, bool> blocks) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
/// <summary>Set when a blocked file is opened.</summary>
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!blocks(path))
{
return stream;
}
Reached.TrySetResult();
return new BlockedStream(stream);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private sealed class BlockedStream(Stream inner) : ReadOnlyStream(inner)
{
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
return 0;
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
}
/// <summary>
/// The real file system, but reading a held file waits until <see cref="Release"/> (or until the job is cancelled), so
/// a test can look at a job while it runs.
/// </summary>
internal sealed class HeldExportFileSystem(Func<string, bool> holds) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Set when a held file is opened.</summary>
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Lets every held read go on.</summary>
public void Release() => _release.TrySetResult();
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!holds(path))
{
return stream;
}
Reached.TrySetResult();
return new HeldStream(stream, _release.Task);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
private sealed class HeldStream(Stream inner, Task release) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await release.WaitAsync(cancellationToken);
return await inner.ReadAsync(buffer, cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
inner.Dispose();
}
base.Dispose(disposing);
}
}
}
/// <summary>The real file system, but reading a chosen library file gives one byte changed (a failing disk or cable).</summary>
internal sealed class CorruptingExportFileSystem(Func<string, bool> corrupts) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
public Stream OpenRead(string path)
{
var stream = _inner.OpenRead(path);
if (!corrupts(path))
{
return stream;
}
using (stream)
{
using var copy = new MemoryStream();
stream.CopyTo(copy);
var bytes = copy.ToArray();
bytes[bytes.Length / 2] ^= 0x5A;
return new MemoryStream(bytes, writable: false);
}
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
}
/// <summary>
/// The real file system, but opening a chosen file throws an error that is not an <see cref="IOException"/> (a decoder
/// or conversion bug on one file): the run stops «interrotto» with the error. Counts the failures.
/// </summary>
internal sealed class FailingExportFileSystem(Func<string, bool> fails) : IExportFileSystem
{
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
private int _failures;
/// <summary>How many times a failing file was opened.</summary>
public int Failures => Volatile.Read(ref _failures);
public Stream OpenRead(string path)
{
if (fails(path))
{
Interlocked.Increment(ref _failures);
throw new InvalidDataException("guasto di prova");
}
return _inner.OpenRead(path);
}
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
public bool FileExists(string path) => _inner.FileExists(path);
public long? FileLength(string path) => _inner.FileLength(path);
}
/// <summary>A read-only wrapper stream.</summary>
internal abstract class ReadOnlyStream(Stream inner) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
inner.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>Every file of a folder tree (relative path → length and SHA-256): equal before and after means nothing was touched.</summary>
internal static class Fingerprint
{
/// <summary>The fingerprint; files whose name starts with <paramref name="skipPrefix"/> (the open database) are left out.</summary>
public static IReadOnlyDictionary<string, string> Of(string folder, string? skipPrefix = null)
{
var files = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (!Directory.Exists(folder))
{
return files;
}
foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
{
if (skipPrefix is not null && Path.GetFileName(file).StartsWith(skipPrefix, StringComparison.Ordinal))
{
continue;
}
var bytes = File.ReadAllBytes(file);
files[Path.GetRelativePath(folder, file).Replace('\\', '/')] = $"{bytes.Length}:{Convert.ToHexStringLower(SHA256.HashData(bytes))}";
}
return files;
}
public static void AreEqual(IReadOnlyDictionary<string, string> expected, IReadOnlyDictionary<string, string> actual, string because)
{
CollectionAssert.AreEqual(expected.Keys.ToList(), actual.Keys.ToList(), $"{because}: {string.Join(", ", actual.Keys)}");
foreach (var (path, print) in expected)
{
Assert.AreEqual(print, actual[path], $"{because}: {path}");
}
}
/// <summary>Temporary files of Febe (<c>.febe-*.part</c>: the probe and the writes) anywhere below the folder.</summary>
public static IReadOnlyList<string> Temporaries(string folder) =>
Directory.Exists(folder) ? Directory.GetFiles(folder, SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories) : [];
}