wholagged 0.3.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wholagged/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """wholagged: is it your internet, your provider or Valve's servers? (Dota 2 for now.)"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ __version__ = "0.3.8"
8
+ APP_NAME = "wholagged" # the product name shown in the window, the CLI and the report
9
+
10
+
11
+ def run_cli() -> int:
12
+ from .checks import run_checks
13
+ from .i18n import t
14
+ from .report import MARKS, side_label
15
+ from .verdict import decide
16
+
17
+ print(f"{APP_NAME} {__version__} · Dota 2 — {t('cli.checking')}\n", flush=True)
18
+
19
+ def on_result(res):
20
+ print(f"{MARKS[res.status]} {res.title}: {res.summary}", flush=True)
21
+ for line in res.details:
22
+ print(f" {line}", flush=True)
23
+
24
+ verdict = decide(run_checks(on_result=on_result))
25
+ print("\n" + "=" * 60)
26
+ # The headings are the report's own labels, so the terminal and the copied report read the same.
27
+ print(f"{t('report.verdict')}: {verdict.headline}")
28
+ print(f"{t('report.side')}: {side_label(verdict.side)}")
29
+ print(verdict.explanation)
30
+ print(f"\n{t('report.advice')}:")
31
+ for i, tip in enumerate(verdict.advice, 1):
32
+ print(f" {i}. {tip}")
33
+ return 0
34
+
35
+
36
+ def main() -> int:
37
+ if "--cli" in sys.argv[1:]:
38
+ return run_cli()
39
+ from .gui import run_gui
40
+
41
+ return run_gui()
wholagged/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from . import main
4
+
5
+ sys.exit(main())
wholagged/checks.py ADDED
@@ -0,0 +1,638 @@
1
+ """Network checks: who is to blame, your internet or Valve's servers.
2
+
3
+ Every check function takes a shared Context and returns a CheckResult.
4
+ Only the standard library is used here, so the module also runs without Qt
5
+ (`uv run wholagged --cli`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import http.client
11
+ import ipaddress
12
+ import json
13
+ import re
14
+ import socket
15
+ import ssl
16
+ import statistics
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from collections.abc import Callable, Iterable
21
+ from concurrent.futures import ThreadPoolExecutor
22
+ from dataclasses import dataclass, field
23
+ from itertools import pairwise
24
+ from typing import Any
25
+
26
+ from . import APP_NAME, __version__, icmp
27
+ from .i18n import Msg
28
+ from .models import CheckResult, Status
29
+
30
+ TCP_TIMEOUT_S = 3.0
31
+ HTTP_TIMEOUT_S = 8.0
32
+ MAX_BODY_BYTES = 4_000_000 # Valve's largest answer (the SDR config) is far below this
33
+ USER_AGENT = f"{APP_NAME}/{__version__}"
34
+
35
+ CM_LIST_URL = (
36
+ "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/"
37
+ "?cellid=0&format=json"
38
+ )
39
+ SDR_CONFIG_URL = "https://api.steampowered.com/ISteamApps/GetSDRConfig/v1/?appid=570"
40
+ GC_VERSION_URL = "https://api.steampowered.com/IGCVersion_570/GetServerVersion/v1/"
41
+
42
+ # Plain IPs, so the internet check does not depend on DNS.
43
+ INTERNET_PROBES = [
44
+ ("1.1.1.1", 443, "Cloudflare"),
45
+ ("8.8.8.8", 443, "Google"),
46
+ ("9.9.9.9", 443, "Quad9"),
47
+ ]
48
+ STEAM_DNS_NAMES = ["api.steampowered.com", "steamcommunity.com"]
49
+ OTHER_DNS_NAMES = ["google.com"]
50
+ CONTROL_PING_IPS = ["1.1.1.1", "8.8.8.8"]
51
+ # Used when the CM list could not be fetched.
52
+ STEAM_FALLBACK_HOSTS = [
53
+ ("store.steampowered.com", 443, "web"),
54
+ ("steamcommunity.com", 443, "web"),
55
+ ("api.steampowered.com", 443, "web"),
56
+ ]
57
+
58
+ CM_TARGETS = 6
59
+ SHOWN_DATA_CENTERS = 5
60
+ # Valve lists a few dozen relay sites. More than this is a bad answer, not a list to cut: dict order could
61
+ # drop the nearest site and make the ping look high. Two ping rounds of 128 at 24 workers stay within budget.
62
+ MAX_POPS = 128
63
+ QUALITY_PINGS = 10
64
+ QUALITY_POPS = 3
65
+ LOSS_WARN_PCT = 5.0
66
+ HIGH_PING_MS = 150.0
67
+ JITTER_WARN_MS = 30.0
68
+
69
+
70
+ @dataclass
71
+ class Context:
72
+ internet_ok: bool = True
73
+ cm_servers: list[dict[str, Any]] = field(default_factory=list)
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Pop:
78
+ code: str
79
+ desc: str
80
+ ip: str
81
+
82
+
83
+ # --------------------------------------------------------------------------- #
84
+ # Helpers
85
+ # --------------------------------------------------------------------------- #
86
+ def _clip(text: str, limit: int = 70) -> str:
87
+ """Someone else's words (the OS's, a server's, a proxy's) as one short line of printable text.
88
+
89
+ A proxy's reason phrase or a bad HTTP status line can carry line breaks and terminal escape codes; they
90
+ would fake lines in the report and run in a terminal. Every non-printable character becomes a space.
91
+ """
92
+ text = " ".join("".join(c if c.isprintable() else " " for c in text).split())
93
+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
94
+
95
+
96
+ VALVE_TEXT_MAX_CHARS = 64 # relay site and data center names ("Washington DC (Sterling)") are far shorter
97
+ MAX_HOSTNAME_CHARS = 253 # the DNS limit
98
+
99
+
100
+ def _valve_text(value: object, limit: int = VALVE_TEXT_MAX_CHARS) -> str | None:
101
+ """A text from Valve that is safe to show: a short, printable, one-line `str`, stripped; else None.
102
+
103
+ Valve's answers are untrusted input, and their texts end up in the rows and in the report users send to
104
+ their provider: a line break or a control character there could fake a line of the report.
105
+ """
106
+ if not isinstance(value, str):
107
+ return None
108
+ text = value.strip()
109
+ return text if text and len(text) <= limit and text.isprintable() else None
110
+
111
+
112
+ def _ipv4(value: object) -> str | None:
113
+ """A strict, public, unicast IPv4 address from Valve ("155.133.226.1"), or None.
114
+
115
+ A malformed address would only fail to ping, which reads as a routing problem. A non-public one is
116
+ never a Valve server, and it can answer: 127.0.0.1 is the PC itself and 192.168.1.1 is often the home
117
+ router, so either would show a perfect ping for a site that wasn't measured. `is_global` rules out
118
+ private, shared (CGNAT), loopback, link-local, documentation, reserved and broadcast addresses; it lets
119
+ multicast through, so that is checked on its own.
120
+ """
121
+ if not isinstance(value, str):
122
+ return None
123
+ try:
124
+ addr = ipaddress.IPv4Address(value)
125
+ except ValueError:
126
+ return None
127
+ return str(addr) if addr.is_global and not addr.is_multicast else None
128
+
129
+
130
+ _HOST_LABEL = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(?<!-)")
131
+ _TOP_LABEL = re.compile(r"[A-Za-z]{2,63}") # "net": letters only, so "0x7f.0.0.1" can't pass as a name
132
+ _LOCAL_NAMES = ("localhost", "local") # the PC itself, or names any machine on the LAN may answer
133
+
134
+
135
+ def _host(value: str) -> str | None:
136
+ """A server's host from Valve: a strict public IPv4 address or a public DNS name, else None.
137
+
138
+ A name has two or more ASCII labels of letters, digits and hyphens and ends in a letters-only label.
139
+ Anything else can't be a Valve server: "cm host" and "[2001:db8::1]" can't be reached, so a list of
140
+ them would blame the provider; "localhost", "0x7f.0.0.1" (127.0.0.1 to the resolver) and one-label LAN
141
+ names reach the PC or the LAN, where the Steam client's own ports would answer. Skipped, a bad list falls
142
+ back to Steam's web servers instead.
143
+ """
144
+ if value.replace(".", "").isdigit(): # all digits: only a strict address ("1.2.3" resolves oddly)
145
+ return _ipv4(value)
146
+ name = value.removesuffix(".")
147
+ labels = name.split(".")
148
+ if (
149
+ len(name) > MAX_HOSTNAME_CHARS
150
+ or len(labels) < 2
151
+ or not all(_HOST_LABEL.fullmatch(label) for label in labels)
152
+ or not _TOP_LABEL.fullmatch(labels[-1])
153
+ or labels[-1].lower() in _LOCAL_NAMES
154
+ ):
155
+ return None
156
+ return value
157
+
158
+
159
+ def short_error(exc: BaseException | str) -> str:
160
+ """A few words on what went wrong: our own (translated) words for the common errors, else the OS's text."""
161
+ if isinstance(exc, str):
162
+ return exc if isinstance(exc, Msg) else _clip(exc)
163
+ if isinstance(exc, (TimeoutError, socket.timeout)):
164
+ return Msg("error.timeout")
165
+ if isinstance(exc, ConnectionRefusedError):
166
+ return Msg("error.refused")
167
+ if isinstance(exc, ConnectionResetError):
168
+ return Msg("error.reset")
169
+ if isinstance(exc, socket.gaierror):
170
+ return Msg("error.dns")
171
+ if isinstance(exc, ssl.SSLError):
172
+ return Msg("error.ssl")
173
+ text = exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc)
174
+ return _clip(text) or type(exc).__name__ # nothing printable left: at least say what it was
175
+
176
+
177
+ def tcp_probe(host: str, port: int, timeout: float = TCP_TIMEOUT_S) -> tuple[float | None, str | None]:
178
+ """Open a TCP connection and close it. Returns (ms, error)."""
179
+ t0 = time.perf_counter()
180
+ try:
181
+ with socket.create_connection((host, port), timeout=timeout):
182
+ pass
183
+ except OSError as exc:
184
+ return None, short_error(exc)
185
+ return (time.perf_counter() - t0) * 1000, None
186
+
187
+
188
+ class HttpFailure(Exception):
189
+ def __init__(self, message: str, status: int | None = None, cert_error: str | None = None) -> None:
190
+ super().__init__(message)
191
+ self.message = message # may be a Msg; `str(exc)` would flatten it to text in one language
192
+ self.status = status
193
+ # Set (to the reason) only when the server's certificate was rejected: system clock, antivirus
194
+ # HTTPS scanning, captive portal or missing CA certificates. Other TLS errors, such as a handshake
195
+ # cut off by a middlebox, stay unflagged because they can be the provider's route.
196
+ self.cert_error = cert_error
197
+
198
+
199
+ def http_get_json(url: str, timeout: float = HTTP_TIMEOUT_S) -> tuple[Any, float]:
200
+ req = urllib.request.Request( # noqa: S310 - only the constant https URLs above
201
+ url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"}
202
+ )
203
+ t0 = time.perf_counter()
204
+ try:
205
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - constant https URLs
206
+ body = resp.read(MAX_BODY_BYTES + 1)
207
+ except urllib.error.HTTPError as exc:
208
+ raise HttpFailure(f"HTTP {exc.code}", status=exc.code) from exc
209
+ except urllib.error.URLError as exc:
210
+ reason = exc.reason
211
+ cert = None
212
+ if isinstance(reason, ssl.SSLCertVerificationError):
213
+ cert = _clip(getattr(reason, "verify_message", None) or "") or "certificate verify failed"
214
+ raise HttpFailure(short_error(reason), cert_error=cert) from exc
215
+ except (OSError, http.client.HTTPException) as exc: # e.g. the link drops while reading the body
216
+ raise HttpFailure(short_error(exc)) from exc
217
+ ms = (time.perf_counter() - t0) * 1000
218
+ if len(body) > MAX_BODY_BYTES:
219
+ raise HttpFailure(Msg("error.too_big"), status=200)
220
+ try:
221
+ return json.loads(body), ms
222
+ except (ValueError, RecursionError) as exc: # RecursionError: nesting deeper than the parser's stack
223
+ raise HttpFailure(Msg("error.not_json"), status=200) from exc
224
+
225
+
226
+ def parallel[T, R](func: Callable[[T], R], items: Iterable[T], workers: int = 16) -> list[R]:
227
+ items = list(items)
228
+ if not items:
229
+ return []
230
+ with ThreadPoolExecutor(max_workers=min(workers, len(items))) as pool:
231
+ return list(pool.map(func, items))
232
+
233
+
234
+ def fmt_ms(ms: float) -> str:
235
+ return "<1 ms" if ms < 1 else f"{ms:.0f} ms"
236
+
237
+
238
+ # --------------------------------------------------------------------------- #
239
+ # 1. Internet
240
+ # --------------------------------------------------------------------------- #
241
+ def check_internet(ctx: Context) -> CheckResult:
242
+ results = parallel(lambda p: tcp_probe(p[0], p[1]), INTERNET_PROBES)
243
+ details: list[str] = []
244
+ ok: list[float] = []
245
+ for (ip, port, name), (ms, err) in zip(INTERNET_PROBES, results):
246
+ if ms is None:
247
+ details.append(Msg("check.probe_failed", target=f"{name} ({ip}:{port})", error=err))
248
+ else:
249
+ details.append(f"{name} ({ip}:{port}) — {fmt_ms(ms)}")
250
+ ok.append(ms)
251
+
252
+ ctx.internet_ok = bool(ok)
253
+ if not ok:
254
+ return CheckResult("internet", Status.FAIL, Msg("check.internet.fail"), details)
255
+ return CheckResult(
256
+ "internet",
257
+ Status.OK,
258
+ Msg("check.internet.ok", ok=len(ok), total=len(INTERNET_PROBES), ms=fmt_ms(min(ok))),
259
+ details,
260
+ latency_ms=min(ok),
261
+ )
262
+
263
+
264
+ # --------------------------------------------------------------------------- #
265
+ # 2. DNS
266
+ # --------------------------------------------------------------------------- #
267
+ def _resolve(name: str) -> tuple[str | None, float | None, str | None]:
268
+ t0 = time.perf_counter()
269
+ try:
270
+ infos = socket.getaddrinfo(name, 443, socket.AF_INET, socket.SOCK_STREAM)
271
+ except OSError as exc:
272
+ return None, None, short_error(exc)
273
+ return infos[0][4][0], (time.perf_counter() - t0) * 1000, None
274
+
275
+
276
+ def check_dns(ctx: Context) -> CheckResult:
277
+ names = STEAM_DNS_NAMES + OTHER_DNS_NAMES
278
+ results = parallel(_resolve, names)
279
+ details: list[str] = []
280
+ failed: list[str] = []
281
+ times: list[float] = []
282
+ for name, (ip, ms, err) in zip(names, results):
283
+ if ip is None:
284
+ failed.append(name)
285
+ details.append(Msg("check.dns.name_failed", name=name, error=err))
286
+ else:
287
+ times.append(ms or 0.0)
288
+ details.append(f"{name} → {ip} ({fmt_ms(ms or 0.0)})")
289
+
290
+ steam_failed = any(n in failed for n in STEAM_DNS_NAMES)
291
+ if len(failed) == len(names):
292
+ return CheckResult("dns", Status.FAIL, Msg("check.dns.fail"), details, data={"steam_dns_fail": True})
293
+ if failed:
294
+ return CheckResult(
295
+ "dns",
296
+ Status.WARN,
297
+ Msg("check.dns.some_failed", names=", ".join(failed)),
298
+ details,
299
+ data={"steam_dns_fail": steam_failed},
300
+ )
301
+ return CheckResult("dns", Status.OK, Msg("check.dns.ok", ms=fmt_ms(max(times))), details,
302
+ latency_ms=max(times))
303
+
304
+
305
+ # --------------------------------------------------------------------------- #
306
+ # 3. Steam Web API
307
+ # --------------------------------------------------------------------------- #
308
+ def check_steam_api(ctx: Context) -> CheckResult:
309
+ try:
310
+ data, ms = http_get_json(CM_LIST_URL)
311
+ except HttpFailure as exc:
312
+ if exc.status is not None:
313
+ # We reached Valve, but Valve answered with an error.
314
+ return CheckResult(
315
+ "steam_api",
316
+ Status.WARN,
317
+ Msg("check.steam_api.server_error", error=exc.message),
318
+ [CM_LIST_URL],
319
+ data={"reached": True, "server_error": True},
320
+ )
321
+ if exc.cert_error:
322
+ # The certificate presented for Valve's name was rejected, so we can't tell whether Valve was
323
+ # reached at all. Usually the PC or a captive portal, not the provider's route.
324
+ return CheckResult(
325
+ "steam_api",
326
+ Status.FAIL,
327
+ Msg("check.steam_api.cert_error", error=exc.message),
328
+ [CM_LIST_URL, Msg("check.steam_api.certificate", reason=exc.cert_error)],
329
+ data={"reached": False, "cert_error": True},
330
+ )
331
+ return CheckResult(
332
+ "steam_api",
333
+ Status.FAIL,
334
+ Msg("check.steam_api.unreachable", error=exc.message),
335
+ [CM_LIST_URL],
336
+ data={"reached": False},
337
+ )
338
+
339
+ response = data.get("response") if isinstance(data, dict) else None
340
+ servers = response.get("serverlist") if isinstance(response, dict) else None
341
+ servers = [s for s in servers if isinstance(s, dict)] if isinstance(servers, list) else []
342
+ if not servers:
343
+ return CheckResult(
344
+ "steam_api",
345
+ Status.WARN,
346
+ Msg("check.steam_api.empty"),
347
+ data={"reached": True, "server_error": True},
348
+ )
349
+
350
+ ctx.cm_servers = servers
351
+ dcs: list[str] = []
352
+ for s in servers:
353
+ dc = _valve_text(s.get("dc"))
354
+ if dc and dc not in dcs:
355
+ dcs.append(dc)
356
+ if len(dcs) == SHOWN_DATA_CENTERS: # all that is shown; a longer search is wasted (rule 3)
357
+ break
358
+ return CheckResult(
359
+ "steam_api",
360
+ Status.OK,
361
+ Msg("check.steam_api.ok", ms=fmt_ms(ms), count=len(servers)),
362
+ [Msg("check.steam_api.data_centers", dcs=", ".join(dcs))] if dcs else [],
363
+ latency_ms=ms,
364
+ data={"reached": True},
365
+ )
366
+
367
+
368
+ # --------------------------------------------------------------------------- #
369
+ # 4. Steam login (CM) servers
370
+ # --------------------------------------------------------------------------- #
371
+ def pick_cm_targets(servers: list[dict[str, Any]], limit: int = CM_TARGETS) -> list[tuple[str, int, str]]:
372
+ websockets = [s for s in servers if s.get("type") == "websockets"]
373
+ pool = websockets or servers
374
+ out: list[tuple[str, int, str]] = []
375
+ for s in pool:
376
+ endpoint = _valve_text(s.get("endpoint"), MAX_HOSTNAME_CHARS + 7) # host, trailing ".", ":", port
377
+ host, sep, port = (endpoint or "").rpartition(":")
378
+ host = _host(host) if sep and host else None
379
+ # ASCII digits only: "²".isdigit() is true, but int("²") raises.
380
+ if not host or not (port.isascii() and port.isdigit() and 0 < int(port) <= 65535):
381
+ continue
382
+ out.append((host, int(port), _valve_text(s.get("dc")) or "?"))
383
+ if len(out) >= limit:
384
+ break
385
+ return out
386
+
387
+
388
+ def check_steam_cm(ctx: Context) -> CheckResult:
389
+ targets = pick_cm_targets(ctx.cm_servers)
390
+ fallback = not targets
391
+ if fallback:
392
+ targets = STEAM_FALLBACK_HOSTS
393
+
394
+ results = parallel(lambda t: tcp_probe(t[0], t[1]), targets)
395
+ details: list[str] = []
396
+ ok: list[float] = []
397
+ for (host, port, dc), (ms, err) in zip(targets, results):
398
+ label = f"{host}:{port} [{dc}]"
399
+ if ms is None:
400
+ details.append(Msg("check.probe_failed", target=label, error=err))
401
+ else:
402
+ ok.append(ms)
403
+ details.append(f"{label} — {fmt_ms(ms)}")
404
+ if fallback:
405
+ details.insert(0, Msg("check.steam_cm.fallback"))
406
+
407
+ n_ok, n = len(ok), len(targets)
408
+ data = {"fallback": fallback, "ok": n_ok, "total": n}
409
+ # Separate keys for the login and the web servers: a language inflects the words around them differently.
410
+ if n_ok == 0:
411
+ summary = Msg("check.steam_cm.web_fail") if fallback else Msg("check.steam_cm.fail")
412
+ return CheckResult("steam_cm", Status.FAIL, summary, details, data=data)
413
+ median = statistics.median(ok)
414
+ if n_ok * 2 >= n:
415
+ shown = fmt_ms(median)
416
+ summary = (Msg("check.steam_cm.web_ok", ok=n_ok, total=n, ms=shown) if fallback
417
+ else Msg("check.steam_cm.ok", ok=n_ok, total=n, ms=shown))
418
+ return CheckResult("steam_cm", Status.OK, summary, details, latency_ms=median, data=data)
419
+ return CheckResult("steam_cm", Status.WARN, Msg("check.steam_cm.partial", ok=n_ok, total=n), details,
420
+ latency_ms=median, data=data)
421
+
422
+
423
+ # --------------------------------------------------------------------------- #
424
+ # 5. Dota 2 Game Coordinator (indirect, through the Web API)
425
+ # --------------------------------------------------------------------------- #
426
+ GC_VERSION_MAX_CHARS = 20 # Valve's version is a number; anything longer is not one
427
+
428
+
429
+ def _gc_note() -> list[str]:
430
+ # Made on every call, not once at import, so it is in the language of the run.
431
+ return [Msg("check.dota_gc.note")]
432
+
433
+
434
+ def _gc_version(result: dict[str, Any]) -> str | None:
435
+ """Valve's GC version as short text, or None when it is missing or not a number / short string."""
436
+ for name in ("active_version", "deploy_version"):
437
+ value = result.get(name)
438
+ if not value or isinstance(value, bool): # 0 / "" mean "no version": try the next one
439
+ continue
440
+ text = _valve_text(str(value) if isinstance(value, int) else value, GC_VERSION_MAX_CHARS)
441
+ if text:
442
+ return text
443
+ return None
444
+
445
+
446
+ def check_dota_gc(ctx: Context) -> CheckResult:
447
+ try:
448
+ data, ms = http_get_json(GC_VERSION_URL)
449
+ except HttpFailure as exc:
450
+ if exc.status is not None and exc.status >= 500:
451
+ return CheckResult("dota_gc", Status.FAIL, Msg("check.dota_gc.down", error=exc.message),
452
+ _gc_note(), data={"gc_down": True})
453
+ # 4xx, bad JSON or a network error: we can't judge.
454
+ return CheckResult("dota_gc", Status.SKIP, Msg("check.dota_gc.unknown", error=exc.message), _gc_note(),
455
+ data={"unknown": True})
456
+
457
+ result = data.get("result") if isinstance(data, dict) else None
458
+ if not isinstance(result, dict) or "success" not in result:
459
+ return CheckResult("dota_gc", Status.SKIP, Msg("check.dota_gc.bad_answer"),
460
+ _gc_note(), data={"unknown": True})
461
+ if result.get("success") is not True:
462
+ return CheckResult("dota_gc", Status.FAIL, Msg("check.dota_gc.down", error="success = false"),
463
+ _gc_note(), data={"gc_down": True})
464
+
465
+ version = _gc_version(result)
466
+ summary = (Msg("check.dota_gc.ok_version", ms=fmt_ms(ms), version=version) if version
467
+ else Msg("check.dota_gc.ok", ms=fmt_ms(ms)))
468
+ return CheckResult("dota_gc", Status.OK, summary, _gc_note(), latency_ms=ms)
469
+
470
+
471
+ # --------------------------------------------------------------------------- #
472
+ # 6. Valve game network (SDR relays): ping, packet loss, jitter
473
+ # --------------------------------------------------------------------------- #
474
+ def parse_sdr_pops(cfg: Any) -> list[Pop]:
475
+ """Valve's relay sites with one IPv4 address each. Entries of the wrong type are skipped, not trusted."""
476
+ pops = cfg.get("pops") if isinstance(cfg, dict) else None
477
+ if not isinstance(pops, dict):
478
+ return []
479
+ out: list[Pop] = []
480
+ for key, pop in pops.items():
481
+ code = _valve_text(key)
482
+ relays = pop.get("relays") if isinstance(pop, dict) else None
483
+ if not code or not isinstance(relays, list):
484
+ continue
485
+ # A strict address, or the site is skipped: one that can't be pinged would look like a routing problem.
486
+ ip = next((addr for r in relays if isinstance(r, dict) and (addr := _ipv4(r.get("ipv4")))), None)
487
+ if ip:
488
+ out.append(Pop(code, _valve_text(pop.get("desc")) or code, ip))
489
+ return out
490
+
491
+
492
+ @dataclass
493
+ class Quality:
494
+ pop: Pop
495
+ sent: int
496
+ received: int
497
+ avg_ms: float | None
498
+ jitter_ms: float | None
499
+
500
+ @property
501
+ def loss_pct(self) -> float:
502
+ return 100.0 * (self.sent - self.received) / self.sent if self.sent else 0.0
503
+
504
+
505
+ def measure_quality(pop: Pop, count: int = QUALITY_PINGS) -> Quality:
506
+ rtts = icmp.ping_series(pop.ip, count)
507
+ got = [r for r in rtts if r is not None]
508
+ avg = statistics.fmean(got) if got else None
509
+ jitter = statistics.fmean(abs(a - b) for a, b in pairwise(got)) if len(got) >= 2 else None
510
+ return Quality(pop, count, len(got), avg, jitter)
511
+
512
+
513
+ def check_relays(ctx: Context) -> CheckResult:
514
+ try:
515
+ cfg, _ = http_get_json(SDR_CONFIG_URL)
516
+ except HttpFailure as exc:
517
+ return CheckResult("relays", Status.SKIP, Msg("check.relays.list_failed", error=exc.message))
518
+ pops = parse_sdr_pops(cfg)
519
+ if not pops:
520
+ return CheckResult("relays", Status.SKIP, Msg("check.relays.empty"))
521
+ if len(pops) > MAX_POPS:
522
+ return CheckResult("relays", Status.SKIP, Msg("check.relays.list_failed", error=Msg("error.too_big")))
523
+
524
+ control = parallel(icmp.ping, CONTROL_PING_IPS)
525
+ first = parallel(lambda p: icmp.ping(p.ip), pops, workers=24)
526
+ rtt = dict(zip(pops, first))
527
+ missing = [p for p in pops if rtt[p] is None]
528
+ for pop, value in zip(missing, parallel(lambda p: icmp.ping(p.ip), missing, workers=24)):
529
+ rtt[pop] = value
530
+
531
+ responding = sorted((p for p in pops if rtt[p] is not None), key=lambda p: rtt[p])
532
+ control_ok = any(c is not None for c in control)
533
+ if not responding:
534
+ if control_ok:
535
+ return CheckResult(
536
+ "relays",
537
+ Status.WARN,
538
+ Msg("check.relays.routing"),
539
+ [Msg("check.relays.checked", count=len(pops))],
540
+ data={"routing": True},
541
+ )
542
+ return CheckResult(
543
+ "relays",
544
+ Status.SKIP,
545
+ Msg("check.relays.icmp_blocked"),
546
+ data={"icmp_blocked": True},
547
+ )
548
+
549
+ details: list[str] = [f"{p.desc} ({p.code}) — {fmt_ms(rtt[p] or 0.0)}" for p in responding[:6]]
550
+ details.append(Msg("check.relays.responded", ok=len(responding), total=len(pops)))
551
+
552
+ quality = parallel(measure_quality, responding[:QUALITY_POPS])
553
+ for q in quality:
554
+ avg = fmt_ms(q.avg_ms) if q.avg_ms is not None else "—"
555
+ jit = fmt_ms(q.jitter_ms) if q.jitter_ms is not None else "—"
556
+ details.append(
557
+ Msg("check.relays.quality", pop=q.pop.desc, sent=q.sent, loss=q.loss_pct, avg=avg, jitter=jit)
558
+ )
559
+
560
+ total_sent = sum(q.sent for q in quality)
561
+ total_recv = sum(q.received for q in quality)
562
+ loss = 100.0 * (total_sent - total_recv) / total_sent if total_sent else 0.0
563
+ best = min((q for q in quality if q.avg_ms is not None), key=lambda q: q.avg_ms or 0.0, default=None)
564
+ best_ms = best.avg_ms if best and best.avg_ms is not None else (rtt[responding[0]] or 0.0)
565
+ best_name = best.pop.desc if best else responding[0].desc
566
+ jitters = [q.jitter_ms for q in quality if q.jitter_ms is not None]
567
+ jitter = min(jitters) if jitters else 0.0
568
+ data = {"loss": round(loss, 1), "best_ms": round(best_ms, 1), "jitter": round(jitter, 1)}
569
+
570
+ if loss > LOSS_WARN_PCT:
571
+ return CheckResult("relays", Status.WARN, Msg("check.relays.lossy", loss=loss),
572
+ details, latency_ms=best_ms, data=data | {"lossy": True})
573
+ if best_ms > HIGH_PING_MS:
574
+ return CheckResult("relays", Status.WARN, Msg("check.relays.high_ping", ms=fmt_ms(best_ms), pop=best_name),
575
+ details, latency_ms=best_ms, data=data | {"high_ping": True})
576
+ if jitter > JITTER_WARN_MS:
577
+ return CheckResult("relays", Status.WARN, Msg("check.relays.jittery", ms=fmt_ms(jitter)),
578
+ details, latency_ms=best_ms, data=data | {"jittery": True})
579
+ return CheckResult(
580
+ "relays",
581
+ Status.OK,
582
+ Msg("check.relays.ok", pop=best_name, ms=fmt_ms(best_ms), loss=loss),
583
+ details,
584
+ latency_ms=best_ms,
585
+ data=data,
586
+ )
587
+
588
+
589
+ # --------------------------------------------------------------------------- #
590
+ # Runner
591
+ # --------------------------------------------------------------------------- #
592
+ @dataclass(frozen=True)
593
+ class CheckSpec:
594
+ key: str
595
+ title_key: str # i18n keys; `title` and `hint` look them up in the language current when they are read
596
+ hint_key: str
597
+ func: Callable[[Context], CheckResult]
598
+
599
+ @property
600
+ def title(self) -> str:
601
+ return Msg(self.title_key) # a Msg, so `CheckResult.title` can be shown again in another language
602
+
603
+ @property
604
+ def hint(self) -> str:
605
+ return Msg(self.hint_key)
606
+
607
+
608
+ CHECKS: list[CheckSpec] = [
609
+ CheckSpec("internet", "check.internet.title", "check.internet.hint", check_internet),
610
+ CheckSpec("dns", "check.dns.title", "check.dns.hint", check_dns),
611
+ CheckSpec("steam_api", "check.steam_api.title", "check.steam_api.hint", check_steam_api),
612
+ CheckSpec("steam_cm", "check.steam_cm.title", "check.steam_cm.hint", check_steam_cm),
613
+ CheckSpec("dota_gc", "check.dota_gc.title", "check.dota_gc.hint", check_dota_gc),
614
+ CheckSpec("relays", "check.relays.title", "check.relays.hint", check_relays),
615
+ ]
616
+
617
+
618
+ def run_checks(
619
+ on_start: Callable[[CheckSpec], None] | None = None,
620
+ on_result: Callable[[CheckResult], None] | None = None,
621
+ ) -> dict[str, CheckResult]:
622
+ ctx = Context()
623
+ results: dict[str, CheckResult] = {}
624
+ for spec in CHECKS:
625
+ if on_start:
626
+ on_start(spec)
627
+ if not ctx.internet_ok:
628
+ res = CheckResult(spec.key, Status.SKIP, Msg("check.skipped_no_internet"))
629
+ else:
630
+ try:
631
+ res = spec.func(ctx)
632
+ except Exception as exc: # noqa: BLE001 - a bug in a check must not kill the run
633
+ res = CheckResult(spec.key, Status.SKIP, Msg("check.internal_error", error=short_error(exc)))
634
+ res.title = spec.title
635
+ results[spec.key] = res
636
+ if on_result:
637
+ on_result(res)
638
+ return results