E5: «Riconosci» va avanti su un file illeggibile e non tocca nulla
Un file della cartella che non si legge (aperto da un altro programma, senza permessi) rende «Non riuscito» solo il suo elemento: prima fermava tutto il lavoro, e «Riprendi» si fermava sempre lì. «Annulla» e il riavvio non tolgono più i .part nelle cartelle di un «Riconosci», come dice la specifica. Una riga orfana «Superato» ricollegata diventa «Copiato», come dice l'elemento; una riga orfana «Tolto» resta «Tolto» anche per il file, come già per i fotogrammi (risposta 51). I nomi numerati si guardano tutti fino a «nome (50)», anche dopo un buco. I byte della libreria di un «Riconosci», che non scrive, non contano più per la prova della cartella: una prova per gruppo di file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
309f4d0402
commit
11e9dd276c
7 files changed
+317
-26
No files matched your search
@@ -88,8 +88,11 @@ public sealed partial class ExportCopier
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = copied[0].Id, LastError = null }, library.Bytes, copied[0].RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Answer 51: a file whose newest copy here is «Tolto» is never recognised, even if its file came back identical.
|
||||
if (await exports.FindLatestCopyAnyFormAsync(destination.Id, account, sha, ct).ConfigureAwait(false) is { State: ExportCopyState.Removed } removed)
|
||||
// Answer 51: a file whose newest copy here is «Tolto» is never recognised, even if its file came back identical;
|
||||
// when the account has no row of it, the newest orphan row (account removed) decides, as for a frame.
|
||||
var latest = await exports.FindLatestCopyAnyFormAsync(destination.Id, account, sha, ct).ConfigureAwait(false)
|
||||
?? await exports.FindLatestOrphanCopyAnyFormAsync(destination.Id, sha, ct).ConfigureAwait(false);
|
||||
if (latest is { State: ExportCopyState.Removed } removed)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = removed.Id, LastError = null }, library.Bytes, removed.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
@@ -140,6 +143,7 @@ public sealed partial class ExportCopier
|
||||
return await NotFoundAsync(x, item, library.Bytes, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var unreadable = new List<Exception>();
|
||||
foreach (var (format, paths) in forms)
|
||||
{
|
||||
MediaConversionResult? conversion = null;
|
||||
@@ -178,7 +182,7 @@ public sealed partial class ExportCopier
|
||||
var identity = new ExportCopyIdentity(destination.Id, account, sha, output.Variant, output.Format, null);
|
||||
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
var failed = current is { State: ExportCopyState.Failed } ? current : null;
|
||||
var result = await TryAdoptAsync(x, item, new FileContext(library, identity), output, failed, paths, ExportItemState.Adopted, ct).ConfigureAwait(false);
|
||||
var result = await TryAdoptAsync(x, item, new FileContext(library, identity), output, failed, paths, ExportItemState.Adopted, ct, unreadable).ConfigureAwait(false);
|
||||
if (result is not null)
|
||||
{
|
||||
if (result.State is ExportItemState.Adopted or ExportItemState.AlreadyCopied)
|
||||
@@ -192,6 +196,11 @@ public sealed partial class ExportCopier
|
||||
}
|
||||
}
|
||||
|
||||
if (await UnreadableAsync(item, library.Bytes, unreadable) is { } failedRead)
|
||||
{
|
||||
return failedRead;
|
||||
}
|
||||
|
||||
// The report shows the path where another file is (the first one looked at).
|
||||
var different = forms[0].Paths[0];
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Different, RelativePath = different, LastError = null }, library.Bytes, different).ConfigureAwait(false);
|
||||
@@ -261,6 +270,7 @@ public sealed partial class ExportCopier
|
||||
}
|
||||
|
||||
// The bytes a row of this very frame recorded at the path: compared without taking the frame again.
|
||||
var unreadable = new List<Exception>();
|
||||
var others = new List<string>();
|
||||
foreach (var path in paths)
|
||||
{
|
||||
@@ -268,7 +278,7 @@ public sealed partial class ExportCopier
|
||||
&& string.Equals(holder.SourceSha256, library.Sha256, StringComparison.Ordinal) && holder.Format == format && holder.FrameAt == at)
|
||||
{
|
||||
var known = new Output(ExportVariant.Frame, format, at, extension, null, bytes, copySha, null, []);
|
||||
if (await TryAdoptAsync(x, item, file, known, failed, [path], ExportItemState.Adopted, ct).ConfigureAwait(false) is { } adopted)
|
||||
if (await TryAdoptAsync(x, item, file, known, failed, [path], ExportItemState.Adopted, ct, unreadable).ConfigureAwait(false) is { } adopted)
|
||||
{
|
||||
return adopted;
|
||||
}
|
||||
@@ -286,12 +296,17 @@ public sealed partial class ExportCopier
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (await TryAdoptAsync(x, item, file, taken, failed, others, ExportItemState.Adopted, ct).ConfigureAwait(false) is { } adopted)
|
||||
if (await TryAdoptAsync(x, item, file, taken, failed, others, ExportItemState.Adopted, ct, unreadable).ConfigureAwait(false) is { } adopted)
|
||||
{
|
||||
return adopted;
|
||||
}
|
||||
}
|
||||
|
||||
if (await UnreadableAsync(item, 0, unreadable) is { } failedRead)
|
||||
{
|
||||
return failedRead;
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Different, RelativePath = paths[0], LastError = null }, 0, paths[0]).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -310,8 +325,17 @@ public sealed partial class ExportCopier
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files of the destination at <paramref name="planned"/> and at its numbered names («nome (2)» … «nome (50)»,
|
||||
/// numbered as the writer numbers them), these until the first one that is not there.
|
||||
/// A file of the destination that could not be read was not adopted: the item is «Non riuscito» with the error (no copy
|
||||
/// row), so the run goes on to the next file and «Riconosci» can be run again. Null when every file was read.
|
||||
/// </summary>
|
||||
private async Task<ItemResult?> UnreadableAsync(ExportItem item, long bytes, List<Exception> unreadable) =>
|
||||
unreadable.Count == 0
|
||||
? null
|
||||
: await FinishAsync(item with { State = ExportItemState.Failed, Note = null, LastError = ExportText.ErrorText(unreadable[0]) }, bytes, null).ConfigureAwait(false);
|
||||
|
||||
/// <summary>
|
||||
/// The files of the destination at <paramref name="planned"/> and at all its numbered names («nome (2)» … «nome (50)»,
|
||||
/// numbered as the writer numbers them): a gap (a copy deleted in the middle) does not hide the names after it.
|
||||
/// </summary>
|
||||
private List<string> PresentNames(string root, string planned, string? keepSuffix)
|
||||
{
|
||||
@@ -332,10 +356,6 @@ public sealed partial class ExportCopier
|
||||
{
|
||||
found.Add(name);
|
||||
}
|
||||
else if (attempt > 1)
|
||||
{
|
||||
break; // the writer takes the first free name: nothing of ours after it
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
|
||||
@@ -71,11 +71,9 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
try
|
||||
{
|
||||
x.Report(_env, ExportPhase.Preparing, null);
|
||||
if (!recognize)
|
||||
{
|
||||
// «Riconosci» writes no .part, so it has none to clean: it only reads the destination (D13 of tappa E5).
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// «Riconosci» writes no .part, so it has none to clean: CleanAsync leaves its runs alone (D13 of tappa E5).
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
|
||||
var layout = _env.Layout();
|
||||
var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false);
|
||||
@@ -269,7 +267,10 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1);
|
||||
x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1;
|
||||
x.GroupFiles++;
|
||||
x.GroupBytes += result.Written ?? result.Bytes;
|
||||
|
||||
// The bytes written count toward the next probe; a «Riconosci» writes nothing, so it probes once per group of
|
||||
// files, not every gigabyte of library files it only looked for.
|
||||
x.GroupBytes += result.Written ?? (x.Run.Kind == ExportRunKind.Recognize ? 0 : result.Bytes);
|
||||
if (x.GroupFiles >= Math.Max(1, _env.GroupFiles) || x.GroupBytes >= _env.GroupBytes)
|
||||
{
|
||||
x.GroupFiles = 0;
|
||||
@@ -1012,7 +1013,9 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
/// database, or held by an orphan row of this very copy, is recorded «Adottato»; one held by a «Superato» row of this
|
||||
/// identity revives it (the item then ends <paramref name="revived"/>); one held by this identity's own copy is
|
||||
/// «Già copiato». A file with the same bytes recorded for another copy is not ours to take. Null when none is adopted.
|
||||
/// Reads files only: nothing is written, renamed or deleted.
|
||||
/// Reads files only: nothing is written, renamed or deleted. A candidate that cannot be read (held open by another
|
||||
/// program, no permission) is not ours to take either: it is added to <paramref name="unreadable"/> and the next one
|
||||
/// is looked at; only the root gone away pauses.
|
||||
/// </summary>
|
||||
private async Task<ItemResult?> TryAdoptAsync(
|
||||
RunContext x,
|
||||
@@ -1022,7 +1025,8 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
ExportCopy? failed,
|
||||
IEnumerable<string> candidates,
|
||||
ExportItemState revived,
|
||||
CancellationToken ct)
|
||||
CancellationToken ct,
|
||||
List<Exception>? unreadable = null)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var destination = x.Destination;
|
||||
@@ -1048,7 +1052,23 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
expected = hash;
|
||||
}
|
||||
|
||||
if (!string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), expected, StringComparison.Ordinal))
|
||||
string found;
|
||||
try
|
||||
{
|
||||
found = await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (!Directory.Exists(root) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } away)
|
||||
{
|
||||
return ItemResult.Paused(away);
|
||||
}
|
||||
|
||||
unreadable?.Add(ex);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!string.Equals(found, expected, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -1234,6 +1254,12 @@ public sealed partial class ExportCopier(ExportEnvironment env)
|
||||
else if (orphan is not null)
|
||||
{
|
||||
copy = await exports.RelinkOrphanCopyAsync(orphan.Id, identity.AccountId, file.Library.Media.Id, now, none).ConfigureAwait(false);
|
||||
if (copy.State != ExportCopyState.Copied)
|
||||
{
|
||||
// An orphan «Superato» (or «Non riuscito») whose bytes are there: the copy is copied now, as the item says.
|
||||
copy = copy with { State = ExportCopyState.Copied, SupersededBySha256 = null, StateChangedAt = now, LastError = null };
|
||||
await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -13,12 +13,20 @@ public static class ExportLeftovers
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
|
||||
/// <summary>Removes our temporary files in the folders of the items of <paramref name="run"/>. Returns how many.</summary>
|
||||
/// <summary>
|
||||
/// Removes our temporary files in the folders of the items of <paramref name="run"/>. Returns how many. A «Riconosci»
|
||||
/// writes no <c>.part</c> and touches no file (§4.10, not even the <c>.part</c> of others): nothing is removed for it,
|
||||
/// whether it runs, is cancelled or is found unfinished at a restart.
|
||||
/// </summary>
|
||||
public static async Task<int> CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
ArgumentNullException.ThrowIfNull(run);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
if (run.Kind == ExportRunKind.Recognize)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false))
|
||||
{
|
||||
return 0;
|
||||
|
||||
@@ -226,6 +226,12 @@ public interface IExportStore
|
||||
/// <summary>The newest row, in any state and any form but a frame, of an original for an account in a destination (D3 of tappa E3).</summary>
|
||||
Task<ExportCopy?> FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The newest orphan row (its account removed), in any state and any form but a frame, of an original in a destination
|
||||
/// («Riconosci», answer 51: a «Tolto» stays «Tolto» for the account added again too).
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindLatestOrphanCopyAnyFormAsync(long destinationId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// After a copy of an original succeeded: its other current «Non riuscito» rows in any form but a frame, for the
|
||||
/// account in the destination, are deleted (they have no file; the identity <paramref name="except"/> is kept).
|
||||
|
||||
@@ -278,12 +278,18 @@ internal static class ExportFilterSql
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (D13, answer 51) for the file itself on <c>m</c> with <c>e</c>, in destination
|
||||
/// <paramref name="destinationId"/>: not copied (<see cref="Copied"/>: with «Una copia sola» a copy for another account
|
||||
/// counts), and its newest row there in any form but a frame is not «Tolto». «Superato» and «Non riuscito» are
|
||||
/// recognised; a «Tolto» stays «Tolto».
|
||||
/// counts), and its newest row there in any form but a frame is not «Tolto»; when the account has no such row, the
|
||||
/// newest orphan row (account removed) decides, as for a frame. «Superato» and «Non riuscito» are recognised; a
|
||||
/// «Tolto» stays «Tolto».
|
||||
/// </summary>
|
||||
public static string RecognizeFile(ExportFilterContext x, long destinationId) =>
|
||||
$"(NOT {Copied(x)} AND ifnull((SELECT c.state FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {Literal(destinationId)} "
|
||||
+ "AND c.account_id = e.account_id AND c.variant <> 'Frame' ORDER BY c.id DESC LIMIT 1), '') <> 'Removed')";
|
||||
public static string RecognizeFile(ExportFilterContext x, long destinationId)
|
||||
{
|
||||
var d = Literal(destinationId);
|
||||
return $"(NOT {Copied(x)} AND ifnull(coalesce("
|
||||
+ $"(SELECT c.state FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {d} AND c.account_id = e.account_id AND c.variant <> 'Frame' ORDER BY c.id DESC LIMIT 1), "
|
||||
+ $"(SELECT c.state FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {d} AND c.account_id IS NULL AND c.variant <> 'Frame' ORDER BY c.id DESC LIMIT 1)"
|
||||
+ "), '') <> 'Removed')";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci» for a frame row <c>c</c> of the file <c>m</c> with <c>e</c> in destination <paramref name="destinationId"/>:
|
||||
|
||||
@@ -1062,6 +1062,21 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
||||
ct);
|
||||
}
|
||||
|
||||
/// <summary>The newest orphan row of an original in any form but a frame (@h, @d).</summary>
|
||||
internal const string LatestOrphanCopyAnyFormSql = $"""
|
||||
SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256
|
||||
WHERE source_sha256 = @h AND destination_id = @d AND account_id IS NULL AND variant <> 'Frame'
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""";
|
||||
|
||||
public Task<ExportCopy?> FindLatestOrphanCopyAnyFormAsync(long destinationId, string sha256, CancellationToken ct = default)
|
||||
{
|
||||
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||
return db.ReadAsync(
|
||||
c => ReadFirst(c.Command(LatestOrphanCopyAnyFormSql).With("@h", sha).With("@d", destinationId), ReadCopy),
|
||||
ct);
|
||||
}
|
||||
|
||||
public Task<int> ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(except);
|
||||
|
||||
@@ -573,6 +573,190 @@ public sealed class ExportRecognizeTests
|
||||
Assert.IsFalse((await bed.Db.Exports.ListRunsAsync(ct)).Any(r => r.Kind == ExportRunKind.Recognize), "a refused start records nothing");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file of the destination that cannot be read (held open by another program, no permission) does not stop the run:
|
||||
/// its item is «Non riuscito» with the error and no copy row, and the next file is recognised.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnUnreadableFileInTheFolderFailsItsItemAndTheRunGoesOn()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
UnreadableExportFileSystem? files = null;
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = files = new UnreadableExportFileSystem(p => p.Contains("usb", StringComparison.Ordinal) && p.Contains("_1.jpg", StringComparison.Ordinal) && p.Contains("u01", StringComparison.Ordinal)) });
|
||||
var locked = await bed.PostAsync(bed.Marta, "u01", 21);
|
||||
var other = await bed.PostAsync(bed.Marta, "u02", 22);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, locked.Media[0]);
|
||||
PutCopy(bed, bed.Marta, other.Media[0]);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual(ExportRunState.Completed, run.State);
|
||||
Assert.IsGreaterThan(0, files!.Refused);
|
||||
var items = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value);
|
||||
Assert.AreEqual(ExportItemState.Failed, items[locked.Media[0].Id].State);
|
||||
StringAssert.StartsWith(items[locked.Media[0].Id].LastError, "Errore di lettura o scrittura");
|
||||
Assert.AreEqual(ExportItemState.Adopted, items[other.Media[0].Id].State);
|
||||
Assert.AreEqual(other.Media[0].Id, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().MediaId, "no row for the file that could not be read");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Annulla» and a restart leave the <c>.part</c> files in the folders of a «Riconosci» alone (§4.10: it removes no
|
||||
/// file, not even the <c>.part</c> of others); a copy job of the same folders cleans its own.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task DiscardAndRestartLeaveThePartFilesOfARecognizeRun()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "p01", 23);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var folder = Path.Combine(bed.Usb, "marta.demo", "altrove");
|
||||
Directory.CreateDirectory(folder);
|
||||
|
||||
async Task<(ExportRun Run, string Stray)> UnfinishedAsync(ExportRunKind kind, string name)
|
||||
{
|
||||
var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Kind = kind, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = bed.Marta.Id, SourceSha256 = post.Media[0].Sha256, RelativePath = "marta.demo/altrove/" + name + ".jpg" }], ct);
|
||||
var stray = Path.Combine(folder, SafeFileWriter.TempPrefix + name + ".part");
|
||||
await File.WriteAllBytesAsync(stray, [1], ct);
|
||||
return (run, stray);
|
||||
}
|
||||
|
||||
var discarded = await UnfinishedAsync(ExportRunKind.Recognize, "annullato");
|
||||
await bed.Service.DiscardAsync(discarded.Run.Id, ct);
|
||||
Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(discarded.Run.Id, ct)).State);
|
||||
Assert.IsTrue(File.Exists(discarded.Stray), "«Annulla» of a «Riconosci» removes nothing");
|
||||
|
||||
var restarted = await UnfinishedAsync(ExportRunKind.Recognize, "riavvio");
|
||||
await bed.Service.RecoverAsync(ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.IsTrue(File.Exists(restarted.Stray), "a restart removes nothing of a «Riconosci»");
|
||||
|
||||
// Control: «Annulla» of a copy job removes the .part files in its items' folders.
|
||||
var copy = await UnfinishedAsync(ExportRunKind.Copy, "copia");
|
||||
await bed.Service.DiscardAsync(copy.Run.Id, ct);
|
||||
Assert.IsFalse(File.Exists(copy.Stray));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An orphan «Superato» row (its account removed) whose bytes are at its path: «Riconosci» links it to the account
|
||||
/// added again and the row is «Copiato», as its item says.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnOrphanSupersededRowIsRelinkedAsCopied()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Marta, "o01", 24);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
var copy = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
await bed.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(779), StateChangedAt = bed.Clock.Now }, ct);
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.PostAsync(again, "o01", 24);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)copyId), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
Assert.AreEqual((again.Id, ExportCopyState.Copied, (string?)null), (row.AccountId, row.State, row.SupersededBySha256));
|
||||
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(again.Id)), ct)).Files, "it counts as copied");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An orphan «Tolto» row stops the file from being recognised for the account added again, as it does for a frame
|
||||
/// (answer 51: a «Tolto» stays «Tolto»).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task AnOrphanRemovedFileStaysRemoved()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "o02", 25);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
var file = bed.GeneralCopy(bed.Marta, post.Media[0]);
|
||||
File.Move(file, file + ".via");
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(copyId, ct))!.State);
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.PostAsync(again, "o02", 25);
|
||||
File.Move(file + ".via", file); // back, byte for byte
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.IsEmpty(await bed.ItemsAsync(run.Id, ct), "not even looked for");
|
||||
var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
|
||||
Assert.AreEqual((copyId, ExportCopyState.Removed, (long?)null), (row.Id, row.State, row.AccountId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The numbered names are all looked at up to «nome (50)»: a copy at «nome (3)» is found even when «nome (2)» is not
|
||||
/// there (a copy deleted in the middle).
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ANumberedSiblingAfterAGapIsAdopted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "g01", 26);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var planned = "marta.demo/" + media.RelativePath;
|
||||
var taken = Full(bed, planned);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(taken)!);
|
||||
await File.WriteAllBytesAsync(taken, [1, 2, 3], ct);
|
||||
var third = ExportPaths.NumberedName(bed.Usb, planned, 3);
|
||||
File.Copy(bed.LibraryFile(bed.Marta, media), Full(bed, third));
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, third), (item.State, item.RelativePath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A «Riconosci» checks the folder once per group of files, not at every gigabyte of library files it only looked
|
||||
/// for: it writes nothing, so its bytes do not count toward the next probe; a copy job's do.
|
||||
/// </summary>
|
||||
[TestMethod]
|
||||
public async Task ARecognizeRunProbesOncePerGroupOfFiles()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var probes = 0;
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with
|
||||
{
|
||||
GroupBytes = 1,
|
||||
WriteProbe = path =>
|
||||
{
|
||||
Interlocked.Increment(ref probes);
|
||||
File.WriteAllBytes(path, "Febe"u8.ToArray());
|
||||
},
|
||||
});
|
||||
await bed.PostAsync(bed.Marta, "q01", 27, 28, 29);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var before = Volatile.Read(ref probes);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.HasCount(3, await bed.ItemsAsync(run.Id, ct));
|
||||
Assert.AreEqual(before + 1, Volatile.Read(ref probes), "one probe for the group of three files");
|
||||
|
||||
// Control: a copy job of the same files probes before each one (one byte per group).
|
||||
before = Volatile.Read(ref probes);
|
||||
await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
Assert.AreEqual(before + 3, Volatile.Read(ref probes));
|
||||
}
|
||||
|
||||
// Helpers -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>«Riconosci» and waits for its job.</summary>
|
||||
@@ -617,6 +801,32 @@ public sealed class ExportRecognizeTests
|
||||
.Select(f => $"{Path.GetRelativePath(folder, f)}:{new FileInfo(f).Length}:{File.GetLastWriteTimeUtc(f).Ticks}")
|
||||
.Order(StringComparer.Ordinal)];
|
||||
|
||||
/// <summary>The real file system, but hashing a chosen file fails as a file held open by another program.</summary>
|
||||
private sealed class UnreadableExportFileSystem(Func<string, bool> refuses) : IExportFileSystem
|
||||
{
|
||||
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
|
||||
private int _refused;
|
||||
|
||||
public int Refused => Volatile.Read(ref _refused);
|
||||
|
||||
public Stream OpenRead(string path) => _inner.OpenRead(path);
|
||||
|
||||
public Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||
{
|
||||
if (refuses(path))
|
||||
{
|
||||
Interlocked.Increment(ref _refused);
|
||||
throw new IOException("Il file è usato da un altro processo.");
|
||||
}
|
||||
|
||||
return _inner.ComputeSha256Async(path, ct);
|
||||
}
|
||||
|
||||
public bool FileExists(string path) => _inner.FileExists(path);
|
||||
|
||||
public long? FileLength(string path) => _inner.FileLength(path);
|
||||
}
|
||||
|
||||
/// <summary>The real file system, counting every read of a file (opened, or hashed).</summary>
|
||||
private sealed class CountingExportFileSystem : IExportFileSystem
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user