E2: copie esterne #71

Merged
Alby96 merged 9 commits from funzione/esportazione-copie into main 2026-11-27 17:59:43 +01:00
28 changed files with 1314 additions and 112 deletions
Showing only changes of commit 36ad5c6f9d - Show all commits

No files matched your search

+8
View File
@@ -621,3 +621,11 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-27 | Tappa E2, livello web: in più al progetto `ExportService.RetryDestinationAsync`, `ExportDestinations.RecheckAndPauseAsync`, `IExportStore.GetEntryCopyCountsAsync` (il «2/3» vuole i numeri), `ExportRootOptions.ShownAs` (la dimostrazione in veste Docker mostra `/esporta` e non la cartella temporanea); `ExportJobDto` con il piano e un messaggio, `ExportOverviewDto` con gli schemi della libreria, `ExportDestinationDto` con `Orphan` e `FormerUsername`, `ExportRunDto` con `Running`; `naming-preview` dice gli errori nella risposta come `/api/settings/naming-preview`. La dimostrazione semina le copie da `DemoHost` dopo l'importazione, con il motore vero | L'interfaccia non può arrivare a `ExportPause` né all'ambiente; stesso codice della pagina dei nomi della libreria |
| 2026-11-27 | Tappa E2, interfaccia: la Dashboard ha le schede **«Motore»** ed **«Esportazione»** (`/dashboard/esportazione`, caricata a richiesta); l'avviso delle copie da riprendere sta nella scheda Motore con gli altri avvisi, sotto i riquadri, così la disposizione del motore a 860 × 900 non cambia. Il resoconto è un dialogo, non una pagina; `toast` riceve un collegamento facoltativo; in Docker un clic sul nome sceglie la cartella e la freccia la apre; l'etichetta di una destinazione è il nome della cartella; nella scheda account filtro «Copie» e «Copia in…» compaiono solo se l'account ha una destinazione | SPECIFICA §10.3; le prove della disposizione della Dashboard restano valide |
| 2026-11-27 | Tappa E2, Docker: niente `VOLUME` né `mkdir` per `/esporta` nel Dockerfile (con un commento che dice perché) e nessun valore di `FEBE_ESPORTA` nell'immagine; l'avvio assegna a `PUID:PGID` la sola cartella `/esporta`, senza ricorsione, solo se le copie sono dichiarate (`FEBE_ESPORTA` con i valori di `Flag`, o `--esporta` fra gli argomenti) e la cartella è di root. In `compose.yml` la cartella del server si chiama `FEBE_CARTELLA_ESPORTA`, non `FEBE_ESPORTA`; `compose.yml` e il modello di Unraid hanno `/esporta` facoltativa (commentata, o vuota fra le impostazioni avanzate) | SPECIFICA §4.10 e §11: un volume anonimo farebbe sembrare `/esporta` montata; dentro ci sono file di Alberto. Lo stesso nome per due cose diverse confonderebbe |
| 2026-11-27 | Tappa E2, revisione: il **nome libero** si sceglie prima di scrivere ed è libero **sul disco e nel database**: «nome (2).ext», «(3)»… finché uno non manca sul disco e non è tenuto da una riga viva; una riga che tiene un nome il cui file **registrato** non c'è più (si guarda il suo percorso, non quello scelto: l'indice confronta senza maiuscole) diventa «Tolto». Dopo la scrittura la stessa regola si riapplica al nome davvero scritto. Precisa la riga «adozione per percorso» qui sopra | Con la scelta dopo la scrittura una riga orfana su «nome (2)» faceva fallire la registrazione (`PathTaken`) con il file già scritto; un nome che differisce solo per le maiuscole toglieva la copia buona |
| 2026-11-27 | Tappa E2, revisione: una copia **«Superato»** il cui file torna identico nella libreria (stesso SHA-256) torna «Copiato» se non c'è un'altra copia corrente né una riga non riuscita della stessa identità; altrimenti diventa «Tolto» e il file si registra come adottato. «Copia di nuovo» cerca il file prima con lo SHA-256 che l'ha superata, poi con quello della copia | Gli indici unici rifiutavano l'adozione (la riga «Superato» tiene percorso e identità); la regola 12 vuole che nulla si tolga dal disco |
| 2026-11-27 | Tappa E2, revisione: il **controllo delle copie** rilegge la radice prima di ogni pagina e, prima di segnare «Tolto», riguarda ogni file mancante; se la radice non risponde più (cartella assente o oltre il tempo massimo) il controllo si ferma e la destinazione va in pausa, senza segnare nulla. Anche la copia, con la radice assente, riguarda il percorso registrato prima di dire «Tolto» | Un disco staccato a metà controllo faceva sembrare tolti tutti i file seguenti |
| 2026-11-27 | Tappa E2, revisione: una copia di più destinazioni interrotta (o finita con un errore) lascia **«Interrotta»** le copie che non erano ancora partite, riprendibili dalla Dashboard; il permesso dei lavori lunghi (`LongWorkGate`) si prende **prima** di preparare il piano e passa al lavoro, così fra controllo e avvio non entra un'importazione | Le copie in coda restavano «In corso» per sempre; prima il permesso si prendeva solo all'avvio del lavoro |
| 2026-11-27 | Tappa E2, revisione: su Linux lo spostamento del `.part` sul nome finale usa `renameat2(RENAME_NOREPLACE)` e, dove manca, `link` + `unlink` (`NoReplaceRename`, P/Invoke della libc, nessuna libreria); se nessuno dei due è disponibile resta il controllo di prima. Su Windows `File.Move` senza sovrascrittura è già atomico | Fra `File.Exists` e `File.Move(overwrite: true)` un file comparso nel frattempo veniva sostituito: la regola 11 lo vieta |
| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file |
| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella |
| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie |
+106 -23
View File
@@ -271,10 +271,19 @@ public sealed class ExportCopier(ExportEnvironment env)
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)
// The file is not there: «Tolto», unless the whole destination went away meanwhile. A root that was away
// for a moment and answers the probe again is asked once more for the file before it is called «Tolto».
if (!Directory.Exists(root))
{
return ItemResult.Paused(gone);
if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone)
{
return ItemResult.Paused(gone);
}
if (current.RelativePath is { } back && Exists(root, back))
{
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = back, Note = null, LastError = null }, bytes, back).ConfigureAwait(false);
}
}
await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false);
@@ -303,8 +312,7 @@ public sealed class ExportCopier(ExportEnvironment env)
}
if (x.OneOnly
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { AccountId: { } other, RelativePath: { } elsewherePath } elsewhere
&& other != accountId
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, accountId, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere
&& await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where
&& Exists(where.RootPath, elsewherePath))
{
@@ -366,14 +374,23 @@ public sealed class ExportCopier(ExportEnvironment env)
if (holder.Identity == file.Identity)
{
if (holder.State == ExportCopyState.Superseded)
{
// Our own bytes, recorded as superseded (the file came back to the library without the change that
// would have revived the row): the copy is copied, not superseded, and must not stay stuck.
return await ReviveAsync(item, file, failed, holder, candidate).ConfigureAwait(false);
}
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 name the record can take: free on the disk and in the database. A path recorded for another copy whose
// file is gone is free again («Tolto»); one whose file is there under another letter case (a case-sensitive
// disk) is not, and the next numbered name is tried.
var chosen = await ChooseNameAsync(destination, planned, 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 };
@@ -389,7 +406,7 @@ public sealed class ExportCopier(ExportEnvironment env)
root,
directory,
(digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal)
? ValueTask.FromResult<string?>(planned)
? ValueTask.FromResult<string?>(chosen)
: throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."),
new SafeWriteOptions
{
@@ -420,14 +437,90 @@ public sealed class ExportCopier(ExportEnvironment env)
return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false);
}
string? taken = null;
if (!string.Equals(saved.RelativePath, planned, StringComparison.Ordinal))
var taken = string.Equals(saved.RelativePath, planned, StringComparison.Ordinal) ? null : ExportText.Notes.NameTaken;
// The writer moved the file onto a name where no file was: a row still holding that path is stale (decision of
// 2026-11-27), also when the name is the one chosen, since a row could appear meanwhile.
await ReleaseStalePathAsync(destination, saved.RelativePath, justWritten: true, ct).ConfigureAwait(false);
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
}
/// <summary>
/// The first of the planned path and its numbered names (numbered as the writer numbers them) that is free on the
/// disk and free, or stale, in the database; the planned path when none is found (the writer then decides).
/// </summary>
private async Task<string> ChooseNameAsync(ExportDestination destination, string planned, CancellationToken ct)
{
for (var attempt = 1; attempt <= MaxSiblings; attempt++)
{
taken = ExportText.Notes.NameTaken;
await ReleaseStalePathAsync(destination, saved.RelativePath, file.Identity, ct).ConfigureAwait(false);
string name;
try
{
name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath);
}
catch (PathTooLongException)
{
break;
}
if (Exists(destination.RootPath, name))
{
continue; // the writer would not take it either
}
if (await ReleaseStalePathAsync(destination, name, justWritten: false, ct).ConfigureAwait(false))
{
return name;
}
}
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
return planned;
}
/// <summary>
/// A Copied or Superseded row on this path (matched without regard to case, as its unique index) whose file is not
/// there becomes «Tolto». The row's own stored path is the one tested: on a case-sensitive disk another letter case
/// is another file. With <paramref name="justWritten"/> this job has just written the file at exactly
/// <paramref name="path"/>, where no file was, so a row with exactly that path is stale without a look. Returns
/// whether the path is free in the database now.
/// </summary>
private async Task<bool> ReleaseStalePathAsync(ExportDestination destination, string path, bool justWritten, CancellationToken ct)
{
var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false);
if (held is null)
{
return true;
}
var stale = held.RelativePath is not { } stored
|| (justWritten && string.Equals(stored, path, StringComparison.Ordinal))
|| !Exists(destination.RootPath, stored);
if (!stale)
{
return false;
}
await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
return true;
}
/// <summary>
/// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the
/// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history.
/// </summary>
private async Task<ItemResult> ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path)
{
var exports = _env.Storage.Exports;
var none = CancellationToken.None;
var now = _env.Clock.Now;
if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null)
{
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false);
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Bytes, path).ConfigureAwait(false);
}
await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false);
return await RecordAsync(item, file, failed, null, path, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false);
}
/// <summary>Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names.</summary>
@@ -468,16 +561,6 @@ public sealed class ExportCopier(ExportEnvironment env)
}
}
/// <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;
+50
View File
@@ -263,10 +263,60 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
}
}
// Then where the folders really are (links, junctions, drive aliases, bind mounts), read-only; the probe stays
// for what this cannot see (a share that points back to this computer).
if (IdentityOverlap(full, shown, context.Protected) is { } aliased)
{
return new ExportFolderVerdict(full, aliased);
}
ct.ThrowIfCancellationRequested();
return ProbeIdentity(full, shown, context.Protected);
}
/// <summary>
/// The identity comparison (decision of 2026-11-27): the candidate is a protected folder, or inside one, when its
/// <see cref="FolderLocation"/> is; it contains one when the protected folder's location is inside the candidate's, or
/// inside (or around) what a mount below the candidate shows.
/// </summary>
private ExportFolderProblem? IdentityOverlap(string full, string shown, IReadOnlyList<ProtectedFolder> protectedFolders)
{
if (FolderIdentity.Locate(full, _mounts, out var real) is not { } candidate || real is null)
{
return null;
}
var below = _mounts.All()
.Where(m => !ExportPaths.Same(m.MountPoint, real) && ExportPaths.IsSameOrInside(m.MountPoint, real))
.Select(FolderIdentity.Of)
.OfType<FolderLocation>()
.ToList();
foreach (var folder in protectedFolders)
{
if (FolderIdentity.Locate(folder.Path, _mounts) is not { } location)
{
continue;
}
if (candidate.IsSame(location))
{
return Same(shown, folder);
}
if (candidate.IsSameOrInside(location))
{
return Inside(shown, folder);
}
if (location.IsSameOrInside(candidate) || below.Any(b => location.IsSameOrInside(b) || b.IsSameOrInside(location)))
{
return Contains(shown, folder);
}
}
return null;
}
private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder)
{
if (ExportPaths.Same(full, protectedPath))
+6 -1
View File
@@ -40,6 +40,10 @@ public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain
/// <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>
/// <param name="HasDestination">
/// A folder of the copies exists (the general one or one of an account, in use): when nothing is to copy, the dialog
/// says «no folder» only when this is false, not because no destination gets files.
/// </param>
public sealed record ExportPlan(
int Files,
long Bytes,
@@ -47,7 +51,8 @@ public sealed record ExportPlan(
int RemovedOrSuperseded,
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestination> Destinations)
IReadOnlyList<ExportPlanDestination> Destinations,
bool HasDestination = true)
{
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
}
+3 -3
View File
@@ -103,8 +103,7 @@ public sealed class ExportPlanner(ExportEnvironment env)
? 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)
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null)
{
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
}
@@ -230,7 +229,8 @@ internal sealed class PlanTally
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);
var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0;
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any);
}
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
+77 -6
View File
@@ -8,7 +8,11 @@ namespace Febe.Core.Export;
/// <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);
/// <param name="Device">
/// The device of its file system (<c>major:minor</c> in <c>mountinfo</c>), or null when unknown: with it the identity
/// test of the folder check sees a bind mount of a folder of the library (decision of 2026-11-27).
/// </param>
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly, string? Device = null);
/// <summary>The mount table (a seam: tests give their own; Linux reads <c>/proc/self/mountinfo</c>).</summary>
public interface IExportMounts
@@ -46,7 +50,7 @@ public sealed class ProcMountInfo(Func<string?>? read = null) : IExportMounts
}
}
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly);
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly, m.Device);
}
/// <summary>
@@ -153,6 +157,54 @@ public static class ExportRoots
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be browsed.</exception>
public static IReadOnlyList<SourceFolderChoice> Browse(ExportRootOptions o, string? relative)
{
var folder = BrowsedFolder(o, relative);
return [.. Subfolders(o, folder).Select(s => s.Choice with { HasSubfolders = HasSubfolders(s.FullPath) })];
}
/// <summary>
/// <see cref="Browse"/> for the web picker, never blocking it (spec §4.10 «I controlli sul disco esterno sono asincroni
/// e brevi»): the listing of the folder gets <paramref name="timeout"/>, and each subfolder gets as much in parallel to
/// tell whether it has subfolders, so a dead share mounted below the folder shows without the arrow instead of
/// hiding the healthy ones.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be browsed, or does not answer in time.</exception>
public static Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, CancellationToken ct) =>
BrowseAsync(o, relative, timeout, HasSubfolders, ct);
/// <summary><see cref="BrowseAsync(ExportRootOptions, string?, TimeSpan, CancellationToken)"/> with the look into a subfolder given (a seam for tests).</summary>
internal static async Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, Func<string, bool> hasSubfolders, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(hasSubfolders);
var folder = BrowsedFolder(o, relative);
IReadOnlyList<Subfolder> subfolders;
try
{
subfolders = await Task.Run(() => Subfolders(o, folder), ct).WaitAsync(timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
throw new ExportFolderException(
$"La cartella {DisplayPath(o, folder)} non risponde entro {timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova.",
ExportFolderProblemKind.NotResponding);
}
async Task<SourceFolderChoice> LookAsync(Subfolder s)
{
try
{
return s.Choice with { HasSubfolders = await Task.Run(() => hasSubfolders(s.FullPath), ct).WaitAsync(timeout, ct).ConfigureAwait(false) };
}
catch (TimeoutException)
{
return s.Choice; // it does not answer: shown, without the arrow
}
}
return await Task.WhenAll(subfolders.Select(LookAsync)).ConfigureAwait(false);
}
private static string BrowsedFolder(ExportRootOptions o, string? relative)
{
ArgumentNullException.ThrowIfNull(o);
string folder;
@@ -169,6 +221,12 @@ public static class ExportRoots
folder = ExportPaths.Trim(Path.GetFullPath(relative));
}
return folder;
}
/// <summary>The subfolders of a folder, sorted, without looking into them.</summary>
private static List<Subfolder> Subfolders(ExportRootOptions o, string folder)
{
if (!Directory.Exists(folder))
{
throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing);
@@ -178,10 +236,7 @@ public static class ExportRoots
{
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()))
.Select(d => new Subfolder(d, new SourceFolderChoice(Path.GetFileName(d), o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d, false)))
.ToList();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
@@ -190,6 +245,22 @@ public static class ExportRoots
}
}
/// <summary>The folder has a subfolder to open (false when it cannot be read).</summary>
private static bool HasSubfolders(string folder)
{
try
{
return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false)).Any();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>A subfolder found by the picker, with its full path.</summary>
private sealed record Subfolder(string FullPath, SourceFolderChoice Choice);
/// <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.
+111 -23
View File
@@ -117,15 +117,29 @@ public sealed class ExportService : IAsyncDisposable
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(request);
var held = new LeaseHolder();
lock (_gate)
{
EnsureIdle();
// The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano
// insieme»): a rebuild or an import cannot start while the runs and their items are being recorded.
if (_env.Gate is { } gate)
{
if (!gate.TryEnter(LongWorkKind.Export, out var lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
}
held.Lease = lease;
}
_starting = true; // a second «Copia in…» meanwhile records nothing
}
try
{
return await StartReservedAsync(request, ct).ConfigureAwait(false);
return await StartReservedAsync(request, held, ct).ConfigureAwait(false);
}
finally
{
@@ -133,10 +147,12 @@ public sealed class ExportService : IAsyncDisposable
{
_starting = false;
}
held.Lease?.Dispose(); // not handed to a job: nothing to copy, or the start failed
}
}
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, CancellationToken ct)
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, LeaseHolder held, CancellationToken ct)
{
var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false);
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
@@ -206,7 +222,8 @@ public sealed class ExportService : IAsyncDisposable
lock (_gate)
{
_starting = false;
StartCopyJob(ordered.Select(r => r.Id).ToList());
StartCopyJob(ordered.Select(r => r.Id).ToList(), held.Lease);
held.Lease = null; // the job owns it now
}
}
catch
@@ -463,26 +480,37 @@ public sealed class ExportService : IAsyncDisposable
}
after = page[^1].Id;
if (!Directory.Exists(destination.RootPath))
if (!await RootAnswersAsync(destination, ct).ConfigureAwait(false))
{
// 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);
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
return;
}
var missing = new List<long>();
var missing = new List<ExportCopy>();
foreach (var copy in page)
{
ct.ThrowIfCancellationRequested();
if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
{
missing.Add(copy.Id);
missing.Add(copy);
}
}
removed += await exports.MarkCopiesRemovedAsync(missing, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
// The disk may have gone away while the page was read (decision of 2026-11-27, §4.10): the root is asked
// again after the files and before anything is marked, and a missing file is looked for once more.
if (missing.Count > 0 && !await RootAnswersAsync(destination, ct).ConfigureAwait(false))
{
await PauseCheckAsync(destination, label, ct).ConfigureAwait(false);
Report(ExportPhase.Finished, done);
return;
}
var gone = missing
.Where(copy => copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
.Select(copy => copy.Id)
.ToList();
removed += await exports.MarkCopiesRemovedAsync(gone, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
done += page.Count;
Report(ExportPhase.Checking, done);
}
@@ -501,6 +529,26 @@ public sealed class ExportService : IAsyncDisposable
Report(ExportPhase.Finished, done);
}
/// <summary>The root of the destination is there, asked within the folder-check time (a dead share must not block).</summary>
private async Task<bool> RootAnswersAsync(ExportDestination destination, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
/// <summary>The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses.</summary>
private async Task PauseCheckAsync(ExportDestination destination, string label, CancellationToken ct)
{
var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
}
private bool FileExists(string root, string relativePath)
{
try
@@ -561,25 +609,59 @@ public sealed class ExportService : IAsyncDisposable
}
}
private void StartCopyJob(IReadOnlyList<long> runIds) =>
StartJob(runIds, async (progress, token) =>
{
foreach (var runId in runIds)
private void StartCopyJob(IReadOnlyList<long> runIds, IDisposable? lease = null) =>
StartJob(
runIds,
async (progress, token) =>
{
token.ThrowIfCancellationRequested();
var next = 0;
try
{
await Copier.CopyAsync(runId, progress, token).ConfigureAwait(false);
for (; next < runIds.Count; next++)
{
token.ThrowIfCancellationRequested();
try
{
await Copier.CopyAsync(runIds[next], 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);
}
}
}
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
finally
{
// Stored with the run (Interrupted, with its error); the next destination still gets its files.
LastJobError = ExportText.ErrorText(ex);
// «Interrompi» (or «Annulla», or the end of Febe) stopped the job before its later destinations: those
// runs were recorded as running and nothing runs them now. They become «interrotto», resumable, as
// RecoverAsync would make them at the next start.
await InterruptQueuedAsync(runIds.Skip(next)).ConfigureAwait(false);
}
},
lease);
/// <summary>Runs of a stopped job that were never reached and are still recorded as running become «interrotto».</summary>
private async Task InterruptQueuedAsync(IEnumerable<long> runIds)
{
foreach (var runId in runIds)
{
try
{
if (await _env.Storage.Exports.GetRunAsync(runId, CancellationToken.None).ConfigureAwait(false) is { State: ExportRunState.Running } run)
{
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false);
}
}
});
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// RecoverAsync makes it «interrotto» at the next start.
}
}
}
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work)
/// <summary>Starts a job; <paramref name="held"/> is a lease of the gate already taken (the job owns it once started).</summary>
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work, IDisposable? held = null)
{
lock (_gate)
{
@@ -588,8 +670,8 @@ public sealed class ExportService : IAsyncDisposable
throw new InvalidOperationException(BusyText);
}
IDisposable? lease = null;
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
var lease = held;
if (lease is null && _env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
{
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
}
@@ -662,6 +744,12 @@ public sealed class ExportService : IAsyncDisposable
private sealed record Job(IReadOnlyList<long> RunIds, CancellationTokenSource Cancellation, Task Task);
/// <summary>A lease of the long-work gate on its way from <see cref="StartAsync"/> to the job.</summary>
private sealed class LeaseHolder
{
public IDisposable? Lease { get; set; }
}
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
{
private (ExportPhase, long?)? _phase;
+162
View File
@@ -0,0 +1,162 @@
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Febe.Core.Export;
/// <summary>
/// Where a folder really is, whatever name it was reached by: the folder check compares these, read-only, besides its
/// probe file (decision of 2026-11-27, widening spec §4.10 «Cartelle rifiutate»).
/// <list type="bullet">
/// <item>Windows: the final path of the folder (<c>GetFinalPathNameByHandle</c> on a handle opened without any access
/// right), which resolves junctions, symbolic links, <c>subst</c> drives and mapped drives (to their UNC path);</item>
/// <item>Linux: the real path (<c>realpath</c>, every symbolic link resolved), then, through the mount table, the
/// device of its file system and the folder of that file system it is (a bind mount of a folder of the library in Docker
/// is the same device, inside the root of the library's mount).</item>
/// </list>
/// </summary>
/// <param name="Device">The device of the file system (<c>major:minor</c>), or null: then <paramref name="Path"/> is a full path.</param>
/// <param name="Path">With a device, the folder within its file system ('/' separated); else the real full path.</param>
internal sealed record FolderLocation(string? Device, string Path)
{
/// <summary>This folder is <paramref name="other"/>.</summary>
public bool IsSame(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.Same(Path, other.Path) : string.Equals(Path, other.Path, ExportPaths.PathComparison));
/// <summary>This folder is <paramref name="other"/> or inside it.</summary>
public bool IsSameOrInside(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.IsSameOrInside(Path, other.Path) : InsidePosix(Path, other.Path));
private bool Comparable(FolderLocation other) => string.Equals(Device, other.Device, StringComparison.Ordinal);
private static bool InsidePosix(string path, string folder)
{
if (string.Equals(path, folder, ExportPaths.PathComparison) || folder == "/")
{
return true;
}
return path.StartsWith(folder.TrimEnd('/') + "/", ExportPaths.PathComparison);
}
}
/// <summary>Finds the <see cref="FolderLocation"/> of a folder (see there).</summary>
internal static class FolderIdentity
{
private const uint FileShareAll = 0x1 | 0x2 | 0x4;
private const uint OpenExisting = 3;
private const uint FileFlagBackupSemantics = 0x02000000;
/// <summary>The location of an existing folder, or null when it cannot be told (missing, unreadable).</summary>
public static FolderLocation? Locate(string fullPath, IExportMounts mounts) => Locate(fullPath, mounts, out _);
/// <summary>The location of an existing folder and its real path, or null when it cannot be told.</summary>
public static FolderLocation? Locate(string fullPath, IExportMounts mounts, out string? real)
{
ArgumentNullException.ThrowIfNull(mounts);
real = RealPath(fullPath);
if (real is null)
{
return null;
}
if (mounts.FindContaining(real) is { Device: { Length: > 0 } device } mount)
{
var relative = Path.GetRelativePath(mount.MountPoint, real).Replace('\\', '/');
var root = mount.Root.TrimEnd('/');
return new FolderLocation(device, relative == "." ? (root.Length == 0 ? "/" : root) : $"{root}/{relative}");
}
return new FolderLocation(null, real);
}
/// <summary>The location of what a mount shows, when its device is known.</summary>
public static FolderLocation? Of(ExportMount mount) =>
mount.Device is { Length: > 0 } device ? new FolderLocation(device, mount.Root.Length > 1 ? mount.Root.TrimEnd('/') : mount.Root) : null;
/// <summary>The path of the folder with every link (and on Windows every drive alias) resolved, or null.</summary>
internal static string? RealPath(string fullPath)
{
try
{
if (!Directory.Exists(fullPath))
{
return null;
}
if (OperatingSystem.IsWindows())
{
return FinalPathWindows(fullPath);
}
return RealPathUnix(fullPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException
or EntryPointNotFoundException or DllNotFoundException)
{
return null;
}
}
private static string? FinalPathWindows(string fullPath)
{
// No access right is asked: only the identity of the folder is read, and nothing is ever written there.
using var handle = CreateFileW(fullPath, 0, FileShareAll, IntPtr.Zero, OpenExisting, FileFlagBackupSemantics, IntPtr.Zero);
if (handle.IsInvalid)
{
return null;
}
var buffer = new char[1024];
var length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0);
if (length >= buffer.Length)
{
buffer = new char[length + 1];
length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0);
}
if (length == 0 || length >= buffer.Length)
{
return null;
}
var path = new string(buffer, 0, (int)length);
if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
{
path = @"\\" + path[8..];
}
else if (path.StartsWith(@"\\?\", StringComparison.Ordinal))
{
path = path[4..];
}
return ExportPaths.Trim(path);
}
private static string? RealPathUnix(string fullPath)
{
var resolved = RealPathNative(fullPath, IntPtr.Zero);
if (resolved == IntPtr.Zero)
{
return null;
}
try
{
return Marshal.PtrToStringUTF8(resolved) is { Length: > 0 } path ? ExportPaths.Trim(path) : null;
}
finally
{
Free(resolved);
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetFinalPathNameByHandleW(SafeFileHandle file, [Out] char[] filePath, uint length, uint flags);
[DllImport("libc", EntryPoint = "realpath", SetLastError = true)]
private static extern IntPtr RealPathNative([MarshalAs(UnmanagedType.LPUTF8Str)] string path, IntPtr resolved);
[DllImport("libc", EntryPoint = "free")]
private static extern void Free(IntPtr pointer);
}
+5 -2
View File
@@ -12,7 +12,9 @@ namespace Febe.Core.Library;
/// <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)
/// <param name="Device">The device of the file system, <c>major:minor</c> (field 3): two mounts with the same device show
/// folders of one file system, so <see cref="Root"/> tells whether one is inside the other.</param>
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source, string? Device = null)
{
/// <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);
@@ -61,7 +63,8 @@ public static class MountInfoTable
point,
fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries),
fields[separator + 1],
MountTable.Unescape(fields[separator + 2])));
MountTable.Unescape(fields[separator + 2]),
fields[2]));
}
return entries;
+108
View File
@@ -0,0 +1,108 @@
using System.Runtime.InteropServices;
namespace Febe.Core.Library;
/// <summary>What <see cref="NoReplaceRename.TryMove"/> did.</summary>
internal enum NoReplaceOutcome
{
/// <summary>The file has its new name.</summary>
Moved,
/// <summary>The new name exists: nothing changed.</summary>
Taken,
/// <summary>The file system cannot do it atomically: nothing changed, the caller checks and moves.</summary>
Unsupported,
}
/// <summary>
/// An atomic rename that never replaces an existing name, on Linux and the other Unix systems (rule 12: Febe never
/// overwrites a file). On Unix <c>File.Move(overwrite: false)</c> checks and then calls rename(2), which replaces: another
/// program, or another Febe writing to the same folder (spec §4.10 «due istanze sulla stessa cartella»), could create the
/// name in between. Only the platform's own C library is called (BCL interop, no external component).
/// <list type="number">
/// <item>Linux: <c>renameat2(…, RENAME_NOREPLACE)</c>; EEXIST means the name is taken;</item>
/// <item>without it (an older kernel, a file system that refuses the flag, another Unix): <c>link</c> then
/// <c>unlink</c> of the temporary name, where link refuses an existing name with EEXIST;</item>
/// <item>without hard links either (vfat, some CIFS mounts): <see cref="NoReplaceOutcome.Unsupported"/>.</item>
/// </list>
/// Not for Windows, where <c>MoveFileEx</c> without <c>MOVEFILE_REPLACE_EXISTING</c> already refuses an existing name.
/// </summary>
internal static class NoReplaceRename
{
private const int AtFdCwd = -100;
private const uint RenameNoReplace = 1;
private const int Eexist = 17; // the same value on Linux, macOS and the BSDs
private static volatile bool _noRenameAt2;
private static volatile bool _noLink;
/// <summary>Renames <paramref name="source"/> to <paramref name="destination"/> unless that name exists.</summary>
public static NoReplaceOutcome TryMove(string source, string destination)
{
ArgumentException.ThrowIfNullOrEmpty(source);
ArgumentException.ThrowIfNullOrEmpty(destination);
if (OperatingSystem.IsWindows())
{
return NoReplaceOutcome.Unsupported;
}
if (OperatingSystem.IsLinux() && !_noRenameAt2)
{
try
{
if (RenameAt2(AtFdCwd, source, AtFdCwd, destination, RenameNoReplace) == 0)
{
return NoReplaceOutcome.Moved;
}
if (Marshal.GetLastPInvokeError() == Eexist)
{
return NoReplaceOutcome.Taken;
}
// EINVAL (the file system refuses the flag), ENOSYS (an older kernel) or another error: try a link.
}
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
{
_noRenameAt2 = true; // a C library without renameat2
}
}
if (_noLink)
{
return NoReplaceOutcome.Unsupported;
}
try
{
if (Link(source, destination) == 0)
{
_ = Unlink(source); // when this fails the caller's clean-up removes the temporary name
return NoReplaceOutcome.Moved;
}
// EPERM, ENOTSUP, EXDEV…: no hard links here. The caller checks and moves, and reports a real error itself.
return Marshal.GetLastPInvokeError() == Eexist ? NoReplaceOutcome.Taken : NoReplaceOutcome.Unsupported;
}
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
{
_noLink = true;
return NoReplaceOutcome.Unsupported;
}
}
[DllImport("libc", EntryPoint = "renameat2", SetLastError = true)]
private static extern int RenameAt2(
int oldDirectory,
[MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath,
int newDirectory,
[MarshalAs(UnmanagedType.LPUTF8Str)] string newPath,
uint flags);
[DllImport("libc", EntryPoint = "link", SetLastError = true)]
private static extern int Link([MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath, [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath);
[DllImport("libc", EntryPoint = "unlink", SetLastError = true)]
private static extern int Unlink([MarshalAs(UnmanagedType.LPUTF8Str)] string path);
}
+25 -3
View File
@@ -330,11 +330,33 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
// On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces:
// two writers of this process could overwrite each other. The check and the rename are therefore done under
// one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name.
// another writer (of this process, another Febe on the same export folder, another program) could take the
// name in between. On Unix the move is therefore an atomic rename that refuses an existing name
// (NoReplaceRename); only where the file system cannot do that, the check and the move are done under one
// lock, which still keeps the writers of this process apart. On Windows the move itself refuses an existing
// name.
lock (MoveGate)
{
if (File.Exists(finalPath) || Directory.Exists(finalPath))
if (Directory.Exists(finalPath))
{
continue;
}
if (!OperatingSystem.IsWindows())
{
var outcome = NoReplaceRename.TryMove(tempPath, finalPath);
if (outcome == NoReplaceOutcome.Moved)
{
return finalPath;
}
if (outcome == NoReplaceOutcome.Taken)
{
continue;
}
}
if (File.Exists(finalPath))
{
continue;
}
+7 -2
View File
@@ -182,8 +182,13 @@ public interface IExportStore
/// </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>
/// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general
/// folder or the own folder of an account still in Febe), of an account still in Febe; with
/// <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row of the account itself never
/// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»).
/// </summary>
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
/// <summary>
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
+20 -8
View File
@@ -115,7 +115,12 @@ internal static class ExportFilterSql
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>
/// <summary>
/// The file is copied in its effective destination, or, with «Una copia sola», copied for another account still in
/// Febe in a destination in use: the rule of the plan and of the copy (decision of 2026-11-27, «una copia altrove conta
/// solo se è di un altro account»). A copy of the same account in a folder that is no longer its effective one, and a
/// copy whose account was removed, do not count.
/// </summary>
public static string Copied(ExportFilterContext x)
{
if (!x.HasCopies)
@@ -124,10 +129,14 @@ internal static class ExportFilterSql
}
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 IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND {OneOnlyMatch(x)})"
: $"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>«Una copia sola»: a copy <c>c</c> counts for the file of <c>e</c> (in a destination in use, tested apart).</summary>
private static string OneOnlyMatch(ExportFilterContext x) =>
$"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))";
/// <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"
@@ -211,7 +220,7 @@ internal static class ExportFilterSql
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) "
: $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 IN (c.source_sha256, c.superseded_by_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),
};
@@ -248,7 +257,7 @@ internal static class ExportFilterSql
private static string CopiedEntries(ExportFilterContext x)
{
var match = x.SamePost == SamePostCopies.OneOnly
? string.Empty
? $" AND {OneOnlyMatch(x)}"
: $" AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id";
return "+e.id IN (SELECT m.entry_id FROM export_copy c CROSS JOIN media m CROSS JOIN entry e "
+ $"WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND m.sha256 = c.source_sha256 AND e.id = m.entry_id{match} "
@@ -267,14 +276,17 @@ internal static class ExportFilterSql
: Copied(x);
/// <summary>
/// The removed or superseded part of <see cref="Replaced"/>: the copy of this file in the effective destination was
/// removed, or a copy was superseded (or removed) by this file. In bulk each EXISTS sits behind its list of SHA-256.
/// The removed or superseded part of <see cref="Replaced"/>: a copy of this very file in the effective destination
/// was removed or superseded (whether or not it names the file that replaced it: the file can be back in the library
/// in another entry), or a copy was superseded (or removed) by this file. The same rows as the plan reads
/// (<c>GetCopyStatesAsync</c>), so filter, marks, counts and plan agree (D3). In bulk each EXISTS sits behind its list
/// of SHA-256.
/// </summary>
private static string History(ExportFilterContext x, bool bulk)
{
var destination = DestinationOf(x);
var removed = $"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)";
+ "AND c.state IN ('Removed', 'Superseded'))";
var superseded = $"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'))";
if (!bulk)
@@ -283,7 +295,7 @@ internal static class ExportFilterSql
}
var inUse = InUse(x);
return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state = 'Removed') AND {removed}) "
return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state IN ('Removed', 'Superseded')) AND {removed}) "
+ $"OR (m.sha256 IN (SELECT c.superseded_by_sha256 FROM export_copy c WHERE c.superseded_by_sha256 IS NOT NULL AND c.destination_id IN ({inUse})) AND {superseded}))";
}
+6 -3
View File
@@ -885,7 +885,8 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
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)
AND (@a IS NULL OR account_id <> @a)
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL))
ORDER BY id DESC LIMIT 1
""";
@@ -947,11 +948,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
ct);
}
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default)
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, 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),
c => ReadFirst(
c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)),
ReadCopy),
ct);
}
+26 -10
View File
@@ -98,7 +98,8 @@ public static class ExportApi
}
var relative = string.IsNullOrWhiteSpace(path) ? string.Empty : path.Trim().Trim('/', '\\').Replace('\\', '/');
var folders = Guard(() => ExportRoots.Browse(root, relative.Length == 0 ? null : relative));
// Never on the request thread without a limit: a dead share below /esporta must not hang the picker.
var folders = await GuardAsync(() => ExportRoots.BrowseAsync(root, relative.Length == 0 ? null : relative, DiskTimeout, ct)).ConfigureAwait(false);
string? parent = relative.Length == 0 ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty;
var full = relative.Length == 0 ? rootFolder : Path.Combine(rootFolder, LibraryLayout.ToPlatform(relative));
return ApiHttp.Json(
@@ -253,8 +254,27 @@ public static class ExportApi
throw new BadRequestException("L'account di questa copia è stato rimosso: non c'è niente da copiare di nuovo.");
}
// The file the library has now: the one that took the place of the copied one, else the copied one itself.
var sha = copy.SupersededBySha256 ?? copy.SourceSha256;
// The file the library has now: the one that took the place of the copied one, else the copied one itself
// (it can be back in the library in another entry while the one that replaced it went).
string? sha = null;
List<MediaLocation> present = [];
foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType<string>().Distinct(StringComparer.Ordinal))
{
present = (await storage.Media.FindBySha256Async(candidate, ct).ConfigureAwait(false))
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
.ToList();
if (present.Count > 0)
{
sha = candidate;
break;
}
}
if (sha is null)
{
throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
}
if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c =>
c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant))
{
@@ -264,12 +284,7 @@ public static class ExportApi
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
var present = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
.ToList();
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null)
?? present.FirstOrDefault()
?? throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0];
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false);
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
@@ -531,7 +546,8 @@ public static class ExportApi
plan.RemovedOrSuperseded,
plan.NotExported,
plan.Missing,
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))]);
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))],
plan.HasDestination);
}
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
+2 -1
View File
@@ -132,7 +132,8 @@ public sealed record ExportPlanDto(
int RemovedOrSuperseded,
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestinationDto> Destinations);
IReadOnlyList<ExportPlanDestinationDto> Destinations,
bool HasDestination = true);
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
+4 -3
View File
@@ -387,10 +387,11 @@ public static class LibraryApi
continue;
}
// The copies made for this account; with «Una copia sola», also the ones made for another account in a
// folder still in use (that is why this file is «Già copiato»).
// The copies made for this account; with «Una copia sola», also the ones made for another account still
// in Febe in a folder still in use (that is why this file is «Già copiato»; a copy whose account was
// removed does not count, as in the plan).
var own = copy.AccountId == Account.Id;
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.State == ExportCopyState.Copied && !destination.IsRetired))
if (!own && !(SamePost == SamePostCopies.OneOnly && copy.AccountId is not null && copy.State == ExportCopyState.Copied && !destination.IsRetired))
{
continue;
}
@@ -33,6 +33,9 @@ export async function mountExport(page) {
let timer = 0;
let ticks = 0;
let stopped = false;
// One reading at a time: a command or a change during a reading asks for one more right after it, never a second chain.
let inFlight = false;
let rerun = false;
page.onLeave(() => {
stopped = true;
clearTimeout(timer);
@@ -53,6 +56,29 @@ export async function mountExport(page) {
async function poll() {
if (stopped) return;
if (inFlight) {
rerun = true;
return;
}
inFlight = true;
clearTimeout(timer);
try {
await read();
} finally {
inFlight = false;
}
if (stopped) return;
clearTimeout(timer);
if (rerun) {
rerun = false;
wasRunning = null;
poll();
return;
}
timer = setTimeout(poll, progress && progress.running ? 1000 : 5000);
}
async function read() {
try {
progress = await api('/api/export/progress', { signal: page.signal });
} catch (error) {
@@ -65,8 +91,6 @@ export async function mountExport(page) {
// The jobs and the folders follow the copy: when it starts or ends, and every few seconds while it works.
if (running !== wasRunning || !running || ticks % 5 === 0) await loadSide();
wasRunning = running;
if (stopped) return;
timer = setTimeout(poll, running ? 1000 : 5000);
}
/** Asks again now (after a command), keeping one timer. */
@@ -165,7 +165,10 @@ export async function destinationDialog({ scope, accountId = null, username = ''
}
}
async function browse(path) {
// focusPath: the folder whose button had the keyboard; after the list is drawn again the focus goes back there
// (or to the first folder), never lost on the page behind the dialog.
async function browse(path, focusPath = null) {
const hadFocus = folderPart.contains(document.activeElement);
try {
const list = await api(`/api/export/folders${path ? `?path=${encodeURIComponent(path)}` : ''}`);
fill(folderPart, h('div.pannello.sfoglia',
@@ -173,10 +176,16 @@ export async function destinationDialog({ scope, accountId = null, username = ''
list.parent != null ? h('button.btn.nudo.piccolo.destra', { type: 'button', onclick: () => browse(list.parent || null) }, icon('arrow-left', 's'), t('esportazione.dialogo.su')) : null),
list.folders.length
? h('ul.sfoglia-elenco', list.folders.map((f) => h(`li${f.path === state.path ? '.scelta' : ''}`,
h('button.sfoglia-voce', { type: 'button', 'aria-pressed': String(f.path === state.path), onclick: () => { state.path = f.path; checkFolder(f.path); browse(list.relative || null); } },
h('button.sfoglia-voce', { type: 'button', dataset: { path: f.path }, 'aria-pressed': String(f.path === state.path), onclick: () => { state.path = f.path; checkFolder(f.path); browse(list.relative || null, f.path); } },
icon(f.path === state.path ? 'circle-check' : 'folder', 's'), h('span', f.name)),
f.hasSubfolders ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('esportazione.dialogo.apri', { nome: f.name }), onclick: () => browse(f.path) }, icon('chevron-right', 's')) : null)))
: h('p.vuoto-elenco', t('esportazione.dialogo.vuota'))));
if (hadFocus) {
const items = [...folderPart.querySelectorAll('.sfoglia-voce')];
const target = items.find((b) => focusPath != null && b.dataset.path === focusPath) || items[0]
|| folderPart.querySelector('button');
if (target) target.focus();
}
} catch (error) {
fill(folderPart, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', error.message)));
}
@@ -409,6 +418,10 @@ export function copyDialog(selection, { title } = {}) {
let plan = null;
let token = 0;
let busy = false;
// The files «tolti o superati» as the plan without «Copia di nuovo» counts them: the choice keeps its label and
// stays on screen whatever the plan with it says (with it they are files to copy).
let againCount = 0;
let refocusAgain = false;
async function load() {
const mine = ++token;
@@ -417,6 +430,7 @@ export function copyDialog(selection, { title } = {}) {
const result = await api('/api/export/plan', { method: 'POST', body: { ...selection, copyAgain } });
if (mine !== token) return;
plan = result;
if (!copyAgain) againCount = result.removedOrSuperseded || 0;
draw();
} catch (error) {
if (mine !== token) return;
@@ -446,16 +460,26 @@ export function copyDialog(selection, { title } = {}) {
d.problem || d.paused ? h('div.avviso.ambra', icon('pause', 's'), h('span', t('esportazione.copia.inAttesa', { problema: d.problem || t('esportazione.inPausa') }))) : null)));
let empty = null;
if (!p.files) {
empty = p.destinations.length === 0 && p.notExported && !p.alreadyCopied && !p.removedOrSuperseded
? h('p.aiuto', t('esportazione.copia.nessunaCartella'))
: h('p.aiuto', t('esportazione.copia.niente'));
// «Nessuna cartella» only when there is really none; files of accounts not exported (or of kinds the folder
// does not copy) have their own words.
let key = 'esportazione.copia.niente';
if (p.hasDestination === false) key = 'esportazione.copia.nessunaCartella';
else if (p.notExported && !p.alreadyCopied && !p.removedOrSuperseded) key = 'esportazione.copia.nienteNonEsportati';
empty = h('p.aiuto', t(key));
}
const again = p.removedOrSuperseded
? h('div.di-nuovo',
checkbox({ checked: copyAgain, label: t('esportazione.copia.diNuovo', { n: p.removedOrSuperseded }), onchange: (v) => { copyAgain = v; load(); } }),
h('p.aiuto', t('esportazione.copia.diNuovoAiuto')))
const choice = againCount || copyAgain
? checkbox({
checked: copyAgain,
label: t('esportazione.copia.diNuovo', { n: againCount || p.removedOrSuperseded }),
onchange: (v) => { copyAgain = v; refocusAgain = true; load(); },
})
: null;
const again = choice
? h('div.di-nuovo', choice, h('p.aiuto', t('esportazione.copia.diNuovoAiuto')))
: null;
fill(content, summary, rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, empty, again);
if (refocusAgain && choice) choice.input.focus();
refocusAgain = false;
fill(start, icon('copy'), t('esportazione.copia.pulsante', { n: p.files }));
start.disabled = busy || !p.files;
}
+27 -4
View File
@@ -5,7 +5,8 @@
import { api, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.js';
import { h, icon, fill } from '../core/dom.js';
import { h, icon, fill, later } from '../core/dom.js';
import { onLibrary } from '../core/engine.js';
import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
import { avatar, label, showError, toast } from '../core/ui.js';
import { confirmDelete } from './library.js';
@@ -26,6 +27,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
let fileIndex = 0;
let zoomed = false;
let token = 0;
// The copies whose «Copia di nuovo» started a job: their button stays «In copia…» until the job ends (spec §4.10).
const copying = new Set();
const where = h('span.dove');
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
@@ -77,6 +80,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
function close() {
document.removeEventListener('keydown', onKey, true);
stopWatching();
onCopiesChanged.cancel();
for (const v of box.querySelectorAll('video')) v.pause();
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
box.remove();
@@ -286,17 +291,24 @@ export function openViewer({ tile, source, origin, onDeleted }) {
const vars = { cartella: copy.destination, giorno: shortDay(copy.at.day, today), nome: copy.forAccount || '' };
const key = { copied: copy.forAccount ? 'copiatoPer' : 'copiato', removed: 'tolto', superseded: 'superato' }[copy.state] || 'fallito';
const text = t(`esportazione.vis.${key}`, vars) + (copy.destinationRetired ? ` (${t('esportazione.vis.tolta')})` : '');
const busy = copying.has(copy.copyId);
const again = copy.canCopyAgain
? h('button.btn.nudo.piccolo.copia-di-nuovo', {
type: 'button',
disabled: busy,
onclick: async (e) => {
const button = e.currentTarget;
button.disabled = true;
const job = await copyAgain(copy.copyId);
if (job) await load(entry.id, fileIndex, media.id);
else button.disabled = false;
if (!job) {
button.disabled = false;
return;
}
// The job runs on: the row says so, and the viewer reads the copies again when it ends (onLibrary «export»).
copying.add(copy.copyId);
await load(entry.id, fileIndex, media.id);
},
}, icon('rotate-cw', 's'), t('esportazione.vis.diNuovo'))
}, icon('rotate-cw', 's'), t(busy ? 'esportazione.vis.inCopia' : 'esportazione.vis.diNuovo'))
: null;
return [h('dt', t('esportazione.vis.copia')), h('dd.riga-copia', h('span', text), again)];
}
@@ -331,6 +343,17 @@ export function openViewer({ tile, source, origin, onDeleted }) {
else close();
}
// A job of the copies ended (or a folder changed): the rows of «Copia» are read again, on the same file.
const onCopiesChanged = later(() => {
if (!entry) return;
copying.clear();
const current = entry.media[fileIndex];
load(entry.id, fileIndex, current ? current.id : null);
}, 400);
const stopWatching = onLibrary((change) => {
if (change.reason === 'export') onCopiesChanged();
});
document.addEventListener('keydown', onKey, true);
document.body.append(box);
closeButton.focus();
+2
View File
@@ -1183,6 +1183,7 @@
"diNuovoAiuto": "Scrive un file nuovo; la copia di prima resta dov'è.",
"niente": "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria.",
"nessunaCartella": "Nessuna cartella delle copie: scegline una in Impostazioni → Esportazione.",
"nienteNonEsportati": "Niente da copiare: questi file sono di account che non si esportano o di tipi che la cartella non copia.",
"pulsante": "Copia 1 file|Copia {n} file",
"vediAvanzamento": "Apri l'esportazione"
},
@@ -1206,6 +1207,7 @@
"fallito": "Non riuscito in {cartella} il {giorno}",
"tolta": "cartella tolta",
"diNuovo": "Copia di nuovo",
"inCopia": "In copia…",
"copiaIn": "Copia in…"
},
"account": {
@@ -637,7 +637,7 @@ public sealed class ExportConstraintTests
var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
{
("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false),
("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original")], true),
("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original"), ("@a", w.Marta)], true),
("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false),
("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false),
};
@@ -100,7 +100,7 @@ public sealed class ExportCopiesFilterTests
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);
Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct: ct))!.Id);
var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct);
Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId);
@@ -178,6 +178,68 @@ public sealed class ExportFolderCheckTests
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
}
[TestMethod]
public async Task ALinkToAFolderInsideTheLibraryIsRecognised()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var library = temp.Combine("libreria");
var inner = Path.Combine(library, "copie", "usb");
Directory.CreateDirectory(inner);
// Not an account folder: a plain folder deep in the library, reached by a link (a junction or a symbolic link
// where the test may make one, else the «\\?\» form of its path on Windows).
var alias = temp.Combine("alias-copie");
try
{
Directory.CreateSymbolicLink(alias, inner);
}
catch (Exception ex) when (OperatingSystem.IsWindows() && ex is IOException or UnauthorizedAccessException)
{
alias = @"\\?\" + Path.GetFullPath(inner);
}
Assert.IsFalse(ExportPaths.IsSameOrInside(alias, library), "the text must not tell");
var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder);
var verdict = await Check().CheckAsync(alias, guarded, ct);
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, verdict.Problem!.Kind);
StringAssert.Contains(verdict.Problem.Message, "è dentro la cartella della libreria");
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
}
[TestMethod]
public async Task ABindMountOfAFolderOfTheLibraryIsRecognised()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
// Docker on Unraid: -v /mnt/user/Febe:/libreria and -v /mnt/user/Febe/copie:/esporta/usb. Two folders that no
// path and no probe relate, on the same device, the second showing a folder inside the first.
var library = temp.Combine("libreria");
var usb = temp.Combine("esporta", "usb");
var nas = temp.Combine("esporta", "nas");
var other = temp.Combine("esporta", "altro");
foreach (var folder in new[] { library, usb, nas, Path.Combine(nas, "Febe", "lib"), other })
{
Directory.CreateDirectory(folder);
}
string Real(string path) => FolderIdentity.RealPath(path)!;
var mounts = new FixedMounts(
new ExportMount(Real(library), "/Febe", "fuse.shfs", false, "0:51"),
new ExportMount(Real(usb), "/Febe/copie", "fuse.shfs", false, "0:51"),
new ExportMount(Real(nas), "/condivisa", "cifs", false, "0:60"),
new ExportMount(Real(Path.Combine(nas, "Febe", "lib")), "/Febe", "fuse.shfs", false, "0:51"), // the library again, below the NAS
new ExportMount(Real(other), "/Altro", "fuse.shfs", false, "0:51"));
var check = new ExportFolderCheck(mounts);
var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder with { Mounts = mounts });
Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(usb, guarded, ct)).Problem!.Kind);
Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(nas, guarded, ct)).Problem!.Kind, "a mount below the candidate shows the library");
Assert.IsTrue((await check.CheckAsync(other, guarded, ct)).Accepted, "another folder of the same device is not the library");
Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
}
[TestMethod]
public async Task TheProbeIsWrittenOnlyInTheCandidate()
{
@@ -0,0 +1,381 @@
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
/// <summary>
/// The cases found by the review of tappa E2 (27 November 2026): a stale row on the free name the writer takes, a
/// path that differs only in letter case, a superseded copy whose file is back in the library, «Una copia sola» with
/// copies of the account itself or of a removed account, a disk unplugged during «Controlla le copie», the later runs of
/// an interrupted «Copia in…», and the long-work gate held while a «Copia in…» is planned.
/// </summary>
[TestClass]
public sealed class ExportReviewTests
{
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task AStaleRowOnTheFreeNameIsReleasedAndTheCopyRecorded()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "970", 40);
var usb = await bed.GeneralAsync(ct: ct);
var planned = "marta.demo/" + post.Media[0].RelativePath;
var numbered = ExportPaths.NumberedName(bed.Usb, planned, 2);
// The planned name holds another file (other bytes); the next name is still recorded for a copy of luca.demo
// whose file Alberto deleted.
var foreign = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(planned));
Directory.CreateDirectory(Path.GetDirectoryName(foreign)!);
await File.WriteAllBytesAsync(foreign, [1, 2, 3], ct);
var stale = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, numbered, 91), ct);
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken, numbered), (item.State, item.Note, item.RelativePath));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportCopyState.Copied, numbered), (copy.State, copy.RelativePath));
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(stale.Id, ct))!.State, "the stale row is «Tolto»");
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(foreign, ct), "the other file is untouched");
// A second «Copia in…» writes nothing more.
var files = Fingerprint.Of(bed.Usb);
var again = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual((0, 1), (again.Plan.Files, again.Plan.AlreadyCopied));
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "no duplicate");
}
[TestMethod]
public async Task APathThatDiffersOnlyInCaseIsNotTakenFromItsCopy()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "971", 41);
var usb = await bed.GeneralAsync(ct: ct);
var planned = "marta.demo/" + post.Media[0].RelativePath;
var slash = planned.LastIndexOf('/');
var shouted = planned[..(slash + 1)] + planned[(slash + 1)..].ToUpperInvariant();
Assert.AreNotEqual(planned, shouted);
// Another copy is recorded and present under the same name in other letters (a case-sensitive disk keeps both).
var other = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(shouted));
Directory.CreateDirectory(Path.GetDirectoryName(other)!);
await File.WriteAllBytesAsync(other, [4, 5, 6], ct);
var held = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, shouted, 92) with { Bytes = 3 }, ct);
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (item.State, item.Note));
Assert.AreEqual(ExportPaths.NumberedName(bed.Usb, planned, 2), item.RelativePath);
Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(held.Id, ct))!.State, "its file is there: not «Tolto»");
CollectionAssert.AreEqual(new byte[] { 4, 5, 6 }, await File.ReadAllBytesAsync(other, ct));
}
[TestMethod]
public async Task ASupersededCopyOfAFileBackInTheLibraryAgreesAndCanBeCopiedAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "972", 42);
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var media = post.Media[0];
// The copy was superseded by another file; that file went, and this one came back (another entry, with no
// change of file that would have revived the row).
Assert.AreEqual(1, await bed.Db.Exports.SupersedeCopiesAsync(bed.Marta.Id, media.Sha256!, Make.Sha(77), bed.Clock.Now, ct));
var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id));
var plan = await bed.Service.PlanAsync(request, ct);
Assert.AreEqual((0, 0, 1), (plan.Files, plan.AlreadyCopied, plan.RemovedOrSuperseded));
Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct), "the filter says what the plan does");
CollectionAssert.AreEqual(new[] { post.Entry.Id }, await EntriesAsync(bed.Db, LibraryCopiesFilter.RemovedOrSuperseded, ct));
Assert.IsEmpty(await EntriesAsync(bed.Db, LibraryCopiesFilter.NotCopied, ct));
// «Copia di nuovo» finds its own bytes at the path: the row is «Copiato» again, nothing is written.
var files = Fingerprint.Of(bed.Usb);
var start = await bed.CopyAsync(request with { CopyAgain = true }, ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual(ExportItemState.AlreadyCopied, item.State);
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportCopyState.Copied, (string?)null), (copy.State, copy.SupersededBySha256));
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
Assert.AreEqual(1, (await bed.Service.PlanAsync(request, ct)).AlreadyCopied);
}
[TestMethod]
public async Task OneCopyOnlyIgnoresTheAccountsOwnCopyInAnotherFolder()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "973", 43);
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
// Her own folder now, the general one still in use for the others.
await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct);
Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([post.Media[0].Id], ct))[post.Media[0].Id]);
}
[TestMethod]
public async Task OneCopyOnlyIgnoresTheCopyOfARemovedAccount()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var lucas = await bed.PostAsync(bed.Luca, "974", 44);
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Luca, ct: ct);
var martas = await bed.PostAsync(bed.Marta, "975", 44); // the same bytes
Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256);
// luca.demo leaves Febe: his copy stays, without an account.
await bed.Db.Accounts.DeleteAsync(bed.Luca.Id, ct);
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct);
Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([martas.Media[0].Id], ct))[martas.Media[0].Id]);
}
[TestMethod]
public async Task OneCopyOnlyFindsTheOtherAccountsCopyBehindTheAccountsOwnNewerOne()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var lucas = await bed.PostAsync(bed.Luca, "976", 45);
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Luca, ct: ct); // the older copy, of luca.demo
var martas = await bed.PostAsync(bed.Marta, "977", 45);
await bed.CopyAccountAsync(bed.Marta, ct: ct); // the newer one, hers («Una copia per account»)
Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256);
await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 0, ct);
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note));
}
[TestMethod]
public async Task ADiskUnpluggedDuringTheCheckMarksNothingRemoved()
{
var ct = TestContext.CancellationToken;
var unplug = new UnplugOnCheck();
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = unplug });
await bed.PostAsync(bed.Marta, "978", 46, 47, 48);
var usb = await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct));
// The disk goes away after the root was found and before the files of the page are looked for.
unplug.Root = bed.Usb;
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.IsTrue(unplug.Unplugged);
Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct), "nothing is «Tolto»");
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt, "the destination is paused");
// Plugged in again, the check finds every file.
Directory.Move(bed.Usb + "-staccato", bed.Usb);
unplug.Root = null;
await bed.Service.CheckCopiesAsync(usb.Id, ct);
await bed.Service.WaitAsync(ct);
Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct));
}
[TestMethod]
public async Task InterruptingAJobOfTwoDestinationsLeavesBothResumable()
{
var ct = TestContext.CancellationToken;
string? blocked = null;
var gated = new GatedExportFileSystem(p => string.Equals(p, Volatile.Read(ref blocked), StringComparison.Ordinal));
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
var martas = await bed.PostAsync(bed.Marta, "979", 49);
var lucas = await bed.PostAsync(bed.Luca, "980", 50);
await bed.GeneralAsync(ct: ct);
await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct);
Volatile.Write(ref blocked, bed.LibraryFile(bed.Marta, martas.Media[0]));
var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([martas.Entry.Id, lucas.Entry.Id])), ct);
Assert.HasCount(2, start.Runs);
await gated.Reached.Task.WaitAsync(Patience, ct);
await bed.Service.InterruptAsync(ct);
Assert.IsFalse(bed.Service.IsBusy);
foreach (var run in start.Runs)
{
Assert.AreEqual((ExportRunState.Interrupted, (string?)null), ((await bed.RunAsync(run.Id, ct)).State, (await bed.RunAsync(run.Id, ct)).LastError), $"run {run.Id}");
}
// «Riprendi tutte» takes both.
Volatile.Write(ref blocked, null);
var resumed = await bed.Service.ResumeAsync(ct: ct);
Assert.HasCount(2, resumed);
await bed.Service.WaitAsync(ct);
foreach (var run in start.Runs)
{
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
}
}
[TestMethod]
public async Task TheLongWorkGateIsHeldWhileACopyIsPlanned()
{
var ct = TestContext.CancellationToken;
GateWatchingClock? clock = null;
await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GateWatchingClock(env.Clock, env.Gate!) });
await bed.PostAsync(bed.Marta, "981", 51, 52);
await bed.GeneralAsync(ct: ct);
clock!.Watching = true;
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
clock.Watching = false;
await bed.Service.WaitAsync(ct);
Assert.IsGreaterThan(0, clock.Looks, "the start read the clock while it planned");
Assert.AreEqual(0, clock.Overlaps, "a rebuild could have started while the runs were recorded");
Assert.IsNull(bed.Gate.Busy);
// Nothing to copy: the gate is free again at once.
var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct);
Assert.IsEmpty(nothing.Runs);
Assert.IsNull(bed.Gate.Busy);
}
[TestMethod]
public void TheRenameNeverReplacesAnExistingName()
{
using var temp = new TempFolder("rename");
var taken = temp.Combine("taken.jpg");
var source = temp.Combine(".febe-0123456789ab.part");
File.WriteAllBytes(taken, [1]);
File.WriteAllBytes(source, [2]);
if (OperatingSystem.IsWindows())
{
// On Windows the move itself refuses an existing name: nothing to do here.
Assert.AreEqual(NoReplaceOutcome.Unsupported, NoReplaceRename.TryMove(source, taken));
}
else
{
Assert.AreEqual(NoReplaceOutcome.Taken, NoReplaceRename.TryMove(source, taken));
CollectionAssert.AreEqual(new byte[] { 1 }, File.ReadAllBytes(taken));
Assert.IsTrue(File.Exists(source));
var free = temp.Combine("free.jpg");
Assert.AreEqual(NoReplaceOutcome.Moved, NoReplaceRename.TryMove(source, free));
CollectionAssert.AreEqual(new byte[] { 2 }, File.ReadAllBytes(free));
Assert.IsFalse(File.Exists(source));
}
Assert.AreEqual(1, File.ReadAllBytes(taken)[0]);
}
/// <summary>A Copied row of a whole original (any SHA-256 given by its seed) at a path, with no file behind it.</summary>
private static ExportCopy StaleCopy(long destinationId, long accountId, string path, int seed) => new()
{
DestinationId = destinationId,
AccountId = accountId,
SourceSha256 = Make.Sha(seed),
Variant = ExportVariant.Whole,
Format = ExportFormat.Original,
State = ExportCopyState.Copied,
RelativePath = path,
Bytes = 1,
CopySha256 = Make.Sha(seed),
CopiedAt = Make.T0,
};
/// <summary>The plan of the account, its counts, its marks and the «Copie» filter tell the same.</summary>
private static async Task AssertAgreeAsync(ExportTestBed bed, Account account, int expectedToWrite, CancellationToken ct)
{
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(account.Id)), ct);
var counts = await bed.Db.Exports.CountAccountFilesAsync(account.Id, ct);
Assert.AreEqual(expectedToWrite, plan.Files, "plan");
Assert.AreEqual(plan.Files, counts.NotCopied, "«non ancora copiati» is what «Copia in…» writes");
Assert.AreEqual(plan.AlreadyCopied, counts.Copied, "«copiati» is what «Copia in…» skips as copied");
var filter = new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied, AccountIds = [account.Id] };
Assert.AreEqual(expectedToWrite, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Mode = MosaicMode.Files }, ct)).Tiles.Count);
var copied = filter with { Copies = LibraryCopiesFilter.Copied };
Assert.AreEqual(plan.AlreadyCopied, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = copied, Mode = MosaicMode.Files }, ct)).Tiles.Count);
}
private static async Task<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)];
/// <summary>The real file system; once <see cref="Root"/> is set, the first look for a file in it takes the disk away.</summary>
private sealed class UnplugOnCheck : IExportFileSystem
{
private int _unplugged;
public string? Root { get; set; }
public bool Unplugged => Volatile.Read(ref _unplugged) != 0;
public Stream OpenRead(string path) => ExportFileSystem.Instance.OpenRead(path);
public Task<string> ComputeSha256Async(string path, CancellationToken ct) => ExportFileSystem.Instance.ComputeSha256Async(path, ct);
public bool FileExists(string path)
{
if (Root is { } root && path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal) && Interlocked.Exchange(ref _unplugged, 1) == 0)
{
Directory.Move(root, root + "-staccato");
}
return ExportFileSystem.Instance.FileExists(path);
}
public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path);
}
/// <summary>
/// The clock of the export; while <see cref="Watching"/>, each look at the time tries to start a rebuild through the
/// long-work gate (and lets it go at once), counting the times it could.
/// </summary>
private sealed class GateWatchingClock(IClock inner, LongWorkGate gate) : IClock
{
private int _looks;
private int _overlaps;
private volatile bool _watching;
public bool Watching
{
get => _watching;
set => _watching = value;
}
public int Looks => Volatile.Read(ref _looks);
public int Overlaps => Volatile.Read(ref _overlaps);
public DateTimeOffset Now
{
get
{
if (Watching)
{
Interlocked.Increment(ref _looks);
if (gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _))
{
Interlocked.Increment(ref _overlaps);
lease.Dispose();
}
}
return inner.Now;
}
}
public TimeZoneInfo LocalZone => inner.LocalZone;
public Task Delay(TimeSpan time, CancellationToken ct) => inner.Delay(time, ct);
}
}
@@ -13,6 +13,8 @@ namespace Febe.Tests.Export;
[TestClass]
public sealed class ExportRootTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void DesktopHasNoRootAndIsActive()
{
@@ -183,6 +185,32 @@ public sealed class ExportRootTests
Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Browse(ExportRootOptions.AnyFolder, "usb")));
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ADeadShareBelowTheRootDoesNotBlockThePicker()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
var root = temp.Combine("esporta");
Directory.CreateDirectory(Path.Combine(root, "nas", "Febe"));
Directory.CreateDirectory(Path.Combine(root, "usb", "Febe"));
var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" };
// The NAS behind /esporta/nas is off: a look into it never answers.
using var dead = new ManualResetEventSlim();
bool Look(string folder) => Path.GetFileName(folder) == "nas" ? dead.Wait(Timeout.Infinite, ct) : Directory.EnumerateDirectories(folder).Any();
var started = System.Diagnostics.Stopwatch.StartNew();
var top = await ExportRoots.BrowseAsync(o, null, TimeSpan.FromMilliseconds(300), Look, ct);
Assert.IsLessThan(TimeSpan.FromSeconds(10), started.Elapsed);
CollectionAssert.AreEqual(new[] { "nas", "usb" }, top.Select(c => c.Name).ToArray());
Assert.IsFalse(top[0].HasSubfolders, "the dead share is shown, without the arrow");
Assert.IsTrue(top[1].HasSubfolders, "the healthy one is listed as usual");
dead.Set();
var missing = await Assert.ThrowsExactlyAsync<ExportFolderException>(() => ExportRoots.BrowseAsync(o, "assente", TimeSpan.FromSeconds(5), ct));
Assert.AreEqual(ExportFolderProblemKind.Missing, missing.Kind);
}
internal static ExportMount Mount(string point, string root = "/", string type = "ext4", bool readOnly = false) =>
new(Path.GetFullPath(point), root, type, readOnly);
+2 -1
View File
@@ -85,7 +85,8 @@ public sealed class MountInfoTests
Assert.IsNull(MountInfoTable.FindContaining([], "/esporta"));
var proc = new ProcMountInfo(() => content);
Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false), proc.FindContaining("/esporta/usb/a"));
Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false, "8:49"), proc.FindContaining("/esporta/usb/a"));
Assert.AreEqual("8:17", MountInfoTable.FindContaining(mounts, "/esporta")!.Device); // the device, for the identity test
Assert.HasCount(4, proc.All());
}
}
+25 -6
View File
@@ -135,11 +135,20 @@ public sealed class ExportInterfaceTests
using var temp = new TempFolder("esporta-selezione-ui");
await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path));
// The three newest entries of the demo have four files still to copy.
// The newest entries of marta.demo (general folder) with a file still to copy. The demo places its entries by the
// hour it is built (decision of 26 November 2026), so how many files they have is asked of the plan, not assumed.
await ui.OpenAsync(new Uri(demo.Address, "/libreria"));
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 3", "il mosaico");
await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico");
var marta = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64();
await ui.OpenAsync(new Uri(demo.Address, $"/libreria?copie=non-copiati&account={marta}"));
await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 1 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico dei non ancora copiati");
Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean());
await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].slice(0, 3).forEach((t) => t.click())");
var files = (await ui.EvalAsync(
"fetch('/api/export/plan', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, "
+ "body: JSON.stringify({ entryIds: [...document.querySelectorAll('.mosaico .tess')].slice(0, 3).map((t) => Number(t.dataset.id)), copyAgain: false }) })"
+ ".then((r) => r.json()).then((j) => j.files)")).GetInt32();
Assert.IsGreaterThan(0, files, "«Non ancora copiati» has files to copy");
const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))";
await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…» nella barra della scelta");
await ui.EvalAsync($"({CopyIn}).click()");
@@ -147,10 +156,10 @@ public sealed class ExportInterfaceTests
const string Dialog = "document.querySelector('.dialogo.copia-in')";
await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo");
var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!;
StringAssert.StartsWith(summary, "4 file", summary);
StringAssert.StartsWith(summary, $"{files} file", summary);
StringAssert.Contains(summary, "circa", "lo spazio");
StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.destinazioni-copia').textContent")).GetString(), "In Disco USB");
Assert.AreEqual("Copia 4 file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString());
Assert.AreEqual($"Copia {files} file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString());
await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()");
await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude");
@@ -160,7 +169,7 @@ public sealed class ExportInterfaceTests
// The job is in the Dashboard tab, finished: the demo copies at once.
await ui.EvalAsync("document.querySelector('.brevi .breve a.breve-link').click()");
await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .elenco-attivita li') !== null", "la linguetta «Esportazione»");
await ui.WaitAsync("document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('4 di 4 file')", "il lavoro di 4 file " + ui.Report());
await ui.WaitAsync($"document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('{files} di {files} file')", $"il lavoro di {files} file " + ui.Report());
}
[TestMethod]
@@ -223,7 +232,17 @@ public sealed class ExportInterfaceTests
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria con «Tolti o superati»");
await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()");
await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && document.querySelector('.mosaico .tess') !== null", "«Tutte le foto»");
await ui.EvalAsync("document.querySelector('.mosaico .tess').click()");
// The first of those files that is on disk (the demo shares the bytes of a picture with a video that has no file,
// and which comes first depends on the hour the demo is built): «Copia in…» is offered only for a file on disk.
var target = (await ui.EvalAsync(
"(async () => { const j = await (await fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000')).json(); "
+ "for (const tile of j.tiles) { if (!tile.cover) continue; const e = await (await fetch('/api/entries/' + tile.id)).json(); "
+ "const m = e.media.find((x) => x.id === tile.cover.mediaId); if (m && m.available) return tile.cover.mediaId; } return 0; })()")).GetInt64();
Assert.IsGreaterThan(0L, target, "a «tolto o superato» file on disk");
var tile = $"document.querySelector('.mosaico .tess[data-id=\"{target}\"]')";
await ui.WaitAsync($"{tile} !== null", "la tessera del file");
await ui.EvalAsync($"{tile}.click()");
await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report());
var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!;