using System.Diagnostics; using System.Runtime.ExceptionServices; using System.Text.RegularExpressions; namespace UCVL.VPNPlus; // Ranks only explicit public nodes from the current authenticated profile. This // is connection planning, not proof of proxy identity or permission to replace a // healthy core. The caller must still validate the selected proxy after start. internal static class PublicTailnetSelection { internal sealed record Candidate(ConfigResponse Response, long LatencyMilliseconds); private static readonly Regex ValidSlug = new("^[a-z0-9][a-z0-9-]{0,79}$", RegexOptions.CultureInvariant); // Use the existing authenticated backend dispatcher for new client-session // allocations. Its real throughput/reservation score is not a bandwidth // capacity measurement and does not split an individual TCP stream. internal static async Task> RankDispatchedAsync( IEnumerable authorizedNodes, string routeMode, Func coolingDown, Func, CancellationToken, Task> dispatch, Func> endpointProbe, CancellationToken token, bool allowKnownEndpoints = false, Action? diagnostic = null, TimeSpan? budget = null) { token.ThrowIfCancellationRequested(); if (routeMode is not ("smart" or "global")) return []; var nodes = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode && n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug)) .DistinctBy(n => n.Slug, StringComparer.Ordinal).Take(32).ToArray(); var excluded = nodes.Where(n => coolingDown(n.Slug)).Select(n => n.Slug).ToHashSet(StringComparer.Ordinal); var remaining = nodes.Where(n => !excluded.Contains(n.Slug)).ToDictionary(n => n.Slug, StringComparer.Ordinal); if (remaining.Count == 0) return []; using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); deadline.CancelAfter(TimeSpan.FromMilliseconds(Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000))); var candidates = new List(); for (var attempt = 0; attempt < 8 && remaining.Count > 0; attempt++) { try { var response = await dispatch(excluded.ToArray(), deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false); deadline.Token.ThrowIfCancellationRequested(); var slug = response?.Node?.Slug; // The backend's auto result must still be in this authenticated // public profile. Never promote private, removed, or repeated nodes. if (slug is null || !remaining.Remove(slug, out var node)) break; excluded.Add(slug); var reachable = await RankAsync([node], routeMode, _ => false, (_, _) => Task.FromResult(response!), endpointProbe, deadline.Token, allowKnownEndpoints, diagnostic).ConfigureAwait(false); candidates.AddRange(reachable); } catch (ApiException error) when (error.StatusCode is 401 or 403) { throw; } catch (OperationCanceledException) when (!token.IsCancellationRequested) { break; } catch (OperationCanceledException) { throw; } catch (Exception) { break; } // Existing domain passes remain available. } token.ThrowIfCancellationRequested(); return candidates; } internal static async Task ConfirmDispatchAsync(Candidate candidate, IEnumerable authorizedNodes, string routeMode, Func, CancellationToken, Task> dispatch, CancellationToken token) { var slugs = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode && n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug)) .Select(n => n.Slug).Distinct(StringComparer.Ordinal).ToArray(); var expected = candidate.Response.Node.Slug; if (!slugs.Contains(expected, StringComparer.Ordinal) || slugs.Length > 32) throw new InvalidOperationException("自动调度候选已不属于当前授权节点范围。请刷新账号信息。"); // Planning may have inspected other nodes. Before starting this proxy, // restore the shared backend reservation to the node actually attempted. var response = await dispatch(slugs.Where(slug => slug != expected).ToArray(), token).ConfigureAwait(false); if (response.Node.Slug != expected || response.RouteMode != routeMode || response.ConnectionScope == PrivateAuxiliaryRouting.Scope) throw new InvalidOperationException("后台调度确认与当前候选不一致,已拒绝连接。"); return response; } internal static async Task> RankAsync( IEnumerable authorizedNodes, string routeMode, Func coolingDown, Func> loadConfig, Func> endpointProbe, CancellationToken token, bool allowKnownEndpoints = false, Action? diagnostic = null, TimeSpan? budget = null) { token.ThrowIfCancellationRequested(); if (routeMode is not ("smart" or "global")) return []; // Snapshot before asynchronous work: profile/cooldown state belongs to // the caller, and private grants must never become public dispatch. var nodes = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode && n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug)) .DistinctBy(n => n.Slug, StringComparer.Ordinal) .Where(n => !coolingDown(n.Slug)).Take(8).ToArray(); if (nodes.Length == 0) return []; var milliseconds = Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); deadline.CancelAfter(TimeSpan.FromMilliseconds(milliseconds)); using var slots = new SemaphoreSlim(3, 3); ApiException? authorizationFailure = null; void Report(string slug, string reason) { // Fixed reason codes only, never exception messages or config JSON. if (!Regex.IsMatch(reason, "^[a-z0-9_]{1,80}$", RegexOptions.CultureInvariant)) reason = "metadata_rejected"; try { diagnostic?.Invoke(slug, reason); } catch { /* Telemetry cannot alter connection planning. */ } } async Task<(Candidate Candidate, int Index)?> Read(NodeInfo node, int index) { var entered = false; try { await slots.WaitAsync(deadline.Token).ConfigureAwait(false); entered = true; // WaitAsync also bounds a buggy callback that ignores its token. var response = await loadConfig(node.Slug, deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false); deadline.Token.ThrowIfCancellationRequested(); if (response?.Node is null || !string.Equals(response.Node.Slug, node.Slug, StringComparison.Ordinal)) { Report(node.Slug, "response_node_mismatch"); return null; } if (!string.Equals(response.RouteMode, routeMode, StringComparison.Ordinal)) { Report(node.Slug, "response_route_mismatch"); return null; } var prepared = TailnetTransport.TryPrepare(response, out var reason, allowKnownEndpoints); if (prepared is null) { Report(node.Slug, reason); return null; } var address = TailnetTransport.Address(prepared); var port = TailnetTransport.Port(prepared); if (address is null || port is < 1 or > 65535) { Report(node.Slug, "prepared_endpoint_invalid"); return null; } using var probeDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token); probeDeadline.CancelAfter(TimeSpan.FromSeconds(3)); var elapsed = Stopwatch.StartNew(); var available = await endpointProbe(address, port, probeDeadline.Token) .WaitAsync(probeDeadline.Token).ConfigureAwait(false); probeDeadline.Token.ThrowIfCancellationRequested(); if (!available) { Report(node.Slug, "endpoint_unreachable"); return null; } Report(node.Slug, "endpoint_reachable"); return (new Candidate(response, Math.Max(0, elapsed.ElapsedMilliseconds)), index); } catch (ApiException error) when (error.StatusCode is 401 or 403) { // Never turn expired/revoked authorization into another node or // public fallback. Cancel sibling work, then propagate unchanged. Interlocked.CompareExchange(ref authorizationFailure, error, null); deadline.Cancel(); Report(node.Slug, "authorization_rejected"); return null; } catch (OperationCanceledException) when (!token.IsCancellationRequested) { Report(node.Slug, "selection_or_probe_deadline"); return null; } catch (OperationCanceledException) { throw; } catch (Exception) { Report(node.Slug, "config_or_probe_unavailable"); return null; } finally { if (entered) slots.Release(); } } var readings = await Task.WhenAll(nodes.Select(Read)).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (authorizationFailure is not null) ExceptionDispatchInfo.Capture(authorizationFailure).Throw(); return readings.Where(r => r is not null).Select(r => r!.Value) .OrderBy(r => r.Candidate.LatencyMilliseconds).ThenBy(r => r.Index) .Select(r => r.Candidate).ToArray(); } }