okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ok-refused 5fdb9aa4a into f-own-intc7ec1e8fe

main
25.6 KiB528 linesraw
1"""One rule for every network call on the install -> update -> launch path (lane NET, owner rules: offline users, no silent waits).
2
3Many people run Strata fully local or behind a network that drops packets without refusing them (a firewall, a black-holed route, a
4broken proxy). There a plain ``urlopen(timeout=60)`` waits a minute per try and setup tried five times per file: 320 s with nothing on
5the screen. The rule here:
6
71. The *connection phase* - name lookup, TCP connect, TLS handshake, a proxy's CONNECT and the wait for the server's first answer (its
8   headers) - gets at most ``FIRST_CONNECT_S`` on the first try and ``RETRY_CONNECT_S`` on the one retry (``CONNECT_LIMITS``). The
9   name lookup runs in a helper thread, because ``getaddrinfo`` itself has no timeout.
102. No retry and no wait when the answer is already clear: no such host (no DNS answer), connection refused, network or host
11   unreachable, a refused certificate, an HTTP error other than 408/429/5xx.
123. One retry, ``RETRY_GAP_S`` later, for a timeout, a reset before the first byte, or HTTP 408/429/5xx. A host that never answers is
13   given up after about 12 + 2 + 30 = 44 s.
144. A host given up under rule 3 after the whole window (12 s, then 30 s) is not tried again for ``HOST_MEMORY_S`` *in the same process*
15   (``HOSTS``, memory only, never on disk (a refusal: rule 4b); a call with shorter limits reads it but never writes it;
16   a new run always tries afresh). The next file from it fails at once with the same message.
174b. A host that REFUSED the connection (connection refused: a proxy that is set but not running, a firewall that resets) is the one
18   exception kept across runs: Windows needs about 2 s to report a refusal, and a launch reads the feed on every start. Its host:port
19   and the time are written to a small note in Strata's own state folder (RefusalNote, REFUSED_NOTE_S = 6 hours; nothing
20   else is written). Only automatic reads (open_url(..., automatic=True): the launch's check for a newer engine of a model's own
21   shape while one is installed) read it and fail at once with the "offline" words. Every read the person asked for by name
22   (strata update, setup, a download) ignores it and tries. The first success from that host removes it. A damaged or unreadable
23   note counts as no note, without a message.
245. Once the answer has come, a read that gets no byte for ``STALL_S`` ends that connection (the caller resumes from the byte it
25   reached). A download stops only after ``GIVE_UP_S`` in a row without a new byte (``StallClock``); there is no total time cap, so a
26   slow link that works keeps working.
276. When the connection phase has not ended after ``WAIT_LINE_AFTER_S``, a line names the host (``WaitLine``), again every
28   ``WAIT_LINE_EVERY_S``.
29
30The words people read are in ``WORDS`` (one place, so a wording change is one edit). Proxy settings (HTTPS_PROXY, the system's) work
31as with ``urllib.request.urlopen``: only the connection class differs.
32"""
33
34from __future__ import annotations
35
36import errno
37import http.client
38import json
39import re
40import socket
41import ssl
42import sys
43import threading
44import time
45import urllib.error
46import urllib.parse
47import urllib.request
48from pathlib import Path
49from typing import Callable, Iterable
50
51FIRST_CONNECT_S = 12.0      # first try: measured, one github.com request in 25 hung while the next answered in 0.5 s
52RETRY_CONNECT_S = 30.0      # the one retry
53CONNECT_LIMITS = (FIRST_CONNECT_S, RETRY_CONNECT_S)
54RETRY_GAP_S = 2.0
55STALL_S = 60.0              # no byte for this long ends one connection (the download resumes)
56GIVE_UP_S = 300.0           # no new byte for this long, across every try, ends the download
57WAIT_LINE_AFTER_S = 5.0
58WAIT_LINE_EVERY_S = 10.0
59HOST_MEMORY_S = 600.0
60REFUSED_NOTE_S = 6 * 3600.0     # rule 4b: a refused host is not asked again by an automatic read for this long
61REFUSED_NOTE_NAME = "refused-hosts.json"
62RETRY_HTTP = (408, 429, 500, 502, 503, 504)
63
64# The words. {host} is a host name, {seconds} a whole number, {what} what was being fetched ("the picture reader").
65WORDS = {
66    "waiting": "Waiting for {host} to answer ({seconds} s so far)",
67    "no_answer": "{host} did not answer within {seconds} seconds, so {what} could not be downloaded.",
68    "offline": "This computer could not connect to {host} (it looks offline), so {what} could not be downloaded.",
69    "again": "{host} did not answer a moment ago either, so {what} could not be downloaded.",
70    "next": ("Check that this computer can open https://{host}, then run the same command again: what is already downloaded is kept. "
71             "Models that are already on this computer still start without the internet."),
72    "stalled": "No data arrived for {minutes} minutes, so the download of {what} stopped at {percent}%.",
73    "stalled_next": "Run the same command again: it continues where it stopped.",
74    "update_no_answer": ("{host} did not answer within {seconds} seconds, so the update check could not run. Check that this computer can open "
75                         "https://{host}, then try again. Strata keeps working with what is installed."),
76    # (W7's two companions, owner 11-10)
77    "update_offline": "this computer could not connect to {host} (it looks offline), so the update check could not run. Strata keeps working with what is installed.",
78    "update_again": "{host} did not answer a moment ago, so the update check was not tried again. Strata keeps working with what is installed.",
79}
80
81#: the waiting line as setup prints it ("  Waiting for github.com to answer (15 s so far) ..."), for the progress readers
82WAITING_RE = re.compile(r"^\s*Waiting for (?P<host>\S+) to answer \((?P<seconds>\d+) s so far\)")
83
84
85def what_words(label: str | None, name: str | None = None) -> str:
86    """What a download is, in the words of a failure message: setup's internal labels become plain words."""
87    low = (label or "").lower()
88    if not label:
89        return "the model files"
90    if "vision" in low or "picture" in low or "mmproj" in low:
91        return "the picture reader"
92    if "llama.cpp" in low:
93        return "the tools that prepare models"
94    if low.startswith(("the ", "a ")):
95        return label
96    if "engine" in low:
97        return "the " + label
98    return label
99
100
101def host_of(url: str) -> str:
102    try:
103        return (urllib.parse.urlsplit(url).hostname or "").lower() or url
104    except ValueError:
105        return url
106
107
108# ------------------------------------------------------------------------------------------------ what went wrong
109
110def kind(exc: BaseException | None) -> str:
111    """'http' (an HTTP answer), 'http_retry' (408/429/5xx), 'cert', 'offline' (no DNS answer, refused, unreachable: clear at once),
112    'no_answer' (a timeout), 'retry' (a reset or a dropped connection before the answer), or 'other'."""
113    if exc is None:
114        return "other"
115    if isinstance(exc, urllib.error.HTTPError):
116        return "http_retry" if exc.code in RETRY_HTTP else "http"
117    from strata_control import tls
118    if tls.is_certificate_error(exc):
119        return "cert"
120    seen = 0
121    while isinstance(exc, urllib.error.URLError) and isinstance(getattr(exc, "reason", None), BaseException) and seen < 4:
122        exc = exc.reason
123        seen += 1
124    if isinstance(exc, urllib.error.URLError):          # a reason that is only text: "timed out" is a timeout, other text is unclear
125        return "no_answer" if "timed out" in str(exc.reason).lower() else "other"
126    if isinstance(exc, socket.gaierror) or isinstance(exc, ConnectionRefusedError):
127        return "offline"
128    if isinstance(exc, OSError) and exc.errno in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN):
129        return "offline"
130    if isinstance(exc, (TimeoutError, socket.timeout)):
131        return "no_answer"
132    if isinstance(exc, ssl.SSLError) and "timed out" in str(exc).lower():
133        return "no_answer"
134    if isinstance(exc, (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, http.client.HTTPException)):
135        return "retry"
136    return "other"
137
138
139class NetFailure(OSError):
140    """A host could not be reached under the rule: `kind` is 'no_answer', 'offline' or 'again' (given up earlier in this run).
141    `seconds` is how long this call waited. str() is the plain headline with `what` = "the download"."""
142
143    def __init__(self, host: str, kind_: str, cause: BaseException | None = None, seconds: float = 0.0):
144        self.host, self.kind, self.cause, self.seconds = host, kind_, cause, seconds
145        super().__init__(self.headline("the download"))
146
147    def headline(self, what: str) -> str:
148        key = {"offline": "offline", "again": "again"}.get(self.kind, "no_answer")
149        return WORDS[key].format(host=self.host, what=what, seconds=max(1, int(round(self.seconds))))
150
151    def next_step(self) -> str:
152        return WORDS["next"].format(host=self.host)
153
154    def detail(self) -> str:
155        """The raw reason, for a log or a Details line only."""
156        c = self.cause
157        return f"{type(c).__name__}: {getattr(c, 'reason', c)}" if c is not None else ""
158
159
160# ------------------------------------------------------------------------------------------------ host memory (rule 4)
161
162class HostMemory:
163    """Hosts that did not answer (rule 3), kept in this process's memory only for `HOST_MEMORY_S`. Nothing is written to disk."""
164
165    def __init__(self, clock: Callable[[], float] = time.monotonic, keep: float | None = None):
166        self._clock, self._keep = clock, keep
167        self._failed: dict[str, float] = {}
168        self._lock = threading.Lock()
169
170    def remember(self, host: str) -> None:
171        with self._lock:
172            self._failed[host] = self._clock()
173
174    def forget(self, host: str | None = None) -> None:
175        with self._lock:
176            if host is None:
177                self._failed.clear()
178            else:
179                self._failed.pop(host, None)
180
181    def failed_recently(self, host: str) -> bool:
182        keep = HOST_MEMORY_S if self._keep is None else self._keep
183        with self._lock:
184            at = self._failed.get(host)
185            if at is None:
186                return False
187            if self._clock() - at >= keep:
188                self._failed.pop(host, None)
189                return False
190            return True
191
192
193HOSTS = HostMemory()
194
195
196def refused(exc: BaseException | None) -> bool:
197    """True when the connection was refused (ConnectionRefusedError, also inside a URLError)."""
198    seen = 0
199    while isinstance(exc, urllib.error.URLError) and isinstance(getattr(exc, "reason", None), BaseException) and seen < 4:
200        exc = exc.reason
201        seen += 1
202    return isinstance(exc, ConnectionRefusedError)
203
204
205class RefusalNote:
206    """Rule 4b: the hosts that refused a connection, on disk (host:port -> the time, seconds since the epoch), kept for REFUSED_NOTE_S.
207    The note lives in Strata's own state folder (strata_control/paths.state_base, read when it is used, so a test HOME redirects it).
208    Every failure to read or write it is silent: a damaged note is no note, an unwritable one is simply not kept."""
209
210    def __init__(self, path: Path | None = None, clock: Callable[[], float] = time.time, keep: float | None = None):
211        self._path, self._clock, self._keep = path, clock, keep
212        self._lock = threading.Lock()
213
214    def path(self) -> Path:
215        if self._path is not None:
216            return Path(self._path)
217        from strata_control import paths
218        return paths.state_base() / "net" / REFUSED_NOTE_NAME
219
220    def _load(self) -> dict[str, float]:
221        try:
222            data = json.loads(self.path().read_text(encoding="utf-8"))
223        except (OSError, ValueError, UnicodeDecodeError):
224            return {}
225        if not isinstance(data, dict):
226            return {}
227        return {str(k): float(v) for k, v in data.items() if isinstance(k, str) and isinstance(v, (int, float)) and not isinstance(v, bool)}
228
229    def _save(self, data: dict[str, float]) -> None:
230        try:
231            p = self.path()
232            if not data:
233                p.unlink(missing_ok=True)
234                return
235            p.parent.mkdir(parents=True, exist_ok=True)
236            from strata_control import atomic
237            atomic.write_text(p, json.dumps(data, sort_keys=True))
238        except OSError:
239            pass
240
241    def refused_recently(self, key: str) -> bool:
242        keep = REFUSED_NOTE_S if self._keep is None else self._keep
243        with self._lock:
244            at = self._load().get(key)
245            return at is not None and 0 <= self._clock() - at < keep
246
247    def remember(self, key: str) -> None:
248        keep = REFUSED_NOTE_S if self._keep is None else self._keep
249        with self._lock:
250            now = self._clock()
251            data = {k: v for k, v in self._load().items() if 0 <= now - v < keep}     # expired entries go when the note is written
252            data[key] = now
253            self._save(data)
254
255    def forget(self, key: str) -> None:
256        with self._lock:
257            try:
258                if not self.path().is_file():
259                    return                               # the usual case: no note at all, nothing is written
260            except OSError:
261                return
262            data = self._load()
263            if key in data:
264                data.pop(key)
265                self._save(data)
266
267
268REFUSALS = RefusalNote()
269
270
271# ------------------------------------------------------------------------------------------------ the waiting line (rule 6)
272
273class WaitLine:
274    """While the block runs: after `after` seconds call say(line) naming the host, then every `every` seconds with the time so far."""
275
276    def __init__(self, host: str, say: Callable[[str], None] | None, after: float | None = None, every: float | None = None,
277                 clock: Callable[[], float] = time.monotonic):
278        self.host, self.say, self.clock = host, say, clock
279        self.after = WAIT_LINE_AFTER_S if after is None else after
280        self.every = WAIT_LINE_EVERY_S if every is None else every
281        self._stop = threading.Event()
282        self._thread: threading.Thread | None = None
283        self.said = 0
284
285    def _run(self) -> None:
286        start = self.clock()
287        if self._stop.wait(self.after):
288            return
289        while not self._stop.is_set():
290            try:
291                self.say(WORDS["waiting"].format(host=self.host, seconds=int(self.clock() - start)))   # type: ignore[misc]
292                self.said += 1
293            except Exception:                                    # noqa: BLE001 - a line that cannot be shown never stops a download
294                pass
295            if self._stop.wait(self.every):
296                return
297
298    def __enter__(self) -> "WaitLine":
299        if self.say is not None:
300            self._thread = threading.Thread(target=self._run, daemon=True, name=f"wait-{self.host}")
301            self._thread.start()
302        return self
303
304    def __exit__(self, *exc) -> bool:
305        self._stop.set()
306        if self._thread is not None:
307            self._thread.join(1.0)
308        return False
309
310
311# ------------------------------------------------------------------------------------------------ the connection phase (rule 1)
312
313def _bounded_getaddrinfo(host: str, port: int, limit: float) -> list:
314    """getaddrinfo has no timeout of its own: a resolver that never answers would hold the call for as long as the system says.
315    It runs in a helper thread here, given up after `limit` seconds (the thread ends by itself later)."""
316    box: dict = {}
317
318    def look() -> None:
319        try:
320            box["infos"] = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
321        except BaseException as exc:                             # noqa: BLE001 - handed to the caller
322            box["error"] = exc
323    t = threading.Thread(target=look, daemon=True, name=f"dns-{host}")
324    t.start()
325    t.join(limit)
326    if t.is_alive():
327        raise TimeoutError(f"no answer to the name lookup of {host} within {limit:.0f} s")
328    if "error" in box:
329        raise box["error"]
330    return box["infos"]
331
332
333def _numeric(timeout) -> float | None:
334    return float(timeout) if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) and timeout > 0 else None
335
336
337def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, *args, **kwargs):  # type: ignore[attr-defined]
338    """socket.create_connection with the whole of DNS + connect bounded by `timeout` (a deadline, not a limit per step). The socket is
339    returned with the time that is left as its timeout, so the TLS handshake and the wait for the answer fit in the same deadline."""
340    limit = _numeric(timeout)
341    if limit is None:
342        return socket.create_connection(address, timeout, source_address)
343    deadline = time.monotonic() + limit
344    host, port = address[0], address[1]
345    infos = _bounded_getaddrinfo(host, port, limit)
346    last: BaseException | None = None
347    for af, socktype, proto, _canon, sa in infos:
348        left = deadline - time.monotonic()
349        if left <= 0:
350            break
351        try:                                                     # through socket.create_connection (a numeric address: no second lookup)
352            sock = socket.create_connection(sa[:2], left, source_address)
353            sock.settimeout(max(0.05, deadline - time.monotonic()))
354            return sock
355        except OSError as exc:
356            last = exc
357    if last is not None and not isinstance(last, (TimeoutError, socket.timeout)):
358        raise last
359    raise TimeoutError(f"{host} did not accept a connection within {limit:.0f} s")
360
361
362class _Bounded:
363    """Mixed into http.client's connection classes: the connection phase ends at a deadline (`timeout` seconds after connect() began,
364    covering the answer's headers too); after the answer the socket gets `stall` (rule 5)."""
365    stall: float = STALL_S
366
367    def _bounded_init(self) -> None:
368        self._create_connection = create_connection             # type: ignore[attr-defined]
369        self._deadline = None
370
371    def connect(self):                                           # type: ignore[override]
372        limit = _numeric(self.timeout)                           # type: ignore[attr-defined]
373        self._deadline = time.monotonic() + limit if limit else None
374        super().connect()                                        # type: ignore[misc]
375        if self._deadline is not None and self.sock is not None:  # type: ignore[attr-defined]
376            self.sock.settimeout(max(0.05, self._deadline - time.monotonic()))     # type: ignore[attr-defined]
377
378    def getresponse(self):                                       # type: ignore[override]
379        sock = self.sock                                         # type: ignore[attr-defined]
380        response = super().getresponse()                         # type: ignore[misc]
381        if self._deadline is not None and sock is not None:
382            try:
383                sock.settimeout(self.stall)
384            except OSError:
385                pass
386        return response
387
388
389class BoundedHTTPConnection(_Bounded, http.client.HTTPConnection):
390    def __init__(self, *a, **k):
391        super().__init__(*a, **k)
392        self._bounded_init()
393
394
395class BoundedHTTPSConnection(_Bounded, http.client.HTTPSConnection):
396    def __init__(self, *a, **k):
397        super().__init__(*a, **k)
398        self._bounded_init()
399
400
401def _handlers(stall: float):
402    http_cls = type("StallHTTPConnection", (BoundedHTTPConnection,), {"stall": stall})
403    https_cls = type("StallHTTPSConnection", (BoundedHTTPSConnection,), {"stall": stall})
404
405    class Http(urllib.request.HTTPHandler):
406        def http_open(self, req):
407            return self.do_open(http_cls, req)
408
409    class Https(urllib.request.HTTPSHandler):
410        def https_open(self, req):
411            kw = {"context": self._context}
412            if sys.version_info < (3, 12) and hasattr(self, "_check_hostname"):
413                kw["check_hostname"] = self._check_hostname
414            return self.do_open(https_cls, req, **kw)
415    return Http, Https
416
417
418def build_opener(*handlers, stall: float | None = None) -> urllib.request.OpenerDirector:
419    """urllib.request.build_opener with the bounded connection classes. `timeout` given to .open() is the connection-phase limit."""
420    http_h, https_h = _handlers(STALL_S if stall is None else stall)
421    return urllib.request.build_opener(http_h, https_h, *handlers)
422
423
424_OPENER: urllib.request.OpenerDirector | None = None
425_OPENER_LOCK = threading.Lock()
426
427
428def urlopen(request, timeout=None):
429    """urllib.request.urlopen with the rule's connection classes: `timeout` bounds the connection phase, reads after the answer stall
430    out after STALL_S. Without a timeout it behaves as urllib does. (Tests that fake the network replace this function.)"""
431    global _OPENER
432    with _OPENER_LOCK:
433        if _OPENER is None:
434            _OPENER = build_opener()
435        opener = _OPENER
436    if timeout is None:
437        return opener.open(request)
438    return opener.open(request, timeout=timeout)
439
440
441# ------------------------------------------------------------------------------------------------ one request under the rule
442
443def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callable[[str], None] | None = None,
444             memory: HostMemory | None = None, limits: Iterable[float] | None = None, gap: float | None = None,
445             sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, check_memory: bool = True,
446             wait_after: float | None = None, wait_every: float | None = None, automatic: bool = False,
447             refusals: RefusalNote | None = None):
448    """open_fn(request, timeout=limit) under rules 1-4b and 6. Returns the answer. Raises NetFailure when the host did not answer or
449    cannot be reached, HTTPError for an HTTP answer (after the one retry of 408/429/5xx), and anything else (a certificate problem, a
450    refusal of the acquisition rule) unchanged.  `automatic`: a read nobody asked for by name; only such a read consults the refusal note
451    (rule 4b, `refusals`, default REFUSALS); every read writes a refusal into it and removes its host after an answer."""
452    url = getattr(request, "full_url", request)
453    host = host or host_of(str(url))
454    try:                                                         # remembered per host and port (a test server on 127.0.0.1 is not github.com)
455        key = (urllib.parse.urlsplit(str(url)).netloc or host).lower()
456    except ValueError:
457        key = host
458    memory = HOSTS if memory is None else memory
459    if check_memory and memory.failed_recently(key):
460        raise NetFailure(host, "again")
461    refusals = REFUSALS if refusals is None else refusals
462    if automatic and refusals.refused_recently(key):
463        raise NetFailure(host, "offline")                     # rule 4b: refused within REFUSED_NOTE_S, not asked again by an automatic read
464    limits = tuple(CONNECT_LIMITS if limits is None else limits)
465    # Only a failure that had the whole window of the rule (12 s, then 30 s) is remembered: a call with shorter limits (an optional read
466    # of 5 s) may READ the memory and skip a host that already failed, but never WRITES it, so a slow but working link that a short read
467    # gave up on still gets its full attempt from a download that needs it (coordinator, 11-10).
468    full = len(limits) >= len(CONNECT_LIMITS) and all(a >= b for a, b in zip(limits, CONNECT_LIMITS))
469    gap = RETRY_GAP_S if gap is None else gap
470    start = clock()
471    with WaitLine(host, say, wait_after, wait_every, clock):
472        for i, limit in enumerate(limits):
473            last = i + 1 >= len(limits)
474            try:
475                answer = open_fn(request, timeout=limit)
476            except urllib.error.HTTPError as exc:
477                if exc.code in RETRY_HTTP and not last:
478                    try:
479                        exc.close()
480                    except Exception:                            # noqa: BLE001
481                        pass
482                    sleep(gap)
483                    continue
484                refusals.forget(key)                             # an HTTP answer: the host is there (rule 4b)
485                raise
486            except (OSError, http.client.HTTPException) as exc:
487                k = kind(exc)
488                if k in ("no_answer", "retry") and not last:
489                    sleep(gap)
490                    continue
491                if k in ("no_answer", "retry"):
492                    if full:
493                        memory.remember(key)
494                    raise NetFailure(host, "no_answer", exc, clock() - start) from None
495                if k == "offline":
496                    if refused(exc):
497                        refusals.remember(key)
498                    raise NetFailure(host, "offline", exc, clock() - start) from None
499                raise
500            refusals.forget(key)                                 # rule 4b: the first success removes the host from the note
501            return answer
502    raise NetFailure(host, "no_answer", None, clock() - start)          # (no limits given)
503
504
505# ------------------------------------------------------------------------------------------------ the download's clock (rule 5)
506
507class StallClock:
508    """`progress(have)` with the bytes so far after every try; `expired()` is True once no new byte came for GIVE_UP_S."""
509
510    def __init__(self, give_up: float | None = None, clock: Callable[[], float] = time.monotonic):
511        self.give_up = GIVE_UP_S if give_up is None else give_up
512        self.clock = clock
513        self.have = -1
514        self.since = clock()
515
516    def progress(self, have: int) -> None:
517        if have > self.have:
518            self.have, self.since = have, self.clock()
519
520    def idle(self) -> float:
521        return self.clock() - self.since
522
523    def expired(self) -> bool:
524        return self.idle() >= self.give_up
525
526    def words(self, what: str, have: int, total: int) -> tuple[str, str]:
527        pct = int(100 * have // total) if total else 0
528        return (WORDS["stalled"].format(minutes=max(1, int(self.give_up // 60)), what=what, percent=pct), WORDS["stalled_next"])