Files

109 lines
5.5 KiB
C#
Raw Permalink Normal View History

namespace UCVL.VPNPlus;
internal sealed partial class MainForm
{
private readonly LearningSyncCoordinator _learningSync = new();
private int? _learningSyncCore;
private readonly TailnetReadinessPolicy _tailnetReadiness = new();
private bool _checkingTailnetReadiness;
private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false };
private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null)
{
_connectionAttemptCancellation?.Cancel();
_accessToken = token;
if (token is null)
{
_runtimeRepairRequired = false;
_statusDetail.AccessibleDescription = null;
_runtimeRepairTip.SetToolTip(_statusDetail, null);
}
_connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64);
_connectionHealth.Invalidate();
_sessionRevision++;
_nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true);
_nextNodeTrafficAttempt = DateTimeOffset.MinValue;
_learningSync.Reset();
_learningSyncCore = null;
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
while (_observationQueue.TryDequeue(out _)) { }
}
private bool TryCancelPendingConnection()
{
if (_connectionAttemptCancellation is not { } pending) return false;
_wantConnected = false;
pending.Cancel();
_connectButton.Enabled = false;
_statusDetail.Text = "正在取消连接并恢复本机网络…";
return true;
}
private TailnetReadinessPolicy.Context ReadTailnetReadinessContext() => new(
_sessionRevision, _xray.CoreId, _wantConnected,
_busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting,
_xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null);
private bool CanRetainAuthorizedCore() => _connectionAuthorization.CanRetain(DateTimeOffset.UtcNow,
Environment.TickCount64, _currentNodeIsPrivateAuxiliary, _privateLeaseDeadlineTicks);
// Recheck the authorized proxy port every ten minutes. Confirmed failure
// on the active path retries the same node's public entry with a fresh grant.
private async Task CheckTailnetReadinessAsync()
{
if (_runtimeRepairRequired || !_wantConnected || _uiOnly || _preview) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket))
{
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting;
return;
}
var reachable = false;
_checkingTailnetReadiness = true;
try
{
if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetEndpointConfirmation.ProbeAsync(
probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
finally { _checkingTailnetReadiness = false; }
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
if (_exiting || IsDisposed || Disposing) return;
if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return;
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy;
if (result == TailnetReadinessPolicy.Result.Fallback && _currentNodeSlug is { } slug)
{
_tailnetPreference.Failed(slug, Environment.TickCount64);
_tailnetPreference.CommitDomainFallback();
_transportRetryNodeSlug = slug;
_connectionHealth.Invalidate();
AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "tcp_endpoint_failed_same_node_domain_fallback", slug).SafeMessage);
await ToggleConnectionAsync(suppressDialogs: true, reconnect: true);
return;
}
if (result == TailnetReadinessPolicy.Result.BecameReady)
{
AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage);
_notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复",
"现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info);
}
}
private async Task ReconnectThroughPreferredTailnetAsync()
{
if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning
|| _xray.UsesTailnet || !_tailnetReadiness.IsReady) return;
if (!PreflightClientRuntime(suppressDialogs: false, clearRepair: true)) return;
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
_tailnetPreference.ResetForUserConnect();
_transportRetryNodeSlug = _currentNodeSlug;
// Explicit operator action, with fresh management authorization and the
// normal same-node/manual constraints. No silent migration of streams.
await ToggleConnectionAsync(reconnect: true);
}
}