Files
Chronos/tests/Chronos.Core.Tests/Archiving/LeaseFileTests.cs
T
Alby96andClaude Opus 5.5 f80fc148bf
CI / Build and test (push) Canceled after 2m45s
CI / PostgreSQL 16 integration (push) Canceled after 0s
CI / PostgreSQL 17 integration (push) Canceled after 0s
CI / Docker image (push) Canceled after 0s
CI / YAML check (push) Canceled after 0s
CI / Windows tests and installer (push) Canceled after 0s
fix(app): build update links from the releases repository address (#7)
Gitea writes a release's html_url and browser_download_url with its ROOT_URL,
which on the owner's server is the plain-http LAN address
http://192.168.30.23:3000. The update check accepts only https links, so it
ignored v0.1.0-rc.1 entirely. The page and download links now come from
ChronosReleasesUrl, the address the build names for its users; only the
tags, file names and sizes are read from Gitea's answer.

The lease renewal test's timer periods follow TestTiming too: on the shared
CI host a 100 ms renewal timer came 700 ms late once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 14:39:10 +02:00

140 lines
5.9 KiB
C#

using System.Text.Json;
using Chronos.Core.Archiving;
using Chronos.Testing;
namespace Chronos.Core.Tests.Archiving;
[Category("archive")]
public sealed class LeaseFileTests(TestContext context)
{
private static void WriteRecord(string path, LeaseRecord record) =>
File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(record, ArchiveJson.Default.LeaseRecord));
[Test]
public void ALeaseIsExclusiveUntilReleased()
{
var locks = context.CreateTempDirectory();
using (var a = LeaseFile.TryAcquire(locks, "seq-1", "server"))
{
Assert.NotNull(a);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
using var other = LeaseFile.TryAcquire(locks, "seq-2", "client");
Assert.NotNull(other);
}
using var b = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(b);
Assert.Equal("client", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
}
[Test]
public void ALeaseReleasedWhileAReaderHoldsItIsTakenOnceTheReaderLetsGo()
{
// Found under load while testing owner review 1: on Windows the released file stays pending deletion while a reader
// has it open, and creating the name answers "access denied" meanwhile instead of succeeding or saying "taken".
var locks = context.CreateTempDirectory();
var held = LeaseFile.TryAcquire(locks, "seq-1", "server")!;
var path = LeaseFile.PathFor(locks, "seq-1");
using var opened = new ManualResetEventSlim();
var reader = new Thread(() =>
{
using var reading = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
opened.Set();
Thread.Sleep(30);
});
reader.Start();
Assert.True(opened.Wait(TimeSpan.FromSeconds(10)), "the reader opened the lease");
held.Dispose();
using var taken = LeaseFile.TryAcquire(locks, "seq-1", "client");
reader.Join();
Assert.NotNull(taken);
Assert.Equal("client", LeaseFile.Read(path)!.Owner);
}
[Test]
public void AnExpiredLeaseOfACrashedHolderIsTakenOver()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "seq-1"), new LeaseRecord("dead", "crashed", "pc", 1, past, past.AddMinutes(2)));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "survivor");
Assert.NotNull(lease);
Assert.Equal("survivor", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
Assert.Count(1, Directory.GetFiles(locks));
}
[Test]
public async Task AHeldLeaseIsRenewedPastItsDuration()
{
var locks = context.CreateTempDirectory();
// Renewals run on timers: a busy CI host delays them, so the lease's duration stretches with the time budgets.
var duration = TimeSpan.FromSeconds(TestTiming.Budget(0.3));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "server", duration);
Assert.NotNull(lease);
await Task.Delay(duration * 3);
Assert.True(lease.IsHeld);
Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - DateTimeOffset.UtcNow).TotalMilliseconds, 0);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client", duration));
}
[Test]
public void AFreshEmptyLeaseFileIsNotStaleButAnOldOneIs()
{
var locks = context.CreateTempDirectory();
var path = LeaseFile.PathFor(locks, "seq-1");
File.WriteAllBytes(path, []);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddHours(-1));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(lease);
}
[Test]
public void ALostLeaseIsDetectedAndNotDeletedByItsFormerHolder()
{
var locks = context.CreateTempDirectory();
var lease = LeaseFile.TryAcquire(locks, "seq-1", "slow");
Assert.NotNull(lease);
var now = DateTimeOffset.UtcNow;
WriteRecord(lease.Path, new LeaseRecord("thief", "other", "pc", 2, now, now.AddMinutes(2)));
Assert.False(lease.Renew());
Assert.False(lease.IsHeld);
lease.Dispose();
Assert.Equal("thief", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Token);
}
[Test]
public async Task WaitingForABusyLeaseTimesOutWithItsHolder()
{
var locks = context.CreateTempDirectory();
using var held = LeaseFile.TryAcquire(locks, "seq-1", "server");
var error = await Assert.ThrowsAsync<LeaseUnavailableException>(() =>
LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromMilliseconds(200)));
Assert.Equal("server", error.Holder!.Owner);
}
[Test]
public async Task WaitingForALeaseSucceedsOnceItIsReleased()
{
var locks = context.CreateTempDirectory();
var held = LeaseFile.TryAcquire(locks, "seq-1", "server")!;
var waiting = LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromSeconds(10));
await Task.Delay(100);
held.Dispose();
using var lease = await waiting;
Assert.Equal("client", lease.Record.Owner);
}
[Test]
public void CleanupRemovesOnlyStaleLeasesAndItsDryRunNothing()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "dead"), new LeaseRecord("t", "crashed", "pc", 1, past, past.AddMinutes(1)));
using var live = LeaseFile.TryAcquire(locks, "live", "server");
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: true));
Assert.Count(2, Directory.GetFiles(locks));
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: false));
Assert.SequenceEqual([LeaseFile.PathFor(locks, "live")], Directory.GetFiles(locks));
}
}