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
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>
330 lines
16 KiB
C#
330 lines
16 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Text.Json;
|
|
using System.Threading.Channels;
|
|
using Chronos.Core.Diagnostics;
|
|
using Chronos.Core.Model;
|
|
using Chronos.Data.Jobs;
|
|
using Chronos.Protocol;
|
|
using Chronos.Protocol.Client;
|
|
|
|
namespace Chronos.Data.Sync;
|
|
|
|
/// <summary>Timing of a <see cref="SyncAgent"/>.</summary>
|
|
public sealed record SyncAgentOptions
|
|
{
|
|
/// <summary>Full comparison while nothing asks for one sooner (catches edits on this PC and missed events).</summary>
|
|
public TimeSpan RefreshInterval { get; init; } = TimeSpan.FromMinutes(2);
|
|
|
|
/// <summary>Server events are collected this long, then their sequences are compared in one pass.</summary>
|
|
public TimeSpan EventDelay { get; init; } = TimeSpan.FromSeconds(1);
|
|
|
|
/// <summary>First wait after a failed refresh or a lost event socket; doubles up to <see cref="MaxBackoff"/>.</summary>
|
|
public TimeSpan MinBackoff { get; init; } = TimeSpan.FromSeconds(5);
|
|
|
|
public TimeSpan MaxBackoff { get; init; } = TimeSpan.FromMinutes(5);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Keeps the sync table of one signed-in server current in the background: a full comparison at start, on request
|
|
/// and every <see cref="SyncAgentOptions.RefreshInterval"/>; the sequences named by the server's <c>sequenceChanged</c>
|
|
/// events (WebSocket) compared again within a second, except those an upload or download is working on (it compares
|
|
/// them when it ends); failures retried with exponential backoff; and, with
|
|
/// <see cref="SyncPolicy.KeepProxiesOffline"/>, background downloads that bring stale proxy caches of the sequences
|
|
/// this PC opened with proxies up to date (a failed one waits with the same backoff). Dispose to stop.
|
|
/// </summary>
|
|
public sealed class SyncAgent : IAsyncDisposable
|
|
{
|
|
private const string LogCategory = "sync";
|
|
|
|
private readonly SyncService _sync;
|
|
private readonly ISyncRemote _remote;
|
|
private readonly Func<SyncPolicy> _policy;
|
|
private readonly JobEngine? _engine;
|
|
private readonly SyncAgentOptions _options;
|
|
private readonly CancellationTokenSource _stopping = new();
|
|
private readonly Channel<bool> _refreshWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
|
private readonly Channel<bool> _eventWake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
|
|
private readonly ConcurrentDictionary<Guid, byte> _changed = new();
|
|
|
|
/// <summary>Proxy downloads this agent queued, by server id, and the failures of each sequence's last ones.</summary>
|
|
private readonly Dictionary<Guid, Guid> _proxyJobs = [];
|
|
|
|
private readonly Dictionary<Guid, (int Failures, DateTime NotBefore)> _proxyFailures = [];
|
|
|
|
/// <summary>
|
|
/// The server's update time at which a cache holding stand-ins (thumbnails or no file in place of proxies) was last
|
|
/// compared with its manifest, or had its download queued.
|
|
/// </summary>
|
|
private readonly Dictionary<Guid, DateTimeOffset> _standInsCompared = [];
|
|
|
|
private readonly SemaphoreSlim _refreshing = new(1, 1);
|
|
private Task _running = Task.CompletedTask;
|
|
private SyncSnapshot? _snapshot;
|
|
private Exception? _lastError;
|
|
|
|
/// <param name="policy">Read before every comparison, so option changes apply at once.</param>
|
|
/// <param name="engine">Queue for proxy downloads; null keeps no proxies offline.</param>
|
|
public SyncAgent(SyncService sync, ISyncRemote remote, Func<SyncPolicy> policy, JobEngine? engine, SyncAgentOptions? options = null)
|
|
{
|
|
_sync = sync;
|
|
_remote = remote;
|
|
_policy = policy;
|
|
_engine = engine;
|
|
_options = options ?? new SyncAgentOptions();
|
|
}
|
|
|
|
public string Server => _remote.Server;
|
|
|
|
/// <summary>The last full comparison; null until the first one finished.</summary>
|
|
public SyncSnapshot? Snapshot => Volatile.Read(ref _snapshot);
|
|
|
|
/// <summary>Why the last full comparison failed; null after a successful one.</summary>
|
|
public Exception? LastError => Volatile.Read(ref _lastError);
|
|
|
|
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
|
|
public event Action? Changed;
|
|
|
|
/// <summary>Starts the comparison and event loops.</summary>
|
|
public void Start()
|
|
{
|
|
var token = _stopping.Token;
|
|
_running = Task.WhenAll(
|
|
Task.Run(() => RefreshLoopAsync(token), CancellationToken.None),
|
|
Task.Run(() => EventLoopAsync(token), CancellationToken.None),
|
|
Task.Run(() => ChangedLoopAsync(token), CancellationToken.None));
|
|
}
|
|
|
|
/// <summary>Asks for a full comparison soon (after an edit on this PC, an option change, a reconnect).</summary>
|
|
public void RequestRefresh() => _refreshWake.Writer.TryWrite(true);
|
|
|
|
/// <summary>Compares everything now; concurrent calls run one after the other.</summary>
|
|
public async Task<SyncSnapshot> RefreshAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stopping.Token);
|
|
await _refreshing.WaitAsync(linked.Token).ConfigureAwait(false);
|
|
try
|
|
{
|
|
var policy = _policy();
|
|
var snapshot = await _sync.RefreshAsync(_remote, policy, linked.Token).ConfigureAwait(false);
|
|
Volatile.Write(ref _snapshot, snapshot);
|
|
Volatile.Write(ref _lastError, null);
|
|
if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
|
|
Changed?.Invoke();
|
|
return snapshot;
|
|
}
|
|
finally
|
|
{
|
|
_refreshing.Release();
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _stopping.CancelAsync().ConfigureAwait(false);
|
|
try
|
|
{
|
|
await _running.ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
}
|
|
_stopping.Dispose();
|
|
}
|
|
|
|
private TimeSpan Backoff(int failures) =>
|
|
TimeSpan.FromTicks(Math.Min(_options.MaxBackoff.Ticks, _options.MinBackoff.Ticks << Math.Min(failures, 20)));
|
|
|
|
private async Task RefreshLoopAsync(CancellationToken cancellationToken)
|
|
{
|
|
var failures = 0;
|
|
while (!cancellationToken.IsCancellationRequested)
|
|
{
|
|
TimeSpan wait;
|
|
try
|
|
{
|
|
await RefreshAsync(cancellationToken).ConfigureAwait(false);
|
|
failures = 0;
|
|
wait = _options.RefreshInterval;
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Warning(LogCategory, $"Comparing with {Server} failed", ex);
|
|
Volatile.Write(ref _lastError, ex);
|
|
Changed?.Invoke();
|
|
wait = Backoff(failures++);
|
|
}
|
|
if (!await WaitAsync(_refreshWake.Reader, wait, cancellationToken).ConfigureAwait(false)) return;
|
|
}
|
|
}
|
|
|
|
/// <summary>Listens to the server's events; a lost socket reconnects with backoff and asks for a full comparison (events were missed).</summary>
|
|
private async Task EventLoopAsync(CancellationToken cancellationToken)
|
|
{
|
|
var failures = 0;
|
|
while (!cancellationToken.IsCancellationRequested)
|
|
{
|
|
try
|
|
{
|
|
await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
failures = 0;
|
|
if (e is not SequenceChangedEvent changed) continue;
|
|
_changed[changed.SequenceId] = 0;
|
|
_eventWake.Writer.TryWrite(true);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}");
|
|
}
|
|
try
|
|
{
|
|
await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
return;
|
|
}
|
|
RequestRefresh();
|
|
}
|
|
}
|
|
|
|
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
|
|
private async Task ChangedLoopAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
while (await _eventWake.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
_eventWake.Reader.TryRead(out _);
|
|
await Task.Delay(_options.EventDelay, cancellationToken).ConfigureAwait(false);
|
|
var ids = _changed.Keys.ToList();
|
|
foreach (var id in ids) _changed.TryRemove(id, out _);
|
|
try
|
|
{
|
|
var busy = await _sync.TransferringAsync(Server, cancellationToken).ConfigureAwait(false);
|
|
var due = ids.Where(id => !busy.Contains(id)).ToList();
|
|
if (due.Count > 0) await _sync.RefreshSequencesAsync(_remote, due, _policy(), cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
|
{
|
|
// Includes timeouts reported as cancellation: the loop goes on and a full comparison catches up.
|
|
Log.Warning(LogCategory, $"Comparing changed sequences of {Server} failed", ex);
|
|
RequestRefresh();
|
|
}
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Queues (background priority) the proxies of server sequences this PC keeps proxies of, without local originals,
|
|
/// whose cache is stale: frames changed on a server that has the sequence's proxies; on such a server, a download
|
|
/// left stand-ins and the server's sequence changed since (the proxy pass that draws frames added after its last one
|
|
/// records the sequence's state, while its flag already offers their proxies); or the server, without the sequence's
|
|
/// proxies, now offers the proxy of a frame the cache holds a stand-in for (<see cref="OffersProxiesAsync"/>). A
|
|
/// sequence whose last download failed waits for its backoff.
|
|
/// </summary>
|
|
private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken)
|
|
{
|
|
foreach (var (remoteId, jobId) in _proxyJobs.ToList())
|
|
{
|
|
var job = await _sync.Database.Jobs.GetAsync(jobId, cancellationToken).ConfigureAwait(false);
|
|
if (job?.State is JobState.Queued or JobState.Running or JobState.Paused) continue;
|
|
_proxyJobs.Remove(remoteId);
|
|
// A download of stand-ins' proxies that did not finish compares the cache with the manifest again (after its
|
|
// backoff when it failed): the server's sequence may never change again to ask for it.
|
|
if (job?.State != JobState.Done) _standInsCompared.Remove(remoteId);
|
|
if (job?.State == JobState.Failed)
|
|
{
|
|
var failures = _proxyFailures.GetValueOrDefault(remoteId).Failures + 1;
|
|
_proxyFailures[remoteId] = (failures, DateTime.UtcNow + Backoff(failures));
|
|
}
|
|
else
|
|
{
|
|
_proxyFailures.Remove(remoteId);
|
|
}
|
|
}
|
|
foreach (var entry in snapshot.Entries)
|
|
{
|
|
if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ProxiesStale: true } link }) continue;
|
|
if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue;
|
|
// A download that left stand-ins on a server with the proxies brings nothing new until the sequence changes: a
|
|
// frame the server offers but cannot serve yet, or one that never gets a proxy, would otherwise be fetched at
|
|
// every refresh.
|
|
if (link.ServerHasProxies ? link.ProxiesFramesVersion is null && ComparedNow(link) : !await OffersProxiesAsync(link, cancellationToken).ConfigureAwait(false))
|
|
continue;
|
|
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background,
|
|
cancellationToken).ConfigureAwait(false);
|
|
_proxyJobs[link.RemoteId] = job.Id;
|
|
// Compared at this update time once the download that brings what the server offers is queued.
|
|
_standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
|
|
}
|
|
}
|
|
|
|
/// <summary>Whether the cache was compared with the server's sequence, or its download queued, at the sequence's current update time.</summary>
|
|
private bool ComparedNow(SyncLink link) =>
|
|
_standInsCompared.TryGetValue(link.RemoteId, out var compared) && SyncService.SameMoment(compared, link.RemoteUpdatedAt);
|
|
|
|
/// <summary>
|
|
/// Whether the server, without the sequence's proxies, now offers the proxy of a frame whose cached file only stands in
|
|
/// for one (a thumbnail, a file of a cache that did not record its kind) or that has no cached file. The sequence's
|
|
/// proxy flag cannot say: a pass sets it only once every frame the server cannot decode has its proxy, a missing or
|
|
/// damaged one never gets a proxy, and clients and render nodes send the other frames' proxies one by one. The
|
|
/// manifest is read once per change of the server's sequence, since a proxy that arrives leaves a new update time
|
|
/// (the proxy pass it queues records the sequence's state). A comparison that offers nothing is recorded here; one
|
|
/// that offers proxies is recorded when their download is queued, and dropped when that download does not finish
|
|
/// (<see cref="QueueProxiesAsync"/>).
|
|
/// </summary>
|
|
private async Task<bool> OffersProxiesAsync(SyncLink link, CancellationToken cancellationToken)
|
|
{
|
|
if (ComparedNow(link)) return false;
|
|
SequenceManifest manifest;
|
|
try
|
|
{
|
|
manifest = await _remote.GetManifestAsync(link.RemoteId, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|
|
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
|
{
|
|
// Compared again at the next refresh; the other sequences go on.
|
|
Log.Info(LogCategory, $"The proxies of {link.Title} on {Server} could not be compared: {ex.Message}");
|
|
return false;
|
|
}
|
|
var cached = _sync.Proxies.Kinds(Server, link.RemoteId);
|
|
if (manifest.Frames.Any(f => f.HasProxy && cached.GetValueOrDefault(f.Id) != ProxyCache.Proxy)) return true;
|
|
_standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
|
|
return false;
|
|
}
|
|
|
|
/// <summary>Waits for a wake-up or the delay; false when stopping.</summary>
|
|
private static async Task<bool> WaitAsync(ChannelReader<bool> wake, TimeSpan delay, CancellationToken cancellationToken)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
timeout.CancelAfter(delay);
|
|
try
|
|
{
|
|
await wake.ReadAsync(timeout.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
|
{
|
|
// The delay elapsed.
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|