Files
Chronos/src/Chronos.Core/Archiving/LeaseFile.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

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

274 lines
11 KiB
C#

using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
namespace Chronos.Core.Archiving;
/// <summary>Content of a lease file: who holds it and until when.</summary>
public sealed record LeaseRecord(string Token, string Owner, string Host, int ProcessId, DateTimeOffset Acquired, DateTimeOffset Expires);
/// <summary>The lease is held by someone else and did not free up in time.</summary>
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;
}
/// <summary>
/// Cross-process exclusive lease stored as <c>.chronos/locks/&lt;name&gt;.lease</c> (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.
/// </summary>
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;
/// <summary>Creates tried, some 130 ms in all, while a released lease's name is still taken by a reader (<see cref="TryCreate"/>).</summary>
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;
/// <summary>False once a renewal found the lease taken over (it expired while this process was stalled).</summary>
public bool IsHeld { get; private set; } = true;
/// <summary>Takes the lease when it is free or stale; null when someone else holds it.</summary>
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;
}
/// <summary>Waits up to <paramref name="wait"/> for the lease, polling with back-off.</summary>
/// <exception cref="LeaseUnavailableException">Still held by someone else after <paramref name="wait"/>.</exception>
public static async Task<LeaseFile> 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));
}
}
/// <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)
{
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);
}
}
}
/// <summary>Removes every stale lease in <paramref name="locksDirectory"/> (maintenance); returns their names.</summary>
public static IReadOnlyList<string> CleanupStale(string locksDirectory, bool dryRun)
{
if (!Directory.Exists(locksDirectory)) return [];
var now = DateTimeOffset.UtcNow;
var removed = new List<string>();
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;
}
/// <summary>Extends the expiry; false when the lease is no longer ours.</summary>
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));
}
}
}
/// <summary>Expired, or unreadable for longer than a lease lasts (a holder that crashed while creating it).</summary>
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.
}
}
}