zapret-kvn/xray_fluent/network/background_workers.py
loop-uh c80fd648ee
Some checks failed
Windows project source guards / test (push) Has been cancelled
client reports: app errors not about a server (vpnbot app_error live)
Errors that are not about any server go in the same batches as
"kind": "app_error", schema 1: step, code, count since the last send,
occurred_at of the first (in the ingest's time), and for a crash only its
frames (module.function:line relative to the package, innermost first, at
most 16) -- never a message, path, user dir, address or URL. The store
counts repeats, sends one code at most once a day per app version and
keeps at most 32 for 7 days. Sources: uncaught exceptions in any thread,
a start that failed before a server was chosen (port:bind for a local
port conflict), a failed subscription fetch (HTTP class or transport, our
service's link or not, route) or parse, a failed update download or
install, TUN without administrator rights, the profile store not read or
written. Errors noted before the reporter exists go when it does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 05:26:26 -05:00

243 lines
11 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.

from __future__ import annotations
import logging
import threading
from collections.abc import Callable
from typing import TYPE_CHECKING
from PyQt6.QtCore import QObject, QThread, pyqtSignal
from ..importer.subscription_http import fetch_subscription
from ..importer.subscription_parser import parse_subscription_payload
_LOG = logging.getLogger(__name__)
if TYPE_CHECKING:
from ..profiles.models import AppState
from ..profiles.storage import StateStorage
class EndpointResolver(QThread):
"""Resolve every host of one immutable endpoint without blocking the GUI."""
resolved = pyqtSignal(int, object, object, object) # generation, endpoint, result, error
def __init__(self, generation: int, endpoint, resolver: Callable, parent=None) -> None:
super().__init__(parent)
self._generation = generation
self._endpoint = endpoint
self._resolver = resolver
def run(self) -> None:
try:
result = self._resolver(self._endpoint)
error: Exception | None = None
except Exception as exc: # DNS errors are reported back on the GUI thread
result = None
error = exc
self.resolved.emit(self._generation, self._endpoint, result, error)
class StateWriter(QObject):
"""Единственный поток записи состояния на диск; побеждает последний снимок.
GUI-поток отдаёт готовый текст (``StateStorage.serialize_state``) и сразу
возвращается; шифрование и запись идут здесь. Промежуточные снимки,
пришедшие во время записи, схлопываются в последний.
"""
failed = pyqtSignal(str)
def __init__(self, storage: StateStorage, parent=None) -> None:
super().__init__(parent)
self._storage = storage
self._cond = threading.Condition()
self._pending: tuple[str, str] | None = None
self._busy = False
self._closed = False
self._thread = threading.Thread(target=self._run, name="state-writer", daemon=True)
self._thread.start()
def submit(self, payload: str, passphrase: str) -> None:
with self._cond:
if self._closed:
return
self._pending = (payload, passphrase)
self._cond.notify_all()
def flush(self, timeout: float = 15.0) -> bool:
"""Дождаться записи всего отданного. Только для выхода из приложения."""
with self._cond:
return self._cond.wait_for(lambda: self._pending is None and not self._busy, timeout)
def close(self, timeout: float = 15.0) -> bool:
done = self.flush(timeout)
with self._cond:
self._closed = True
self._cond.notify_all()
self._thread.join(timeout=1.0)
return done
def _run(self) -> None:
while True:
with self._cond:
self._cond.wait_for(lambda: self._pending is not None or self._closed)
if self._pending is None:
return
payload, passphrase = self._pending
self._pending = None
self._busy = True
try:
self._storage.write_serialized(payload, passphrase)
except Exception as exc:
_note_storage_failure("save")
self.failed.emit(str(exc))
finally:
with self._cond:
self._busy = False
self._cond.notify_all()
def _route_outcomes(failures) -> str:
"""Что на самом деле вышло при загрузке по каждому маршруту, простыми словами.
Проба проверяет рукопожатие и один запрос к корню сайта, но сама загрузка идёт другим
клиентом и с другим запросом. Если их итоги расходятся, человек должен видеть оба, а не
только вывод пробы.
"""
names = {False: "напрямую", True: "через VPN"}
parts = [f"{names.get(bool(item.via_proxy), '?')} — {item.reason}" for item in failures if getattr(item, "reason", "")]
return f" Итог самой загрузки: {'; '.join(parts)}." if parts else ""
class SubscriptionUpdateWorker(QThread):
"""Fetch and parse a subscription without mutating application state."""
completed = pyqtSignal(object, object, object) # Subscription, fetch result, parsed result | None
failed = pyqtSignal(object, str, bool) # Subscription, sanitized message, VPN route untried
progress = pyqtSignal(str, str) # subscription id, phase
def __init__(
self,
subscription,
*,
mode: str,
proxy_port: int | None,
force_refresh: bool = False,
servers_available: bool = True,
parent=None,
) -> None:
super().__init__(parent)
self._subscription = subscription
self._mode = mode
self._proxy_port = proxy_port
self._force_refresh = bool(force_refresh)
# Есть ли в приложении хоть один сервер: от этого зависит совет в тексте отказа.
self._servers_available = bool(servers_available)
self._cancel = threading.Event()
def cancel(self) -> None:
"""Stop waiting for the network; the worker then fails promptly."""
self._cancel.set()
def run(self) -> None:
try:
fetched = fetch_subscription(
self._subscription,
mode=self._mode,
proxy_port=self._proxy_port,
force_refresh=self._force_refresh,
cancel=self._cancel,
on_route=lambda via_proxy: self.progress.emit(
self._subscription.id, "proxy" if via_proxy else "download"
),
)
if fetched.not_modified:
self.completed.emit(self._subscription, fetched, None)
return
self.progress.emit(self._subscription.id, "parse")
parsed = parse_subscription_payload(
fetched.data,
headers=fetched.headers,
source_url=self._subscription.url,
include_pattern=self._subscription.include_pattern,
exclude_pattern=self._subscription.exclude_pattern,
hidden_source_keys=set(self._subscription.hidden_source_keys),
)
self.completed.emit(self._subscription, fetched, parsed)
except Exception as exc:
from ..importer.subscription_http import (
SubscriptionUnreachableError,
sanitize_fetch_error,
)
tunnel_untried = isinstance(exc, SubscriptionUnreachableError) and exc.tunnel_untried
if not self._cancel.is_set():
_note_subscription_failure(self._subscription, exc)
message = sanitize_fetch_error(exc)
if isinstance(exc, SubscriptionUnreachableError) and exc.host and not self._cancel.is_set():
message = self._explain_unreachable(exc, message)
self.failed.emit(self._subscription, message, tunnel_untried)
def _explain_unreachable(self, exc, fallback: str) -> str:
"""Ни один маршрут не ответил: проверить по стадиям и назвать виновника.
Проба идёт один раз после отказа и сама ограничена по времени; её сбой
не должен заменить отказ загрузки, поэтому при любой ошибке остаётся
прежний текст.
"""
try:
from ..network.fetch_diagnosis import diagnose
tunnel_port = self._proxy_port if self._mode in {"auto", "proxy"} and self._proxy_port and self._proxy_port > 0 else None
diagnosis = diagnose(
exc.host, exc.port, tunnel_port=tunnel_port, servers_available=self._servers_available
)
for line in diagnosis.log_lines:
_LOG.info(line)
return diagnosis.message() + _route_outcomes(getattr(exc, "failures", ()))
except Exception as error: # noqa: BLE001 — диагностика не должна ломать отчёт об отказе
_LOG.warning("diagnosis failed: %s: %s", type(error).__name__, error)
return fallback
def _note_subscription_failure(subscription, exc: BaseException) -> None:
"""A subscription that could not be fetched as an app error (vpnbot «app_error live» 2026-11-20): the HTTP class
or the transport error, whether it is our service's link and the route — never the URL or the host."""
try:
from ..client_reports import app_errors
from ..importer.subscription_http import (
SubscriptionServerResponseError,
SubscriptionUnreachableError,
)
from ..importer.subscription_parser import SubscriptionParseError
ours = bool(getattr(subscription, "service", False))
answer = exc if isinstance(exc, SubscriptionServerResponseError) else exc.__cause__
if isinstance(answer, SubscriptionServerResponseError) and answer.status is not None:
route = "proxy" if getattr(answer, "via_proxy", False) else "direct"
app_errors.note(app_errors.subscription_error_of(int(answer.status), None, ours, route))
elif isinstance(exc, SubscriptionUnreachableError) and exc.failures:
last = exc.failures[-1]
route = "proxy" if last.via_proxy else "direct"
found = app_errors.code("sub", last.kind)
if found:
app_errors.note(app_errors.AppError(app_errors.STEP_SUBSCRIPTION, found,
subscription=app_errors.SubscriptionFact(ours, route)))
elif isinstance(exc, SubscriptionParseError):
app_errors.note(app_errors.AppError(app_errors.STEP_SUBSCRIPTION, "sub:parse",
subscription=app_errors.SubscriptionFact(ours, "direct")))
except Exception:
pass
def _note_storage_failure(what: str) -> None:
"""The profile store could not be read or written, as an app error (vpnbot «app_error live» 2026-11-20)."""
try:
from ..client_reports import app_errors
app_errors.note(app_errors.AppError(app_errors.STEP_STORAGE, f"storage:{what}"))
except Exception:
pass