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; /// /// 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. /// 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; } /// The folder of the general destination (created, empty). public string Usb => Temp.Combine("usb"); /// /// A new bed. changes the environment (a file system seam, a Docker root…) before the /// service is built. /// public static async Task CreateAsync(Func? 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, }; return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate); } /// The general folder at (or another folder), every type unless told. public async Task 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; /// The own folder of an account, created under the temporary folder. public async Task 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; } /// A post of the account with small photos (distinct scenes give distinct bytes; the same scene the same bytes). public Task 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))]); /// A small photo (fast to encode). public static TestFile Photo(int position, int scene) => TestFile.Photo(position, scene, 96, 120); /// «Copia in…» and waits for the job to end. public async Task CopyAsync(ExportJobRequest request, CancellationToken ct = default) { var start = await Service.StartAsync(request, ct); await Service.WaitAsync(ct); return start; } /// «Copia in…» of every file of an account. public Task CopyAccountAsync(Account account, bool copyAgain = false, CancellationToken ct = default) => CopyAsync(new ExportJobRequest(new ExportSelection.Account(account.Id), copyAgain), ct); public async Task> ItemsAsync(long runId, CancellationToken ct = default) => await Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, Limit = 10_000 }, ct); public async Task RunAsync(long runId, CancellationToken ct = default) => (await Db.Exports.GetRunAsync(runId, ct))!; /// Where a file of the account goes in the general folder «Come la libreria». public string GeneralCopy(Account account, Media media) => Path.Combine(Usb, account.Username, LibraryLayout.ToPlatform(media.RelativePath!)); /// The library file. 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(); } } /// A disk with settable free space and largest file (null: not measurable, no limit). 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; } /// An engine session that the test starts and ends. internal sealed class FakeSessionState : IEngineSessionState { private volatile bool _inSession; public bool InSession { get => _inSession; set => _inSession = value; } } /// A clock whose delays really pass a little (so a waiting loop does not spin) and move the time on. internal sealed class WaitingClock(IClock inner) : IClock { private long _delays; public DateTimeOffset Now => inner.Now; public TimeZoneInfo LocalZone => inner.LocalZone; /// How many delays were asked. 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); } } /// A mount table given by the test, on any platform (the longest mount point that holds the path wins). 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 All() => mounts; } /// The real file system, but the first read of a blocked file never ends until the job is cancelled. internal sealed class GatedExportFileSystem(Func blocks) : IExportFileSystem { private readonly IExportFileSystem _inner = ExportFileSystem.Instance; /// Set when a blocked file is opened. 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 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 ReadAsync(Memory 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(); } } /// /// The real file system, but reading a held file waits until (or until the job is cancelled), so /// a test can look at a job while it runs. /// internal sealed class HeldExportFileSystem(Func holds) : IExportFileSystem { private readonly IExportFileSystem _inner = ExportFileSystem.Instance; private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); /// Set when a held file is opened. public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); /// Lets every held read go on. 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 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 ReadAsync(Memory 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); } } } /// The real file system, but reading a chosen library file gives one byte changed (a failing disk or cable). internal sealed class CorruptingExportFileSystem(Func 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 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); } /// A read-only wrapper stream. 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); } } /// Every file of a folder tree (relative path → length and SHA-256): equal before and after means nothing was touched. internal static class Fingerprint { /// The fingerprint; files whose name starts with (the open database) are left out. public static IReadOnlyDictionary Of(string folder, string? skipPrefix = null) { var files = new SortedDictionary(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 expected, IReadOnlyDictionary 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}"); } } /// Temporary files of Febe (.febe-*.part: the probe and the writes) anywhere below the folder. public static IReadOnlyList Temporaries(string folder) => Directory.Exists(folder) ? Directory.GetFiles(folder, SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories) : []; }