diff --git a/src/Titano.Core/Archiving/LeaseFile.cs b/src/Titano.Core/Archiving/LeaseFile.cs
index 7a460481..dbd1ced7 100644
--- a/src/Titano.Core/Archiving/LeaseFile.cs
+++ b/src/Titano.Core/Archiving/LeaseFile.cs
@@ -27,6 +27,8 @@ public sealed class LeaseFile : IDisposable
private const string Extension = ".lease";
private const string StaleExtension = ".stale";
+ private const int ReadAttempts = 5;
+ private static readonly TimeSpan ReadRetryDelay = TimeSpan.FromMilliseconds(20);
private readonly Lock _gate = new();
private readonly Timer _renewal;
private LeaseRecord _record;
@@ -84,15 +86,29 @@ public sealed class LeaseFile : IDisposable
}
/// The current holder of a lease, or null when free or unreadable.
+ ///
+ /// Readers share read, write and delete so they never block a renewal, a release or a takeover. A renewal rewrites
+ /// the record in place, so a read can meet a torn record or (on Windows) a sharing violation for a few milliseconds:
+ /// it is retried briefly before the lease is reported unreadable.
+ ///
public static LeaseRecord? Read(string path)
{
- try
+ for (var attempt = 1; ; attempt++)
{
- return JsonSerializer.Deserialize(File.ReadAllBytes(path), ArchiveJson.Default.LeaseRecord);
- }
- catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
- {
- return null;
+ try
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
+ return JsonSerializer.Deserialize(stream, ArchiveJson.Default.LeaseRecord);
+ }
+ catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
+ {
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
+ {
+ if (attempt == ReadAttempts) return null;
+ Thread.Sleep(ReadRetryDelay);
+ }
}
}