zapret-kvn/xray_fluent/diagnostics/path_test/runner.py
loop-uh a06dd17b2b Path-test (Windows): «Проверка соединения» on the logs page
DNS, TCP, platform TLS and the stock naive.exe (real config builder helper_config, dummy credentials, no own ClientHello) per
saved server host, one full log (text and JSONL, hosts masked unless ticked, also in the diagnostic archive). By button, one
selected server by default; all servers only on a tick, one at a time with 10-20 s pauses, cancel on the same button, gate
journal; egress allowlist entries with reasons. Work of the KVN session c_9doawlxyy2 (branch feat/path-test), squashed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 12:18:34 -05:00

106 lines
5.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Прогон проверки: по каждому хосту один DNS, затем раунды; в раунде TCP, платформенный TLS и настоящий клиент идут рядом.
Правило шлюза проверок (требование незаметности, ``network/probe_gate.py``): по кнопке — по одному серверу; между серверами
одного прохода пауза со случайным разбросом (10–20 с), проход можно отменить, каждая проверка записывается в журнал шлюза.
Пачка одновременных рукопожатий к разным адресам выдала бы весь список подписки оборудованию провайдера, поэтому хосты
идут ПО ОЧЕРЕДИ (параллельны только три шага одного раунда к одному и тому же серверу).
Явно здоровый хост (первые EARLY_STOP_ROUNDS раундов целиком чистые) завершается раньше. Нечистый хост всегда проходит ВСЕ
раунды: 12 попыток отличают перегруженный фронт («3 из 12») от постоянного правила («0 из 12»).
Шаги подставляются, поэтому весь прогон проверяется без сети; в приложении это реальные клиенты (правило владельца).
"""
from __future__ import annotations
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from ...network import probe_gate
from .model import Attempt, HostVerdict, Outcome, Target, TargetResult
from .verdicts import judge
ATTEMPTS = 12
SPACING_S = 1.5
EARLY_STOP_ROUNDS = 4
@dataclass(frozen=True, slots=True)
class Outcomes:
results: tuple[TargetResult, ...]
verdicts: tuple[HostVerdict, ...]
class PathTestRunner:
def __init__(
self,
dns: Callable[[Target], Attempt],
tcp: Callable[[Target], Attempt],
platform_tls: Callable[[Target], Attempt],
real_client: Callable[[Target], Attempt],
*,
attempts: int = ATTEMPTS,
spacing: float = SPACING_S,
sleep: Callable[[float], None] = time.sleep,
host_pause: Callable[[], float] = probe_gate.sweep_pause,
cancelled: Callable[[], bool] = lambda: False,
gate: probe_gate.ProbeGate = probe_gate.GATE,
) -> None:
self._dns, self._tcp, self._tls, self._real = dns, tcp, platform_tls, real_client
self._attempts, self._spacing, self._sleep = attempts, spacing, sleep
self._host_pause, self._cancelled, self._gate = host_pause, cancelled, gate
def run(self, targets: list[Target], progress: Callable[[int, int], None] | None = None) -> Outcomes:
ordered = sorted(targets, key=lambda t: not t.control)
servers = sum(1 for t in ordered if not t.control)
results: list[TargetResult] = []
probed_servers = 0
for index, target in enumerate(ordered):
if self._cancelled():
break
if not target.control:
if probed_servers:
# Между серверами одного прохода: пауза со случайным разбросом, прерываемая отменой.
self._interruptible_pause(self._host_pause())
if self._cancelled():
break
probed_servers += 1
# Журнал шлюза: один сервер по кнопке (USER), несколько подряд (SWEEP).
self._gate.record(probe_gate.SWEEP if servers > 1 and not target.control else probe_gate.USER, target.host)
results.append(self._run_host(target))
if progress is not None:
progress(index + 1, len(ordered))
control = next((r for r in results if r.target.control), None)
verdicts = tuple(judge(r, control if control is not r else None) for r in results)
return Outcomes(tuple(results), verdicts)
def _interruptible_pause(self, seconds: float) -> None:
left = seconds
while left > 0 and not self._cancelled():
step = min(0.5, left)
self._sleep(step)
left -= step
def _run_host(self, target: Target) -> TargetResult:
collected: list[Attempt] = []
lookup = self._dns(target)
collected.append(lookup)
if not lookup.outcome.answered:
return TargetResult(target, tuple(collected))
clean_rounds = 0
with ThreadPoolExecutor(max_workers=3, thread_name_prefix="path-test-step") as steps:
for round_no in range(1, self._attempts + 1):
if self._cancelled():
break
futures = [steps.submit(self._tcp, target), steps.submit(self._tls, target), steps.submit(self._real, target)]
t, p, r = (f.result() for f in futures)
collected.extend((t, p, r))
ok = lambda a: a.outcome.answered or a.outcome is Outcome.NOT_RUN # noqa: E731
clean = t.outcome.answered and ok(p) and ok(r)
clean_rounds = clean_rounds + 1 if clean else 0
if clean_rounds >= EARLY_STOP_ROUNDS and round_no == clean_rounds:
break
if round_no < self._attempts:
self._sleep(self._spacing)
return TargetResult(target, tuple(collected))