fix(archive): lease reads never block the holder and survive a renewal in progress
A renewal rewrites the lease in place. On Windows a concurrent read hit a sharing violation and reported the lease as unreadable; anywhere, a read could meet a torn record, and a reader without delete sharing could stop the holder from releasing or a writer from breaking a stale lease. Readers now share read, write and delete and retry briefly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
1 file changed
+22
-6
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>The current holder of a lease, or null when free or unreadable.</summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user