155 lines
6.3 KiB
C#
155 lines
6.3 KiB
C#
namespace UCVL.VPNPlus;
|
|
|
|
// Optional management APIs must neither interrupt a working data plane nor gate
|
|
// one another. The owner supplies a bounded token and a session/core epoch check;
|
|
// this class never stores credentials, changes routes, or starts/stops a core.
|
|
internal sealed class LearningSyncCoordinator
|
|
{
|
|
private enum Endpoint { Upload, Rules, Ack }
|
|
private sealed class Gate
|
|
{
|
|
internal int Failures;
|
|
internal long NotBefore;
|
|
}
|
|
|
|
private readonly Func<long> _clock;
|
|
private readonly object _sync = new();
|
|
private readonly Gate[] _gates = [new(), new(), new()];
|
|
private long _generation;
|
|
private long _lastNow;
|
|
private bool _hasNow;
|
|
private int _running;
|
|
private string? _pendingAck;
|
|
|
|
internal LearningSyncCoordinator(Func<long>? monotonicClock = null)
|
|
=> _clock = monotonicClock ?? (() => Environment.TickCount64);
|
|
|
|
// Call on login/logout/account change. In-flight old-session results cannot
|
|
// reintroduce a pending acknowledgement or an old session's retry penalty.
|
|
internal void Reset()
|
|
{
|
|
lock (_sync)
|
|
{
|
|
_generation++;
|
|
_pendingAck = null;
|
|
foreach (var gate in _gates) { gate.Failures = 0; gate.NotBefore = 0; }
|
|
}
|
|
}
|
|
|
|
internal async Task RunAsync(
|
|
Func<bool> isCurrent,
|
|
Func<CancellationToken, Task> upload,
|
|
Func<CancellationToken, Task<RoutingManifest>> fetchRules,
|
|
Func<RoutingManifest, CancellationToken, Task<bool>> applyRules,
|
|
Func<string, CancellationToken, Task> acknowledge,
|
|
CancellationToken cancellationToken,
|
|
Action<string>? diagnostic = null)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0) return;
|
|
var generation = Volatile.Read(ref _generation);
|
|
bool Current()
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
return generation == Volatile.Read(ref _generation) && isCurrent();
|
|
}
|
|
|
|
try
|
|
{
|
|
if (!Current()) return;
|
|
await AttemptAsync(Endpoint.Upload, upload);
|
|
if (!Current()) return;
|
|
|
|
await AttemptAsync(Endpoint.Rules, async token =>
|
|
{
|
|
var manifest = await fetchRules(token);
|
|
if (!Current()) return;
|
|
// The callback must also guard its own asynchronous mutation.
|
|
// A rejected/stale apply is never acknowledged as installed.
|
|
if (!await applyRules(manifest, token) || !Current()) return;
|
|
lock (_sync)
|
|
if (generation == _generation && !string.IsNullOrWhiteSpace(manifest.Revision))
|
|
_pendingAck = manifest.Revision;
|
|
});
|
|
if (!Current()) return;
|
|
|
|
string? revision;
|
|
lock (_sync) revision = _pendingAck;
|
|
if (revision is not null && await AttemptAsync(Endpoint.Ack, token => acknowledge(revision, token)))
|
|
{
|
|
lock (_sync)
|
|
if (generation == _generation && _pendingAck == revision) _pendingAck = null;
|
|
}
|
|
}
|
|
finally { Volatile.Write(ref _running, 0); }
|
|
|
|
async Task<bool> AttemptAsync(Endpoint endpoint, Func<CancellationToken, Task> operation)
|
|
{
|
|
if (!Current()) return false;
|
|
lock (_sync)
|
|
if (generation != _generation || Now() < _gates[(int)endpoint].NotBefore) return false;
|
|
try
|
|
{
|
|
await operation(cancellationToken);
|
|
if (!Current()) return false;
|
|
var recovered = false;
|
|
lock (_sync)
|
|
{
|
|
if (generation != _generation) return false;
|
|
var gate = _gates[(int)endpoint];
|
|
recovered = gate.Failures != 0;
|
|
gate.Failures = 0; gate.NotBefore = 0;
|
|
}
|
|
if (recovered) Report(endpoint, "recovered");
|
|
return true;
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
|
|
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
|
{
|
|
// Never convert authentication loss to an optional-API fallback.
|
|
// A delayed response from a previous account must not log out its successor.
|
|
if (!Current()) return false;
|
|
throw;
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
if (!Current()) return false;
|
|
var unsupported = error is ApiException { StatusCode: 404 or 405 };
|
|
lock (_sync)
|
|
{
|
|
if (generation != _generation) return false;
|
|
var gate = _gates[(int)endpoint];
|
|
gate.Failures = Math.Min(gate.Failures + 1, 16);
|
|
// Unsupported: 2, 4, 8, 15 min. Transient: 1, 2, 4, 5 min.
|
|
var first = unsupported ? 120_000L : 60_000L;
|
|
var maximum = unsupported ? 900_000L : 300_000L;
|
|
var delay = Math.Min(first * (1L << Math.Min(gate.Failures - 1, 4)), maximum);
|
|
var now = Now();
|
|
gate.NotBefore = now > long.MaxValue - delay ? long.MaxValue : now + delay;
|
|
}
|
|
Report(endpoint, unsupported ? "unsupported.backoff" : "transient.backoff");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
void Report(Endpoint endpoint, string outcome)
|
|
{
|
|
// Only fixed endpoint/outcome identifiers; never exception text,
|
|
// manifests, URLs, revisions, tokens, or user-provided content.
|
|
var name = endpoint switch { Endpoint.Upload => "upload", Endpoint.Rules => "rules", _ => "ack" };
|
|
try { diagnostic?.Invoke("learning." + name + "." + outcome); }
|
|
catch { /* Diagnostics cannot break a working learning/data path. */ }
|
|
}
|
|
}
|
|
|
|
// All reads occur under _sync. A clock regression cannot retry early, and
|
|
// wall-clock/time-zone changes never affect the default monotonic clock.
|
|
private long Now()
|
|
{
|
|
var value = _clock();
|
|
if (!_hasNow || value > _lastNow) _lastNow = value;
|
|
_hasNow = true;
|
|
return _lastNow;
|
|
}
|
|
}
|