using System.Text.Json; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; namespace Chronos.Core.Archiving; /// Content of a lease file: who holds it and until when. public sealed record LeaseRecord(string Token, string Owner, string Host, int ProcessId, DateTimeOffset Acquired, DateTimeOffset Expires); /// The lease is held by someone else and did not free up in time. public sealed class LeaseUnavailableException(string name, LeaseRecord? holder) : IOException(Loc.L("Archive.Error.Busy", holder?.Owner ?? "?")) { public string Name { get; } = name; public LeaseRecord? Holder { get; } = holder; } /// /// Cross-process exclusive lease stored as .chronos/locks/<name>.lease (BRIEF ยง7), for writers that share /// an archive over a network (server and client). Creation uses create-new semantics, which SMB and local file /// systems both make atomic. A lease past its expiry is stale (its holder crashed or lost the share) and is taken /// over by renaming it aside, which only one contender can do. The holder renews it in the background while held. /// public sealed class LeaseFile : IDisposable { public static readonly TimeSpan DefaultDuration = TimeSpan.FromMinutes(2); private const string Extension = ".lease"; private const string StaleExtension = ".stale"; private const int ReadAttempts = 5; /// Creates tried, some 130 ms in all, while a released lease's name is still taken by a reader (). private const int CreateAttempts = 8; private static readonly TimeSpan ReadRetryDelay = TimeSpan.FromMilliseconds(20); private readonly Lock _gate = new(); private readonly Timer _renewal; private LeaseRecord _record; private bool _released; private LeaseFile(string path, string name, LeaseRecord record, TimeSpan duration) { Path = path; Name = name; _record = record; Duration = duration; var period = duration / 3; _renewal = new Timer(_ => Renew(), null, period, period); } public string Path { get; } public string Name { get; } public TimeSpan Duration { get; } public LeaseRecord Record => _record; /// False once a renewal found the lease taken over (it expired while this process was stalled). public bool IsHeld { get; private set; } = true; /// Takes the lease when it is free or stale; null when someone else holds it. public static LeaseFile? TryAcquire(string locksDirectory, string name, string owner, TimeSpan? duration = null) { var length = duration ?? DefaultDuration; var path = PathFor(locksDirectory, name); Directory.CreateDirectory(locksDirectory); for (var attempt = 0; attempt < 3; attempt++) { var now = DateTimeOffset.UtcNow; var record = new LeaseRecord(Guid.NewGuid().ToString("N"), owner, Environment.MachineName, Environment.ProcessId, now, now + length); if (TryCreate(path, record)) return new LeaseFile(path, name, record, length); if (!IsStale(path, now)) return null; BreakStale(path, now); } return null; } /// Waits up to for the lease, polling with back-off. /// Still held by someone else after . public static async Task AcquireAsync(string locksDirectory, string name, string owner, TimeSpan wait, TimeSpan? duration = null, CancellationToken cancellationToken = default) { var deadline = DateTime.UtcNow + wait; var delay = TimeSpan.FromMilliseconds(20); while (true) { if (TryAcquire(locksDirectory, name, owner, duration) is { } lease) return lease; if (DateTime.UtcNow >= deadline) throw new LeaseUnavailableException(name, Read(PathFor(locksDirectory, name))); await Task.Delay(delay, cancellationToken).ConfigureAwait(false); delay = TimeSpan.FromMilliseconds(System.Math.Min(delay.TotalMilliseconds * 2, 500)); } } /// 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) { for (var attempt = 1; ; attempt++) { 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); } } } /// Removes every stale lease in (maintenance); returns their names. public static IReadOnlyList CleanupStale(string locksDirectory, bool dryRun) { if (!Directory.Exists(locksDirectory)) return []; var now = DateTimeOffset.UtcNow; var removed = new List(); foreach (var path in Directory.EnumerateFiles(locksDirectory, "*" + Extension)) { if (!IsStale(path, now)) continue; removed.Add(System.IO.Path.GetFileNameWithoutExtension(path)); if (!dryRun) BreakStale(path, now); } if (!dryRun) { foreach (var path in Directory.EnumerateFiles(locksDirectory, "*" + StaleExtension)) { if (File.GetLastWriteTimeUtc(path) + DefaultDuration < now.UtcDateTime) TryDelete(path); } } return removed; } /// Extends the expiry; false when the lease is no longer ours. public bool Renew() { lock (_gate) { if (_released || !IsHeld) return false; if (Read(Path)?.Token != _record.Token) { IsHeld = false; Log.Warning("archive", $"Lease {Name} was taken over by another writer"); return false; } var renewed = _record with { Expires = DateTimeOffset.UtcNow + Duration }; try { // In-place rewrite: a rename would open a window in which the lease looks free. using var fs = new FileStream(Path, FileMode.Truncate, FileAccess.Write, FileShare.Read); fs.Write(JsonSerializer.SerializeToUtf8Bytes(renewed, ArchiveJson.Default.LeaseRecord)); fs.Flush(flushToDisk: true); _record = renewed; return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Runs on a timer thread: an escaping exception would end the process. Log.Warning("archive", $"Lease {Name} could not be renewed", ex); return false; } } } public void Dispose() { _renewal.Dispose(); lock (_gate) { if (_released) return; _released = true; if (!IsHeld || Read(Path)?.Token != _record.Token) return; try { File.Delete(Path); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // It expires on its own. Log.Warning("archive", $"Lease {Name} could not be released", ex); } } } internal static string PathFor(string locksDirectory, string name) => System.IO.Path.Combine(locksDirectory, name + Extension); private static bool TryCreate(string path, LeaseRecord record) { for (var attempt = 1; ; attempt++) { try { using var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read); fs.Write(JsonSerializer.SerializeToUtf8Bytes(record, ArchiveJson.Default.LeaseRecord)); fs.Flush(flushToDisk: true); return true; } catch (IOException) when (File.Exists(path)) { return false; } catch (IOException) when (attempt < CreateAttempts) { // The holder released the lease between the failed create and the check: the name is free again. } catch (UnauthorizedAccessException) when (attempt < CreateAttempts) { // On Windows a lease released while a reader still holds it open (readers share deletion) stays pending // deletion, and creating its name answers "access denied" until the reader lets go, a moment later. Thread.Sleep(1 << (attempt - 1)); } } } /// Expired, or unreadable for longer than a lease lasts (a holder that crashed while creating it). private static bool IsStale(string path, DateTimeOffset now) { if (Read(path) is { } record) return record.Expires < now; try { return File.Exists(path) && File.GetLastWriteTimeUtc(path) + DefaultDuration < now.UtcDateTime; } catch (IOException) { return false; } } private static void BreakStale(string path, DateTimeOffset now) { var aside = path + "." + Guid.NewGuid().ToString("N")[..8] + StaleExtension; try { File.Move(path, aside); } catch (IOException) { return; // another contender broke it first } if (IsStale(aside, now)) { TryDelete(aside); return; } // A contender renewed or re-created the lease between our check and the rename: give it back. try { File.Move(aside, path, overwrite: false); } catch (IOException) { TryDelete(aside); } } private static void TryDelete(string path) { try { File.Delete(path); } catch (IOException) { // A leftover file is harmless; maintenance removes it. } } }