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); var first = LeaseFile.Read(lease.Path)!.Expires; await Task.Delay(duration * 3); Assert.True(lease.IsHeld); // Renewed: the expiry moved on. Whether it is still ahead of the clock at this instant depends on when the last // timer ran, which a busy runner can delay by a few milliseconds past it. Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - first).TotalMilliseconds, duration.TotalMilliseconds); 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(() => 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)); } }