Third fix round of owner review 2, phase 4a (Reorganize), cross-cutting items. - Server render filing now runs under the sequence lease, so it can meet a busy sequence or an offline archive. Both completions (client render uploads and render-node results) used to answer 500 and leave the upload stuck in Committing until a restart. They now answer 503 sequence_busy or archive_offline, which clients retry. The upload goes back to receiving with its part file and the node keeps its job (UploadService.ReceiveAgainAsync). - Save both: when this PC's copy cannot be written (another index moved the folder), the server's version is no longer applied, even if this index's scan relocates the row before the apply would run. A copy that has to be dropped is deleted from where the folder is now, as a best effort. - Export rebase on a folder move (scan and Reorganize): the sequence's own export follows the folder unless its file is still at the old path and not at the new one. A file written into a re-created old folder therefore keeps a row that finds it, so the file is never stranded. - A render job refuses to start when its folder is not where the index has it, which also stops it from re-creating the old folder. Renders fetched by sync are now filed under the sequence lease into the current folder, or not at all (new string Errors.Archive.FolderMoved, en and it). - The proxy pass holds the thumbnail lease one batch at a time (a quarter of the lease wait), then lets it go for longer than a waiter's poll and reads the folder and sidecar again. Before, another process's Reorganize, sequence deletion or pack compaction could wait out its lease wait and fail. Updated the stale comments on that lease and ARCHITECTURE.md to match. Tests cover each fix, and each new test fails with its fix reverted. Also covered: proxy store and pass in a moved folder, RenderStore with the folder gone, Take server with the folder moved, and an editor save with the folder moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 811509d32a118ed50ad10d47d4b002e534da9d77)
280 lines
11 KiB
C#
280 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/<name>.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);
|
|
|
|
/// <summary>The longest a writer waiting for a lease (<see cref="AcquireAsync"/>) sleeps between two tries.</summary>
|
|
public static readonly TimeSpan LongestPoll = TimeSpan.FromMilliseconds(500);
|
|
|
|
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, LongestPoll.TotalMilliseconds));
|
|
}
|
|
}
|
|
|
|
/// <summary>The current holder of the lease <paramref name="name"/> in <paramref name="locksDirectory"/>, or null when free or unreadable.</summary>
|
|
public static LeaseRecord? Holder(string locksDirectory, string name) => Read(PathFor(locksDirectory, name));
|
|
|
|
/// <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.
|
|
}
|
|
}
|
|
}
|