fix(server): keep convert dry runs like Reorganize's, say what a new sequence lacks
The convert endpoint planned the whole selection inside the HTTP request, again for every mode, quality keystroke and confirmation, with no limit: behind a proxy an all-sequence conversion could never get past its dry run or its apply. - ReorganizePlanCache becomes PlanCache, shared by Reorganize and Convert: one plan per key made apart from the request, two at once across both kinds, eight kept, 15-minute timeout, 5-minute lifetime, 503 plan_dropped. Keys are typed records (ReorganizePlanKey, ConvertPlanKey) that also say which exceptions are refusals. - A conversion plan is keyed by archive, a convert stamp of the index (SequenceRepository.GetConvertStampAsync: the Reorganize stamp plus, per planned sequence, the photos' count, sizes, formats, pixel sizes and missing, corrupt, preview-only and undecodable flags), the sequences and the target with the quality that counts. Not the mode: the request's mode and options are set on the kept plan, and the free space is measured again at every request through the engine. A plan made while the volume was away is not kept (503 archive_offline). - New sequence holds the converted copies alone: the dry run says the skipped photos are not copied into it (Archive.Convert.NotCopied.*, Server.Convert.OnPcNew), the panel's totals, column and confirmation give the count, and so does the desktop's summary. - Panel: the preview is asked in Replace's neutral words; a dry run cut off by a proxy is asked again while the totals show how long it takes, plan_dropped is retried once; an apply the server let go plans again, a changed one shows Admin.Convert.PlanChanged, and one with no answer is not resent (its job may be queued). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit f0b1e379ce7c08b6d3459ab25ca6214c8f366f6c)
This commit is contained in:
1 parent
d0bbd77c92
commit
8174852a2c
22 files changed
+927
-342
No files matched your search
@@ -1,10 +1,13 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Codecs.Jpeg;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
@@ -12,8 +15,9 @@ using Chronos.Testing;
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Mass conversion on the server (owner review 2, R7): <c>POST /api/v1/archive/convert</c>, its dry run, the <c>convert</c> job
|
||||
/// that applies the confirmed plan, what the request may not do, and the formats the server leaves to a PC.
|
||||
/// Mass conversion on the server (owner review 2, R7): <c>POST /api/v1/archive/convert</c>, its dry run and the plan kept from
|
||||
/// it in either mode (<see cref="PlanCache"/>) with the free space measured at every request, the <c>convert</c> job that
|
||||
/// applies the confirmed plan, what the request may not do, and the formats the server leaves to a PC.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class ConvertTests(TestContext context)
|
||||
@@ -174,12 +178,126 @@ public sealed class ConvertTests(TestContext context)
|
||||
await UntilIdleAsync(server);
|
||||
|
||||
admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it");
|
||||
using var dry = await admin.PostAsJsonAsync(Url, new ConvertRequest([id], false, "linear-dng", null, "new-sequence", DryRun: true), ProtocolJson.Default.ConvertRequest);
|
||||
var plan = await dry.ReadAsync(ProtocolJson.Default.ConvertPlanDto);
|
||||
var italian = CultureInfo.GetCultureInfo("it");
|
||||
var plan = await DryRunAsync(admin, new ConvertRequest([id], false, "linear-dng", null, "replace", DryRun: true));
|
||||
Assert.Equal((1, 2), (plan.Photos, plan.Skipped));
|
||||
var skipped = plan.Steps.Single().Skipped.Single();
|
||||
Assert.Equal(("convert_on_pc", 2), (skipped.Reason, skipped.Photos));
|
||||
Assert.Equal(Chronos.Core.Localization.Loc.Get("Server.Convert.OnPc", System.Globalization.CultureInfo.GetCultureInfo("it")), skipped.Message);
|
||||
Assert.Equal(Loc.Get("Server.Convert.OnPc", italian), skipped.Message);
|
||||
// Into a new sequence, which holds the converted copies alone: the dry run says the copy lacks them.
|
||||
var copies = await DryRunAsync(admin, new ConvertRequest([id], false, "linear-dng", null, "new-sequence", DryRun: true));
|
||||
Assert.Equal((1, 2), (copies.Photos, copies.Skipped));
|
||||
var left = copies.Steps.Single().Skipped.Single();
|
||||
Assert.Equal(("convert_on_pc", 2, Loc.Get("Server.Convert.OnPcNew", italian)), (left.Reason, left.Photos, left.Message));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADryRunIsKeptInEitherModeWhileTheIndexStaysAsItWas()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it");
|
||||
var italian = CultureInfo.GetCultureInfo("it");
|
||||
var plans = server.Services.GetRequiredService<PlanCache>();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ConvertRequest([id], false, "tiff16", null, "replace", DryRun: true);
|
||||
var shown = await DryRunAsync(admin, request);
|
||||
Assert.Equal(("replace", 3, 0), (shown.Mode, shown.Photos, shown.Skipped));
|
||||
Assert.Equal(1, plans.Count);
|
||||
|
||||
// A photo gone on disk alone is not in the index: the same dry run again, in the other mode or at another quality of
|
||||
// a lossless target, is the plan made before, in the request's mode and quality.
|
||||
var first = (await server.Database.Frames.ListBySequenceAsync(id))[0];
|
||||
var file = Path.Combine(server.Options.ArchivePath, first.RelativePath);
|
||||
var bytes = await File.ReadAllBytesAsync(file);
|
||||
File.Delete(file);
|
||||
var copies = await DryRunAsync(admin, request with { Mode = "new-sequence" });
|
||||
Assert.Equal(("new-sequence", 3, 0), (copies.Mode, copies.Photos, copies.Skipped));
|
||||
Assert.NotEqual(shown.Fingerprint, copies.Fingerprint);
|
||||
var quality = await DryRunAsync(admin, request with { Quality = 50 });
|
||||
Assert.Equal((50, 3, shown.Fingerprint), (quality.Quality, quality.Photos, quality.Fingerprint));
|
||||
Assert.Equal(1, plans.Count);
|
||||
|
||||
// A change of what it reads plans again at once: the photo is found missing, and each mode says what becomes of it.
|
||||
await Uploads.UploadAsync(editor, Photo(3), "IMG_0004.JPG", sessionKey: "roof");
|
||||
await UntilIdleAsync(server);
|
||||
var replan = await DryRunAsync(admin, request);
|
||||
Assert.Equal((3, 1), (replan.Photos, replan.Skipped));
|
||||
var stays = replan.Steps.Single().Skipped.Single();
|
||||
Assert.Equal(("missing", 1, Loc.Get("Archive.Convert.Skipped.Missing", italian)), (stays.Reason, stays.Photos, stays.Message));
|
||||
var left = (await DryRunAsync(admin, request with { Mode = "new-sequence" })).Steps.Single().Skipped.Single();
|
||||
Assert.Equal(("missing", 1, Loc.Get("Archive.Convert.NotCopied.Missing", italian)), (left.Reason, left.Photos, left.Message));
|
||||
|
||||
// The photo back on disk alone: still the plan kept. Another upload plans again, and the confirmation takes that
|
||||
// plan, then lets it go once its job is queued.
|
||||
await File.WriteAllBytesAsync(file, bytes);
|
||||
Assert.Equal(replan.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
await Uploads.UploadAsync(editor, Photo(4), "IMG_0005.JPG", sessionKey: "roof");
|
||||
await UntilIdleAsync(server);
|
||||
var whole = await DryRunAsync(admin, request);
|
||||
Assert.Equal((5, 0), (whole.Photos, whole.Skipped));
|
||||
var kept = plans.Count;
|
||||
JobDto job;
|
||||
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = whole.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
{
|
||||
await applied.ExpectAsync(HttpStatusCode.Accepted);
|
||||
job = await applied.ReadAsync(ProtocolJson.Default.JobDto);
|
||||
}
|
||||
Assert.Equal(kept - 1, plans.Count);
|
||||
await UntilJobAsync(admin, job.Id, "done");
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Tiff), "converted");
|
||||
|
||||
// Converted: the next dry run is another plan, which says why nothing converts, in New sequence's words too.
|
||||
var done = await DryRunAsync(admin, request with { Mode = "new-sequence" });
|
||||
Assert.Equal((0, 5), (done.Photos, done.Skipped));
|
||||
Assert.Equal(Loc.Get("Archive.Convert.NotCopied.SameFormat", italian), done.Steps.Single().Skipped.Single().Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheFreeSpaceIsMeasuredAgainAtEveryRequest()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, services: s =>
|
||||
{
|
||||
ArchiveModule.Register(s);
|
||||
s.AddSingleton<FakeVolumeSpace>();
|
||||
s.AddSingleton<VolumeSpace>(sp => sp.GetRequiredService<FakeVolumeSpace>());
|
||||
});
|
||||
var volumes = server.Services.GetRequiredService<FakeVolumeSpace>();
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var admin = await server.AdminAsync();
|
||||
Guid id = default;
|
||||
for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId;
|
||||
await UntilIdleAsync(server);
|
||||
var request = new ConvertRequest([id], false, "linear-dng", null, "replace", DryRun: true);
|
||||
const long Full = 1_000_000, Free = 100_000_000_000;
|
||||
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Full, 4 * Free));
|
||||
var tight = await DryRunAsync(admin, request);
|
||||
Assert.Equal((false, (long?)Full), (tight.Space.Enough, tight.Space.Free));
|
||||
using (var refused = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = tight.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
Assert.Equal(tight.Space.Required.ToString(CultureInfo.InvariantCulture), (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "not_enough_space")).Details);
|
||||
|
||||
// Space freed since: the plan kept, with the free space now; and the confirmation measures it again too.
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Free, 4 * Free));
|
||||
var freed = await DryRunAsync(admin, request);
|
||||
Assert.Equal((true, (long?)Free, tight.Fingerprint, tight.Space.Required), (freed.Space.Enough, freed.Space.Free, freed.Fingerprint, freed.Space.Required));
|
||||
Assert.Equal(1, server.Services.GetRequiredService<PlanCache>().Count);
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Full, 4 * Free));
|
||||
using (var filled = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = freed.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
await filled.ExpectErrorAsync(HttpStatusCode.Conflict, "not_enough_space");
|
||||
volumes.Set(server.Options.ArchivePath, new VolumeFigures(Free, 4 * Free));
|
||||
using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = freed.Fingerprint }, ProtocolJson.Default.ConvertRequest))
|
||||
await UntilJobAsync(admin, (await applied.ReadAsync(ProtocolJson.Default.JobDto)).Id, "done");
|
||||
Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Dng), "converted");
|
||||
}
|
||||
|
||||
private static async Task<ConvertPlanDto> DryRunAsync(HttpClient client, ConvertRequest request)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync(Url, request with { DryRun = true }, ProtocolJson.Default.ConvertRequest);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ConvertPlanDto);
|
||||
}
|
||||
|
||||
/// <summary>Every reason a photo stays as it is has its wire name and its sentence in the catalog (en and it).</summary>
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Conversion;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The dry runs the server keeps (<see cref="PlanCache"/>, owner review 2, R7) as Convert's endpoint uses them: what a
|
||||
/// conversion plan is kept by (<see cref="ConvertPlanKey"/>), what refuses it, and the turns and room it shares with
|
||||
/// Reorganize's plans. The rest of what the cache does is in <see cref="ReorganizeTests"/>.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class PlanCacheTests
|
||||
{
|
||||
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
|
||||
|
||||
[Test]
|
||||
public void AConversionPlanIsKeptByWhatConvertsNotByTheMode()
|
||||
{
|
||||
var archive = Guid.NewGuid();
|
||||
var (x, y) = (Guid.NewGuid(), Guid.NewGuid());
|
||||
var tiff = ConvertPlanKey.Of(archive, "stamp", [x, y], new ConvertOptions(ConvertTarget.Tiff16, 80));
|
||||
// The mode is not part of it, and neither is the quality of a lossless target; a JPEG's is.
|
||||
Assert.Equal(tiff, ConvertPlanKey.Of(archive, "stamp", [x, y], new ConvertOptions(ConvertTarget.Tiff16)));
|
||||
Assert.Equal(ConvertPlanKey.Of(archive, "stamp", [x], new ConvertOptions(ConvertTarget.Jpeg, 80)),
|
||||
ConvertPlanKey.Of(archive, "stamp", [x], new ConvertOptions(ConvertTarget.Jpeg, 80)));
|
||||
Assert.NotEqual(ConvertPlanKey.Of(archive, "stamp", [x], new ConvertOptions(ConvertTarget.Jpeg, 80)),
|
||||
ConvertPlanKey.Of(archive, "stamp", [x], new ConvertOptions(ConvertTarget.Jpeg, 95)));
|
||||
// Another target, order of the sequences, every sequence, stamp or archive is another plan.
|
||||
Assert.NotEqual(tiff, ConvertPlanKey.Of(archive, "stamp", [x, y], new ConvertOptions(ConvertTarget.LinearDng)));
|
||||
Assert.NotEqual(tiff, ConvertPlanKey.Of(archive, "stamp", [y, x], new ConvertOptions(ConvertTarget.Tiff16)));
|
||||
Assert.NotEqual(tiff, ConvertPlanKey.Of(archive, "stamp", null, new ConvertOptions(ConvertTarget.Tiff16)));
|
||||
Assert.NotEqual(tiff, ConvertPlanKey.Of(archive, "other", [x, y], new ConvertOptions(ConvertTarget.Tiff16)));
|
||||
Assert.NotEqual(tiff, ConvertPlanKey.Of(Guid.NewGuid(), "stamp", [x, y], new ConvertOptions(ConvertTarget.Tiff16)));
|
||||
// A Reorganize of the same sequences is never the same plan.
|
||||
Assert.NotEqual<PlanKey>(ConvertPlanKey.Of(archive, "stamp", null, new ConvertOptions(ConvertTarget.Tiff16)),
|
||||
ReorganizePlanKey.Of(archive, "stamp", null, new RenameTemplates(Folder: "moved/{date}")));
|
||||
|
||||
// A sequence not in the archive refuses it; a failure (a sidecar unreadable, a bug) does not.
|
||||
Assert.True(tiff.Refuses(new ArgumentException("Not in the archive.")));
|
||||
foreach (var failure in new Exception[] { new ArgumentNullException("plan"), new IOException("The disk went away."), new NestedRenameException("a/b", "a") })
|
||||
Assert.False(tiff.Refuses(failure), failure.GetType().Name);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConversionAndReorganizePlansShareTheTurnsAndTheRoom()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new PlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var started = new ConcurrentDictionary<string, bool>();
|
||||
Func<CancellationToken, Task<RenamePlan>> Rename(int i) => async stop =>
|
||||
{
|
||||
started["reorganize" + i] = true;
|
||||
await release.Task.WaitAsync(stop);
|
||||
return new RenamePlan(Guid.NewGuid(), archive, []);
|
||||
};
|
||||
var made = 0;
|
||||
Task<ConvertPlan> Convert(CancellationToken stop)
|
||||
{
|
||||
started["convert"] = true;
|
||||
Interlocked.Increment(ref made);
|
||||
return Task.FromResult(new ConvertPlan(archive, new ConvertOptions(ConvertTarget.LinearDng), ConvertMode.Replace, [], new ConvertSpace(0, null)));
|
||||
}
|
||||
|
||||
// Every turn taken by a Reorganize: a conversion waits for one.
|
||||
var renames = Enumerable.Range(0, PlanCache.Concurrency)
|
||||
.Select(i => plans.GetOrPlanAsync(ReorganizePlanKey.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates), Rename(i))).ToList();
|
||||
await EventuallyAsync(() => started.Count == PlanCache.Concurrency);
|
||||
var key = ConvertPlanKey.Of(archive, "stamp", null, new ConvertOptions(ConvertTarget.LinearDng));
|
||||
var converting = plans.GetOrPlanAsync(key, Convert);
|
||||
await Task.Delay(200);
|
||||
Assert.False(started.ContainsKey("convert"), "no turn while Reorganize holds them");
|
||||
release.SetResult();
|
||||
var plan = await converting;
|
||||
foreach (var rename in renames) await rename;
|
||||
Assert.True(ReferenceEquals(plan, await plans.GetOrPlanAsync(key, Convert)), "kept");
|
||||
Assert.Equal(1, made);
|
||||
Assert.Equal(PlanCache.Concurrency + 1, plans.Count);
|
||||
|
||||
// A refusal is kept as a plan is, a failure is not; the room is shared: the oldest of either kind goes first.
|
||||
var unknown = ConvertPlanKey.Of(archive, "stamp", [Guid.NewGuid()], new ConvertOptions(ConvertTarget.LinearDng));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(unknown, _ => throw new ArgumentException("Not in the archive.")));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(unknown, Convert));
|
||||
var offline = ConvertPlanKey.Of(archive, "stamp", [Guid.NewGuid()], new ConvertOptions(ConvertTarget.Tiff16));
|
||||
await Assert.ThrowsAsync<ArchiveOfflineException>(() => plans.GetOrPlanAsync(offline, _ => throw new ArchiveOfflineException("/archive", ArchiveAvailability.Offline)));
|
||||
await plans.GetOrPlanAsync(offline, Convert);
|
||||
Assert.Equal(2, made);
|
||||
for (var i = 0; i < PlanCache.Capacity; i++)
|
||||
{
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(ConvertPlanKey.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], new ConvertOptions(ConvertTarget.Jpeg)), Convert);
|
||||
}
|
||||
Assert.Equal(PlanCache.Capacity, plans.Count);
|
||||
await plans.GetOrPlanAsync(key, Convert);
|
||||
Assert.Equal(3 + PlanCache.Capacity, made);
|
||||
}
|
||||
|
||||
/// <summary>Waits until <paramref name="condition"/> holds.</summary>
|
||||
private static async Task EventuallyAsync(Func<bool> condition, [System.Runtime.CompilerServices.CallerArgumentExpression(nameof(condition))] string? expression = null)
|
||||
{
|
||||
var until = DateTime.UtcNow + Wait;
|
||||
while (!condition())
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, expression);
|
||||
await Task.Delay(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize on the server (owner review 2, R7): <c>POST /api/v1/archive/reorganize</c>, its dry run and the plan kept from it
|
||||
/// for the confirmation (<see cref="ReorganizePlanCache"/>), the <c>move</c> job that applies the confirmed plan (paused and
|
||||
/// for the confirmation (<see cref="PlanCache"/>), the <c>move</c> job that applies the confirmed plan (paused and
|
||||
/// resumed too), and what the request may not do, against the real archive engine.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
@@ -562,7 +562,7 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
Directory.CreateDirectory(target);
|
||||
Assert.Equal(free.Fingerprint, (await DryRunAsync(admin, request)).Fingerprint);
|
||||
await UntilIdleAsync(server);
|
||||
clock.Advance(ReorganizePlanCache.Lifetime);
|
||||
clock.Advance(PlanCache.Lifetime);
|
||||
var later = await DryRunAsync(admin, request);
|
||||
Assert.Equal("moved/2026-09-28 (2)", later.Steps.Single().ToFolder);
|
||||
using (var changed = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = free.Fingerprint }, ProtocolJson.Default.ReorganizeRequest))
|
||||
@@ -604,7 +604,7 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
public async Task KeptPlansAreTheNewestFewWithinTheirLifetime()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
using var plans = new PlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
var made = 0;
|
||||
@@ -613,38 +613,38 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
made++;
|
||||
return Task.FromResult(new RenamePlan(Guid.NewGuid(), archive, []));
|
||||
}
|
||||
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
ReorganizePlanKey Key(int i) => ReorganizePlanKey.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
|
||||
var kept = await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.True(ReferenceEquals(kept, await plans.GetOrPlanAsync(Key(0), Plan)), "kept");
|
||||
Assert.Equal(1, made);
|
||||
// Another order of the sequences, every sequence, another stamp or other templates is another plan.
|
||||
var (x, y) = (Guid.NewGuid(), Guid.NewGuid());
|
||||
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [y, x], templates));
|
||||
Assert.Equal(ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x, y], templates with { }));
|
||||
Assert.NotEqual(ReorganizePlanCache.Key.Of(archive, "stamp", null, templates), ReorganizePlanCache.Key.Of(archive, "stamp", [x], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "other", [new Guid(0, 0, 0, new byte[8])], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(0, 0, 0, new byte[8])], templates with { File = "{n}" }));
|
||||
Assert.NotEqual(ReorganizePlanKey.Of(archive, "stamp", [x, y], templates), ReorganizePlanKey.Of(archive, "stamp", [y, x], templates));
|
||||
Assert.Equal(ReorganizePlanKey.Of(archive, "stamp", [x, y], templates), ReorganizePlanKey.Of(archive, "stamp", [x, y], templates with { }));
|
||||
Assert.NotEqual(ReorganizePlanKey.Of(archive, "stamp", null, templates), ReorganizePlanKey.Of(archive, "stamp", [x], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanKey.Of(archive, "other", [new Guid(0, 0, 0, new byte[8])], templates));
|
||||
Assert.NotEqual(Key(0), ReorganizePlanKey.Of(archive, "stamp", [new Guid(0, 0, 0, new byte[8])], templates with { File = "{n}" }));
|
||||
|
||||
// At most Capacity plans: the oldest goes first.
|
||||
for (var i = 1; i <= ReorganizePlanCache.Capacity; i++)
|
||||
for (var i = 1; i <= PlanCache.Capacity; i++)
|
||||
{
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(i), Plan);
|
||||
}
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
await plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan);
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(1 + PlanCache.Capacity, made);
|
||||
await plans.GetOrPlanAsync(Key(PlanCache.Capacity), Plan);
|
||||
Assert.Equal(1 + PlanCache.Capacity, made);
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(2 + PlanCache.Capacity, made);
|
||||
|
||||
// A plan is kept for its lifetime, from when it was made, even before its timer lets it go.
|
||||
clock.Advance(ReorganizePlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
clock.Advance(PlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(2 + PlanCache.Capacity, made);
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
await plans.GetOrPlanAsync(Key(0), Plan);
|
||||
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(3 + PlanCache.Capacity, made);
|
||||
|
||||
// A refusal follows from the same reads, and is kept as a plan is: a folder inside a sequence's, a sequence not in the
|
||||
// archive. A failure is not kept, and neither is a plan or refusal forgotten.
|
||||
@@ -652,22 +652,22 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
await Assert.ThrowsAsync<NestedRenameException>(() => plans.GetOrPlanAsync(Key(99), Plan));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), _ => throw new ArgumentException("Not in the archive.")));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => plans.GetOrPlanAsync(Key(98), Plan));
|
||||
Assert.Equal(3 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(3 + PlanCache.Capacity, made);
|
||||
await Assert.ThrowsAsync<IOException>(() => plans.GetOrPlanAsync(Key(97), _ => throw new IOException("The sidecar cannot be read.")));
|
||||
await plans.GetOrPlanAsync(Key(97), Plan);
|
||||
Assert.Equal(4 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(4 + PlanCache.Capacity, made);
|
||||
plans.Forget(Key(99));
|
||||
await plans.GetOrPlanAsync(Key(99), Plan);
|
||||
Assert.Equal(5 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(5 + PlanCache.Capacity, made);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APlanIsMadeOnceForEveryRequestAndOutlivesOneCutOff()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
using var plans = new PlanCache(clock);
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
var key = ReorganizePlanCache.Key.Of(Guid.NewGuid(), "stamp", null, templates);
|
||||
var key = ReorganizePlanKey.Of(Guid.NewGuid(), "stamp", null, templates);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var made = 0;
|
||||
async Task<RenamePlan> SlowPlan(CancellationToken stop)
|
||||
@@ -687,22 +687,22 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
var again = plans.GetOrPlanAsync(key, SlowPlan);
|
||||
var meanwhile = plans.GetOrPlanAsync(key, SlowPlan);
|
||||
// Being made, it is not the one let go for other plans.
|
||||
for (var i = 0; i < ReorganizePlanCache.Capacity; i++)
|
||||
await plans.GetOrPlanAsync(ReorganizePlanCache.Key.Of(key.ArchiveId, "stamp", [new Guid(i, 0, 0, new byte[8])], templates), PlanAtOnce);
|
||||
for (var i = 0; i < PlanCache.Capacity; i++)
|
||||
await plans.GetOrPlanAsync(ReorganizePlanKey.Of(key.ArchiveId, "stamp", [new Guid(i, 0, 0, new byte[8])], templates), PlanAtOnce);
|
||||
release.SetResult();
|
||||
var plan = await again;
|
||||
Assert.True(ReferenceEquals(plan, await meanwhile), "one plan for both");
|
||||
Assert.True(ReferenceEquals(plan, await plans.GetOrPlanAsync(key, SlowPlan)), "kept");
|
||||
Assert.Equal(1 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
Assert.Equal(1 + PlanCache.Capacity, made);
|
||||
Assert.Equal(PlanCache.Capacity, plans.Count);
|
||||
|
||||
// Its timer lets it go at the end of its lifetime, with no request asking.
|
||||
clock.Advance(ReorganizePlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
clock.Advance(PlanCache.Lifetime - TimeSpan.FromSeconds(1));
|
||||
Assert.Equal(PlanCache.Capacity, plans.Count);
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
Assert.Equal(0, plans.Count);
|
||||
await plans.GetOrPlanAsync(key, SlowPlan);
|
||||
Assert.Equal(2 + ReorganizePlanCache.Capacity, made);
|
||||
Assert.Equal(2 + PlanCache.Capacity, made);
|
||||
|
||||
Task<RenamePlan> PlanAtOnce(CancellationToken stop)
|
||||
{
|
||||
@@ -715,10 +715,10 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
public async Task PlansAreMadeAFewAtOnceAndStopWhenLetGoOrPastTheirTime()
|
||||
{
|
||||
var clock = new SteppedTimeProvider();
|
||||
using var plans = new ReorganizePlanCache(clock);
|
||||
using var plans = new PlanCache(clock);
|
||||
var archive = Guid.NewGuid();
|
||||
var templates = new RenameTemplates(Folder: "moved/{date}");
|
||||
ReorganizePlanCache.Key Key(int i) => ReorganizePlanCache.Key.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
ReorganizePlanKey Key(int i) => ReorganizePlanKey.Of(archive, "stamp", [new Guid(i, 0, 0, new byte[8])], templates);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var started = new ConcurrentDictionary<int, bool>();
|
||||
var stopped = new ConcurrentDictionary<int, bool>();
|
||||
@@ -739,16 +739,16 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
};
|
||||
|
||||
// A few are made at once; the others wait for their turn.
|
||||
var asked = Enumerable.Range(0, ReorganizePlanCache.Capacity).Select(i => plans.GetOrPlanAsync(Key(i), Plan(i))).ToList();
|
||||
await EventuallyAsync(() => started.Count == ReorganizePlanCache.Concurrency);
|
||||
var asked = Enumerable.Range(0, PlanCache.Capacity).Select(i => plans.GetOrPlanAsync(Key(i), Plan(i))).ToList();
|
||||
await EventuallyAsync(() => started.Count == PlanCache.Concurrency);
|
||||
await Task.Delay(200);
|
||||
Assert.SequenceEqual(Enumerable.Range(0, ReorganizePlanCache.Concurrency), started.Keys.Order());
|
||||
Assert.SequenceEqual(Enumerable.Range(0, PlanCache.Concurrency), started.Keys.Order());
|
||||
|
||||
// One more lets go the plan asked first, being made with none kept: it stops, its waiter is told, the next one starts.
|
||||
var newest = plans.GetOrPlanAsync(Key(ReorganizePlanCache.Capacity), Plan(ReorganizePlanCache.Capacity));
|
||||
var newest = plans.GetOrPlanAsync(Key(PlanCache.Capacity), Plan(PlanCache.Capacity));
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => asked[0]);
|
||||
await EventuallyAsync(() => stopped.ContainsKey(0) && started.ContainsKey(ReorganizePlanCache.Concurrency));
|
||||
Assert.Equal(ReorganizePlanCache.Capacity, plans.Count);
|
||||
await EventuallyAsync(() => stopped.ContainsKey(0) && started.ContainsKey(PlanCache.Concurrency));
|
||||
Assert.Equal(PlanCache.Capacity, plans.Count);
|
||||
release.SetResult();
|
||||
foreach (var plan in asked.Skip(1).Append(newest)) await plan;
|
||||
Assert.SequenceEqual([0], stopped.Keys);
|
||||
@@ -765,7 +765,7 @@ public sealed class ReorganizeTests(TestContext context)
|
||||
var stuck = plans.GetOrPlanAsync(Key(21), Hanging(21));
|
||||
await EventuallyAsync(() => started.ContainsKey(20) && started.ContainsKey(21));
|
||||
var waiting = plans.GetOrPlanAsync(Key(22), Plan(22));
|
||||
clock.Advance(ReorganizePlanCache.PlanTimeout - TimeSpan.FromSeconds(1));
|
||||
clock.Advance(PlanCache.PlanTimeout - TimeSpan.FromSeconds(1));
|
||||
Assert.False(hung.IsCompleted, "still in time");
|
||||
clock.Advance(TimeSpan.FromSeconds(1));
|
||||
foreach (var plan in new[] { hung, stuck, waiting }) await Assert.ThrowsAsync<OperationCanceledException>(() => plan);
|
||||
|
||||
Reference in new issue
Block a user