okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c7ec1e8fe
main
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 8headers) - gets at most ``FIRST_CONNECT_S`` on the first try and ``RETRY_CONNECT_S`` on the one retry (``CONNECT_LIMITS``). The 9name 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 11unreachable, 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 13given 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; 16a 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 18exception kept across runs: Windows needs about 2 s to report a refusal, and a launch reads the feed on every start. Its host:port 19and the time are written to a small note in Strata's own state folder (RefusalNote, REFUSED_NOTE_S = 6 hours; nothing 20else is written). Only automatic reads (open_url(..., automatic=True): the launch's check for a newer engine of a model's own 21shape 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 23note 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 25reached). A download stops only after ``GIVE_UP_S`` in a row without a new byte (``StallClock``); there is no total time cap, so a 26slow 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.""" 87low = (label or "" ).lower () 88if not label : 89return "the model files" 90if "vision" in low or "picture" in low or "mmproj" in low : 91return "the picture reader" 92if "llama.cpp" in low : 93return "the tools that prepare models" 94if low .startswith (("the " ,"a " )): 95return label 96if "engine" in low : 97return "the " + label 98return label 99 100 101def host_of (url :str )-> str : 102try : 103return (urllib .parse .urlsplit (url ).hostname or "" ).lower ()or url 104except ValueError : 105return 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'.""" 113if exc is None : 114return "other" 115if isinstance (exc ,urllib .error .HTTPError ): 116return "http_retry" if exc .code in RETRY_HTTP else "http" 117from strata_control import tls 118if tls .is_certificate_error (exc ): 119return "cert" 120seen = 0 121while isinstance (exc ,urllib .error .URLError )and isinstance (getattr (exc ,"reason" ,None ),BaseException )and seen < 4 : 122exc = exc .reason 123seen += 1 124if isinstance (exc ,urllib .error .URLError ):# a reason that is only text: "timed out" is a timeout, other text is unclear 125return "no_answer" if "timed out" in str (exc .reason ).lower ()else "other" 126if isinstance (exc ,socket .gaierror )or isinstance (exc ,ConnectionRefusedError ): 127return "offline" 128if isinstance (exc ,OSError )and exc .errno in (errno .ENETUNREACH ,errno .EHOSTUNREACH ,errno .ENETDOWN ): 129return "offline" 130if isinstance (exc , (TimeoutError ,socket .timeout )): 131return "no_answer" 132if isinstance (exc ,ssl .SSLError )and "timed out" in str (exc ).lower (): 133return "no_answer" 134if isinstance (exc , (ConnectionResetError ,ConnectionAbortedError ,BrokenPipeError ,http .client .HTTPException )): 135return "retry" 136return "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 143def __init__ (self ,host :str ,kind_ :str ,cause :BaseException | None = None ,seconds :float = 0.0 ): 144self .host ,self .kind ,self .cause ,self .seconds = host ,kind_ ,cause ,seconds 145super ().__init__ (self .headline ("the download" )) 146 147def headline (self ,what :str )-> str : 148key = {"offline" :"offline" ,"again" :"again" }.get (self .kind ,"no_answer" ) 149return WORDS [key ].format (host = self .host ,what = what ,seconds = max (1 ,int (round (self .seconds )))) 150 151def next_step (self )-> str : 152return WORDS ["next" ].format (host = self .host ) 153 154def detail (self )-> str : 155"""The raw reason, for a log or a Details line only.""" 156c = self .cause 157return 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 165def __init__ (self ,clock :Callable [[],float ]= time .monotonic ,keep :float | None = None ): 166self ._clock ,self ._keep = clock ,keep 167self ._failed :dict [str ,float ]= {} 168self ._lock = threading .Lock () 169 170def remember (self ,host :str )-> None : 171with self ._lock : 172self ._failed [host ]= self ._clock () 173 174def forget (self ,host :str | None = None )-> None : 175with self ._lock : 176if host is None : 177self ._failed .clear () 178else : 179self ._failed .pop (host ,None ) 180 181def failed_recently (self ,host :str )-> bool : 182keep = HOST_MEMORY_S if self ._keep is None else self ._keep 183with self ._lock : 184at = self ._failed .get (host ) 185if at is None : 186return False 187if self ._clock ()- at >= keep : 188self ._failed .pop (host ,None ) 189return False 190return 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).""" 198seen = 0 199while isinstance (exc ,urllib .error .URLError )and isinstance (getattr (exc ,"reason" ,None ),BaseException )and seen < 4 : 200exc = exc .reason 201seen += 1 202return 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. 207The note lives in Strata's own state folder (strata_control/paths.state_base, read when it is used, so a test HOME redirects it). 208Every failure to read or write it is silent: a damaged note is no note, an unwritable one is simply not kept.""" 209 210def __init__ (self ,path :Path | None = None ,clock :Callable [[],float ]= time .time ,keep :float | None = None ): 211self ._path ,self ._clock ,self ._keep = path ,clock ,keep 212self ._lock = threading .Lock () 213 214def path (self )-> Path : 215if self ._path is not None : 216return Path (self ._path ) 217from strata_control import paths 218return paths .state_base ()/ "net" / REFUSED_NOTE_NAME 219 220def _load (self )-> dict [str ,float ]: 221try : 222data = json .loads (self .path ().read_text (encoding = "utf-8" )) 223except (OSError ,ValueError ,UnicodeDecodeError ): 224return {} 225if not isinstance (data ,dict ): 226return {} 227return {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 229def _save (self ,data :dict [str ,float ])-> None : 230try : 231p = self .path () 232if not data : 233p .unlink (missing_ok = True ) 234return 235p .parent .mkdir (parents = True ,exist_ok = True ) 236from strata_control import atomic 237atomic .write_text (p ,json .dumps (data ,sort_keys = True )) 238except OSError : 239pass 240 241def refused_recently (self ,key :str )-> bool : 242keep = REFUSED_NOTE_S if self ._keep is None else self ._keep 243with self ._lock : 244at = self ._load ().get (key ) 245return at is not None and 0 <= self ._clock ()- at < keep 246 247def remember (self ,key :str )-> None : 248keep = REFUSED_NOTE_S if self ._keep is None else self ._keep 249with self ._lock : 250now = self ._clock () 251data = {k :v for k ,v in self ._load ().items ()if 0 <= now - v < keep }# expired entries go when the note is written 252data [key ]= now 253self ._save (data ) 254 255def forget (self ,key :str )-> None : 256with self ._lock : 257try : 258if not self .path ().is_file (): 259return # the usual case: no note at all, nothing is written 260except OSError : 261return 262data = self ._load () 263if key in data : 264data .pop (key ) 265self ._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 276def __init__ (self ,host :str ,say :Callable [[str ],None ]| None ,after :float | None = None ,every :float | None = None , 277clock :Callable [[],float ]= time .monotonic ): 278self .host ,self .say ,self .clock = host ,say ,clock 279self .after = WAIT_LINE_AFTER_S if after is None else after 280self .every = WAIT_LINE_EVERY_S if every is None else every 281self ._stop = threading .Event () 282self ._thread :threading .Thread | None = None 283self .said = 0 284 285def _run (self )-> None : 286start = self .clock () 287if self ._stop .wait (self .after ): 288return 289while not self ._stop .is_set (): 290try : 291self .say (WORDS ["waiting" ].format (host = self .host ,seconds = int (self .clock ()- start )))# type: ignore[misc] 292self .said += 1 293except Exception :# noqa: BLE001 - a line that cannot be shown never stops a download 294pass 295if self ._stop .wait (self .every ): 296return 297 298def __enter__ (self )-> "WaitLine" : 299if self .say is not None : 300self ._thread = threading .Thread (target = self ._run ,daemon = True ,name = f"wait- { self . host } " ) 301self ._thread .start () 302return self 303 304def __exit__ (self ,* exc )-> bool : 305self ._stop .set () 306if self ._thread is not None : 307self ._thread .join (1.0 ) 308return 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. 315It runs in a helper thread here, given up after `limit` seconds (the thread ends by itself later).""" 316box :dict = {} 317 318def look ()-> None : 319try : 320box ["infos" ]= socket .getaddrinfo (host ,port ,0 ,socket .SOCK_STREAM ) 321except BaseException as exc :# noqa: BLE001 - handed to the caller 322box ["error" ]= exc 323t = threading .Thread (target = look ,daemon = True ,name = f"dns- { host } " ) 324t .start () 325t .join (limit ) 326if t .is_alive (): 327raise TimeoutError (f"no answer to the name lookup of { host } within { limit :.0f } s" ) 328if "error" in box : 329raise box ["error" ] 330return box ["infos" ] 331 332 333def _numeric (timeout )-> float | None : 334return 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 339returned with the time that is left as its timeout, so the TLS handshake and the wait for the answer fit in the same deadline.""" 340limit = _numeric (timeout ) 341if limit is None : 342return socket .create_connection (address ,timeout ,source_address ) 343deadline = time .monotonic ()+ limit 344host ,port = address [0 ],address [1 ] 345infos = _bounded_getaddrinfo (host ,port ,limit ) 346last :BaseException | None = None 347for af ,socktype ,proto ,_canon ,sa in infos : 348left = deadline - time .monotonic () 349if left <= 0 : 350break 351try :# through socket.create_connection (a numeric address: no second lookup) 352sock = socket .create_connection (sa [:2 ],left ,source_address ) 353sock .settimeout (max (0.05 ,deadline - time .monotonic ())) 354return sock 355except OSError as exc : 356last = exc 357if last is not None and not isinstance (last , (TimeoutError ,socket .timeout )): 358raise last 359raise 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, 364covering the answer's headers too); after the answer the socket gets `stall` (rule 5).""" 365stall :float = STALL_S 366 367def _bounded_init (self )-> None : 368self ._create_connection = create_connection # type: ignore[attr-defined] 369self ._deadline = None 370 371def connect (self ):# type: ignore[override] 372limit = _numeric (self .timeout )# type: ignore[attr-defined] 373self ._deadline = time .monotonic ()+ limit if limit else None 374super ().connect ()# type: ignore[misc] 375if self ._deadline is not None and self .sock is not None :# type: ignore[attr-defined] 376self .sock .settimeout (max (0.05 ,self ._deadline - time .monotonic ()))# type: ignore[attr-defined] 377 378def getresponse (self ):# type: ignore[override] 379sock = self .sock # type: ignore[attr-defined] 380response = super ().getresponse ()# type: ignore[misc] 381if self ._deadline is not None and sock is not None : 382try : 383sock .settimeout (self .stall ) 384except OSError : 385pass 386return response 387 388 389class BoundedHTTPConnection (_Bounded ,http .client .HTTPConnection ): 390def __init__ (self ,* a ,** k ): 391super ().__init__ (* a ,** k ) 392self ._bounded_init () 393 394 395class BoundedHTTPSConnection (_Bounded ,http .client .HTTPSConnection ): 396def __init__ (self ,* a ,** k ): 397super ().__init__ (* a ,** k ) 398self ._bounded_init () 399 400 401def _handlers (stall :float ): 402http_cls = type ("StallHTTPConnection" , (BoundedHTTPConnection ,), {"stall" :stall }) 403https_cls = type ("StallHTTPSConnection" , (BoundedHTTPSConnection ,), {"stall" :stall }) 404 405class Http (urllib .request .HTTPHandler ): 406def http_open (self ,req ): 407return self .do_open (http_cls ,req ) 408 409class Https (urllib .request .HTTPSHandler ): 410def https_open (self ,req ): 411kw = {"context" :self ._context } 412if sys .version_info < (3 ,12 )and hasattr (self ,"_check_hostname" ): 413kw ["check_hostname" ]= self ._check_hostname 414return self .do_open (https_cls ,req ,** kw ) 415return 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.""" 420http_h ,https_h = _handlers (STALL_S if stall is None else stall ) 421return 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 430out after STALL_S. Without a timeout it behaves as urllib does. (Tests that fake the network replace this function.)""" 431global _OPENER 432with _OPENER_LOCK : 433if _OPENER is None : 434_OPENER = build_opener () 435opener = _OPENER 436if timeout is None : 437return opener .open (request ) 438return 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 , 444memory :HostMemory | None = None ,limits :Iterable [float ]| None = None ,gap :float | None = None , 445sleep :Callable [[float ],None ]= time .sleep ,clock :Callable [[],float ]= time .monotonic ,check_memory :bool = True , 446wait_after :float | None = None ,wait_every :float | None = None ,automatic :bool = False , 447refusals :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 449cannot be reached, HTTPError for an HTTP answer (after the one retry of 408/429/5xx), and anything else (a certificate problem, a 450refusal 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.""" 452url = getattr (request ,"full_url" ,request ) 453host = host or host_of (str (url )) 454try :# remembered per host and port (a test server on 127.0.0.1 is not github.com) 455key = (urllib .parse .urlsplit (str (url )).netloc or host ).lower () 456except ValueError : 457key = host 458memory = HOSTS if memory is None else memory 459if check_memory and memory .failed_recently (key ): 460raise NetFailure (host ,"again" ) 461refusals = REFUSALS if refusals is None else refusals 462if automatic and refusals .refused_recently (key ): 463raise NetFailure (host ,"offline" )# rule 4b: refused within REFUSED_NOTE_S, not asked again by an automatic read 464limits = 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). 468full = len (limits )>= len (CONNECT_LIMITS )and all (a >= b for a ,b in zip (limits ,CONNECT_LIMITS )) 469gap = RETRY_GAP_S if gap is None else gap 470start = clock () 471with WaitLine (host ,say ,wait_after ,wait_every ,clock ): 472for i ,limit in enumerate (limits ): 473last = i + 1 >= len (limits ) 474try : 475answer = open_fn (request ,timeout = limit ) 476except urllib .error .HTTPError as exc : 477if exc .code in RETRY_HTTP and not last : 478try : 479exc .close () 480except Exception :# noqa: BLE001 481pass 482sleep (gap ) 483continue 484refusals .forget (key )# an HTTP answer: the host is there (rule 4b) 485raise 486except (OSError ,http .client .HTTPException )as exc : 487k = kind (exc ) 488if k in ("no_answer" ,"retry" )and not last : 489sleep (gap ) 490continue 491if k in ("no_answer" ,"retry" ): 492if full : 493memory .remember (key ) 494raise NetFailure (host ,"no_answer" ,exc ,clock ()- start )from None 495if k == "offline" : 496if refused (exc ): 497refusals .remember (key ) 498raise NetFailure (host ,"offline" ,exc ,clock ()- start )from None 499raise 500refusals .forget (key )# rule 4b: the first success removes the host from the note 501return answer 502raise 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 510def __init__ (self ,give_up :float | None = None ,clock :Callable [[],float ]= time .monotonic ): 511self .give_up = GIVE_UP_S if give_up is None else give_up 512self .clock = clock 513self .have = - 1 514self .since = clock () 515 516def progress (self ,have :int )-> None : 517if have > self .have : 518self .have ,self .since = have ,self .clock () 519 520def idle (self )-> float : 521return self .clock ()- self .since 522 523def expired (self )-> bool : 524return self .idle ()>= self .give_up 525 526def words (self ,what :str ,have :int ,total :int )-> tuple [str ,str ]: 527pct = int (100 * have // total )if total else 0 528return (WORDS ["stalled" ].format (minutes = max (1 ,int (self .give_up // 60 )),what = what ,percent = pct ),WORDS ["stalled_next" ])