E2: correzioni della revisione delle copie esterne
- Nome libero scelto prima di scrivere, libero sul disco e nel database; una riga orfana sul nome diventa «Tolto» (guardando il suo percorso, anche se differisce solo per le maiuscole): prima la copia finiva «Non riuscito» con il file già scritto, o toglieva la copia buona. - «Controlla le copie» rilegge la radice e riguarda i file mancanti; con il disco staccato si ferma e mette in pausa senza segnare nulla. - Su Linux lo spostamento sul nome finale non sostituisce mai un file (renameat2 RENAME_NOREPLACE, poi link e unlink). - Le copie in coda di un lavoro interrotto diventano «Interrotta» e si riprendono; il permesso dei lavori lunghi si tiene già nel piano. - «Superato» con il file di nuovo in libreria: filtro, piano e «Copia di nuovo» d'accordo; l'adozione ravviva la riga invece di fallire. - «Una copia sola» con una regola sola in filtro, piano, visualizzatore e copiatore (solo copie di un altro account in cartelle in uso). - Controllo della cartella per identità vera (percorso finale, realpath, dispositivo di mountinfo): riconosce collegamenti e bind mount di una sottocartella della libreria. - Sfoglia delle cartelle con tempi massimi; «Nessuna cartella» solo se non ce n'è; «In copia…» nel visualizzatore; numero e fuoco stabili in «Copia di nuovo anche…»; una sola lettura per volta nella Dashboard. - Prove dell'interfaccia indipendenti dall'ora e dal file scelto; prove nuove in ExportReviewTests, ExportFolderCheckTests, ExportRootTests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28c7f814b1
commit
36ad5c6f9d
28 files changed
+1314
-112
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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, []);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user