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

+8
View File
@@ -182,6 +182,7 @@ public sealed class FebeApp : IAsyncDisposable
// The same services as a normal start, on the empty temporary database, so that every endpoint can be built;
// the configuration gate answers 503 before any of them runs.
var longWork = new LongWorkGate();
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
@@ -190,9 +191,11 @@ public sealed class FebeApp : IAsyncDisposable
Clock = Clock,
Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")),
DataFolder = data.Root,
Gate = longWork,
});
await StartWebAsync(hooks, services =>
{
services.AddSingleton(longWork);
services.AddSingleton<IFebeStorage>(Database);
services.AddSingleton(library);
services.AddSingleton<IClock>(Clock);
@@ -236,6 +239,9 @@ public sealed class FebeApp : IAsyncDisposable
var library = new FebeLibrary(Database, data, layout, Clock, hashes);
var staging = Path.Combine(data.Root, "temporanei");
// One gate for import, copies to external folders and rebuild: they never run together (spec §4.10).
var longWork = new LongWorkGate();
// Import (spec §9). Docker: sources under /importa, read-only, over the fixed library; what was running when
// Febe stopped becomes «interrotto». Windows: the web layer's ImportHub builds the service over the library
// and builds it again when the library folder changes in Impostazioni (any source folder, native picker).
@@ -255,6 +261,7 @@ public sealed class FebeApp : IAsyncDisposable
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot),
DataFolder = data.Root,
Gate = longWork,
});
LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false));
}
@@ -321,6 +328,7 @@ public sealed class FebeApp : IAsyncDisposable
await StartWebAsync(hooks, s =>
{
s.AddSingleton(longWork);
s.AddSingleton<IFebeStorage>(Database);
s.AddSingleton(library);
s.AddSingleton<IClock>(Clock);
+106
View File
@@ -0,0 +1,106 @@
using System.Diagnostics.CodeAnalysis;
namespace Febe.Core.Abstractions;
/// <summary>The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»).</summary>
public enum LongWorkKind
{
/// <summary>An import job: analysis or copy (spec §9).</summary>
Import,
/// <summary>A job of copies to external folders (spec §4.10).</summary>
Export,
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
Rebuild,
}
/// <summary>
/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole
/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing
/// it twice releases nothing more.
/// </summary>
public sealed class LongWorkGate
{
private readonly Lock _lock = new();
private Lease? _holder;
/// <summary>Who holds the gate, or null when it is free.</summary>
public LongWorkKind? Busy
{
get
{
lock (_lock)
{
return _holder?.Kind;
}
}
}
/// <summary>
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
/// kind, the same one included) holds it.
/// </summary>
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
{
lock (_lock)
{
if (_holder is { } holder)
{
lease = null;
busyWith = holder.Kind;
return false;
}
var taken = new Lease(this, kind);
_holder = taken;
lease = taken;
busyWith = null;
return true;
}
}
/// <summary>The Italian answer when <paramref name="wanted"/> cannot start because <paramref name="busy"/> is running.</summary>
public static string BusyMessage(LongWorkKind wanted, LongWorkKind busy) => (wanted, busy) switch
{
(LongWorkKind.Import, LongWorkKind.Import) => "C'è già un'importazione al lavoro: aspetta che finisca o interrompila.",
(LongWorkKind.Export, LongWorkKind.Export) => "C'è già una copia al lavoro: aspetta che finisca o interrompila.",
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
};
private static string Verb(LongWorkKind kind) => kind switch
{
LongWorkKind.Import => "importa",
LongWorkKind.Export => "copia",
_ => "ricostruisci",
};
private void Release(Lease lease)
{
lock (_lock)
{
if (ReferenceEquals(_holder, lease))
{
_holder = null;
}
}
}
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
{
private int _disposed;
public LongWorkKind Kind { get; } = kind;
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
gate.Release(this);
}
}
}
}
@@ -0,0 +1,29 @@
using Febe.Core.Engine;
namespace Febe.Core.Export;
/// <summary>Whether the engine is in a session now: copies never run during one (spec §4.10, decision D11 of tappa E2).</summary>
public interface IEngineSessionState
{
bool InSession { get; }
}
/// <summary>No engine (tests, a start with problems): never in a session.</summary>
public sealed class NoEngineSession : IEngineSessionState
{
public static readonly NoEngineSession Instance = new();
private NoEngineSession()
{
}
public bool InSession => false;
}
/// <summary>The session of the running engine.</summary>
public sealed class RuntimeSessionState(EngineRuntime runtime) : IEngineSessionState
{
private readonly EngineRuntime _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
public bool InSession => _runtime.CurrentSession is not null;
}
+31
View File
@@ -0,0 +1,31 @@
using Febe.Core.Domain;
namespace Febe.Core.Export;
/// <summary>«Esporta questo account» (spec §4.10).</summary>
public static class ExportAccounts
{
/// <summary>On when Alberto never chose: decision of Alberto, 27 November 2026 (D1 of tappa E2).</summary>
public const bool DefaultEnabled = true;
/// <summary>The switch of an account from its stored choice (null: none recorded).</summary>
public static bool IsEnabled(bool? stored) => stored ?? DefaultEnabled;
}
/// <summary>
/// The effective destination of an account (D2): its own folder in use, otherwise the general folder in use, otherwise
/// none; with the switch «Esporta questo account».
/// </summary>
public sealed record EffectiveDestination(long AccountId, ExportDestination? Destination, bool Enabled)
{
/// <summary>The account's own folder.</summary>
public bool IsOwn => Destination?.Scope == ExportScope.Account;
public bool HasDestination => Destination is not null;
/// <summary>The switch is on and there is a destination: files of the account may be copied (D3).</summary>
public bool Exports => Enabled && Destination is not null;
/// <summary>The account's files of this content type are copied (D3, D4).</summary>
public bool Wants(ContentTypes type) => Exports && (Destination!.ContentTypes & type) != ContentTypes.None;
}
+672
View File
@@ -0,0 +1,672 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// One export job towards one destination (spec §4.10 «Come si copia»; decisions D11, D12, D16, D17 of tappa E2):
/// <list type="bullet">
/// <item>before each group of files (at most <see cref="ExportEnvironment.GroupFiles"/> files, or until
/// <see cref="ExportEnvironment.GroupBytes"/> bytes are reached) the destination is checked with a probe file; a failed
/// check pauses the destination and the job, never the red strip;</item>
/// <item>each file is written to a <c>.part</c> in its final folder, hashed while writing, read back from the disk and
/// compared, compared with the library's SHA-256, then renamed to a free name: nothing is ever overwritten, and no
/// other file of the destination is deleted or moved;</item>
/// <item>a file already at the planned path with the same SHA-256 is adopted, not written again;</item>
/// <item>«Tolto» and «Superato» are never copied again by themselves, only with «Copia di nuovo»;</item>
/// <item>nothing is copied during an engine session: the job waits;</item>
/// <item>resumable: every file has its state, and the target path is recorded before its <c>.part</c> exists.</item>
/// </list>
/// </summary>
public sealed class ExportCopier(ExportEnvironment env)
{
private const int PageSize = 500;
private const int MaxSiblings = 1000;
private const int MaxPath = WindowsFileNames.MaxPathLength;
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <summary>
/// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation
/// the job becomes «interrotto» and <see cref="OperationCanceledException"/> is thrown.
/// </summary>
/// <exception cref="KeyNotFoundException">No such job.</exception>
/// <exception cref="InvalidOperationException">The job already ended.</exception>
public async Task<ExportRun> CopyAsync(long runId, IProgress<ExportProgress>? progress = null, CancellationToken ct = default)
{
var store = _env.Storage.Exports;
var none = CancellationToken.None;
var run = await store.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
if (run.State is not (ExportRunState.Running or ExportRunState.Interrupted or ExportRunState.Paused))
{
throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere.");
}
var destination = await store.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false);
if (destination is null || destination.IsRetired)
{
run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = ExportText.RetiredDestination };
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
return run;
}
run = run with { State = ExportRunState.Running, LastError = null };
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
var x = new RunContext(run, destination, progress);
try
{
x.Report(_env, ExportPhase.Preparing, null);
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
var layout = _env.Layout();
var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false);
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
x.Naming = library.Naming;
x.SetFileTime = library.SetFileTimeToPublication;
x.OneOnly = settings.SamePost == SamePostCopies.OneOnly;
x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false);
x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false);
var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false);
x.FilesTotal = summary.Total;
x.FilesDone = summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending);
x.ByState = new Dictionary<ExportItemState, int>(summary.ByState);
x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false);
var groupFiles = 0;
long groupBytes = 0;
long after = 0;
while (true)
{
var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
after = page[^1].Id;
foreach (var item in page)
{
ct.ThrowIfCancellationRequested();
if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
{
return await PauseAsync(x, problem).ConfigureAwait(false);
}
await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false);
var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false);
if (result.Pause is { } pause)
{
return await PauseAsync(x, pause).ConfigureAwait(false);
}
x.FilesDone++;
x.BytesDone += result.Bytes;
x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1);
x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1;
groupFiles++;
groupBytes += result.Bytes;
if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes)
{
groupFiles = 0;
groupBytes = 0;
}
x.Report(_env, ExportPhase.Copying, result.Path);
}
}
var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false);
run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null };
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
await _env.Storage.Events.AppendAsync(
new EventRecord
{
At = _env.Clock.Now,
Code = "esportazione-completata",
Message = ExportText.CompletionMessage(final, x.Destination),
Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success,
AccountId = x.Destination.AccountId,
},
none).ConfigureAwait(false);
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
x.ByState = new Dictionary<ExportItemState, int>(final.ByState);
x.Report(_env, ExportPhase.Finished, null);
return run;
}
catch (Exception ex)
{
var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested;
run = run with { State = ExportRunState.Interrupted, LastError = cancelled ? null : ExportText.ErrorText(ex) };
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
throw;
}
}
/// <summary>
/// Checks a destination before a group of copies: the mount rule in Docker, then the folder check with its probe
/// file and the identity test (WP1.3). Returns why it cannot be written, or null; a success clears its pause.
/// </summary>
internal async Task<string?> CheckDestinationAsync(ExportDestination destination, CancellationToken ct)
{
if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mount)
{
return mount;
}
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
var verdict = await _env.CreateFolderCheck().CheckAsync(destination.RootPath, context, ct).ConfigureAwait(false);
return verdict.Problem switch
{
null => null,
{ Kind: ExportFolderProblemKind.Missing or ExportFolderProblemKind.NotResponding } =>
$"{ExportDestinations.Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati, poi riprendi.",
{ } problem => problem.Message,
};
}
private async Task<string?> ProbeAsync(RunContext x, CancellationToken ct)
{
var problem = await CheckDestinationAsync(x.Destination, ct).ConfigureAwait(false);
if (problem is null && (x.Destination.PausedAt is not null || x.Destination.LastError is not null))
{
x.Destination = await ExportPause.ClearAsync(_env, x.Destination).ConfigureAwait(false);
}
return problem;
}
private async Task<ExportRun> PauseAsync(RunContext x, string message)
{
x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false);
var run = x.Run with { State = ExportRunState.Paused, LastError = message };
await _env.Storage.Exports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false);
x.Report(_env, ExportPhase.Finished, null);
return run;
}
private async Task WaitOutsideSessionAsync(RunContext x, CancellationToken ct)
{
while (_env.Session.InSession)
{
x.Report(_env, ExportPhase.WaitingForSession, null);
await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false);
}
}
private async Task<long> PendingBytesAsync(long runId, CancellationToken ct)
{
long total = 0;
long after = 0;
while (true)
{
var page = await _env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
return total;
}
after = page[^1].Id;
foreach (var item in page)
{
if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes })
{
total += bytes;
}
}
}
}
private async Task<ItemResult> ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct)
{
var storage = _env.Storage;
var exports = storage.Exports;
var none = CancellationToken.None;
var destination = x.Destination;
var root = destination.RootPath;
// a. No longer in the library.
if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account)
{
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false);
}
var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null;
var entry = media is null ? null : await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
var source = media is { Sha256.Length: 64, RelativePath: not null } && EntryStateRules.IsPresent(media.State) && entry?.AccountId == accountId
? _env.ResolveSourcePath(account, media)
: null;
if (source is null || media is null || entry is null)
{
return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false);
}
// The account may have been switched off, or got another folder, or the destination stopped taking this type
// since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy.
var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false);
if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id
|| !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight)))
{
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false);
}
// b. The file may have changed since the job was planned.
var sha = media.Sha256!;
if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal))
{
item = item with { SourceSha256 = sha };
}
var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0;
var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null);
var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight);
// c. Already copied, removed, superseded, copied for another account, or failed before.
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
ExportCopy? failed = null;
if (current is { State: ExportCopyState.Copied })
{
if (current.RelativePath is { } copied && Exists(root, copied))
{
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false);
}
// The file is not there: «Tolto», unless the whole destination went away meanwhile.
if (!Directory.Exists(root) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone)
{
return ItemResult.Paused(gone);
}
await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false);
if (!x.CopyAgain)
{
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false);
}
}
else if (current is { State: ExportCopyState.Failed })
{
failed = current;
}
else if (!x.CopyAgain)
{
var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false);
if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded })
{
var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded;
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false);
}
if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced)
{
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false);
}
}
if (x.OneOnly
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { AccountId: { } other, RelativePath: { } elsewherePath } elsewhere
&& other != accountId
&& await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where
&& Exists(where.RootPath, elsewherePath))
{
return await FinishAsync(
item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null },
bytes,
null).ConfigureAwait(false);
}
return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false);
}
/// <summary>d. and e.: the path, the limits of the disk, adoption, the safe write and its record.</summary>
private async Task<ItemResult> WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct)
{
var exports = _env.Storage.Exports;
var none = CancellationToken.None;
var destination = x.Destination;
var root = destination.RootPath;
string planned;
try
{
planned = ExportPaths.RelativePathFor(
destination,
ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone),
MaxPath);
}
catch (PathTooLongException ex)
{
return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false);
}
if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max)
{
return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false);
}
if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin)
{
return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes));
}
// Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …).
foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath))
{
var full = LibraryLayout.FullPath(root, candidate);
if (_env.FileSystem.FileLength(full) != file.Bytes
|| !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal))
{
continue;
}
var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false);
if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal)))
{
return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false);
}
if (holder.Identity == file.Identity)
{
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false);
}
// The same bytes, recorded for another copy: not ours to take.
}
// A path recorded for another copy whose file is gone is free again («Tolto»).
await ReleaseStalePathAsync(destination, planned, file.Identity, ct).ConfigureAwait(false);
// The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items).
item = item with { RelativePath = planned };
await exports.UpdateItemsAsync([item], none).ConfigureAwait(false);
SavedFile saved;
try
{
var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty;
await using var content = _env.FileSystem.OpenRead(file.Source);
saved = (await new SafeFileWriter(MaxPath).SaveAsync(
content,
root,
directory,
(digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal)
? ValueTask.FromResult<string?>(planned)
: throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."),
new SafeWriteOptions
{
RequireExistingRoot = true,
VerifyFromDisk = true,
LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null,
},
ct).ConfigureAwait(false))!;
}
catch (ContentChangedException ex)
{
return await FailAsync(item, file, failed, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
if (IsDiskFull(ex))
{
return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left
? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes)
: ExportText.DiskFull(destination));
}
if ((ex is ExportRootMissingException or DirectoryNotFoundException || !Directory.Exists(root)) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
{
return ItemResult.Paused(problem); // the item stays pending
}
return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false);
}
string? taken = null;
if (!string.Equals(saved.RelativePath, planned, StringComparison.Ordinal))
{
taken = ExportText.Notes.NameTaken;
await ReleaseStalePathAsync(destination, saved.RelativePath, file.Identity, ct).ConfigureAwait(false);
}
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
}
/// <summary>Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names.</summary>
private IEnumerable<string> AdoptionCandidates(string root, string planned, string? previous)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (seen.Add(planned) && Exists(root, planned))
{
yield return planned;
}
if (previous is null)
{
yield break;
}
for (var attempt = 1; attempt <= MaxSiblings; attempt++)
{
string name;
try
{
name = ExportPaths.NumberedName(root, previous, attempt, MaxPath);
}
catch (PathTooLongException)
{
yield break;
}
if (!Exists(root, name))
{
yield break; // the writer takes the first free name: nothing of ours after it
}
if (seen.Add(name))
{
yield return name;
}
}
}
/// <summary>A Copied or Superseded row of another copy on this path whose file is not there becomes «Tolto».</summary>
private async Task ReleaseStalePathAsync(ExportDestination destination, string path, ExportCopyIdentity identity, CancellationToken ct)
{
var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false);
if (held is not null && held.Identity != identity && !Exists(destination.RootPath, path))
{
await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
}
}
private async Task<ItemResult> RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note)
{
var exports = _env.Storage.Exports;
var none = CancellationToken.None;
var now = _env.Clock.Now;
ExportCopy copy;
try
{
if (failed is not null)
{
copy = failed with
{
State = ExportCopyState.Copied,
Origin = origin,
RelativePath = path,
Bytes = bytes,
CopySha256 = file.Sha256,
CopiedAt = now,
StateChangedAt = now,
LastError = null,
MediaId = file.Media.Id,
};
await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false);
}
else if (orphan is not null)
{
copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false);
}
else
{
copy = await exports.AddCopyAsync(
new ExportCopy
{
DestinationId = file.Identity.DestinationId,
AccountId = file.Identity.AccountId,
MediaId = file.Media.Id,
SourceSha256 = file.Sha256,
Variant = ExportVariant.Whole,
Format = ExportFormat.Original,
State = ExportCopyState.Copied,
Origin = origin,
RelativePath = path,
Bytes = bytes,
CopySha256 = file.Sha256,
CopiedAt = now,
},
none).ConfigureAwait(false);
}
}
catch (DuplicateRecordException)
{
// Taken meanwhile by another record. The file written stays where it is: nothing is ever removed.
return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false);
}
var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied;
return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false);
}
/// <summary>f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on.</summary>
private async Task<ItemResult> FailAsync(ExportItem item, FileContext file, ExportCopy? failed, string error, string? note)
{
var exports = _env.Storage.Exports;
var none = CancellationToken.None;
long? copyId = failed?.Id;
try
{
if (failed is not null)
{
await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false);
}
else
{
copyId = (await exports.AddCopyAsync(
new ExportCopy
{
DestinationId = file.Identity.DestinationId,
AccountId = file.Identity.AccountId,
MediaId = file.Media.Id,
SourceSha256 = file.Sha256,
Variant = ExportVariant.Whole,
Format = ExportFormat.Original,
State = ExportCopyState.Failed,
CopiedAt = _env.Clock.Now,
LastError = error,
},
none).ConfigureAwait(false)).Id;
}
}
catch (DuplicateRecordException)
{
// The identity got a current row meanwhile: that one tells the state.
}
return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false);
}
private async Task<ItemResult> FinishAsync(ExportItem item, long bytes, string? path)
{
await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false);
return new ItemResult(item.State, bytes, path, null);
}
private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct)
{
if (entry.Kind is not (EntryKind.Story or EntryKind.Highlight))
{
return (null, false);
}
var collections = await _env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false);
return (collections.FirstOrDefault()?.Title, collections.Count > 0);
}
private bool Exists(string root, string relativePath)
{
try
{
return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath));
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>«Disco pieno»: ERROR_DISK_FULL or ERROR_HANDLE_DISK_FULL on Windows, ENOSPC elsewhere.</summary>
internal static bool IsDiskFull(Exception ex) =>
ex is IOException io
&& (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28
|| io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase));
private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight);
/// <summary>What happened to an item; <see cref="Pause"/> stops the job with the destination paused.</summary>
private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause)
{
public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message);
}
private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress<ExportProgress>? progress)
{
private readonly Dictionary<long, ExportDestination?> _destinations = [];
public ExportRun Run { get; } = run;
public ExportDestination Destination { get; set; } = destination;
public LibraryNaming? Naming { get; set; }
public bool SetFileTime { get; set; } = true;
public bool OneOnly { get; set; }
public bool CopyAgain { get; set; }
public IReadOnlyDictionary<long, EffectiveDestination> Effective { get; set; } = new Dictionary<long, EffectiveDestination>();
public int FilesDone { get; set; }
public int FilesTotal { get; set; }
public long BytesDone { get; set; }
public long BytesTotal { get; set; }
public Dictionary<ExportItemState, int> ByState { get; set; } = [];
public async Task<ExportDestination?> DestinationAsync(IFebeStorage storage, long id, CancellationToken ct)
{
if (!_destinations.TryGetValue(id, out var row))
{
_destinations[id] = row = await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false);
}
return row;
}
public void Report(ExportEnvironment env, ExportPhase phase, string? current) =>
progress?.Report(new ExportProgress(
Run.Id,
phase,
FilesDone,
FilesTotal,
BytesDone,
Math.Max(BytesTotal, BytesDone),
current,
ExportDestinations.Label(Destination),
new Dictionary<ExportItemState, int>(ByState),
env.Clock.Now));
}
}
+387
View File
@@ -0,0 +1,387 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»).</summary>
/// <param name="Scope">General folder or own folder of an account.</param>
/// <param name="AccountId">The account of an own folder; null for the general folder.</param>
/// <param name="Path">The folder as chosen (Docker: relative to <c>/esporta</c>, or a full path inside it).</param>
/// <param name="Label">Name shown; null: the last segment of the folder.</param>
/// <param name="ContentTypes">At least one type.</param>
/// <param name="NamingScheme">General scheme; null: «Come la libreria».</param>
/// <param name="HighlightNamingScheme">Scheme of highlight collections; null: «Come la libreria».</param>
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
public sealed record DestinationSpec(
ExportScope Scope,
long? AccountId,
string Path,
string? Label,
ContentTypes ContentTypes,
string? NamingScheme,
string? HighlightNamingScheme,
string? ProfileNamingScheme,
bool Automatic = false,
bool OnlyNew = true);
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
/// <summary>A destination in use that now overlaps a protected folder (WP1.10 of tappa E2).</summary>
public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem);
/// <summary>What Impostazioni and the Dashboard show of a destination.</summary>
/// <param name="Destination">The stored row (paused or not).</param>
/// <param name="Reachable">The folder answered now (and, in Docker, sits on a usable mount).</param>
/// <param name="Problem">Why it is not reachable, or the error of its pause; null when fine.</param>
/// <param name="Counts">Copies per state, every state present.</param>
/// <param name="FreeBytes">Free space when reachable and measurable.</param>
public sealed record ExportDestinationStatus(
ExportDestination Destination,
bool Reachable,
string? Problem,
IReadOnlyDictionary<ExportCopyState, int> Counts,
long? FreeBytes);
/// <summary>
/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched
/// here except through <see cref="ExportFolderCheck"/> (its probe, only in the candidate folder).
/// </summary>
public sealed class ExportDestinations(ExportEnvironment env)
{
/// <summary>The answer to «Togli la cartella».</summary>
public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono.";
/// <summary>A destination with an unfinished job cannot be retired nor moved.</summary>
public const string UnfinishedRunText = "C'è un lavoro di copia non finito verso questa cartella: finiscilo o annullalo, poi cambia cartella.";
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <summary>The name shown for a destination: its label, or the last segment of its folder.</summary>
public static string Label(ExportDestination destination)
{
ArgumentNullException.ThrowIfNull(destination);
if (!string.IsNullOrWhiteSpace(destination.Label))
{
return destination.Label.Trim();
}
var trimmed = ExportPaths.Trim(destination.RootPath);
var name = System.IO.Path.GetFileName(trimmed);
return string.IsNullOrEmpty(name) ? trimmed : name;
}
/// <summary>The effective destination of an account (D2) with its switch (D1).</summary>
public async Task<EffectiveDestination> ResolveAsync(long accountId, CancellationToken ct)
{
var exports = _env.Storage.Exports;
var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false);
var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(accountId, ct).ConfigureAwait(false));
return new EffectiveDestination(accountId, destination, enabled);
}
/// <summary>The effective destination of every account, with one read of each table.</summary>
public async Task<IReadOnlyDictionary<long, EffectiveDestination>> ResolveAllAsync(CancellationToken ct)
{
var accounts = await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false);
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
var switches = await _env.Storage.Exports.ListAccountExportSwitchesAsync(ct).ConfigureAwait(false);
var general = destinations.FirstOrDefault(d => d.Scope == ExportScope.General);
var own = destinations.Where(d => d.Scope == ExportScope.Account && d.AccountId is not null).ToDictionary(d => d.AccountId!.Value);
return accounts.ToDictionary(
a => a.Id,
a => new EffectiveDestination(
a.Id,
own.GetValueOrDefault(a.Id) ?? general,
ExportAccounts.IsEnabled(switches.TryGetValue(a.Id, out var on) ? on : null)));
}
/// <summary>
/// Adds a destination after checking folder (WP1.3), content types and naming schemes.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be a destination.</exception>
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid (Italian message).</exception>
public async Task<DestinationSaveResult> CreateAsync(DestinationSpec spec, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(spec);
var account = await CheckScopeAsync(spec, ct).ConfigureAwait(false);
var warnings = ValidateSettings(spec);
if (spec.Scope == ExportScope.General && await _env.Storage.Exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false) is not null)
{
throw new ArgumentException("C'è già una cartella generale: cambiala invece di aggiungerne un'altra.", nameof(spec));
}
if (account is not null && await _env.Storage.Exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) is not null)
{
throw new ArgumentException(OwnFolderInUse(account), nameof(spec));
}
var full = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false);
var now = _env.Clock.Now;
var row = Build(spec, full, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
try
{
return new DestinationSaveResult(await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false), warnings);
}
catch (DuplicateRecordException)
{
throw new ArgumentException(
account is null ? "C'è già una cartella generale: cambiala invece di aggiungerne un'altra." : OwnFolderInUse(account),
nameof(spec));
}
}
/// <summary>
/// Changes a destination. The same folder updates the row; another folder retires it and adds a new row (the copies
/// stay with the retired one), refused while an unfinished job writes to it.
/// </summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="ExportFolderException">The new folder cannot be a destination.</exception>
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid.</exception>
/// <exception cref="InvalidOperationException">An unfinished job uses the old folder.</exception>
public async Task<DestinationSaveResult> UpdateAsync(long id, DestinationSpec spec, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(spec);
var exports = _env.Storage.Exports;
var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
if (stored.IsRetired)
{
throw new ArgumentException("Questa cartella è stata tolta: non si modifica più.", nameof(id));
}
if (stored.Scope != spec.Scope || stored.AccountId != spec.AccountId)
{
throw new ArgumentException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.", nameof(spec));
}
var warnings = ValidateSettings(spec);
var now = _env.Clock.Now;
string? full = null;
try
{
full = ExportRoots.Resolve(_env.Root, spec.Path);
}
catch (ExportFolderException)
{
// Not the same folder: the full check below gives the reason.
}
if (full is not null && ExportPaths.Same(full, stored.RootPath))
{
var since = !spec.Automatic ? null
: stored.Automatic ? stored.AutomaticSince
: spec.OnlyNew ? now : (DateTimeOffset?)null;
var updated = Build(spec, stored.RootPath, stored.CreatedAt) with
{
Id = stored.Id,
AutomaticSince = since,
PausedAt = stored.PausedAt,
LastError = stored.LastError,
};
await exports.UpdateDestinationAsync(updated, ct).ConfigureAwait(false);
return new DestinationSaveResult(updated, warnings);
}
if (stored.IsOrphan)
{
throw new ArgumentException("La cartella di un account rimosso non si cambia: toglila, oppure ridalla all'account quando torna.", nameof(spec));
}
await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false);
var newFolder = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false);
// Two transactions, as the store wants: the old folder is retired with its copies, then the new one is added.
await exports.RetireDestinationAsync(id, now, CancellationToken.None).ConfigureAwait(false);
var row = Build(spec, newFolder, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
return new DestinationSaveResult(await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false), warnings);
}
/// <summary>«Togli la cartella»: only the configuration goes; copies and files stay (<see cref="RetiredText"/>).</summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="InvalidOperationException">An unfinished job uses it.</exception>
public async Task RetireAsync(long id, CancellationToken ct)
{
var stored = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
if (stored.IsRetired)
{
return;
}
await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false);
await _env.Storage.Exports.RetireDestinationAsync(id, _env.Clock.Now, ct).ConfigureAwait(false);
}
/// <summary>«Esporta questo account».</summary>
/// <exception cref="KeyNotFoundException">No such account.</exception>
public async Task SetAccountEnabledAsync(long accountId, bool enabled, CancellationToken ct)
{
_ = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Account {accountId} non trovato.");
await _env.Storage.Exports.SetAccountExportEnabledAsync(accountId, enabled, ct).ConfigureAwait(false);
}
/// <summary>Checks a folder for the dialog, before saving (WP1.3).</summary>
public async Task<ExportFolderVerdict> CheckFolderAsync(string candidate, CancellationToken ct)
{
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false);
}
/// <summary>
/// Checks again every destination in use against the protected folders, with <paramref name="extraAccountFolders"/>
/// (an account folder about to be saved). Only overlaps are conflicts: an unreachable folder is checked anyway at the
/// start of its next group of copies.
/// </summary>
public Task<IReadOnlyList<ExportFolderConflict>> RecheckAsync(IReadOnlyList<string>? extraAccountFolders, CancellationToken ct) =>
RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct);
/// <summary>As <see cref="RecheckAsync"/>, with folders of any kind (a new library root is <see cref="ProtectedFolderKind.Library"/>).</summary>
public async Task<IReadOnlyList<ExportFolderConflict>> RecheckAgainstAsync(IReadOnlyList<ProtectedFolder>? extra, CancellationToken ct)
{
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
if (destinations.Count == 0)
{
return [];
}
var context = await _env.FolderContextAsync(extra, ct).ConfigureAwait(false);
var check = _env.CreateFolderCheck();
var verdicts = await Task.WhenAll(destinations.Select(async d => (Destination: d, Verdict: await check.CheckAsync(d.RootPath, context, ct).ConfigureAwait(false))))
.ConfigureAwait(false);
return verdicts
.Where(v => v.Verdict.Problem is { IsOverlap: true })
.Select(v => new ExportFolderConflict(v.Destination, v.Verdict.Problem!))
.ToList();
}
/// <summary>Whether a destination answers now, its pause, its copies and its free space.</summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
public async Task<ExportDestinationStatus> StatusAsync(long id, CancellationToken ct)
{
var destination = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
var counts = await _env.Storage.Exports.CountCopiesAsync(id, ct).ConfigureAwait(false);
if (destination.IsRetired)
{
return new ExportDestinationStatus(destination, false, "Questa cartella è stata tolta.", counts, null);
}
if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mountProblem)
{
return new ExportDestinationStatus(destination, false, mountProblem, counts, null);
}
bool reachable;
try
{
reachable = await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
reachable = false;
}
if (!reachable)
{
return new ExportDestinationStatus(
destination,
false,
$"{Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati.",
counts,
null);
}
long? free;
try
{
free = await Task.Run(() => _env.Disk.FreeBytes(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
free = null;
}
return new ExportDestinationStatus(destination, true, destination.PausedAt is not null ? destination.LastError : null, counts, free);
}
private async Task<Account?> CheckScopeAsync(DestinationSpec spec, CancellationToken ct)
{
if (spec.Scope == ExportScope.General)
{
return spec.AccountId is null
? null
: throw new ArgumentException("La cartella generale non è di un account.", nameof(spec));
}
if (spec.AccountId is not { } accountId)
{
throw new ArgumentException("Scegli l'account di questa cartella.", nameof(spec));
}
return await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false)
?? throw new ArgumentException("Questo account non c'è più.", nameof(spec));
}
/// <summary>Content types and naming schemes; returns the warnings of the schemes.</summary>
private static List<string> ValidateSettings(DestinationSpec spec)
{
if (spec.ContentTypes == ContentTypes.None || (spec.ContentTypes & ~ContentTypes.All) != ContentTypes.None)
{
throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec));
}
var errors = new List<string>();
var warnings = new List<string>();
void Check(string? text, NamingSchemeUse use)
{
if (Clean(text) is not { } scheme)
{
return;
}
var validation = NamingScheme.Validate(scheme, use);
errors.AddRange(validation.Errors.Select(e => NamingPreview.Prefix(use) + e));
warnings.AddRange(validation.Warnings.Select(w => NamingPreview.Prefix(use) + w));
}
Check(spec.NamingScheme, NamingSchemeUse.General);
Check(spec.HighlightNamingScheme, NamingSchemeUse.Highlight);
Check(spec.ProfileNamingScheme, NamingSchemeUse.ProfilePicture);
return errors.Count > 0 ? throw new ArgumentException(string.Join(" ", errors), nameof(spec)) : warnings;
}
private async Task<string> CheckedFolderAsync(string path, CancellationToken ct)
{
var verdict = await CheckFolderAsync(path, ct).ConfigureAwait(false);
return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath;
}
private async Task EnsureNoUnfinishedRunAsync(long destinationId, CancellationToken ct)
{
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
if (unfinished.Any(r => r.DestinationId == destinationId))
{
throw new InvalidOperationException(UnfinishedRunText);
}
}
private static ExportDestination Build(DestinationSpec spec, string root, DateTimeOffset createdAt) => new()
{
Scope = spec.Scope,
AccountId = spec.AccountId,
Label = Clean(spec.Label),
RootPath = root,
ContentTypes = spec.ContentTypes,
NamingScheme = Clean(spec.NamingScheme),
HighlightNamingScheme = Clean(spec.HighlightNamingScheme),
ProfileNamingScheme = Clean(spec.ProfileNamingScheme),
Automatic = spec.Automatic,
CreatedAt = createdAt,
};
private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
private static string OwnFolderInUse(Account account) => $"@{account.Username} ha già una cartella sua: cambiala invece di aggiungerne un'altra.";
}
+82
View File
@@ -0,0 +1,82 @@
using Febe.Core.Alerts;
namespace Febe.Core.Export;
/// <summary>Free space and the largest file a destination's disk accepts (a seam: tests give their own).</summary>
public interface IExportDisk
{
/// <summary>Bytes free for Febe on the disk of <paramref name="root"/>; null when it cannot be measured.</summary>
long? FreeBytes(string root);
/// <summary>The largest file the file system accepts (FAT32: 4 GB − 1); null when there is no known limit.</summary>
long? MaxFileBytes(string root);
}
/// <summary>Limits of the space check before each copy (spec §4.10 «Spazio»).</summary>
public static class ExportSpace
{
/// <summary>The margin left free after the next file (decision of Alberto, question Q6 of tappa E2): 64 MiB.</summary>
public const long Margin = 64L * 1024 * 1024;
/// <summary>The largest file on FAT32: 4 GiB − 1 byte.</summary>
public const long Fat32Limit = (4L * 1024 * 1024 * 1024) - 1;
private static readonly HashSet<string> FatTypes = new(StringComparer.OrdinalIgnoreCase) { "FAT32", "FAT", "vfat", "msdos", "fat" };
/// <summary>True for the names Windows (<c>DriveFormat</c>) and Linux (mount type) give to FAT file systems.</summary>
public static bool IsFat(string? fileSystem) => fileSystem is not null && FatTypes.Contains(fileSystem);
}
/// <summary>
/// The real disks: free space through <see cref="DriveFreeSpaceProbe"/> (a UNC share gives null: the Windows edition
/// registers its own measure), the FAT32 limit from the drive format on Windows and from the mount type on Linux.
/// </summary>
public sealed class SystemExportDisk(IExportMounts mounts) : IExportDisk
{
private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts));
public long? FreeBytes(string root)
{
if (string.IsNullOrWhiteSpace(root))
{
return null;
}
try
{
return new DriveFreeSpaceProbe().Measure(root)?.AvailableBytes;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
return null;
}
}
public long? MaxFileBytes(string root)
{
if (string.IsNullOrWhiteSpace(root))
{
return null;
}
try
{
string? type;
if (OperatingSystem.IsWindows())
{
var drive = Path.GetPathRoot(Path.GetFullPath(root));
type = string.IsNullOrEmpty(drive) || drive.StartsWith(@"\\", StringComparison.Ordinal) ? null : new DriveInfo(drive).DriveFormat;
}
else
{
type = _mounts.FindContaining(Path.GetFullPath(root))?.FileSystemType;
}
return ExportSpace.IsFat(type) ? ExportSpace.Fat32Limit : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException)
{
return null;
}
}
}
+144
View File
@@ -0,0 +1,144 @@
using System.Security.Cryptography;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// What the export needs from the rest of Febe (spec §4.10). Built once by the composition (the web layer's export
/// hub); the layout is a function because on Windows the library folder can change while Febe runs.
/// </summary>
public sealed record ExportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>The library folder and account folders now.</summary>
public required Func<LibraryLayout> Layout { get; init; }
/// <summary>The Data folder: a destination may not overlap it.</summary>
public required string DataFolder { get; init; }
public required IClock Clock { get; init; }
/// <summary>Docker <c>/importa</c>: a destination may not overlap it. Null on Windows.</summary>
public string? ImportRoot { get; init; }
/// <summary>Where destinations may be chosen (Docker: <c>/esporta</c>).</summary>
public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder;
/// <summary>
/// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's
/// <c>LibraryFileResolver</c>). Use <see cref="ResolveSourcePath"/>.
/// </summary>
public Func<Account, Media, string?>? ResolveSource { get; init; }
/// <summary>Reading and hashing files (library files and files found in a destination).</summary>
public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance;
/// <summary>Free space and the FAT32 limit of a destination.</summary>
public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo());
/// <summary>Copies never run during an engine session.</summary>
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
/// <summary>Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests).</summary>
public LongWorkGate? Gate { get; init; }
/// <summary>Time allowed to a check of a destination folder (a disconnected share must not block).</summary>
public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>How often a waiting job looks whether the engine session ended.</summary>
public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>A group of copies, checked with a probe before it starts: at most this many files…</summary>
public int GroupFiles { get; init; } = 100;
/// <summary>…or this many planned bytes, whichever comes first.</summary>
public long GroupBytes { get; init; } = 1L << 30;
/// <summary>The checker of destination folders of this environment.</summary>
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout);
/// <summary>The protected folders now (Data, library, account folders, <c>/importa</c>) and the extra ones.</summary>
public Task<ExportFolderContext> FolderContextAsync(IReadOnlyList<ProtectedFolder>? extra, CancellationToken ct) =>
ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct);
/// <summary>The full path of a library file present on disk, or null (<see cref="ResolveSource"/> or the layout).</summary>
public string? ResolveSourcePath(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(media);
if (ResolveSource is { } resolve)
{
return resolve(account, media);
}
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
{
return null;
}
try
{
var path = Layout().FullPath(account, media.RelativePath);
return FileSystem.FileExists(path) ? path : null;
}
catch (ArgumentException)
{
return null;
}
}
}
/// <summary>File operations of the export (a seam, like <c>IImportFileSystem</c>).</summary>
public interface IExportFileSystem
{
/// <summary>Opens a file for reading only.</summary>
Stream OpenRead(string path);
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
Task<string> ComputeSha256Async(string path, CancellationToken ct);
bool FileExists(string path);
/// <summary>Size of a file, or null when it is not there.</summary>
long? FileLength(string path);
}
/// <summary>The real file system.</summary>
public sealed class ExportFileSystem : IExportFileSystem
{
private const int BufferSize = 128 * 1024;
private ExportFileSystem()
{
}
public static ExportFileSystem Instance { get; } = new();
public Stream OpenRead(string path) =>
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
{
await using var stream = OpenRead(path);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
public bool FileExists(string path) => File.Exists(path);
public long? FileLength(string path)
{
try
{
var info = new FileInfo(path);
return info.Exists ? info.Length : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return null;
}
}
}
+389
View File
@@ -0,0 +1,389 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>Why a folder cannot be a destination (spec §4.10 «Cartelle rifiutate»).</summary>
public enum ExportFolderProblemKind
{
Empty,
NotFullyQualified,
OutsideExportRoot,
ExportRootItself,
ParentSegment,
NotMounted,
ReadOnlyMount,
Missing,
NotAFolder,
Link,
RootOfDisk,
PathTooLong,
InsideProtected,
ContainsProtected,
SameAsProtected,
ProbeFailed,
NotResponding,
}
/// <summary>A refused folder: the kind and the Italian message that says why and what to do.</summary>
public sealed record ExportFolderProblem(ExportFolderProblemKind Kind, string Message)
{
/// <summary>The folder overlaps Data, Libreria, an account folder or <c>/importa</c> (the conflicts of a re-check).</summary>
public bool IsOverlap => Kind is ExportFolderProblemKind.InsideProtected or ExportFolderProblemKind.ContainsProtected or ExportFolderProblemKind.SameAsProtected;
}
/// <summary>The outcome of a folder check.</summary>
/// <param name="FullPath">The full path of the candidate (as typed when it could not be resolved).</param>
/// <param name="Problem">Null when the folder is accepted.</param>
public sealed record ExportFolderVerdict(string FullPath, ExportFolderProblem? Problem)
{
public bool Accepted => Problem is null;
}
/// <summary>What a protected folder is.</summary>
public enum ProtectedFolderKind
{
/// <summary>The Data folder.</summary>
Data,
/// <summary>The library folder.</summary>
Library,
/// <summary>The folder of an account (inside the library or outside it).</summary>
Account,
/// <summary>The root of the import sources (Docker <c>/importa</c>).</summary>
Import,
}
/// <summary>A folder a destination may neither be, sit inside nor contain.</summary>
/// <param name="Path">Full path.</param>
/// <param name="Kind">What it is (for the message).</param>
/// <param name="Username">The account of an account folder, when known.</param>
public sealed record ProtectedFolder(string Path, ProtectedFolderKind Kind, string? Username)
{
/// <summary>«la cartella dei dati di Febe», «la cartella dell'account @x»…</summary>
public string Description => Kind switch
{
ProtectedFolderKind.Data => "la cartella dei dati di Febe",
ProtectedFolderKind.Library => "la cartella della libreria",
ProtectedFolderKind.Import => "la cartella delle importazioni",
_ => Username is { Length: > 0 } name ? $"la cartella dell'account @{name}" : "la cartella di un account",
};
}
/// <summary>The folders a candidate is checked against, and where destinations may be chosen.</summary>
public sealed record ExportFolderContext(IReadOnlyList<ProtectedFolder> Protected, ExportRootOptions Root);
/// <summary>A folder or path that cannot be used as a destination; the message (Italian) says why. The API answers 400.</summary>
public sealed class ExportFolderException : IOException
{
public ExportFolderException()
{
}
public ExportFolderException(string message)
: base(message)
{
}
public ExportFolderException(string message, Exception innerException)
: base(message, innerException)
{
}
public ExportFolderException(string message, ExportFolderProblemKind kind)
: base(message) => Kind = kind;
/// <summary>The kind of refusal, when known.</summary>
public ExportFolderProblemKind? Kind { get; }
}
/// <summary>
/// Checks a candidate destination folder (spec §4.10, decision D13 of tappa E2): textual checks first, then the
/// identity test with a probe file written and removed <b>only in the candidate</b>, so that a drive letter and a UNC
/// path to the same place are recognised. In Data, Libreria, the account folders and <c>/importa</c> the probe is only
/// looked for, read-only. Everything that touches the disk runs in the background with a timeout (10 s by default): a
/// disconnected share never blocks the caller.
/// </summary>
public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null)
{
/// <summary>Prefix of the probe file (a temporary file of <see cref="SafeFileWriter"/>: <c>.febe-prova-*.part</c>).</summary>
public const string ProbePrefix = SafeFileWriter.TempPrefix + "prova-";
private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts));
private readonly TimeSpan _timeout = timeout ?? TimeSpan.FromSeconds(10);
/// <summary>A new probe file name: <c>.febe-prova-&lt;12 hex&gt;.part</c>.</summary>
public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix;
/// <summary>
/// The protected folders: Data, the library, the folder of every account (outside the library too), the extra
/// folders (an account folder or a library root about to be saved) and the import root.
/// </summary>
public static async Task<ExportFolderContext> ContextAsync(
IFebeStorage storage,
LibraryLayout layout,
string dataFolder,
string? importRoot,
ExportRootOptions root,
IReadOnlyList<ProtectedFolder>? extra = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(layout);
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
ArgumentNullException.ThrowIfNull(root);
var folders = new List<ProtectedFolder>
{
new(Full(dataFolder), ProtectedFolderKind.Data, null),
new(Full(layout.Root), ProtectedFolderKind.Library, null),
};
foreach (var account in await storage.Accounts.ListAsync(ct).ConfigureAwait(false))
{
string folder;
try
{
folder = Full(layout.AccountFolder(account));
}
catch (ArgumentException)
{
continue; // an unusable stored folder protects nothing
}
folders.Add(new ProtectedFolder(folder, ProtectedFolderKind.Account, account.Username));
}
foreach (var folder in extra ?? [])
{
folders.Add(folder with { Path = Full(folder.Path) });
}
if (importRoot is { Length: > 0 })
{
folders.Add(new ProtectedFolder(Full(importRoot), ProtectedFolderKind.Import, null));
}
return new ExportFolderContext(folders, root);
}
/// <summary>
/// Checks <paramref name="candidate"/>. Never throws for a refused folder (the verdict says why); only
/// <paramref name="ct"/> cancels it.
/// </summary>
public async Task<ExportFolderVerdict> CheckAsync(string candidate, ExportFolderContext context, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(context);
if (string.IsNullOrWhiteSpace(candidate))
{
return new ExportFolderVerdict(candidate ?? string.Empty, new ExportFolderProblem(ExportFolderProblemKind.Empty, "Scegli la cartella in cui copiare i file."));
}
string full;
try
{
full = ExportRoots.Resolve(context.Root, candidate);
}
catch (ExportFolderException ex)
{
return new ExportFolderVerdict(candidate, new ExportFolderProblem(ex.Kind ?? ExportFolderProblemKind.NotFullyQualified, ex.Message));
}
try
{
return await Task.Run(() => CheckOnDisk(full, context, ct), ct).WaitAsync(_timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return new ExportFolderVerdict(full, new ExportFolderProblem(
ExportFolderProblemKind.NotResponding,
$"La cartella non risponde entro {_timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova."));
}
}
private ExportFolderVerdict CheckOnDisk(string full, ExportFolderContext context, CancellationToken ct)
{
var o = context.Root;
var shown = ExportRoots.DisplayPath(o, full);
ExportFolderVerdict Refuse(ExportFolderProblemKind kind, string message) => new(full, new ExportFolderProblem(kind, message));
if (ExportRoots.MountCheck(o, full) is { } mountProblem)
{
return new ExportFolderVerdict(full, mountProblem);
}
if (File.Exists(full))
{
return Refuse(ExportFolderProblemKind.NotAFolder, $"{shown} è un file: scegli una cartella.");
}
if (!Directory.Exists(full))
{
return Refuse(
ExportFolderProblemKind.Missing,
$"La cartella {shown} non esiste. Febe non crea mai la cartella di una destinazione: creala tu, o collega il disco, poi sceglila di nuovo.");
}
if (o.Root is not null && new DirectoryInfo(full).LinkTarget is not null)
{
return Refuse(ExportFolderProblemKind.Link, "La cartella scelta è un collegamento: scegli la cartella a cui punta.");
}
if (IsRootOfDisk(full))
{
return Refuse(
ExportFolderProblemKind.RootOfDisk,
$"{shown} è la radice di un disco o di una condivisione: scegli una sua cartella, così i file di Febe non si mescolano al resto.");
}
try
{
WindowsFileNames.FitPath(full, ["x"]);
}
catch (PathTooLongException)
{
return Refuse(
ExportFolderProblemKind.PathTooLong,
$"Il percorso di {shown} è troppo lungo: i nomi dei file non ci starebbero nei {WindowsFileNames.MaxPathLength} caratteri. Scegli una cartella con un percorso più corto.");
}
// Textual overlap first: it needs no write.
foreach (var folder in context.Protected)
{
if (Overlap(full, folder.Path, shown, folder) is { } problem)
{
return new ExportFolderVerdict(full, problem);
}
}
ct.ThrowIfCancellationRequested();
return ProbeIdentity(full, shown, context.Protected);
}
private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder)
{
if (ExportPaths.Same(full, protectedPath))
{
return Same(shown, folder);
}
if (ExportPaths.IsSameOrInside(full, protectedPath))
{
return Inside(shown, folder);
}
return ExportPaths.IsSameOrInside(protectedPath, full) ? Contains(shown, folder) : null;
}
private static ExportFolderProblem Same(string shown, ProtectedFolder folder) =>
new(ExportFolderProblemKind.SameAsProtected, $"{shown} è {folder.Description}: scegli un'altra cartella.");
private static ExportFolderProblem Inside(string shown, ProtectedFolder folder) =>
new(ExportFolderProblemKind.InsideProtected, $"{shown} è dentro {folder.Description}: scegli una cartella fuori.");
private static ExportFolderProblem Contains(string shown, ProtectedFolder folder) =>
new(ExportFolderProblemKind.ContainsProtected, $"{shown} contiene {folder.Description}: scegli una cartella che non la contenga.");
/// <summary>
/// The identity test of spec §4.10: a probe written in the candidate only, then looked for (never written) up the
/// parents of each protected folder (the candidate contains it, or is it) and, for each parent of the candidate, at the
/// same relative path under each protected folder (the candidate is inside it).
/// </summary>
private static ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList<ProtectedFolder> protectedFolders)
{
var name = NewProbeName();
var probe = Path.Combine(full, name);
try
{
try
{
using var stream = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None);
stream.Write("Febe"u8);
stream.Flush(flushToDisk: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
var reason = ex is UnauthorizedAccessException ? "accesso negato" : ex.Message;
return new ExportFolderVerdict(full, new ExportFolderProblem(
ExportFolderProblemKind.ProbeFailed,
$"Febe non riesce a scrivere in {shown} ({reason}): controlla i permessi o che il disco non sia in sola lettura."));
}
foreach (var folder in protectedFolders)
{
// (a) The candidate is the protected folder, or one of its parents, under another name.
for (var ancestor = folder.Path; ancestor is not null; ancestor = Path.GetDirectoryName(ancestor))
{
if (Exists(Path.Combine(ancestor, name)))
{
var problem = ExportPaths.Same(ancestor, folder.Path) ? Same(shown, folder) : Contains(shown, folder);
return new ExportFolderVerdict(full, problem);
}
}
}
// (b) The candidate is inside a protected folder under another name: for each parent M of the candidate,
// the probe would appear at F/<candidate relative to M> for the protected folder F that is M.
for (var parent = Path.GetDirectoryName(full); parent is not null; parent = Path.GetDirectoryName(parent))
{
var relative = Path.GetRelativePath(parent, full);
foreach (var folder in protectedFolders)
{
if (Exists(Path.Combine(folder.Path, relative, name)))
{
return new ExportFolderVerdict(full, Inside(shown, folder));
}
}
}
return new ExportFolderVerdict(full, null);
}
finally
{
try
{
File.Delete(probe);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: a probe left behind is a temporary file of Febe, harmless.
}
}
}
private static bool Exists(string path)
{
try
{
return File.Exists(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return false;
}
}
/// <summary>
/// Decision D15: on Windows the path is its own root (<c>C:\</c>, <c>\\srv\share</c>); on Linux it is <c>/</c> or
/// exactly a mount point that shows the root of its file system.
/// </summary>
private bool IsRootOfDisk(string full)
{
if (OperatingSystem.IsWindows())
{
var root = Path.GetPathRoot(full);
return !string.IsNullOrEmpty(root) && ExportPaths.Same(root, full);
}
if (full == "/")
{
return true;
}
var mount = _mounts.FindContaining(full);
return mount is not null && string.Equals(ExportPaths.Trim(mount.MountPoint), full, StringComparison.Ordinal) && mount.Root == "/";
}
private static string Full(string path) => ExportPaths.Trim(Path.GetFullPath(path));
}
+89
View File
@@ -0,0 +1,89 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// The <c>.part</c> files a crash left in a destination (spec §4.10): removed only in the folders where the items of
/// an unfinished job were to be written, never by a scan of the destination, never in a folder of no item. Only our
/// own temporary names (<c>.febe-*.part</c>, the probes included) are touched.
/// </summary>
public static class ExportLeftovers
{
private const int PageSize = 1000;
/// <summary>Removes our temporary files in the folders of the items of <paramref name="run"/>. Returns how many.</summary>
public static async Task<int> CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(run);
ArgumentNullException.ThrowIfNull(destination);
if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false))
{
return 0;
}
var folders = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
long after = 0;
while (true)
{
var page = await env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = run.Id, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
after = page[^1].Id;
foreach (var item in page)
{
if (item.RelativePath is { } relative && item.State is ExportItemState.Pending or ExportItemState.Failed)
{
try
{
if (Path.GetDirectoryName(LibraryLayout.FullPath(destination.RootPath, relative)) is { } folder)
{
folders.Add(folder);
}
}
catch (ArgumentException)
{
// A path that would leave the root: nothing of ours can be there.
}
}
}
}
var removed = 0;
foreach (var folder in folders)
{
ct.ThrowIfCancellationRequested();
try
{
removed += await Task.Run(() => SafeFileWriter.CleanupTemporaryFiles(folder, recursive: false), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return removed; // the disk stopped answering: the next resume tries again
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: a leftover .part takes some space, nothing more.
}
}
return removed;
}
private static async Task<bool> AnswersAsync(ExportEnvironment env, string root, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(root), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
}
+114
View File
@@ -0,0 +1,114 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>What a «Copia in…» is asked for (spec §4.10 «Manuale sempre»).</summary>
public abstract record ExportSelection
{
private ExportSelection()
{
}
/// <summary>Files by id: a selection of «Tutte le foto», a file of the viewer.</summary>
public sealed record Media(IReadOnlyList<long> MediaIds) : ExportSelection;
/// <summary>Entries by id: a grouped selection, an entry of the viewer.</summary>
public sealed record Entries(IReadOnlyList<long> EntryIds) : ExportSelection;
/// <summary>The current filter («Copia i file in…» of the CSV menu).</summary>
public sealed record Filter(LibraryFilter LibraryFilter, MosaicMode Mode) : ExportSelection;
/// <summary>Every file of an account (the account card).</summary>
public sealed record Account(long AccountId) : ExportSelection;
}
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
/// <summary>
/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective
/// destination of its account (D5).
/// </summary>
/// <param name="Files">Files to write.</param>
/// <param name="Bytes">Their bytes.</param>
/// <param name="AlreadyCopied">Already in their destination (or, with «Una copia sola», copied for another account).</param>
/// <param name="RemovedOrSuperseded">
/// «Tolti o superati»: never copied again by themselves. With <see cref="ExportJobRequest.CopyAgain"/> they are also
/// counted in <paramref name="Files"/> and <paramref name="Bytes"/>, since they will be written.
/// </param>
/// <param name="NotExported">«Esporta questo account» off, no destination, or a content type the destination does not take.</param>
/// <param name="Missing">«File non presente in libreria».</param>
/// <param name="Destinations">Each destination that gets files, with whether it answers now.</param>
public sealed record ExportPlan(
int Files,
long Bytes,
int AlreadyCopied,
int RemovedOrSuperseded,
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestination> Destinations)
{
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
}
/// <summary>A destination of a plan.</summary>
/// <param name="Username">The account of an own folder; null for the general folder.</param>
/// <param name="Files">Files to write there.</param>
/// <param name="Paused">The destination is paused (its last check failed).</param>
/// <param name="Problem">Why it cannot be written now (not reachable, not mounted, paused), in Italian; null when fine.</param>
/// <param name="FreeBytes">Free space, when it can be measured.</param>
public sealed record ExportPlanDestination(
long DestinationId,
string Label,
string RootPath,
ExportScope Scope,
string? Username,
int Files,
long Bytes,
bool Paused,
string? Problem,
long? FreeBytes);
/// <summary>What the export job is doing.</summary>
public enum ExportPhase
{
Preparing,
/// <summary>«Controlla le copie».</summary>
Checking,
/// <summary>An engine session is running: copies wait for it to end (decision D11).</summary>
WaitingForSession,
Copying,
Finished,
}
/// <summary>Progress of the export job, for the progress card (polled, D20).</summary>
/// <param name="RunId">The job's run being worked on; null for «Controlla le copie» and when nothing ever ran.</param>
/// <param name="BytesTotal">Bytes of the files still pending when the run (re)started, plus those done since; 0 when unknown.</param>
public sealed record ExportProgress(
long? RunId,
ExportPhase Phase,
int FilesDone,
int FilesTotal,
long BytesDone,
long BytesTotal,
string? CurrentFile,
string? DestinationLabel,
IReadOnlyDictionary<ExportItemState, int> ByState,
DateTimeOffset UpdatedAt)
{
/// <summary>0..1: by bytes when known, otherwise by files.</summary>
public double Fraction => BytesTotal > 0
? Math.Clamp((double)BytesDone / BytesTotal, 0, 1)
: FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0;
}
/// <summary>What <c>ExportService.StartAsync</c> did: one run per destination (D6), and the plan it followed.</summary>
public sealed record ExportStart(IReadOnlyList<ExportRun> Runs, ExportPlan Plan);
/// <summary>The export job ended (however it ended): the runs it worked on, and whether copies may have changed.</summary>
public sealed record ExportJobFinished(IReadOnlyList<long> RunIds, bool CopiesChanged);
@@ -0,0 +1,35 @@
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>
/// The «Risultato» tree of a destination's naming (spec §4.10 «Nomi dei file»): the library preview rendered with the
/// destination's schemes, «Come la libreria» (null) taking the library's. In the general folder each file sits under
/// its account segment.
/// </summary>
public static class ExportNamingPreview
{
public static NamingPreview Build(
ExportScope scope,
string? general,
string? highlight,
string? profile,
LibraryNaming library,
TimeZoneInfo zone,
string sampleAccount = "nome.utente")
{
ArgumentNullException.ThrowIfNull(library);
var preview = NamingPreview.Build(general ?? library.General.Text, highlight ?? library.Highlight.Text, profile ?? library.ProfilePicture.Text, zone, sampleAccount);
if (scope != ExportScope.General)
{
return preview;
}
var segment = WindowsFileNames.SanitizeSegment(sampleAccount);
return preview with
{
Folders = preview.Folders.Select(f => f with { Path = [segment, .. f.Path] }).ToList(),
};
}
}
+145
View File
@@ -0,0 +1,145 @@
using System.Globalization;
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>Paths and content types of the export (spec §4.10).</summary>
public static class ExportPaths
{
/// <summary>Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does.</summary>
public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or inside it, as text (full paths).</summary>
public static bool IsSameOrInside(string path, string folder)
{
ArgumentNullException.ThrowIfNull(path);
ArgumentNullException.ThrowIfNull(folder);
var p = Trim(path);
var f = Trim(folder);
return string.Equals(p, f, PathComparison)
|| p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) || f.EndsWith(Path.AltDirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison);
}
/// <summary>The same folder, as text.</summary>
public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison);
/// <summary>A full path without its trailing separator (a root such as <c>C:\</c> or <c>/</c> keeps it).</summary>
public static string Trim(string path)
{
ArgumentNullException.ThrowIfNull(path);
return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path;
}
/// <summary>
/// The content type of a file (decision D4 of tappa E2): a post photo or video, a story (also a highlight when the
/// story is in a collection), a highlight, a tagged post, a profile picture. The «Copie» filter repeats it in SQL.
/// </summary>
public static ContentTypes TypeOf(EntryKind kind, MediaKind media, bool inHighlight) => kind switch
{
EntryKind.Post => media == MediaKind.Photo ? ContentTypes.PostPhotos : ContentTypes.PostVideos,
EntryKind.Story => inHighlight ? ContentTypes.Stories | ContentTypes.Highlights : ContentTypes.Stories,
EntryKind.Highlight => ContentTypes.Highlights,
EntryKind.Tagged => ContentTypes.Tagged,
EntryKind.ProfilePicture => ContentTypes.ProfilePicture,
_ => ContentTypes.None,
};
/// <summary>Folder of imported files without a known date or code (as the import names it).</summary>
public const string ImportedFolder = "importati";
/// <summary>
/// The path of a copy below the destination root, as sanitized segments, before <see cref="RelativePathFor"/>
/// (decision D18 of tappa E2). «Come la libreria» (a null scheme) renders the library's current scheme again, except
/// for a file the import left in <c>importati/</c>, which keeps its path. A story in a highlight collection takes the
/// highlight scheme only when the destination takes highlights and not stories. In the general folder the account
/// segment comes first.
/// </summary>
public static IReadOnlyList<string> Segments(
ExportDestination d,
LibraryNaming library,
Account account,
Entry entry,
Media media,
string? highlightTitle,
bool inHighlight,
TimeZoneInfo zone)
{
ArgumentNullException.ThrowIfNull(d);
ArgumentNullException.ThrowIfNull(library);
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(entry);
ArgumentNullException.ThrowIfNull(media);
ArgumentNullException.ThrowIfNull(zone);
var stored = media.RelativePath is { Length: > 0 } path
? LibraryLayout.ToStored(path)
: throw new ArgumentException("Il file non è nella libreria: non ha un percorso.", nameof(media));
var renderAs = entry.Kind == EntryKind.Story && inHighlight
&& d.ContentTypes.HasFlag(ContentTypes.Highlights) && !d.ContentTypes.HasFlag(ContentTypes.Stories)
? EntryKind.Highlight
: entry.Kind;
var use = UseOf(renderAs);
var text = use switch
{
NamingSchemeUse.Highlight => d.HighlightNamingScheme,
NamingSchemeUse.ProfilePicture => d.ProfileNamingScheme,
_ => d.NamingScheme,
};
IReadOnlyList<string> segments;
if (text is null && stored.StartsWith(ImportedFolder + "/", StringComparison.Ordinal))
{
segments = stored.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(WindowsFileNames.SanitizeSegment).ToList();
}
else
{
var scheme = (text is null ? null : NamingScheme.Validate(text, use).Scheme) ?? library.For(renderAs);
var extension = Path.GetExtension(stored).TrimStart('.').ToLowerInvariant();
var values = NamingValues.For(
account.Username,
entry with { Kind = renderAs },
media.Position,
extension,
renderAs == EntryKind.Highlight ? highlightTitle : null,
media.Sha256);
segments = scheme.Render(values, zone);
}
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
}
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
{
ArgumentNullException.ThrowIfNull(d);
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
}
/// <summary>
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash.
/// </summary>
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
if (attempt <= 1)
{
return string.Join('/', segments);
}
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath));
}
/// <summary>The scheme that names an entry kind.</summary>
public static NamingSchemeUse UseOf(EntryKind kind) => kind switch
{
EntryKind.Highlight => NamingSchemeUse.Highlight,
EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture,
_ => NamingSchemeUse.General,
};
}
+70
View File
@@ -0,0 +1,70 @@
using Febe.Core.Domain;
namespace Febe.Core.Export;
/// <summary>
/// The pause of a destination (spec §4.10): its probe could not be written, it is not reachable, or the disk is full.
/// The state shows in Impostazioni and in the Dashboard and the next check clears it. Never the red strip: the event
/// <c>esportazione-in-pausa</c> is not an alert of the engine.
/// </summary>
public static class ExportPause
{
/// <summary>Code of the event written once when a destination goes into pause.</summary>
public const string PausedEventCode = "esportazione-in-pausa";
/// <summary>
/// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it
/// is). The event is written only on the transition from running to paused. Returns the stored row.
/// </summary>
public static async Task<ExportDestination> PauseAsync(ExportEnvironment env, ExportDestination destination, string message)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(destination);
ArgumentException.ThrowIfNullOrWhiteSpace(message);
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
if (stored.IsRetired)
{
return stored;
}
var wasPaused = stored.PausedAt is not null;
if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal))
{
return stored;
}
var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message };
await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false);
if (!wasPaused)
{
await env.Storage.Events.AppendAsync(
new EventRecord
{
At = env.Clock.Now,
Code = PausedEventCode,
Severity = EventSeverity.Warning,
Message = $"{ExportDestinations.Label(paused)} in pausa: {message}",
AccountId = paused.AccountId,
},
CancellationToken.None).ConfigureAwait(false);
}
return paused;
}
/// <summary>Clears the pause of a destination after a check succeeded. Returns the stored row.</summary>
public static async Task<ExportDestination> ClearAsync(ExportEnvironment env, ExportDestination destination)
{
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(destination);
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null))
{
return stored;
}
var cleared = stored with { PausedAt = null, LastError = null };
await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false);
return cleared;
}
}
+238
View File
@@ -0,0 +1,238 @@
using System.Runtime.CompilerServices;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the
/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are
/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog.
/// </summary>
public sealed class ExportPlanner(ExportEnvironment env)
{
private const int PageSize = 2000;
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
public async Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(request);
var destinations = new ExportDestinations(_env);
var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false);
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
var tally = new PlanTally();
await foreach (var file in EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
{
tally.Add(file);
}
return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false);
}
/// <summary>
/// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an
/// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with
/// «Una copia sola» the same file counts once across accounts.
/// </summary>
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
ExportJobRequest request,
IReadOnlyDictionary<long, EffectiveDestination> effective,
ExportSettings settings,
[EnumeratorCancellation] CancellationToken ct)
{
var exports = _env.Storage.Exports;
var oneOnly = settings.SamePost == SamePostCopies.OneOnly;
var seen = new HashSet<(long Destination, long Account, string Sha256)>();
long after = 0;
while (true)
{
var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false);
if (page.Count == 0)
{
yield break;
}
after = page[^1].MediaId;
var keys = new Dictionary<long, HashSet<(long AccountId, string Sha256)>>();
foreach (var c in page)
{
if (Due(c, effective) is { } destination)
{
if (!keys.TryGetValue(destination, out var set))
{
keys[destination] = set = [];
}
set.Add((c.AccountId, c.Sha256!));
}
}
var states = new Dictionary<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
foreach (var (destination, set) in keys)
{
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
}
foreach (var c in page)
{
if (!IsPresent(c))
{
yield return new PlannedFile(c, null, PlannedCopy.Missing);
continue;
}
if (Due(c, effective) is not { } destination)
{
yield return new PlannedFile(c, null, PlannedCopy.NotExported);
continue;
}
var sha = c.Sha256!;
var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha);
var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null;
PlannedFile planned;
if (state == ExportCopyState.Copied)
{
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
}
else if (state is ExportCopyState.Removed or ExportCopyState.Superseded)
{
planned = request.CopyAgain
? new PlannedFile(c, destination, PlannedCopy.Write, Again: true)
: new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded);
}
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { } other
&& other.AccountId != c.AccountId)
{
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
}
else
{
planned = new PlannedFile(c, destination, PlannedCopy.Write);
}
if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key))
{
planned = planned with { Action = PlannedCopy.AlreadyCopied, Again = false };
}
yield return planned;
}
}
}
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
/// <summary>The destination a present file goes to (D3), or null when it is not exported.</summary>
private static long? Due(ExportCandidate c, IReadOnlyDictionary<long, EffectiveDestination> effective) =>
IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight))
? e.Destination!.Id
: null;
}
/// <summary>A candidate with what the plan does with it.</summary>
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
internal enum PlannedCopy
{
Write,
AlreadyCopied,
RemovedOrSuperseded,
NotExported,
Missing,
}
/// <summary>Counts of a plan while its files go by.</summary>
internal sealed class PlanTally
{
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
public int Files { get; private set; }
public long Bytes { get; private set; }
public int AlreadyCopied { get; private set; }
public int RemovedOrSuperseded { get; private set; }
public int NotExported { get; private set; }
public int Missing { get; private set; }
public void Add(PlannedFile file)
{
switch (file.Action)
{
case PlannedCopy.Missing:
Missing++;
return;
case PlannedCopy.NotExported:
NotExported++;
return;
case PlannedCopy.AlreadyCopied:
AlreadyCopied++;
break;
case PlannedCopy.RemovedOrSuperseded:
RemovedOrSuperseded++;
break;
case PlannedCopy.Write:
var bytes = file.Candidate.Bytes ?? 0;
Files++;
Bytes += bytes;
if (file.Again)
{
RemovedOrSuperseded++;
}
var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value);
_byDestination[file.DestinationId.Value] = (f + 1, b + bytes);
return;
}
_byDestination.TryAdd(file.DestinationId!.Value, (0, 0));
}
/// <summary>The plan. With <paramref name="checkDestinations"/> each destination is asked whether it answers now.</summary>
public async Task<ExportPlan> BuildAsync(
ExportEnvironment env,
ExportDestinations destinations,
IReadOnlyDictionary<long, EffectiveDestination> effective,
bool checkDestinations,
CancellationToken ct)
{
var rows = effective.Values.Where(e => e.Destination is not null).Select(e => e.Destination!).DistinctBy(d => d.Id).ToDictionary(d => d.Id);
var accounts = (await env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
var list = new List<ExportPlanDestination>();
foreach (var (id, (files, bytes)) in _byDestination.OrderBy(d => rows.TryGetValue(d.Key, out var r) && r.Scope == ExportScope.General ? 0 : 1).ThenBy(d => d.Key))
{
var d = rows.TryGetValue(id, out var row) ? row : await env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false);
if (d is null)
{
continue;
}
string? problem = null;
long? free = null;
if (checkDestinations)
{
var status = await destinations.StatusAsync(id, ct).ConfigureAwait(false);
problem = status.Problem;
free = status.FreeBytes;
}
problem ??= d.PausedAt is not null ? d.LastError : null;
var username = d.AccountId is { } a ? accounts.GetValueOrDefault(a) : null;
list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free));
}
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list);
}
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
public IReadOnlyCollection<long> Destinations => _byDestination.Keys;
}
+106
View File
@@ -0,0 +1,106 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>The report of an export job (spec §4.10): counts, per account, and the files that need a look.</summary>
/// <param name="Problems">At most <see cref="ExportReports.MaxProblems"/> lines: failed, missing, and skipped files with a note.</param>
public sealed record ExportReport(
ExportRun Run,
ExportDestination Destination,
int Total,
IReadOnlyDictionary<ExportItemState, int> ByState,
long BytesCopied,
IReadOnlyList<ExportReportAccount> Accounts,
IReadOnlyList<ExportReportLine> Problems);
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
/// <summary>A file of the report, with its reason in Italian.</summary>
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
/// <summary>Builds the report of a job from the database (no CSV in E2: §4.10 leaves «Copiato in» in the CSV out of 0.3.0).</summary>
public sealed class ExportReports(ExportEnvironment env)
{
public const int MaxProblems = 200;
private const int PageSize = 1000;
/// <summary>A name for files whose account was removed.</summary>
public const string RemovedAccount = "account rimosso";
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <exception cref="KeyNotFoundException">No such job.</exception>
public async Task<ExportReport> BuildAsync(long runId, CancellationToken ct = default)
{
var exports = _env.Storage.Exports;
var run = await exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
var destination = await exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Destinazione di esportazione {run.DestinationId} non trovata.");
var summary = await exports.GetRunSummaryAsync(runId, ct).ConfigureAwait(false);
var names = (await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
string Name(long? id) => id is { } a && names.TryGetValue(a, out var n) ? n : RemovedAccount;
var accounts = new Dictionary<long, int[]>();
var problems = new List<ExportReportLine>();
long bytes = 0;
long after = 0;
while (true)
{
var page = await exports.ListItemsAsync(new ExportItemQuery { RunId = runId, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
after = page[^1].Id;
foreach (var item in page)
{
var key = item.AccountId ?? 0;
if (!accounts.TryGetValue(key, out var row))
{
accounts[key] = row = new int[4];
}
switch (item.State)
{
case ExportItemState.Copied or ExportItemState.Adopted:
row[0]++;
if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b })
{
bytes += b;
}
break;
case ExportItemState.AlreadyCopied:
row[1]++;
break;
case ExportItemState.Skipped or ExportItemState.Missing:
row[2]++;
break;
case ExportItemState.Failed:
row[3]++;
break;
}
var problem = item.State is ExportItemState.Failed or ExportItemState.Missing
|| (item.State == ExportItemState.Skipped && item.Note is not null);
if (problem && problems.Count < MaxProblems)
{
var text = item.State == ExportItemState.Failed
? item.LastError ?? ExportText.Note(item.Note) ?? ExportText.State(item.State)
: ExportText.Note(item.Note) ?? ExportText.State(item.State);
problems.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, text));
}
}
}
var perAccount = accounts
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]))
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
.ToList();
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems);
}
}
+269
View File
@@ -0,0 +1,269 @@
using Febe.Core.Import;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>A mounted file system, as the export needs it (spec §4.10 «Docker e Windows»).</summary>
/// <param name="MountPoint">Where it is mounted.</param>
/// <param name="Root">Folder of its file system shown there (<c>/</c>: the root of that file system).</param>
/// <param name="FileSystemType">File system type (<c>vfat</c> for FAT32).</param>
/// <param name="ReadOnly">Mounted read-only.</param>
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly);
/// <summary>The mount table (a seam: tests give their own; Linux reads <c>/proc/self/mountinfo</c>).</summary>
public interface IExportMounts
{
/// <summary>The mount that holds a full path, or null (always null on Windows).</summary>
ExportMount? FindContaining(string fullPath);
/// <summary>Every mount (empty on Windows).</summary>
IReadOnlyList<ExportMount> All();
}
/// <summary>The mounts of this process from <c>/proc/self/mountinfo</c>, read at each call (it is small).</summary>
public sealed class ProcMountInfo(Func<string?>? read = null) : IExportMounts
{
private readonly Func<string?> _read = read ?? MountInfoTable.ReadProcSelf;
public ExportMount? FindContaining(string fullPath)
{
ArgumentNullException.ThrowIfNull(fullPath);
var mounts = Read();
return mounts.Count == 0 ? null : Map(MountInfoTable.FindContaining(mounts, fullPath));
}
public IReadOnlyList<ExportMount> All() => Read().Select(m => Map(m)!).ToList();
private IReadOnlyList<MountInfoEntry> Read()
{
try
{
return _read() is { } content ? MountInfoTable.Parse(content) : [];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return [];
}
}
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly);
}
/// <summary>
/// Where destinations may be chosen. Docker: subfolders of <c>/esporta</c>, only when it is declared
/// (<c>--esporta</c>, <c>FEBE_ESPORTA</c>) and the destination sits on a mount at <c>/esporta</c> or below it (decision of
/// Alberto, question Q2 of tappa E2). Windows: any folder, through the native picker.
/// </summary>
public sealed record ExportRootOptions
{
/// <summary>Docker: the full path of <c>/esporta</c>. Null: any folder.</summary>
public string? Root { get; init; }
/// <summary><c>--esporta</c> or <c>FEBE_ESPORTA</c> (always true without a root).</summary>
public bool Declared { get; init; }
/// <summary>The mount table.</summary>
public IExportMounts Mounts { get; init; } = new ProcMountInfo();
/// <summary>Windows (and development): any folder.</summary>
public static ExportRootOptions AnyFolder { get; } = new() { Declared = true };
/// <summary>Docker: destinations under <paramref name="root"/>.</summary>
public static ExportRootOptions Docker(string root, bool declared, IExportMounts? mounts = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
return new ExportRootOptions { Root = ExportPaths.Trim(Path.GetFullPath(root)), Declared = declared, Mounts = mounts ?? new ProcMountInfo() };
}
}
/// <summary>Whether copies to external folders can be written at all, and why not.</summary>
/// <param name="Active">True: destinations may be created and written.</param>
/// <param name="Root">Docker: the root (<c>/esporta</c>); null on Windows.</param>
/// <param name="Problem">Italian text of the reason when not active.</param>
public sealed record ExportRootState(bool Active, string? Root, string? Problem);
/// <summary>The rules of the export root (spec §4.10, §11): <c>/esporta</c> in Docker, any folder on Windows.</summary>
public static class ExportRoots
{
/// <summary>Copies to external folders are switched off in Docker (not declared).</summary>
public const string NotDeclaredText =
"Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1 (o --esporta) e una cartella del server montata su /esporta.";
/// <summary>Whether the root is usable: always without a root; in Docker declared and with a mount at or below it.</summary>
public static ExportRootState Evaluate(ExportRootOptions o)
{
ArgumentNullException.ThrowIfNull(o);
if (o.Root is not { } root)
{
return new ExportRootState(true, null, null);
}
if (!o.Declared)
{
return new ExportRootState(false, root, NotDeclaredText);
}
return o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root))
? new ExportRootState(true, root, null)
: new ExportRootState(false, root, NotMountedText(o));
}
/// <summary>
/// Null when a destination may be written as far as the mounts are concerned (always on Windows); otherwise the
/// Italian reason: not declared, not on a mount at or below the root, or a read-only mount.
/// </summary>
public static string? MountProblem(ExportRootOptions o, string destinationFullPath) => MountCheck(o, destinationFullPath)?.Message;
internal static ExportFolderProblem? MountCheck(ExportRootOptions o, string destinationFullPath)
{
ArgumentNullException.ThrowIfNull(o);
ArgumentException.ThrowIfNullOrWhiteSpace(destinationFullPath);
if (o.Root is not { } root)
{
return null;
}
if (!o.Declared)
{
return new ExportFolderProblem(ExportFolderProblemKind.NotMounted, NotDeclaredText);
}
var full = ExportPaths.Trim(Path.GetFullPath(destinationFullPath));
var mount = o.Mounts.FindContaining(full);
if (mount is null || !ExportPaths.IsSameOrInside(ExportPaths.Trim(mount.MountPoint), root))
{
return new ExportFolderProblem(
ExportFolderProblemKind.NotMounted,
o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root))
? $"{DisplayPath(o, full)} non è su una cartella montata in {DisplayPath(o, root)}: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di {DisplayPath(o, root)}."
: NotMountedText(o));
}
return mount.ReadOnly
? new ExportFolderProblem(ExportFolderProblemKind.ReadOnlyMount, $"{DisplayPath(o, full)} è montata in sola lettura: Febe non può copiarci nulla.")
: null;
}
/// <summary>
/// Subfolders offered by the picker in Docker: <paramref name="relative"/> is relative to the root, and so are the
/// returned paths. Without a root it is an absolute folder. Links, hidden and system folders are skipped.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be browsed.</exception>
public static IReadOnlyList<SourceFolderChoice> Browse(ExportRootOptions o, string? relative)
{
ArgumentNullException.ThrowIfNull(o);
string folder;
if (o.Root is { } root)
{
folder = string.IsNullOrWhiteSpace(relative) ? root : Resolve(o, relative, allowRoot: true);
}
else if (string.IsNullOrWhiteSpace(relative) || !Path.IsPathFullyQualified(relative))
{
throw new ExportFolderException("Scegli la cartella da sfogliare con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified);
}
else
{
folder = ExportPaths.Trim(Path.GetFullPath(relative));
}
if (!Directory.Exists(folder))
{
throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing);
}
try
{
return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false))
.Order(StringComparer.Ordinal)
.Select(d => new SourceFolderChoice(
Path.GetFileName(d),
o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d,
Directory.EnumerateDirectories(d, "*", ImportSources.Enumeration(recursive: false)).Any()))
.ToList();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new ExportFolderException($"Febe non riesce a leggere {DisplayPath(o, folder)}: controlla che il disco sia collegato.", ExportFolderProblemKind.Missing);
}
}
/// <summary>
/// The full path of a chosen folder: in Docker the root plus a relative path (or a full path inside the root), never
/// the root itself, never with «..»; without a root a fully qualified path.
/// </summary>
/// <exception cref="ExportFolderException">The path cannot be a destination; the message says why.</exception>
public static string Resolve(ExportRootOptions o, string chosen) => Resolve(o, chosen, allowRoot: false);
/// <summary>The path shown to Alberto: in Docker «/esporta/usb»; elsewhere the full path.</summary>
public static string DisplayPath(ExportRootOptions o, string full)
{
ArgumentNullException.ThrowIfNull(o);
ArgumentNullException.ThrowIfNull(full);
if (o.Root is { } root && ExportPaths.IsSameOrInside(full, root))
{
var relative = Path.GetRelativePath(root, full);
return relative == "." ? LibraryLayout.ToStored(root) : LibraryLayout.ToStored(root).TrimEnd('/') + "/" + LibraryLayout.ToStored(relative);
}
return full;
}
private static string Resolve(ExportRootOptions o, string chosen, bool allowRoot)
{
ArgumentNullException.ThrowIfNull(o);
if (string.IsNullOrWhiteSpace(chosen))
{
throw new ExportFolderException("Scegli la cartella in cui copiare i file.", ExportFolderProblemKind.Empty);
}
var display = o.Root is { } shown ? DisplayPath(o, shown) : null;
// Refused as text, before any normalisation: «..» never walks out of the list the picker shows.
if (chosen.Split('/', '\\').Any(s => s == ".."))
{
throw new ExportFolderException(
display is null ? "«..» non è ammesso: scegli la cartella con il suo percorso completo." : $"«..» non è ammesso: scegli una sottocartella di {display} dall'elenco.",
ExportFolderProblemKind.ParentSegment);
}
if (o.Root is not { } root)
{
if (!Path.IsPathFullyQualified(chosen))
{
throw new ExportFolderException("Scegli la cartella con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified);
}
return ExportPaths.Trim(FullPath(chosen));
}
var full = ExportPaths.Trim(Path.IsPathFullyQualified(chosen) ? FullPath(chosen) : FullPath(Path.Combine(root, chosen.TrimStart('/', '\\'))));
if (!ExportPaths.IsSameOrInside(full, root))
{
throw new ExportFolderException(
$"In Docker le copie vanno solo in una sottocartella di {display}: monta lì una cartella del server e sceglila dall'elenco.",
ExportFolderProblemKind.OutsideExportRoot);
}
if (!allowRoot && ExportPaths.Same(full, root))
{
throw new ExportFolderException($"Scegli una sottocartella di {display}: {display} stessa non è una destinazione.", ExportFolderProblemKind.ExportRootItself);
}
return full;
}
private static string FullPath(string path)
{
try
{
return Path.GetFullPath(path);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
throw new ExportFolderException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ExportFolderProblemKind.NotFullyQualified);
}
}
private static string NotMountedText(ExportRootOptions o) =>
$"{DisplayPath(o, o.Root!)} è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su {DisplayPath(o, o.Root!)}.";
}
+26
View File
@@ -0,0 +1,26 @@
using System.Globalization;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// Settings of one export job (like <c>ImportRunSettings</c>): a row of the <c>setting</c> table each, so the schema
/// stays as E1 left it. Cleared when the job completes, is cancelled or deleted.
/// </summary>
internal static class ExportRunSettings
{
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
public static async Task<bool> GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct)
{
var text = await store.GetAsync(CopyAgainKey(runId), ct).ConfigureAwait(false);
return string.Equals(text?.Trim(), "1", StringComparison.Ordinal);
}
public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct);
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.SetAsync(CopyAgainKey(runId), null, ct);
}
+642
View File
@@ -0,0 +1,642 @@
using System.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// The copies to external folders for the interface (spec §4.10): one background job at a time, never together with
/// an import or a rebuild (<see cref="LongWorkGate"/>), never during an engine session. A «Copia in…» makes one job
/// record per destination (decision D6 of tappa E2) and the job works on them in order. Every state lives in the
/// database: after a restart call <see cref="RecoverAsync"/> once; «Riprendi» is always Alberto's.
/// </summary>
public sealed class ExportService : IAsyncDisposable
{
private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila.";
private const int ItemBatch = 2000;
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
private readonly ExportEnvironment _env;
private readonly Lock _gate = new();
private Job? _job;
private ExportProgress? _current;
private long _lastPublished;
private Task _cleanup = Task.CompletedTask;
private bool _starting;
public ExportService(ExportEnvironment env)
{
ArgumentNullException.ThrowIfNull(env);
_env = env;
Destinations = new ExportDestinations(env);
Planner = new ExportPlanner(env);
Copier = new ExportCopier(env);
Reports = new ExportReports(env);
}
/// <summary>Progress of the running job, at most four times a second and at every change of phase (pool thread).</summary>
public event EventHandler<ExportProgress>? ProgressChanged;
/// <summary>The job ended, however it ended (pool thread): the interface refreshes tiles and filter.</summary>
public event EventHandler<ExportJobFinished>? JobFinished;
public ExportDestinations Destinations { get; }
public ExportPlanner Planner { get; }
public ExportCopier Copier { get; }
public ExportReports Reports { get; }
/// <summary>The runs of the running job; empty when idle (and for «Controlla le copie», which has none).</summary>
public IReadOnlyList<long> ActiveRunIds
{
get
{
lock (_gate)
{
return _job is { Task.IsCompleted: false } job ? job.RunIds : [];
}
}
}
/// <summary>A job is running.</summary>
public bool IsBusy
{
get
{
lock (_gate)
{
return _starting || _job is { Task.IsCompleted: false };
}
}
}
/// <summary>The last error of a background job that could not be stored with its run (normally null).</summary>
public string? LastJobError { get; private set; }
/// <summary>
/// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the
/// <c>.part</c> files of unfinished jobs are removed in the background, only in their items' folders. Never resumes
/// by itself. Returns how many jobs became interrupted.
/// </summary>
public async Task<int> RecoverAsync(CancellationToken ct = default)
{
var active = ActiveRunIds;
var recovered = 0;
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
foreach (var run in unfinished)
{
if (run.State == ExportRunState.Running && !active.Contains(run.Id))
{
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false);
recovered++;
}
}
var toClean = unfinished.Where(r => !active.Contains(r.Id)).ToList();
lock (_gate)
{
_cleanup = Task.Run(() => CleanLeftoversAsync(toClean));
}
return recovered;
}
/// <summary>The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers).</summary>
public Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct);
/// <summary>
/// «Copia in…»: records one job per destination that gets files, with its items, and starts copying in the
/// background. Files not exported or missing are only counted in the returned plan. When nothing is due, no job is
/// recorded and nothing starts.
/// </summary>
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(request);
lock (_gate)
{
EnsureIdle();
_starting = true; // a second «Copia in…» meanwhile records nothing
}
try
{
return await StartReservedAsync(request, ct).ConfigureAwait(false);
}
finally
{
lock (_gate)
{
_starting = false;
}
}
}
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, CancellationToken ct)
{
var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false);
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
var tally = new PlanTally();
var runs = new Dictionary<long, ExportRun>();
var pending = new List<ExportItem>();
var exports = _env.Storage.Exports;
try
{
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
{
tally.Add(file);
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported)
{
continue;
}
if (!runs.TryGetValue(destination, out var run))
{
run = await exports.CreateRunAsync(
new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
CancellationToken.None).ConfigureAwait(false);
runs[destination] = run;
if (request.CopyAgain)
{
await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false);
}
}
pending.Add(new ExportItem
{
RunId = run.Id,
MediaId = file.Candidate.MediaId,
AccountId = file.Candidate.AccountId,
SourceSha256 = file.Candidate.Sha256,
Variant = ExportVariant.Whole,
Format = ExportFormat.Original,
State = ExportItemState.Pending,
});
if (pending.Count >= ItemBatch)
{
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
pending.Clear();
}
}
if (pending.Count > 0)
{
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
}
}
catch
{
await StopRunsAsync(runs.Values).ConfigureAwait(false);
throw;
}
var plan = await tally.BuildAsync(_env, Destinations, effective, checkDestinations: false, CancellationToken.None).ConfigureAwait(false);
var ordered = runs.Values.OrderBy(r => r.Id).ToList();
if (ordered.Count == 0)
{
return new ExportStart([], plan);
}
try
{
lock (_gate)
{
_starting = false;
StartCopyJob(ordered.Select(r => r.Id).ToList());
}
}
catch
{
await StopRunsAsync(ordered).ConfigureAwait(false);
throw;
}
return new ExportStart(ordered, plan);
}
/// <summary>
/// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a
/// paused one checks its destination first and pauses again if it still does not answer).
/// </summary>
public async Task<IReadOnlyList<ExportRun>> ResumeAsync(IReadOnlyList<long>? runIds = null, CancellationToken ct = default)
{
EnsureIdle();
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
List<ExportRun> chosen;
if (runIds is null)
{
chosen = unfinished.ToList();
}
else
{
chosen = [];
foreach (var id in runIds.Distinct())
{
var run = unfinished.FirstOrDefault(r => r.Id == id);
if (run is null)
{
_ = await _env.Storage.Exports.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {id} non trovato.");
throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere.");
}
chosen.Add(run);
}
}
chosen = chosen.OrderBy(r => r.Id).ToList();
if (chosen.Count > 0)
{
StartCopyJob(chosen.Select(r => r.Id).ToList());
}
return chosen;
}
/// <summary>«Interrompi»: stops the running job and waits until its states are saved.</summary>
public async Task InterruptAsync(CancellationToken ct = default)
{
Job? job;
lock (_gate)
{
job = _job is { Task.IsCompleted: false } j ? j : null;
}
if (job is null)
{
return;
}
await job.Cancellation.CancelAsync().ConfigureAwait(false);
await job.Task.WaitAsync(ct).ConfigureAwait(false);
}
/// <summary>
/// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our
/// <c>.part</c> files in its folders go; no other file is touched, and the copies made stay.
/// </summary>
public async Task DiscardAsync(long runId, CancellationToken ct = default)
{
if (ActiveRunIds.Contains(runId))
{
await InterruptAsync(ct).ConfigureAwait(false);
}
var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
if (run.State is ExportRunState.Completed or ExportRunState.Cancelled)
{
return;
}
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false);
if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination)
{
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
}
}
/// <summary>
/// «Controlla le copie»: a job without a record (not resumable, idempotent) that looks for every Copied or
/// Superseded copy of a destination and marks «Tolto» those whose file is gone. Never touches a file.
/// </summary>
public async Task CheckCopiesAsync(long destinationId, CancellationToken ct = default)
{
EnsureIdle();
var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata.");
if (destination.IsRetired)
{
throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da controllare.");
}
StartJob([], (progress, token) => CheckJobAsync(destination, progress, token));
}
/// <summary>The progress of the running job, or a snapshot of the newest job.</summary>
public async Task<ExportProgress> GetProgressAsync(CancellationToken ct = default)
{
lock (_gate)
{
if (_job is { Task.IsCompleted: false } && _current is { } current)
{
return current;
}
}
var newest = (await _env.Storage.Exports.ListRecentRunsAsync(1, ct).ConfigureAwait(false)).FirstOrDefault();
return newest is null
? new ExportProgress(null, ExportPhase.Finished, 0, 0, 0, 0, null, null, new Dictionary<ExportItemState, int>(), _env.Clock.Now)
: await SnapshotAsync(newest, ct).ConfigureAwait(false);
}
/// <summary>Waits for the running job (if any) to end, however it ends.</summary>
public async Task WaitAsync(CancellationToken ct = default)
{
Job? job;
Task cleanup;
lock (_gate)
{
job = _job;
cleanup = _cleanup;
}
if (job is not null)
{
await job.Task.WaitAsync(ct).ConfigureAwait(false);
}
await cleanup.WaitAsync(ct).ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
Job? job;
Task cleanup;
lock (_gate)
{
job = _job;
cleanup = _cleanup;
}
if (job is not null)
{
await job.Cancellation.CancelAsync().ConfigureAwait(false);
await job.Task.ConfigureAwait(false);
job.Cancellation.Dispose();
}
await cleanup.ConfigureAwait(false);
}
private async Task<ExportProgress> SnapshotAsync(ExportRun run, CancellationToken ct)
{
var summary = await _env.Storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false);
var destination = await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false);
var phase = run.State == ExportRunState.Running && IsBusy ? ExportPhase.Copying : ExportPhase.Finished;
return new ExportProgress(
run.Id,
phase,
summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending),
summary.Total,
0,
0,
null,
destination is null ? null : ExportDestinations.Label(destination),
summary.ByState,
_env.Clock.Now);
}
private async Task CheckJobAsync(ExportDestination destination, IProgress<ExportProgress> progress, CancellationToken ct)
{
var exports = _env.Storage.Exports;
var label = ExportDestinations.Label(destination);
var counts = await exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
var total = counts.GetValueOrDefault(ExportCopyState.Copied) + counts.GetValueOrDefault(ExportCopyState.Superseded);
void Report(ExportPhase phase, int done) =>
progress.Report(new ExportProgress(null, phase, done, total, 0, 0, null, label, new Dictionary<ExportItemState, int>(), _env.Clock.Now));
Report(ExportPhase.Checking, 0);
if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem)
{
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
Report(ExportPhase.Finished, 0);
return;
}
await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false);
var done = 0;
var removed = 0;
foreach (var state in new[] { ExportCopyState.Copied, ExportCopyState.Superseded })
{
long after = 0;
while (true)
{
while (_env.Session.InSession)
{
Report(ExportPhase.WaitingForSession, done);
await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false);
}
var page = await exports.ListCopiesAsync(destination.Id, state, after, 1000, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
after = page[^1].Id;
if (!Directory.Exists(destination.RootPath))
{
// The disk went away during the check: nothing is «Tolto» because of that.
var gone = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
await ExportPause.PauseAsync(_env, destination, gone).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
return;
}
var missing = new List<long>();
foreach (var copy in page)
{
ct.ThrowIfCancellationRequested();
if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
{
missing.Add(copy.Id);
}
}
removed += await exports.MarkCopiesRemovedAsync(missing, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
done += page.Count;
Report(ExportPhase.Checking, done);
}
}
await _env.Storage.Events.AppendAsync(
new EventRecord
{
At = _env.Clock.Now,
Code = "esportazione-controllo",
Message = ExportText.CheckMessage(done, removed, destination),
Severity = removed > 0 ? EventSeverity.Warning : EventSeverity.Success,
AccountId = destination.AccountId,
},
CancellationToken.None).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
}
private bool FileExists(string root, string relativePath)
{
try
{
return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath));
}
catch (ArgumentException)
{
return false;
}
}
private async Task CleanLeftoversAsync(IReadOnlyList<ExportRun> runs)
{
foreach (var run in runs)
{
try
{
if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId).ConfigureAwait(false) is { } destination)
{
await ExportLeftovers.CleanAsync(_env, run, destination, CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Best effort: the resume of that job cleans again.
}
}
}
private async Task StopRunsAsync(IEnumerable<ExportRun> runs)
{
foreach (var run in runs)
{
try
{
// The job never started: nothing was copied, there is nothing to resume.
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// RecoverAsync makes it «interrotto» at the next start.
}
}
}
private void EnsureIdle()
{
if (IsBusy)
{
throw new InvalidOperationException(BusyText);
}
if (_env.Gate?.Busy is { } busy)
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy));
}
}
private void StartCopyJob(IReadOnlyList<long> runIds) =>
StartJob(runIds, async (progress, token) =>
{
foreach (var runId in runIds)
{
token.ThrowIfCancellationRequested();
try
{
await Copier.CopyAsync(runId, progress, token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
{
// Stored with the run (Interrupted, with its error); the next destination still gets its files.
LastJobError = ExportText.ErrorText(ex);
}
}
});
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work)
{
lock (_gate)
{
if (_job is { Task.IsCompleted: false })
{
throw new InvalidOperationException(BusyText);
}
IDisposable? lease = null;
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
}
_job?.Cancellation.Dispose();
var cancellation = new CancellationTokenSource();
var reporter = new Reporter(this);
LastJobError = null;
_current = new ExportProgress(runIds.Count > 0 ? runIds[0] : null, runIds.Count > 0 ? ExportPhase.Preparing : ExportPhase.Checking, 0, 0, 0, 0, null, null, new Dictionary<ExportItemState, int>(), _env.Clock.Now);
var task = Task.Run(async () =>
{
try
{
await work(reporter, cancellation.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
// Interrupted: the states were saved by the job.
}
catch (Exception ex)
{
LastJobError = ExportText.ErrorText(ex);
}
finally
{
try
{
var last = _current is { } c ? c with { Phase = ExportPhase.Finished, UpdatedAt = _env.Clock.Now } : null;
if (last is not null)
{
Publish(last, force: true);
}
}
finally
{
lease?.Dispose();
}
try
{
JobFinished?.Invoke(this, new ExportJobFinished(runIds, CopiesChanged: true));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// A handler failed: the job is over all the same.
}
}
});
_job = new Job(runIds, cancellation, task);
}
}
private void Publish(ExportProgress progress, bool force)
{
lock (_gate)
{
_current = progress;
}
var now = Stopwatch.GetTimestamp();
var last = Interlocked.Read(ref _lastPublished);
if (!force && Stopwatch.GetElapsedTime(last, now) < ProgressInterval)
{
return;
}
Interlocked.Exchange(ref _lastPublished, now);
ProgressChanged?.Invoke(this, progress);
}
private sealed record Job(IReadOnlyList<long> RunIds, CancellationTokenSource Cancellation, Task Task);
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
{
private (ExportPhase, long?)? _phase;
public void Report(ExportProgress value)
{
var key = (value.Phase, value.RunId);
var changed = _phase != key;
_phase = key;
owner.Publish(value, changed);
}
}
}
@@ -0,0 +1,36 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// «Superato» (spec §4.10): the library file of an account changed («Tieni il più grande», a slot filled again with
/// other bytes, a rebuild that found other bytes on disk), so its copies are of a file the library no longer has. The
/// copies stay where they are; they are only marked, and the new file is never copied by itself.
/// </summary>
public static class ExportSupersession
{
/// <summary>
/// Marks the copies of the account's old file as superseded by the new one. A no-op when the old SHA-256 is null or
/// equal to the new one, or when a present file of that account still has the old SHA-256. Writes are not
/// cancellable: the library already changed.
/// </summary>
public static async Task<int> FileChangedAsync(IFebeStorage storage, long accountId, string? oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentException.ThrowIfNullOrWhiteSpace(newSha256);
if (oldSha256 is not { Length: 64 } || newSha256.Length != 64 || string.Equals(oldSha256, newSha256, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
var old = oldSha256.ToLowerInvariant();
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
{
return 0;
}
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
}
}
+138
View File
@@ -0,0 +1,138 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// Texts of the copies to external folders for Alberto (spec §4.10, §10.4): sentence case, dots for thousands, the same
/// names everywhere. Notes are stored in <c>export_item.note</c> as English codes (<see cref="Notes"/>) and shown with
/// <see cref="Note"/>.
/// </summary>
public static class ExportText
{
/// <summary>The codes of <c>export_item.note</c>.</summary>
public static class Notes
{
public const string SourceMissing = "SourceMissing";
public const string AccountRemoved = "AccountRemoved";
public const string Removed = "Removed";
public const string Superseded = "Superseded";
public const string CopiedForAnotherAccount = "CopiedForAnotherAccount";
public const string SourceChanged = "SourceChanged";
public const string TooLargeForFileSystem = "TooLargeForFileSystem";
public const string NameTaken = "NameTaken";
public const string PathTaken = "PathTaken";
public const string NotExported = "NotExported";
}
/// <summary>Name of the state of a file of a job.</summary>
public static string State(ExportItemState state) => state switch
{
ExportItemState.Pending => "In attesa",
ExportItemState.Copied => "Copiato",
ExportItemState.Adopted => "Adottato",
ExportItemState.AlreadyCopied => "Già copiato",
ExportItemState.Skipped => "Saltato",
ExportItemState.Missing => "File non presente in libreria",
ExportItemState.Failed => "Non riuscito",
_ => state.ToString(),
};
/// <summary>Name of the state of a copy.</summary>
public static string CopyState(ExportCopyState state) => state switch
{
ExportCopyState.Copied => "Copiato",
ExportCopyState.Removed => "Tolto",
ExportCopyState.Superseded => "Superato",
ExportCopyState.Failed => "Non riuscito",
_ => state.ToString(),
};
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
public static string? Note(string? code) => code switch
{
null or "" => null,
Notes.SourceMissing => "File non presente in libreria",
Notes.AccountRemoved => "L'account è stato rimosso",
Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)",
Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo",
Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)",
Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato",
Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta",
Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero",
Notes.PathTaken => "Percorso preso nel frattempo: riprova",
Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella",
_ => code,
};
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many;
/// <summary>The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.»</summary>
public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination)
{
ArgumentNullException.ThrowIfNull(summary);
ArgumentNullException.ThrowIfNull(destination);
int Of(ExportItemState s) => summary.ByState.GetValueOrDefault(s);
var parts = new List<string> { Count(Of(ExportItemState.Copied) + Of(ExportItemState.Adopted), "file copiato", "file copiati") };
if (Of(ExportItemState.AlreadyCopied) > 0)
{
parts.Add(Count(Of(ExportItemState.AlreadyCopied), "già copiato", "già copiati"));
}
if (Of(ExportItemState.Skipped) > 0)
{
parts.Add(Count(Of(ExportItemState.Skipped), "saltato", "saltati"));
}
if (Of(ExportItemState.Missing) > 0)
{
parts.Add(Count(Of(ExportItemState.Missing), "non presente in libreria", "non presenti in libreria"));
}
if (Of(ExportItemState.Failed) > 0)
{
parts.Add(Count(Of(ExportItemState.Failed), "non riuscito", "non riusciti"));
}
return $"Copia in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}.";
}
/// <summary>The event of «Controlla le copie».</summary>
public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination)
{
ArgumentNullException.ThrowIfNull(destination);
var text = $"Controllate {ItalianText.Number(checkedCopies)} copie in {ExportDestinations.Label(destination)}: ";
return text + (removed == 0 ? "ci sono tutte." : $"{Count(removed, "non c'è più (tolta)", "non ci sono più (tolte)")}.");
}
/// <summary>The space is not enough for the next file (decision D16).</summary>
public static string NoSpace(ExportDestination destination, long free, string file, long bytes) =>
$"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per copiare {file} ({ItalianText.Bytes(bytes)}) serve più spazio, "
+ $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi.";
/// <summary>The disk said it is full.</summary>
public static string DiskFull(ExportDestination destination) =>
$"Su {ExportDestinations.Label(destination)} non c'è più spazio: libera spazio, poi riprendi.";
/// <summary>A file over the FAT32 limit.</summary>
public static string TooLarge(long bytes) =>
$"Il file pesa {ItalianText.Bytes(bytes)}: su un disco FAT32 un file non può superare 4 GB.";
/// <summary>The destination was retired while a job used it.</summary>
public const string RetiredDestination = "La cartella è stata tolta.";
/// <summary>An error for Alberto, without paths of secrets: the message of a file error, or a generic sentence.</summary>
public static string ErrorText(Exception ex)
{
ArgumentNullException.ThrowIfNull(ex);
return ex switch
{
ExportFolderException folder => folder.Message,
IOException io => $"Errore di lettura o scrittura: {io.Message}",
UnauthorizedAccessException => "Febe non ha il permesso di scrivere nella cartella: controlla i permessi.",
_ => $"Errore inatteso ({ex.GetType().Name}): riprova; se si ripete, segnalalo.",
};
}
}
+4
View File
@@ -1,5 +1,6 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
@@ -545,6 +546,9 @@ public sealed class ImportCopier(ImportEnvironment env)
media.State,
env.Clock.Now,
none).ConfigureAwait(false);
// The copies of the old file in external folders are now «Superato» (spec §4.10): never copied again by themselves.
await ExportSupersession.FileChangedAsync(env.Storage, account.Id, media.Sha256, saved.Sha256, env.Clock.Now, none).ConfigureAwait(false);
await context.Ingest.TryAppendJournalAsync(entry.Id, none).ConfigureAwait(false);
if (entry.InstagramId is null && string.IsNullOrWhiteSpace(entry.Code) && !string.Equals(oldRelative, saved.RelativePath, StringComparison.Ordinal))
{
@@ -58,6 +58,12 @@ public sealed record ImportEnvironment
/// <summary>Reading, hashing and deleting source files.</summary>
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
/// <summary>
/// The gate shared with the export and the rebuild (spec §4.10: they never run together). Null: no other long work
/// to keep out (tests, the import alone).
/// </summary>
public LongWorkGate? Gate { get; init; }
/// <summary>Files analysed at the same time (hashing and decoding).</summary>
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
+17
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
@@ -283,6 +284,12 @@ public sealed class ImportService : IAsyncDisposable
{
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
// Checked up front too, so a refused start records nothing; StartJob takes the gate for real.
if (_env.Gate?.Busy is { } busy)
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy));
}
}
private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, CancellationToken, Task> work)
@@ -294,6 +301,12 @@ public sealed class ImportService : IAsyncDisposable
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
}
IDisposable? lease = null;
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value));
}
_job?.Cancellation.Dispose();
var cancellation = new CancellationTokenSource();
var reporter = new Reporter(this);
@@ -322,6 +335,10 @@ public sealed class ImportService : IAsyncDisposable
{
// The database is closing: nothing to publish.
}
finally
{
lease?.Dispose();
}
}
});
_job = new Job(runId, phase, cancellation, task);
@@ -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)
{
+85
View File
@@ -1,4 +1,5 @@
using Febe.Core.Domain;
using Febe.Core.Export;
namespace Febe.Core.Storage;
@@ -169,6 +170,90 @@ public interface IExportStore
/// <summary>Removes a job with its items. Only records: copies stay.</summary>
Task DeleteRunAsync(long runId, CancellationToken ct = default);
// Tappa E2: the copies to external folders ----------------------------------------------------------------------
/// <summary>Every recorded «Esporta questo account», in one read: only accounts with a row (absent = the default).</summary>
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
/// <summary>
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> is
/// this SHA-256: the library file that took the place of a copied one, never copied again by itself.
/// </summary>
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
/// <summary>«Una copia sola»: the newest Copied row of this original, variant and format in a destination in use, any account.</summary>
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
/// <summary>
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
/// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row
/// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
/// </summary>
Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
long destinationId,
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
CancellationToken ct = default);
/// <summary>«Controlla le copie»: Copied or Superseded rows become Removed («Tolto», state time <paramref name="at"/>) in one transaction. Returns the rows changed.</summary>
Task<int> MarkCopiesRemovedAsync(IReadOnlyList<long> copyIds, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// The library files of a «Copia in…», by media id, a page at a time (after <paramref name="afterMediaId"/>), present
/// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter
/// the files of its entries (with «Tutte le foto», only the files it shows).
/// </summary>
Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default);
/// <summary>Jobs for the Dashboard: newest first, at most <paramref name="limit"/>.</summary>
Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default);
/// <summary>
/// The mark of each tile of a page (decision D3 of tappa E2): of the files of the entry that are due (present, of an
/// account with «Esporta questo account» on, a destination and a content type it takes), how many are copied in
/// the account's effective destination. Entries without due files are absent.
/// </summary>
Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
Task<ExportAccountCounts> CountAccountFilesAsync(long accountId, CancellationToken ct = default);
}
/// <summary>A library file a «Copia in…» may copy (one row per media, with what the plan needs of its entry).</summary>
public sealed record ExportCandidate(
long MediaId,
long EntryId,
long AccountId,
EntryKind EntryKind,
MediaKind MediaKind,
MediaState State,
string? Sha256,
long? Bytes,
string? RelativePath,
int Position,
bool InHighlight);
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
public enum ExportMark
{
None,
Partly,
Copied,
}
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
/// <param name="Due">Files that go to the account's effective destination.</param>
/// <param name="NotCopied">Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included).</param>
/// <param name="RemovedOrSuperseded">Due files whose copy was removed from the destination or superseded: never copied again by themselves.</param>
/// <param name="Failed">Due files whose last copy failed (also counted in <paramref name="NotCopied"/>).</param>
public sealed record ExportAccountCounts(int Due, int NotCopied, int RemovedOrSuperseded, int Failed)
{
/// <summary>Due files copied.</summary>
public int Copied => Due - NotCopied - RemovedOrSuperseded;
}
/// <summary>A page of the items of an export job.</summary>
+19
View File
@@ -30,6 +30,22 @@ public enum LibraryKindFilter
Posts,
}
/// <summary>
/// The «Copie» filter (spec §4.6, §4.10), over the files that are due (decision D3 of tappa E2): «Non ancora copiati»,
/// «Copiati», «Tolti o superati». Null: «Tutti».
/// </summary>
public enum LibraryCopiesFilter
{
/// <summary>«Non ancora copiati»: an entry with a due file that «Copia in…» would copy (a failed copy included).</summary>
NotCopied,
/// <summary>«Copiati»: an entry whose due files are all copied in their effective destination.</summary>
Copied,
/// <summary>«Tolti o superati»: an entry with a due file whose copy was removed or superseded (never copied again by itself).</summary>
RemovedOrSuperseded,
}
/// <summary>Filters of the library mosaic and of the account tabs (spec §4.6).</summary>
public sealed record LibraryFilter
{
@@ -54,6 +70,9 @@ public sealed record LibraryFilter
/// <summary>Entry states shown. Null means <see cref="EntryStateRules.Visible"/> (entries with files).</summary>
public IReadOnlyList<EntryState>? States { get; init; }
/// <summary>«Copie» (null: «Tutti»). With «Tutte le foto» it applies to each file.</summary>
public LibraryCopiesFilter? Copies { get; init; }
}
/// <summary>
+42 -15
View File
@@ -343,13 +343,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// in SQL, no sort, and the day bounds are computed once per day rather than once per entry.
var command = c.Command(string.Empty);
var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true);
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true, files: files);
var counts = files ? FileCounts(c, filter) : null;
var perEntry = files && counts is null;
command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
: perEntry
? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
? $"SELECT e.published_at, {FilesOfEntry(c, filter)} FROM entry e WHERE {where} ORDER BY e.published_at"
: $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue;
@@ -417,15 +417,22 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// --------------------------------------------------------------------------------------------- «Tutte le foto»
/// <summary>The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video».</summary>
private static string FileTerms(LibraryFilter filter) =>
/// <summary>
/// The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video», and of the
/// class of the «Copie» filter. With «Copie» the term reads the entry <c>e</c> of the file too (account and kind), so
/// the caller must have it in scope (<see cref="NeedsEntry"/>).
/// </summary>
internal static string FileTerms(SqliteConnection c, LibraryFilter filter) =>
// The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index.
"+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty,
};
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies) : string.Empty);
/// <summary>The file terms of this filter read the entry of the file (the «Copie» filter).</summary>
private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null;
/// <summary>
/// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a
@@ -439,7 +446,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
return null;
}
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id");
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter)} GROUP BY m.entry_id");
var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader();
while (r.Read())
@@ -459,8 +467,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
/// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary>
private static string FilesOfEntry(LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})";
private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, filter)})";
/// <summary>
/// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as
@@ -575,7 +583,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var where = BuildWhere(c, command, filter, files: true);
var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}");
if (cursor is { } at)
{
@@ -607,8 +615,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
using var command = c.Command(string.Empty);
var list = command.AddList("f", chunk);
var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m";
command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail "
+ $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position";
+ $"FROM {from} WHERE m.entry_id IN ({list}) AND {FileTerms(c, filter)} ORDER BY m.entry_id, m.position";
using var r = command.ExecuteReader();
while (r.Read())
{
@@ -638,11 +647,16 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{
using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter);
var terms = FileTerms(filter);
var where = BuildWhere(c, command, filter, files: true);
var terms = FileTerms(c, filter);
var position = older ? ">" : "<";
// With «Copie» the file terms read the entry: the first branch then joins it instead of testing it apart.
var first = NeedsEntry(filter)
? $"SELECT EXISTS (SELECT 1 FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} AND {where}) "
: $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) ";
command.CommandText =
$"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} "
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "
first
+ $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) "
+ $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))";
command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position);
@@ -730,6 +744,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
}
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
/// <param name="c">The connection (for the accounts of a search and the export tables of «Copie»).</param>
/// <param name="command">The command that gets the parameters.</param>
/// <param name="filter">The filter.</param>
/// <param name="files">
/// «Tutte le foto»: «Copie» keeps an entry when one of its files is of the chosen class, rather than judging the entry
/// as a whole (all its due files copied, for «Copiati»).
/// </param>
/// <param name="aggregate">
/// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and
/// «Video» then test the key of each post, on a covering index, against one list of the entries that have such
@@ -738,7 +759,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
/// hundred posts in index order.
/// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two.
/// </param>
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false)
internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false, bool files = false)
{
var byList = aggregate && filter.AccountIds is not { Count: > 0 };
// The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index):
@@ -790,6 +811,12 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
command.With("@prov", Sql.Enum(provenance));
}
if (filter.Copies is { } copies)
{
var export = ExportFilterSql.Load(c);
parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies));
}
var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0)
{
+225
View File
@@ -0,0 +1,225 @@
using System.Globalization;
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
namespace Febe.Data.Stores;
/// <summary>
/// What the «Copie» filter, the tile marks and the account counts need of the export tables, read once per query:
/// the destinations in use, the switches that are off, «Una copia sola», and whether any copy, failure or removed or
/// superseded row exists at all (so the common cases pay nothing for what is not there).
/// </summary>
internal sealed record ExportFilterContext(
long? GeneralId,
ContentTypes GeneralTypes,
IReadOnlyList<(long AccountId, long DestinationId, ContentTypes Types)> Own,
IReadOnlySet<long> Off,
SamePostCopies SamePost,
bool HasCopies,
bool HasFailed,
bool HasHistory)
{
public bool HasDestination => GeneralId is not null || Own.Count > 0;
public IEnumerable<long> InUse => (GeneralId is { } g ? [g] : Array.Empty<long>()).Concat(Own.Select(o => o.DestinationId));
}
/// <summary>
/// The SQL of decision D3 of tappa E2 on <c>media m</c> joined to its <c>entry e</c>: a file is <b>due</b> when it is
/// present, its account has «Esporta questo account» on and an effective destination (its own folder in use, else the
/// general folder in use), and that destination takes its content type (D4). The values (ids and content types) are
/// integers from the database and are written into the text, so the terms can be repeated in one statement without
/// parameters colliding.
/// </summary>
internal static class ExportFilterSql
{
private const string Present = "m.sha256 IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')";
/// <summary>The content type of a file as a bit of <see cref="ContentTypes"/>, as <see cref="ExportPaths.TypeOf"/>.</summary>
internal const string TypeOfFile =
"(CASE e.kind WHEN 'Post' THEN (CASE m.kind WHEN 'Photo' THEN 1 ELSE 2 END) "
+ "WHEN 'Story' THEN (4 | (CASE WHEN EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id) THEN 8 ELSE 0 END)) "
+ "WHEN 'Highlight' THEN 8 WHEN 'Tagged' THEN 16 WHEN 'ProfilePicture' THEN 32 ELSE 0 END)";
/// <summary>Reads the context of one query.</summary>
public static ExportFilterContext Load(SqliteConnection c)
{
long? general = null;
var generalTypes = ContentTypes.None;
var own = new List<(long, long, ContentTypes)>();
using (var r = c.Command("SELECT id, scope, account_id, content_types FROM export_destination WHERE removed_at IS NULL").ExecuteReader())
{
while (r.Read())
{
if (r.GetString(1) == nameof(ExportScope.General))
{
general = r.GetInt64(0);
generalTypes = (ContentTypes)r.GetInt32(3);
}
else if (r.GetInt64OrNull(2) is { } account)
{
own.Add((account, r.GetInt64(0), (ContentTypes)r.GetInt32(3)));
}
}
}
var off = new HashSet<long>();
using (var r = c.Command("SELECT account_id FROM export_account WHERE enabled = 0").ExecuteReader())
{
while (r.Read())
{
off.Add(r.GetInt64(0));
}
}
var samePost = c.Command("SELECT value FROM setting WHERE key = @k").With("@k", ExportSettingKeys.SamePost).ExecuteScalar() is string value
&& string.Equals(value, nameof(SamePostCopies.OneOnly), StringComparison.Ordinal)
? SamePostCopies.OneOnly
: SamePostCopies.OnePerAccount;
if (general is null && own.Count == 0)
{
return new ExportFilterContext(null, ContentTypes.None, own, off, samePost, false, false, false);
}
var inUse = string.Join(", ", (general is { } g ? [g] : Array.Empty<long>()).Concat(own.Select(o => o.Item2)).Select(Literal));
bool Any(string states) => c.Command(
$"SELECT EXISTS (SELECT 1 FROM export_copy WHERE destination_id IN ({inUse}) AND state IN ({states}))").ScalarInt64() != 0;
return new ExportFilterContext(general, generalTypes, own, off, samePost, Any("'Copied'"), Any("'Failed'"), Any("'Removed', 'Superseded'"));
}
/// <summary>The file <c>m</c> of entry <c>e</c> is due (D3).</summary>
public static string DueFile(ExportFilterContext x)
{
if (!x.HasDestination)
{
return "0";
}
var general = x.GeneralId is null ? "0" : TypeTerm(x.GeneralTypes);
var branches = new StringBuilder();
foreach (var (account, _, types) in x.Own)
{
branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {(x.Off.Contains(account) ? "0" : TypeTerm(types))}");
}
foreach (var account in x.Off.Where(a => x.Own.All(o => o.AccountId != a)))
{
branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN 0");
}
var destination = branches.Length == 0 ? general : $"(CASE e.account_id{branches} ELSE {general} END)";
return destination == "1" ? $"({Present})" : $"({Present} AND {destination})";
}
/// <summary>The file is copied in its effective destination (or, with «Una copia sola», in any destination in use).</summary>
public static string Copied(ExportFilterContext x)
{
if (!x.HasCopies)
{
return "0";
}
return x.SamePost == SamePostCopies.OneOnly
? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame')"
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant <> 'Frame')";
}
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
public static string Failed(ExportFilterContext x) => !x.HasFailed
? "0"
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')";
/// <summary>
/// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was
/// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index.
/// </summary>
public static string Replaced(ExportFilterContext x)
{
if (!x.HasHistory)
{
return "0";
}
var destination = DestinationOf(x);
return $"(NOT {Copied(x)} AND NOT {Failed(x)} AND ("
+ $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL) "
+ $"OR EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
+ "AND c.state IN ('Superseded', 'Removed'))))";
}
/// <summary>«Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded).</summary>
public static string NotCopied(ExportFilterContext x) => x.HasHistory ? $"(NOT {Copied(x)} AND NOT {Replaced(x)})" : $"(NOT {Copied(x)})";
/// <summary>The term of «Tutte le foto» on <c>m</c> (with <c>e</c> its entry): a due file of the chosen class.</summary>
public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter) => filter switch
{
LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {Copied(x)})",
LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x)})",
LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x)})",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
};
/// <summary>
/// The term of the grouped mosaic on <c>entry e</c>. «Copiati»: every due file copied, behind a list of the entries
/// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due
/// file removed or superseded, behind the list of the entries with such a row.
/// </summary>
public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter)
{
if (!x.HasDestination)
{
return "0";
}
string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})";
return filter switch
{
LibraryCopiesFilter.Copied => !x.HasCopies
? "0"
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) "
+ $"AND c.state = 'Copied' AND c.variant <> 'Frame') AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}",
LibraryCopiesFilter.NotCopied => Files(NotCopied(x)),
LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory
? "0"
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = coalesce(c.superseded_by_sha256, c.source_sha256) "
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state IN ('Removed', 'Superseded')) AND {Files(Replaced(x))}",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null),
};
}
/// <summary>With «Tutte le foto» an entry qualifies when one of its files does.</summary>
public static string EntryOfFiles(ExportFilterContext x, LibraryCopiesFilter filter) =>
x.HasDestination ? $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {FileTerm(x, filter)})" : "0";
/// <summary>The effective destination of the account of <c>e</c>: its own folder, else the general one (NULL: none).</summary>
public static string DestinationOf(ExportFilterContext x)
{
var general = x.GeneralId is { } g ? Literal(g) : "NULL";
if (x.Own.Count == 0)
{
return general;
}
var builder = new StringBuilder("(CASE e.account_id");
foreach (var (account, destination, _) in x.Own)
{
builder.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {destination}");
}
return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString();
}
private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal));
private static string TypeTerm(ContentTypes types) =>
(types & ContentTypes.All) == ContentTypes.All ? "1"
: (types & ContentTypes.All) == ContentTypes.None ? "0"
: string.Create(CultureInfo.InvariantCulture, $"(({TypeOfFile} & {(int)(types & ContentTypes.All)}) <> 0)");
private static string Literal(long value) => value.ToString(CultureInfo.InvariantCulture);
}
+327
View File
@@ -1,4 +1,5 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Microsoft.Data.Sqlite;
@@ -868,4 +869,330 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery();
},
ct);
// Tappa E2 -------------------------------------------------------------------------------------------------------
/// <summary>SQLite allows 999 parameters per statement: id lists go in chunks below that.</summary>
private const int IdChunk = 900;
internal const string ReplacedCopySql = $"""
SELECT {CopyColumns} FROM export_copy
WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed')
ORDER BY id DESC LIMIT 1
""";
internal const string CopiedElsewhereSql = $"""
SELECT {CopyColumns} FROM export_copy
WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL)
ORDER BY id DESC LIMIT 1
""";
internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit";
/// <summary>The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256.</summary>
internal static string CopyStatesSql(string shaList) => $"""
SELECT account_id, source_sha256, state, id FROM export_copy
WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original'
""";
/// <summary>The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by).</summary>
internal static string ReplacedStatesSql(string shaList) => $"""
SELECT account_id, superseded_by_sha256, state, id FROM export_copy
WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND state IN ('Superseded', 'Removed')
""";
private const string CandidateColumns =
"m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, "
+ "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)";
private static ExportCandidate ReadCandidate(SqliteDataReader r) => new(
r.GetInt64(0),
r.GetInt64(1),
r.GetInt64(2),
r.GetEnum<EntryKind>(3),
r.GetEnum<MediaKind>(4),
r.GetEnum<MediaState>(5),
r.GetTextOrNull(6),
r.GetInt64OrNull(7),
r.GetTextOrNull(8),
r.GetInt32(9),
r.GetBool(10));
public Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
c =>
{
var switches = new Dictionary<long, bool>();
using var r = c.Command("SELECT account_id, enabled FROM export_account").ExecuteReader();
while (r.Read())
{
switches[r.GetInt64(0)] = r.GetBool(1);
}
return switches;
},
ct);
public Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c => ReadFirst(c.Command(ReplacedCopySql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy),
ct);
}
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default)
{
var sha = ExportValues.Sha(sha256, nameof(sha256));
return db.ReadAsync(
c => ReadFirst(c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)), ReadCopy),
ct);
}
public Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
long destinationId,
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(keys);
var wanted = keys.Select(k => (k.AccountId, Sha256: ExportValues.Sha(k.Sha256, nameof(keys)))).ToHashSet();
return db.ReadAsync<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
c =>
{
// Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row
// replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here.
var current = new Dictionary<(long, string), ExportCopyState>();
var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
void Keep(Dictionary<(long, string), (long Id, ExportCopyState State)> into, (long, string) key, long id, ExportCopyState state)
{
if (!into.TryGetValue(key, out var seen) || seen.Id < id)
{
into[key] = (id, state);
}
}
void Read(Func<string, string> sql, string[] chunk, Action<(long, string), ExportCopyState, long> add)
{
using var command = c.Command(string.Empty).With("@d", destinationId);
command.CommandText = sql(command.AddList("h", chunk));
using var r = command.ExecuteReader();
while (r.Read())
{
var key = (r.GetInt64(0), r.GetString(1));
if (wanted.Contains(key))
{
add(key, r.GetEnum<ExportCopyState>(2), r.GetInt64(3));
}
}
}
foreach (var chunk in wanted.Select(k => k.Sha256).Distinct(StringComparer.Ordinal).Chunk(IdChunk))
{
Read(CopyStatesSql, chunk, (key, state, id) =>
{
if (state is ExportCopyState.Copied or ExportCopyState.Failed)
{
current[key] = state;
}
else
{
Keep(newest, key, id, state);
}
});
Read(ReplacedStatesSql, chunk, (key, state, id) => Keep(replaced, key, id, state));
}
var result = new Dictionary<(long AccountId, string Sha256), ExportCopyState>();
foreach (var key in wanted)
{
if (current.TryGetValue(key, out var state))
{
result[key] = state;
}
else if (newest.TryGetValue(key, out var history))
{
result[key] = history.State;
}
else if (replaced.TryGetValue(key, out var by))
{
result[key] = by.State;
}
}
return result;
},
ct);
}
public Task<int> MarkCopiesRemovedAsync(IReadOnlyList<long> copyIds, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(copyIds);
if (copyIds.Count == 0)
{
return Task.FromResult(0);
}
return db.WriteAsync(
w =>
{
var changed = 0;
foreach (var chunk in copyIds.Distinct().Chunk(IdChunk))
{
var command = w.Command(string.Empty).With("@at", Sql.Time(at));
var list = command.AddList("i", chunk);
// A Superseded row keeps the SHA-256 of the file that replaced it: still never copied again by itself.
command.CommandText = $"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({list}) AND state IN ('Copied', 'Superseded')";
changed += command.ExecuteNonQuery();
}
return changed;
},
ct);
}
public Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(selection);
var n = Math.Clamp(limit, 1, 10_000);
return db.ReadAsync<IReadOnlyList<ExportCandidate>>(
c =>
{
List<ExportCandidate> Page(Func<SqliteCommand, string> where)
{
using var command = c.Command(string.Empty).With("@after", afterMediaId).With("@n", (long)n);
var terms = where(command);
command.CommandText = $"SELECT {CandidateColumns} FROM media m JOIN entry e ON e.id = m.entry_id WHERE {terms} AND m.id > @after ORDER BY m.id LIMIT @n";
return ReadAll(command, ReadCandidate);
}
// Id lists go in chunks: each chunk gives its first n files after the key, and the first n of all of them are
// the page.
List<ExportCandidate> ByIds(IReadOnlyList<long> ids, string column) =>
ids.Distinct().Chunk(IdChunk)
.SelectMany(chunk => Page(command => $"{column} IN ({command.AddList("x", chunk)})"))
.OrderBy(x => x.MediaId)
.Take(n)
.ToList();
return selection switch
{
ExportSelection.Media media => ByIds(media.MediaIds, "m.id"),
ExportSelection.Entries entries => ByIds(entries.EntryIds, "m.entry_id"),
ExportSelection.Account account => Page(command =>
{
command.With("@acc", account.AccountId);
return $"e.account_id = @acc AND +e.state IN ({command.AddList("st", EntryStateRules.Visible.Select(s => s.ToString()))})";
}),
ExportSelection.Filter filter => Page(command =>
{
var where = EntryStore.BuildWhere(c, command, filter.LibraryFilter, aggregate: true, files: filter.Mode == MosaicMode.Files);
// «Tutte le foto»: only the files the mosaic shows (EntryStore.FileTerms, on m with its entry e).
return filter.Mode == MosaicMode.Files ? $"{where} AND {EntryStore.FileTerms(c, filter.LibraryFilter)}" : where;
}),
_ => throw new ArgumentOutOfRangeException(nameof(selection)),
};
},
ct);
}
public Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(
c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun),
ct);
public Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportMark>>(
c =>
{
var marks = new Dictionary<long, ExportMark>();
var x = ExportFilterSql.Load(c);
if (!x.HasDestination || entryIds.Count == 0)
{
return marks;
}
foreach (var chunk in entryIds.Distinct().Chunk(IdChunk))
{
using var command = c.Command(string.Empty);
var list = command.AddList("x", chunk);
command.CommandText = $"""
SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END)
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)}
GROUP BY m.entry_id
""";
using var r = command.ExecuteReader();
while (r.Read())
{
var due = r.GetInt32(1);
var copied = r.GetInt32(2);
marks[r.GetInt64(0)] = copied == 0 ? ExportMark.None : copied >= due ? ExportMark.Copied : ExportMark.Partly;
}
}
return marks;
},
ct);
}
public Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(mediaIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportMark>>(
c =>
{
var marks = new Dictionary<long, ExportMark>();
var x = ExportFilterSql.Load(c);
if (!x.HasDestination || mediaIds.Count == 0)
{
return marks;
}
foreach (var chunk in mediaIds.Distinct().Chunk(IdChunk))
{
using var command = c.Command(string.Empty);
var list = command.AddList("x", chunk);
command.CommandText = $"""
SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id
WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)}
""";
using var r = command.ExecuteReader();
while (r.Read())
{
marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None;
}
}
return marks;
},
ct);
}
public Task<ExportAccountCounts> CountAccountFilesAsync(long accountId, CancellationToken ct = default) =>
db.ReadAsync(
c =>
{
var x = ExportFilterSql.Load(c);
if (!x.HasDestination)
{
return new ExportAccountCounts(0, 0, 0, 0);
}
using var command = c.Command($"""
SELECT COUNT(*),
ifnull(SUM(CASE WHEN {ExportFilterSql.NotCopied(x)} THEN 1 ELSE 0 END), 0),
ifnull(SUM(CASE WHEN {ExportFilterSql.Replaced(x)} THEN 1 ELSE 0 END), 0),
ifnull(SUM(CASE WHEN {ExportFilterSql.Failed(x)} AND NOT {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END), 0)
FROM media m JOIN entry e ON e.id = m.entry_id
WHERE e.account_id = @a AND {ExportFilterSql.DueFile(x)}
""").With("@a", accountId);
using var r = command.ExecuteReader();
r.Read();
return new ExportAccountCounts(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt32(3));
},
ct);
}
+5 -3
View File
@@ -231,14 +231,16 @@ public static class SettingsApi
throw new BadRequestException("Per confermare scrivi la parola «ricostruisci».");
}
// An import service built without the shared gate (a composition of tests) is still checked by itself.
if ((await import.GetAsync(ct).ConfigureAwait(false)).ActiveRunId is not null)
{
throw new BadRequestException("C'è un'importazione al lavoro: aspetta che finisca, poi ricostruisci.");
throw new BadRequestException(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import));
}
if (!job.TryStart())
// The gate covers import, copies to external folders and another rebuild (spec §4.10).
if (!job.TryStart(out var busy))
{
throw new BadRequestException("La ricostruzione è già in corso.");
throw new BadRequestException(busy ?? LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild));
}
return ApiHttp.Message("Ricostruzione avviata: Febe rilegge le cartelle degli account e i loro file _febe.jsonl. Nessun file viene spostato o cancellato.");
+4 -1
View File
@@ -73,10 +73,13 @@ public static class FebeWeb
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
services.TryAddSingleton<FolderSizes>();
// One gate for import, copies to external folders and rebuild (spec §4.10); the composition may register its own
// instance first, the one its import service already uses.
services.TryAddSingleton<LongWorkGate>();
services.TryAddSingleton<RebuildJob>();
services.TryAddSingleton(sp => sp.GetService<ImportService>() is { } import
? new ImportHub(import, sp.GetRequiredService<IClock>(), sp.GetRequiredService<LibraryChanges>())
: new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>()));
: new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>(), sp.GetRequiredService<LongWorkGate>()));
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
+8 -2
View File
@@ -21,6 +21,7 @@ public sealed class ImportHub : IAsyncDisposable
private readonly IClock _clock;
private readonly FebeWebOptions? _options;
private readonly LibraryChanges _changes;
private readonly LongWorkGate? _longWork;
private readonly bool _owned;
private ImportService? _service;
private bool _stale;
@@ -35,9 +36,13 @@ public sealed class ImportHub : IAsyncDisposable
_service.ProgressChanged += OnProgress;
}
/// <summary>Builds its own service over the library of the web host.</summary>
public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes)
/// <summary>
/// Builds its own service over the library of the web host. <paramref name="longWork"/> is the gate shared with the
/// copies to external folders and the rebuild (null: the import alone, as in some tests).
/// </summary>
public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes, LongWorkGate? longWork = null)
{
_longWork = longWork;
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_library = library ?? throw new ArgumentNullException(nameof(library));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
@@ -127,6 +132,7 @@ public sealed class ImportHub : IAsyncDisposable
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder,
DataFolder = library.Data.Root,
Gate = _longWork,
});
}
+22 -6
View File
@@ -156,9 +156,10 @@ public sealed class FolderSizes(IClock clock)
/// <summary>
/// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report,
/// one at a time. It never moves, renames or deletes a file (rule 12).
/// one at a time, never together with an import or a copy to external folders (the shared <see cref="LongWorkGate"/>,
/// spec §4.10). It never moves, renames or deletes a file (rule 12).
/// </summary>
public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes)
public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate)
{
private readonly Lock _gate = new();
private Task? _task;
@@ -176,18 +177,32 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
}
}
/// <summary>Starts the rebuild; false when one is already running.</summary>
public bool TryStart()
/// <summary>Starts the rebuild; false when one is already running or another long job holds the gate.</summary>
public bool TryStart() => TryStart(out _);
/// <summary>
/// Starts the rebuild; false, with the Italian reason in <paramref name="busy"/>, when a rebuild, an import or a copy
/// to external folders is running.
/// </summary>
public bool TryStart(out string? busy)
{
lock (_gate)
{
if (_task is { IsCompleted: false })
{
busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild);
return false;
}
if (!gate.TryEnter(LongWorkKind.Rebuild, out var lease, out var holder))
{
busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, holder!.Value);
return false;
}
busy = null;
State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
_task = Task.Run(RunAsync);
_task = Task.Run(() => RunAsync(lease));
return true;
}
}
@@ -195,8 +210,9 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
/// <summary>Waits for the running rebuild (tests).</summary>
public Task WaitAsync() => _task ?? Task.CompletedTask;
private async Task RunAsync()
private async Task RunAsync(IDisposable lease)
{
using var held = lease;
var progress = new SyncProgress<RebuildProgress>(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked });
try
{
@@ -0,0 +1,124 @@
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Data;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The «Copie» filter, the tile marks, the account counts and the store lookups of tappa E2 on a small real database
/// (decision D3: only due files count). WP5 of tappa E2 adds the full set and the timings over 200,000 entries.
/// </summary>
[TestClass]
public sealed class ExportCopiesFilterTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheCopiesFilterSplitsDueFilesIntoCopiedNotCopiedAndRemoved()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await ExportWorld.CreateAsync(db);
// A post of marta.demo with two photos: only the first is copied («Copiato in parte»).
var pair = await db.Entries.AddAsync(
Make.Entry(w.Marta, "777", Make.T0.AddDays(1)),
[Make.Stored(Make.Photo(1), Make.Sha(2), "post/b1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(3), "post/b2.jpg")],
ct);
var pairEntry = pair.Stored.Entry.Id;
// Marta's own folder has her shared post and the first photo of the pair; luca.demo's tagged post was copied
// in the general folder and then removed from it.
await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct);
await db.Exports.AddCopyAsync(w.WholeCopy("b1.jpg", destination: w.Own, media: pair.Stored.Media[0].Id) with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) }, ct);
var removed = await db.Exports.AddCopyAsync(
w.WholeCopy("luca.demo/a.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed },
ct);
Assert.IsTrue(AreSame([w.MartaEntry], await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)));
Assert.IsTrue(AreSame([pairEntry], await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)));
Assert.IsTrue(AreSame([w.LucaEntry], await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct)));
Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, ct));
Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, TestZones.Rome, ct: ct)).Sum(d => d.Count));
// «Tutte le foto» judges each file: the copied photo of the pair is «Copiato», the other «Non ancora copiato».
var copiedFiles = await FilesAsync(db, LibraryCopiesFilter.Copied, ct);
Assert.IsTrue(AreSame([w.MartaMedia, pair.Stored.Media[0].Id], copiedFiles));
Assert.IsTrue(AreSame([pair.Stored.Media[1].Id], await FilesAsync(db, LibraryCopiesFilter.NotCopied, ct)));
Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Marta] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
Assert.AreEqual(0, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Luca] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
var marks = await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry, pairEntry], ct);
Assert.AreEqual(ExportMark.Copied, marks[w.MartaEntry]);
Assert.AreEqual(ExportMark.None, marks[w.LucaEntry]);
Assert.AreEqual(ExportMark.Partly, marks[pairEntry]);
var fileMarks = await db.Exports.GetFileMarksAsync([.. pair.Stored.Media.Select(m => m.Id)], ct);
Assert.AreEqual(ExportMark.Copied, fileMarks[pair.Stored.Media[0].Id]);
Assert.AreEqual(ExportMark.None, fileMarks[pair.Stored.Media[1].Id]);
Assert.AreEqual(new ExportAccountCounts(3, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct));
// «Esporta questo account» off: marta.demo has no due files any more.
await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct);
Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct)).ContainsKey(w.MartaEntry));
var switches = await db.Exports.ListAccountExportSwitchesAsync(ct);
Assert.IsFalse(switches[w.Marta]);
Assert.IsFalse(switches.ContainsKey(w.Luca));
// «Controlla le copie» turns a Copied row into Removed.
Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([removed.Id, (await db.Exports.FindCurrentCopyAsync(new ExportCopyIdentity(w.Own, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null), ct))!.Id], Make.T0.AddDays(2), ct));
}
[TestMethod]
public async Task TheStoreAnswersThePlannerLookups()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var db = await TestDatabase.OpenAsync(temp);
var w = await ExportWorld.CreateAsync(db);
var copy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct);
await db.Exports.AddCopyAsync(
w.WholeCopy("luca.demo/old.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with
{
SourceSha256 = Make.Sha(9),
CopySha256 = Make.Sha(9),
State = ExportCopyState.Superseded,
SupersededBySha256 = Make.Sha(1),
},
ct);
var states = await db.Exports.GetCopyStatesAsync(w.General, [(w.Luca, Make.Sha(1)), (w.Marta, Make.Sha(1))], ct);
Assert.AreEqual(ExportCopyState.Superseded, states[(w.Luca, Make.Sha(1))]);
Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(1))));
Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]);
Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct));
Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct));
Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct))!.Id);
var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct);
Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId);
Assert.AreEqual(EntryKind.Post, byAccount[0].EntryKind);
var byFilter = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Files), 0, 10, ct);
Assert.HasCount(2, byFilter);
Assert.AreEqual(w.LucaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([w.LucaEntry, w.MartaEntry]), w.MartaMedia, 10, ct)).Single().MediaId);
Assert.AreEqual(w.MartaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Media([w.MartaMedia, w.LucaMedia]), 0, 1, ct)).Single().MediaId);
var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 }, ct);
Assert.AreEqual(run.Id, (await db.Exports.ListRecentRunsAsync(5, ct)).Single().Id);
}
private static async Task<List<long>> EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) =>
[.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)];
private static async Task<List<long>> FilesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) =>
[.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter }, Mode = MosaicMode.Files }, ct)).Tiles.Select(t => t.CoverMediaId!.Value)];
private static bool AreSame(IEnumerable<long> expected, IEnumerable<long> actual) => expected.Order().SequenceEqual(actual.Order());
}
@@ -0,0 +1,358 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The copy job of tappa E2 (WP1b) on a real library and real folders: paths, never overwriting, adoption by path,
/// «Tolto» and «Copia di nuovo», pause of a missing destination, engine sessions, leftovers and «Superato». WP5 adds
/// the full set.
/// </summary>
[TestClass]
public sealed class ExportCopyJobTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task ACopyGoesUnderTheAccountSegmentAndIsNotWrittenTwice()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "777", Make.T0.AddDays(-1)), [TestFile.Photo(1, 1), TestFile.Photo(2, 2)]);
var usb = await w.GeneralAsync(ct);
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(2, plan.Files);
Assert.AreEqual(usb.Id, plan.Destinations.Single().DestinationId);
Assert.IsNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError);
foreach (var media in post.Media)
{
var copied = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(media.RelativePath!));
Assert.IsTrue(File.Exists(copied), copied);
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(w.Library.Layout.FullPath(w.Marta, media.RelativePath!), ct), await File.ReadAllBytesAsync(copied, ct));
}
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*.part", SearchOption.AllDirectories));
var report = await w.Service.Reports.BuildAsync(run.Id, ct);
Assert.AreEqual(2, report.ByState[ExportItemState.Copied]);
Assert.AreEqual(2, report.Accounts.Single().Copied);
// Nothing is written twice: the plan says «già copiati», a second job finds them.
var again = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.AreEqual(0, again.Files);
Assert.AreEqual(2, again.AlreadyCopied);
var second = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(2, (await w.Library.Db.Exports.GetRunSummaryAsync(second.Runs.Single().Id, ct)).ByState[ExportItemState.AlreadyCopied]);
Assert.HasCount(2, Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task ARemovedCopyIsNotCopiedAgainUnlessAsked()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "778", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var copy = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(post.Media[0].RelativePath!));
File.Delete(copy); // Alberto removed it from the disk
var skipped = await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = skipped.Runs.Single().Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Skipped, item.State);
Assert.AreEqual(ExportText.Notes.Removed, item.Note);
Assert.IsFalse(File.Exists(copy));
var plan = await w.Service.PlanAsync(request, ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
var again = await w.Service.StartAsync(request with { CopyAgain = true }, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(1, again.Plan.Files);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = again.Runs.Single().Id }, ct)).Single().State);
Assert.IsTrue(File.Exists(copy));
}
[TestMethod]
public async Task AFileAlreadyThereIsAdoptedAndAnotherFileIsNeverOverwritten()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var first = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "779", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4)]);
var second = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "780", Make.T0.AddDays(-2)), [TestFile.Photo(1, 5)]);
await w.GeneralAsync(ct);
var same = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(first.Media[0].RelativePath!));
var other = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(second.Media[0].RelativePath!));
Directory.CreateDirectory(Path.GetDirectoryName(same)!);
Directory.CreateDirectory(Path.GetDirectoryName(other)!);
File.Copy(w.Library.Layout.FullPath(w.Marta, first.Media[0].RelativePath!), same);
await File.WriteAllBytesAsync(other, [1, 2, 3], ct); // something else with that name
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var items = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = start.Runs.Single().Id }, ct)).ToDictionary(i => i.MediaId!.Value);
Assert.AreEqual(ExportItemState.Adopted, items[first.Media[0].Id].State);
Assert.AreEqual(ExportItemState.Copied, items[second.Media[0].Id].State);
Assert.AreEqual(ExportText.Notes.NameTaken, items[second.Media[0].Id].Note);
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(other, ct));
var renamed = Path.Combine(w.Usb, LibraryLayout.ToPlatform(items[second.Media[0].Id].RelativePath!));
StringAssert.EndsWith(renamed, " (2).jpg");
Assert.IsTrue(File.Exists(renamed));
Assert.AreEqual(ExportCopyOrigin.Adopted, (await w.Library.Db.Exports.GetCopyAsync(items[first.Media[0].Id].CopyId!.Value, ct))!.Origin);
}
[TestMethod]
public async Task AMissingDestinationPausesAndIsNeverCreated()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "781", Make.T0.AddDays(-1)), [TestFile.Photo(1, 6)]);
var usb = await w.GeneralAsync(ct);
Directory.Delete(w.Usb); // the disk was unplugged
var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
Assert.IsNotNull(plan.Destinations.Single().Problem);
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.IsFalse(Directory.Exists(w.Usb));
var paused = (await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
Assert.IsNotNull(paused.PausedAt);
Assert.Contains("non è raggiungibile", paused.LastError!);
Assert.AreEqual(ExportItemState.Pending, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single().State);
// The disk is back: «Riprendi» clears the pause and copies.
Directory.CreateDirectory(w.Usb);
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsNull((await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
}
[TestMethod]
public async Task CopiesWaitForTheEngineSessionAndForSpace()
{
var ct = TestContext.CancellationToken;
var session = new CountedSession(3);
var disk = new FakeDisk();
await using var w = await World.CreateAsync(session, disk);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "782", Make.T0.AddDays(-1)), [TestFile.Photo(1, 7)]);
await w.GeneralAsync(ct);
var before = w.Library.Clock.Now;
disk.Free = 1000; // less than the file plus 64 MB
var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct);
await w.Service.WaitAsync(ct);
var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!;
Assert.AreEqual(ExportRunState.Paused, run.State);
Assert.Contains("margine di 64 MB", run.LastError!);
Assert.AreEqual(w.Library.Clock.Now, before + TimeSpan.FromSeconds(15)); // three polls of 5 s while the session ran
disk.Free = null;
disk.Max = 10; // a FAT32 disk, with a tiny limit for the test
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual(ExportItemState.Failed, item.State);
Assert.AreEqual(ExportText.Notes.TooLargeForFileSystem, item.Note);
Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.AreEqual(ExportCopyState.Failed, (await w.Library.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.State);
}
[TestMethod]
public async Task LeftoversGoOnlyInTheFoldersOfAnUnfinishedJob()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "783", Make.T0.AddDays(-1)), [TestFile.Photo(1, 8)]);
var usb = await w.GeneralAsync(ct);
var relative = "marta.demo/" + post.Media[0].RelativePath;
var folder = Path.GetDirectoryName(Path.Combine(w.Usb, LibraryLayout.ToPlatform(relative)))!;
Directory.CreateDirectory(folder);
var leftover = Path.Combine(folder, ".febe-0123456789ab.part");
var elsewhere = Path.Combine(w.Usb, ".febe-ba9876543210.part");
await File.WriteAllBytesAsync(leftover, [9], ct);
await File.WriteAllBytesAsync(elsewhere, [9], ct);
// A job interrupted after it recorded the target path.
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
await w.Library.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct);
Assert.AreEqual(1, await w.Service.RecoverAsync(ct));
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Interrupted, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State);
Assert.IsFalse(File.Exists(leftover));
Assert.IsTrue(File.Exists(elsewhere)); // the root holds no item: never cleaned
await w.Service.ResumeAsync(null, ct);
await w.Service.WaitAsync(ct);
Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.GetItemAsync(item.Id, ct))!.State);
}
[TestMethod]
public async Task ASwitchedOffAccountIsSkippedWhenAJobResumes()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "786", Make.T0.AddDays(-1)), [TestFile.Photo(1, 11)]);
var usb = await w.GeneralAsync(ct);
var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = w.Library.Clock.Now }, ct);
await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
await w.Service.Destinations.SetAccountEnabledAsync(w.Marta.Id, false, ct);
await w.Service.ResumeAsync([run.Id], ct);
await w.Service.WaitAsync(ct);
var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single();
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotExported), (item.State, item.Note));
Assert.IsEmpty(Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories));
}
[TestMethod]
public async Task AChangedLibraryFileSupersedesItsCopies()
{
var ct = TestContext.CancellationToken;
await using var w = await World.CreateAsync();
var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "784", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]);
await w.GeneralAsync(ct);
var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id));
await w.Service.StartAsync(request, ct);
await w.Service.WaitAsync(ct);
// «Tieni il più grande» put another file in the slot.
var oldSha = post.Media[0].Sha256!;
var newSha = Make.Sha(4242);
await w.Library.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, 10, newSha, null, 1, 1, null, false), MediaState.Downloaded, w.Library.Clock.Now, ct);
Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, newSha, newSha, w.Library.Clock.Now, ct));
Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, oldSha, newSha, w.Library.Clock.Now, ct));
var copies = await w.Library.Db.Exports.ListCopiesBySha256Async(newSha, ct);
Assert.AreEqual(ExportCopyState.Superseded, copies.Single().State);
Assert.AreEqual(1, (await w.Service.PlanAsync(request, ct)).RemovedOrSuperseded);
}
[TestMethod]
public async Task AnExportDoesNotStartWhileAnImportHoldsTheGate()
{
var ct = TestContext.CancellationToken;
var gate = new LongWorkGate();
await using var w = await World.CreateAsync(gate: gate);
await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "785", Make.T0.AddDays(-1)), [TestFile.Photo(1, 10)]);
await w.GeneralAsync(ct);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct));
Assert.StartsWith("C'è un'importazione al lavoro", refused.Message);
Assert.IsEmpty(await w.Library.Db.Exports.ListRunsAsync(ct));
lease.Dispose();
}
[TestMethod]
public void PathsFollowTheLibraryTheAccountSegmentAndTheHighlightRule()
{
var naming = LibraryNaming.Default;
var account = Make.Account("marta.demo") with { Id = 1 };
var general = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = Path.GetTempPath(), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 };
var story = Make.Entry(1, "9001", Make.T0, EntryKind.Story);
var media = Make.Stored(Make.Photo(), Make.Sha(1), "storie/2026/x.jpg");
var asStory = ExportPaths.Segments(general, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
Assert.AreEqual("marta.demo", asStory[0]);
Assert.AreEqual("storie", asStory[1]);
var onlyHighlights = general with { Scope = ExportScope.Account, AccountId = 1, ContentTypes = ContentTypes.Highlights };
var asHighlight = ExportPaths.Segments(onlyHighlights, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "evidenza", "Estate" }, asHighlight.Take(2).ToArray());
var imported = media with { RelativePath = "importati/IMG_0001.JPG" };
CollectionAssert.AreEqual(new[] { "marta.demo", "importati", "IMG_0001.JPG" }, ExportPaths.Segments(general, naming, account, story, imported, null, false, TestZones.Rome).ToArray());
var renamed = ExportPaths.Segments(general with { NamingScheme = @"{anno}\{codice}_{n}" }, naming, account, story, imported, null, false, TestZones.Rome);
CollectionAssert.AreEqual(new[] { "marta.demo", "2026", "9001_1.jpg" }, renamed.ToArray());
var deep = general with { RootPath = Path.Combine(Path.GetTempPath(), new string('d', 150)) };
var fitted = ExportPaths.RelativePathFor(deep, ["marta.demo", new string('x', 120) + ".jpg"]);
Assert.IsLessThanOrEqualTo(240, Path.TrimEndingDirectorySeparator(deep.RootPath).Length + 1 + fitted.Length);
StringAssert.EndsWith(fitted, ".jpg");
}
private sealed class CountedSession(int polls) : IEngineSessionState
{
private int _left = polls;
public bool InSession => Interlocked.Decrement(ref _left) >= 0;
}
private sealed class FakeDisk : IExportDisk
{
public long? Free { get; set; }
public long? Max { get; set; }
public long? FreeBytes(string root) => Free;
public long? MaxFileBytes(string root) => Max;
}
private sealed class World : IAsyncDisposable
{
private readonly TempFolder _temp;
private World(TempFolder temp, TestLibrary library, ExportService service, Account marta)
{
_temp = temp;
Library = library;
Service = service;
Marta = marta;
Usb = temp.Combine("usb");
Directory.CreateDirectory(Usb);
}
public TestLibrary Library { get; }
public ExportService Service { get; }
public Account Marta { get; }
public string Usb { get; }
public static async Task<World> CreateAsync(IEngineSessionState? session = null, IExportDisk? disk = null, LongWorkGate? gate = null)
{
var temp = new TempFolder();
var library = await TestLibrary.CreateAsync(temp);
var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var env = new ExportEnvironment
{
Storage = library.Db,
Layout = () => library.Layout,
DataFolder = library.Data.Root,
Clock = library.Clock,
Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) },
Disk = disk ?? new FakeDisk(),
Session = session ?? NoEngineSession.Instance,
Gate = gate,
};
return new World(temp, library, new ExportService(env), marta);
}
public async Task<ExportDestination> GeneralAsync(CancellationToken ct) =>
(await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, Usb, "Disco USB", ContentTypes.All, null, null, null), ct)).Destination;
public async ValueTask DisposeAsync()
{
await Service.DisposeAsync();
await Library.DisposeAsync();
_temp.Dispose();
}
}
}
@@ -0,0 +1,172 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder
/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set.
/// </summary>
[TestClass]
public sealed class ExportFoundationTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheGateLetsOneLongJobRunAtATime()
{
var gate = new LongWorkGate();
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _));
Assert.AreEqual(LongWorkKind.Import, gate.Busy);
Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy));
Assert.AreEqual(LongWorkKind.Import, busy);
Assert.AreEqual(
"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.",
LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
lease.Dispose();
Assert.IsNull(gate.Busy);
Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _));
lease.Dispose(); // a second dispose of the old lease releases nothing
Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy);
rebuild.Dispose();
}
[TestMethod]
public async Task AnImportDoesNotStartWhileTheGateIsHeld()
{
using var temp = new TempFolder();
await using var bed = await ImportTestBed.CreateAsync(temp);
var gate = new LongWorkGate();
await using var service = new ImportService(bed.Environment with { Gate = gate });
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _));
var refused = await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken));
Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken));
lease.Dispose();
var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken);
await service.WaitAsync(run.Id, TestContext.CancellationToken);
Assert.IsNull(gate.Busy); // the job's lease went with it
}
[TestMethod]
public void MountInfoGivesRootMountPointAndType()
{
const string content = """
22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw
40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw
41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw
bad line
""";
var mounts = MountInfoTable.Parse(content);
Assert.HasCount(3, mounts);
Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint);
Assert.IsTrue(mounts[2].ReadOnly);
Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root);
Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType);
Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint);
var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content));
Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active);
Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active);
if (!OperatingSystem.IsWindows())
{
// Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold.
Assert.IsTrue(ExportRoots.Evaluate(o).Active);
Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe"));
Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!);
Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro"));
}
Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind);
Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly<ExportFolderException>(() => ExportRoots.Resolve(o, "/")).Kind);
}
[TestMethod]
public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var library = temp.Combine("libreria");
var data = temp.Combine("dati");
var outside = temp.Combine("copie");
Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
Directory.CreateDirectory(data);
Directory.CreateDirectory(outside);
var context = new ExportFolderContext(
[new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")],
ExportRootOptions.AnyFolder);
var check = new ExportFolderCheck(new ProcMountInfo(() => null));
var accepted = await check.CheckAsync(outside, context, ct);
Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message);
Assert.IsEmpty(Directory.GetFileSystemEntries(outside));
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind);
Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste")));
}
[TestMethod]
public async Task TheSafeWriterNeverCreatesAMissingRoot()
{
using var temp = new TempFolder();
var root = temp.Combine("disco-assente");
using var source = new MemoryStream([1, 2, 3]);
await Assert.ThrowsExactlyAsync<ExportRootMissingException>(() => new SafeFileWriter().SaveAsync(
source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken));
Assert.IsFalse(Directory.Exists(root));
Directory.CreateDirectory(root);
source.Position = 0;
var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken);
Assert.AreEqual("a/b.jpg", saved.RelativePath);
}
[TestMethod]
public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct);
var env = new ExportEnvironment { Storage = library.Db, Layout = () => library.Layout, DataFolder = library.Data.Root, Clock = library.Clock, Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) } };
var destinations = new ExportDestinations(env);
var usb = temp.Combine("usb");
Directory.CreateDirectory(usb);
Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false });
await Assert.ThrowsExactlyAsync<ExportFolderException>(() => destinations.CreateAsync(Spec(library.Layout.Root), ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct));
await Assert.ThrowsExactlyAsync<ArgumentException>(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct));
var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct);
Assert.AreEqual("Disco USB", saved.Destination.Label);
var all = await destinations.ResolveAllAsync(ct);
Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id);
Assert.IsTrue(all[account.Id].Exports);
await destinations.SetAccountEnabledAsync(account.Id, false, ct);
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports);
var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct);
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => destinations.RetireAsync(saved.Destination.Id, ct));
await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct);
await destinations.RetireAsync(saved.Destination.Id, ct);
Assert.IsTrue(Directory.Exists(usb));
Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination);
Assert.IsEmpty(await destinations.RecheckAsync(null, ct));
static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null);
}
}