mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 07:48:45 +00:00
netpolicy: a refused feed host is remembered for 6 hours by the launch's automatic check
A feed host that refuses the connection (a proxy that is set but not running, a firewall that resets) costs about 2.0 s on Windows before the refusal is reported (measured 2.03-2.04 s on the owner PC). A launch of a model with its own engine shape reads the feed on every start to look for a newer engine, so such a PC paid it on every start. The existing host memory (rule 4) lives in one process only and never notes refusals. Rule 4b (strata_control/netpolicy.py): a refusal is written to a small note in Strata's own state folder (paths.state_base()/net/refused-hosts.json: host:port and the time, nothing else), kept 6 hours (REFUSED_NOTE_S). Only automatic reads (open_url(..., automatic=True)) read it and fail at once with the existing "offline" words. Every read the person asked for by name (strata update, setup, a download) ignores it and tries. The first answer from the host (also an HTTP error answer) removes it. A damaged or unreadable note counts as no note, without a message. Rule 4's text now points at 4b. automatic=True is passed only by `strata launch` -> shape_engine.ensure, and only while an engine of that shape is installed (feed.fetch, transfer.read_small and updater.Context carry the flag); setup's call and a shape with no engine read the feed always. No new user-visible words. Tests: tests/terminal/test_net_refused_note.py (the note's values, 6 hours, host and port, a clock that went back, damaged notes, open_url's automatic and explicit reads, removal on an answer, only refusals noted, a real refused loopback port); two tests in test_shape_engine.py (the launch check connects once then not again, setup and a shape with no engine still read). Owner 11-11, item 19 "remembering refused update feeds on Windows": Ok.
This commit is contained in:
1 parent
ded0053f69
commit
5fdb9aa4ad
8 files changed
+348
-15
No files matched your search
@@ -886,7 +886,8 @@ class Runner:
|
||||
self.emit("engine", shape_engine.WORDS["checking"].format(model=name))
|
||||
source = update_cmd._feed_source(argparse.Namespace(feed=self.feed or os.environ.get("STRATA_UPDATE_FEED")), root or ec.components_dir())
|
||||
said: list[str] = []
|
||||
exe = shape_engine.ensure(shape, source, components=root, emit=lambda m: (said.append(m), self.emit("engine", m, 0)), title=title)
|
||||
exe = shape_engine.ensure(shape, source, components=root, emit=lambda m: (said.append(m), self.emit("engine", m, 0)), title=title,
|
||||
automatic=True) # with an engine installed, a check nobody asked for (netpolicy rule 4b)
|
||||
if exe is None:
|
||||
self.no_engine(said[-1] if said else shape_engine.WORDS["fetch_failed"].format(model=name, why="nothing was fetched"))
|
||||
return
|
||||
|
||||
@@ -701,8 +701,9 @@ def feed_name(platform: str | None = None) -> str:
|
||||
return AARCH64_FEED_NAME if platform == "linux-aarch64" else FEED_NAME
|
||||
|
||||
|
||||
def fetch(source: str, trusted: dict[str, bytes], *, timeout: float = 30, say=None, **guards) -> Feed:
|
||||
"""Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path)."""
|
||||
def fetch(source: str, trusted: dict[str, bytes], *, timeout: float = 30, say=None, automatic: bool = False, **guards) -> Feed:
|
||||
"""Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path). `automatic`: a read
|
||||
nobody asked for by name (strata_control/netpolicy.py rule 4b: a host that refused within the last hours is not asked again)."""
|
||||
if not trusted:
|
||||
raise FeedError("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), "
|
||||
"so no update can be verified; nothing was downloaded")
|
||||
@@ -716,8 +717,8 @@ def fetch(source: str, trusted: dict[str, bytes], *, timeout: float = 30, say=No
|
||||
elif transfer.kind_of(source) in ("http", "https") and not source.rsplit("/", 1)[-1].endswith(".json"):
|
||||
location = source.rstrip("/") + "/" + feed_name()
|
||||
try:
|
||||
payload = transfer.read_small(location, timeout=timeout, say=say)
|
||||
signature = transfer.read_small(location + SIGNATURE_SUFFIX, timeout=timeout, say=say)
|
||||
payload = transfer.read_small(location, timeout=timeout, say=say, automatic=automatic)
|
||||
signature = transfer.read_small(location + SIGNATURE_SUFFIX, timeout=timeout, say=say, automatic=automatic)
|
||||
except transfer.Unreachable as exc:
|
||||
f = exc.failure # the network rule (W7 and its two companions): the host, and that nothing installed is lost
|
||||
key = {"offline": "update_offline", "again": "update_again"}.get(f.kind, "update_no_answer")
|
||||
|
||||
+101
-5
@@ -12,8 +12,15 @@ the screen. The rule here:
|
||||
3. 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
|
||||
given up after about 12 + 2 + 30 = 44 s.
|
||||
4. 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*
|
||||
(``HOSTS``, memory only, never on disk; a call with shorter limits reads it but never writes it;
|
||||
(``HOSTS``, memory only, never on disk (a refusal: rule 4b); a call with shorter limits reads it but never writes it;
|
||||
a new run always tries afresh). The next file from it fails at once with the same message.
|
||||
4b. A host that REFUSED the connection (connection refused: a proxy that is set but not running, a firewall that resets) is the one
|
||||
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
|
||||
and the time are written to a small note in Strata's own state folder (RefusalNote, REFUSED_NOTE_S = 6 hours; nothing
|
||||
else is written). Only automatic reads (open_url(..., automatic=True): the launch's check for a newer engine of a model's own
|
||||
shape while one is installed) read it and fail at once with the "offline" words. Every read the person asked for by name
|
||||
(strata update, setup, a download) ignores it and tries. The first success from that host removes it. A damaged or unreadable
|
||||
note counts as no note, without a message.
|
||||
5. Once the answer has come, a read that gets no byte for ``STALL_S`` ends that connection (the caller resumes from the byte it
|
||||
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
|
||||
slow link that works keeps working.
|
||||
@@ -28,6 +35,7 @@ from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import http.client
|
||||
import json
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
@@ -37,6 +45,7 @@ import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Callable, Iterable
|
||||
|
||||
FIRST_CONNECT_S = 12.0 # first try: measured, one github.com request in 25 hung while the next answered in 0.5 s
|
||||
@@ -48,6 +57,8 @@ GIVE_UP_S = 300.0 # no new byte for this long, across every try, ends
|
||||
WAIT_LINE_AFTER_S = 5.0
|
||||
WAIT_LINE_EVERY_S = 10.0
|
||||
HOST_MEMORY_S = 600.0
|
||||
REFUSED_NOTE_S = 6 * 3600.0 # rule 4b: a refused host is not asked again by an automatic read for this long
|
||||
REFUSED_NOTE_NAME = "refused-hosts.json"
|
||||
RETRY_HTTP = (408, 429, 500, 502, 503, 504)
|
||||
|
||||
# The words. {host} is a host name, {seconds} a whole number, {what} what was being fetched ("the picture reader").
|
||||
@@ -182,6 +193,81 @@ class HostMemory:
|
||||
HOSTS = HostMemory()
|
||||
|
||||
|
||||
def refused(exc: BaseException | None) -> bool:
|
||||
"""True when the connection was refused (ConnectionRefusedError, also inside a URLError)."""
|
||||
seen = 0
|
||||
while isinstance(exc, urllib.error.URLError) and isinstance(getattr(exc, "reason", None), BaseException) and seen < 4:
|
||||
exc = exc.reason
|
||||
seen += 1
|
||||
return isinstance(exc, ConnectionRefusedError)
|
||||
|
||||
|
||||
class RefusalNote:
|
||||
"""Rule 4b: the hosts that refused a connection, on disk (host:port -> the time, seconds since the epoch), kept for REFUSED_NOTE_S.
|
||||
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).
|
||||
Every failure to read or write it is silent: a damaged note is no note, an unwritable one is simply not kept."""
|
||||
|
||||
def __init__(self, path: Path | None = None, clock: Callable[[], float] = time.time, keep: float | None = None):
|
||||
self._path, self._clock, self._keep = path, clock, keep
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def path(self) -> Path:
|
||||
if self._path is not None:
|
||||
return Path(self._path)
|
||||
from strata_control import paths
|
||||
return paths.state_base() / "net" / REFUSED_NOTE_NAME
|
||||
|
||||
def _load(self) -> dict[str, float]:
|
||||
try:
|
||||
data = json.loads(self.path().read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError, UnicodeDecodeError):
|
||||
return {}
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
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)}
|
||||
|
||||
def _save(self, data: dict[str, float]) -> None:
|
||||
try:
|
||||
p = self.path()
|
||||
if not data:
|
||||
p.unlink(missing_ok=True)
|
||||
return
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
from strata_control import atomic
|
||||
atomic.write_text(p, json.dumps(data, sort_keys=True))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def refused_recently(self, key: str) -> bool:
|
||||
keep = REFUSED_NOTE_S if self._keep is None else self._keep
|
||||
with self._lock:
|
||||
at = self._load().get(key)
|
||||
return at is not None and 0 <= self._clock() - at < keep
|
||||
|
||||
def remember(self, key: str) -> None:
|
||||
keep = REFUSED_NOTE_S if self._keep is None else self._keep
|
||||
with self._lock:
|
||||
now = self._clock()
|
||||
data = {k: v for k, v in self._load().items() if 0 <= now - v < keep} # expired entries go when the note is written
|
||||
data[key] = now
|
||||
self._save(data)
|
||||
|
||||
def forget(self, key: str) -> None:
|
||||
with self._lock:
|
||||
try:
|
||||
if not self.path().is_file():
|
||||
return # the usual case: no note at all, nothing is written
|
||||
except OSError:
|
||||
return
|
||||
data = self._load()
|
||||
if key in data:
|
||||
data.pop(key)
|
||||
self._save(data)
|
||||
|
||||
|
||||
REFUSALS = RefusalNote()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the waiting line (rule 6)
|
||||
|
||||
class WaitLine:
|
||||
@@ -357,10 +443,12 @@ def urlopen(request, timeout=None):
|
||||
def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callable[[str], None] | None = None,
|
||||
memory: HostMemory | None = None, limits: Iterable[float] | None = None, gap: float | None = None,
|
||||
sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, check_memory: bool = True,
|
||||
wait_after: float | None = None, wait_every: float | None = None):
|
||||
"""open_fn(request, timeout=limit) under rules 1-4 and 6. Returns the answer. Raises NetFailure when the host did not answer or
|
||||
wait_after: float | None = None, wait_every: float | None = None, automatic: bool = False,
|
||||
refusals: RefusalNote | None = None):
|
||||
"""open_fn(request, timeout=limit) under rules 1-4b and 6. Returns the answer. Raises NetFailure when the host did not answer or
|
||||
cannot be reached, HTTPError for an HTTP answer (after the one retry of 408/429/5xx), and anything else (a certificate problem, a
|
||||
refusal of the acquisition rule) unchanged."""
|
||||
refusal of the acquisition rule) unchanged. `automatic`: a read nobody asked for by name; only such a read consults the refusal note
|
||||
(rule 4b, `refusals`, default REFUSALS); every read writes a refusal into it and removes its host after an answer."""
|
||||
url = getattr(request, "full_url", request)
|
||||
host = host or host_of(str(url))
|
||||
try: # remembered per host and port (a test server on 127.0.0.1 is not github.com)
|
||||
@@ -370,6 +458,9 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab
|
||||
memory = HOSTS if memory is None else memory
|
||||
if check_memory and memory.failed_recently(key):
|
||||
raise NetFailure(host, "again")
|
||||
refusals = REFUSALS if refusals is None else refusals
|
||||
if automatic and refusals.refused_recently(key):
|
||||
raise NetFailure(host, "offline") # rule 4b: refused within REFUSED_NOTE_S, not asked again by an automatic read
|
||||
limits = tuple(CONNECT_LIMITS if limits is None else limits)
|
||||
# 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
|
||||
# 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
|
||||
@@ -381,7 +472,7 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab
|
||||
for i, limit in enumerate(limits):
|
||||
last = i + 1 >= len(limits)
|
||||
try:
|
||||
return open_fn(request, timeout=limit)
|
||||
answer = open_fn(request, timeout=limit)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code in RETRY_HTTP and not last:
|
||||
try:
|
||||
@@ -390,6 +481,7 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab
|
||||
pass
|
||||
sleep(gap)
|
||||
continue
|
||||
refusals.forget(key) # an HTTP answer: the host is there (rule 4b)
|
||||
raise
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
k = kind(exc)
|
||||
@@ -401,8 +493,12 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab
|
||||
memory.remember(key)
|
||||
raise NetFailure(host, "no_answer", exc, clock() - start) from None
|
||||
if k == "offline":
|
||||
if refused(exc):
|
||||
refusals.remember(key)
|
||||
raise NetFailure(host, "offline", exc, clock() - start) from None
|
||||
raise
|
||||
refusals.forget(key) # rule 4b: the first success removes the host from the note
|
||||
return answer
|
||||
raise NetFailure(host, "no_answer", None, clock() - start) # (no limits given)
|
||||
|
||||
|
||||
|
||||
@@ -314,10 +314,12 @@ def update_one(ctx, feed, shape: str, *, install_missing: bool = True, title: st
|
||||
|
||||
|
||||
def ensure(shape: str, source: str, *, components: Path | None = None, hardware: dict | None = None, emit: Callable[[str], None] = print, cancel=None,
|
||||
quiet_when_current: bool = True, title: str | None = None) -> Path | None:
|
||||
quiet_when_current: bool = True, title: str | None = None, automatic: bool = False) -> Path | None:
|
||||
"""The engine of `shape` is installed and up to date, from the signed feed at `source` (a URL or a folder). Returns its program, or None with one plain line through `emit` when
|
||||
there is none (not in the feed, nothing for this PC, the feed cannot be read). A newer package is fetched only when the feed can be read; an installed one keeps running when it
|
||||
cannot. This is what setup and `strata launch` call when a model of that shape is chosen."""
|
||||
cannot. This is what setup and `strata launch` call when a model of that shape is chosen. `automatic` (`strata launch`): with an engine installed,
|
||||
the check for a newer one is a read nobody asked for, so a feed host that refused within the last hours is not asked again (netpolicy rule 4b);
|
||||
without one the feed is always read."""
|
||||
from strata_control import acquisition, feed as feedmod, signing, updater
|
||||
components = Path(components) if components else ec.components_dir()
|
||||
hw = hardware or updater.detect_hardware()
|
||||
@@ -327,6 +329,7 @@ def ensure(shape: str, source: str, *, components: Path | None = None, hardware:
|
||||
emit(WORDS["fetching"].format(model=name))
|
||||
ctx = updater.Context(components=components, source=source, trusted=signing.load_trusted_keys(), hardware=hw, cancel=cancel,
|
||||
feed_timeout=5.0 if have else 30.0, # an installed engine: a launch must not wait long for a feed that is not there
|
||||
automatic=bool(automatic and have),
|
||||
emit=lambda event: emit(event["message"]) if event.get("event") == "phase" and event.get("message") and event.get("phase") != "feed" else None)
|
||||
try:
|
||||
with updater.update_lock(components):
|
||||
|
||||
@@ -191,7 +191,7 @@ def _open_small(request, timeout: float, limit: int) -> bytes:
|
||||
return response.read(limit + 1)
|
||||
|
||||
|
||||
def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30, say=None) -> bytes:
|
||||
def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30, say=None, automatic: bool = False) -> bytes:
|
||||
"""A small document (the feed, its signature). Larger than `limit` is refused, not truncated.
|
||||
A web address gets one more try when the first one times out or the connection fails: about one request in 25 to github.com hung for the whole
|
||||
timeout on a PC whose next 24 answered in half a second (measured on a 3060 PC: the first-run card said "offline" a moment before the install's
|
||||
@@ -206,7 +206,8 @@ def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30,
|
||||
def attempt(req, timeout):
|
||||
_SERVER_DATE.clear() # only the answer of the try that worked counts
|
||||
return _open_small(req, timeout, limit)
|
||||
data = netpolicy.open_url(attempt, request, limits=(min(timeout, FIRST_TRY_SECONDS), timeout), say=say) # say: the waiting line (W1)
|
||||
data = netpolicy.open_url(attempt, request, limits=(min(timeout, FIRST_TRY_SECONDS), timeout), say=say,
|
||||
automatic=automatic) # automatic: a read nobody asked for (netpolicy rule 4b) # say: the waiting line (W1)
|
||||
except netpolicy.NetFailure as failure:
|
||||
raise Unreachable(failure, "the update feed") from None
|
||||
else:
|
||||
|
||||
@@ -355,6 +355,7 @@ class Context:
|
||||
allow_no_model_smoke: bool = True
|
||||
state_base: Path | None = None # where tuning/recheck.json goes (default: the per-user state folder)
|
||||
feed_timeout: float = 30.0 # seconds a read of the feed may wait (the quiet daily check uses 5)
|
||||
automatic: bool = False # a read of the feed nobody asked for by name (netpolicy rule 4b: the refusal note)
|
||||
gate: object | None = None # strata_control.engine_update.ModelGate: what to do when a model is loaded (None: refuse before anything is downloaded)
|
||||
|
||||
def say(self, phase: str, message: str, **extra) -> None:
|
||||
@@ -379,7 +380,8 @@ def open_feed(ctx: Context, state: State) -> feedmod.Feed:
|
||||
last = (state.data.get("feed") or {}).get("sequence")
|
||||
ctx.say("feed", "Reading the signed update feed")
|
||||
try:
|
||||
loaded = feedmod.fetch(ctx.source, ctx.trusted, timeout=ctx.feed_timeout, last_sequence=last, channel=ctx.channel, now=ctx.now)
|
||||
loaded = feedmod.fetch(ctx.source, ctx.trusted, timeout=ctx.feed_timeout, last_sequence=last, channel=ctx.channel, now=ctx.now,
|
||||
automatic=ctx.automatic)
|
||||
except feedmod.FeedDowngrade as exc:
|
||||
raise feedmod.FeedDowngrade(downgrade_words(exc.sequence, exc.accepted, state.path)) from None
|
||||
for line in loaded.skipped: # an entry from a newer release that this Control cannot use: said once, never an error
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""netpolicy rule 4b (owner 11-11, "Remembering refused update feeds on Windows": Ok): a feed host that REFUSED the connection is remembered
|
||||
on disk for 6 hours, in Strata's own state folder, host:port and the time only. Only automatic reads (`automatic=True`) read the note; a read
|
||||
the person asked for by name ignores it; the first answer from the host removes it; a damaged or unreadable note is no note, without a message.
|
||||
|
||||
Windows needs about 2.0 s to report a refused connection (measured 2.03-2.04 s on the owner PC, owner-20261110-2003-a8da); a launch of a model
|
||||
with its own engine shape read the feed on every start, so a PC behind a dead proxy paid that on every start. Every test here works in a test
|
||||
HOME (conftest.py and launch_support.Home redirect the state folder) or on a note file of its own."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from strata_control import netpolicy, paths, transfer
|
||||
from tests.terminal.launch_support import Home
|
||||
from tests.terminal.test_netpolicy import refused_port
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, t: float = 1_000_000.0):
|
||||
self.t = t
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.t
|
||||
|
||||
|
||||
def note_in(folder: Path, clock=None) -> netpolicy.RefusalNote:
|
||||
return netpolicy.RefusalNote(path=folder / "net" / netpolicy.REFUSED_NOTE_NAME, clock=clock or Clock())
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
t = tempfile.TemporaryDirectory(prefix="strata-refused-")
|
||||
self.addCleanup(t.cleanup)
|
||||
self.dir = Path(t.name)
|
||||
self.clock = Clock()
|
||||
self.note = note_in(self.dir, self.clock)
|
||||
netpolicy.HOSTS.forget()
|
||||
self.addCleanup(netpolicy.HOSTS.forget)
|
||||
|
||||
|
||||
def refuse(request, timeout):
|
||||
raise ConnectionRefusedError(10061 if os.name == "nt" else 111, "refused")
|
||||
|
||||
|
||||
class TheNote(Base):
|
||||
def test_the_values_of_the_rule(self):
|
||||
self.assertEqual(netpolicy.REFUSED_NOTE_S, 6 * 3600)
|
||||
with Home(): # the default note lives in Strata's own state folder (read when used)
|
||||
self.assertEqual(netpolicy.REFUSALS.path(), paths.state_base() / "net" / "refused-hosts.json")
|
||||
base = Path(os.environ["LOCALAPPDATA" if os.name == "nt" else "XDG_STATE_HOME"])
|
||||
self.assertEqual(netpolicy.REFUSALS.path().parent.parent.parent, base, "inside the test HOME's state folder")
|
||||
|
||||
def test_host_port_and_time_only_and_six_hours(self):
|
||||
self.note.remember("github.com:443")
|
||||
self.assertEqual(json.loads(self.note.path().read_text(encoding="utf-8")), {"github.com:443": self.clock.t})
|
||||
self.assertTrue(self.note.refused_recently("github.com:443"))
|
||||
self.assertFalse(self.note.refused_recently("github.com:8443"), "per host AND port")
|
||||
self.clock.t += 6 * 3600 - 1
|
||||
self.assertTrue(self.note.refused_recently("github.com:443"))
|
||||
self.clock.t += 1
|
||||
self.assertFalse(self.note.refused_recently("github.com:443"), "after 6 hours the host is asked again")
|
||||
self.note.remember("example.org:443") # writing drops the expired entries
|
||||
self.assertEqual(sorted(json.loads(self.note.path().read_text(encoding="utf-8"))), ["example.org:443"])
|
||||
|
||||
def test_a_clock_that_went_back_does_not_keep_a_host_forever(self):
|
||||
self.note.remember("github.com:443")
|
||||
self.clock.t -= 3600
|
||||
self.assertFalse(self.note.refused_recently("github.com:443"))
|
||||
|
||||
def test_forget_removes_the_host_and_the_empty_note(self):
|
||||
self.note.remember("a:1")
|
||||
self.note.remember("b:2")
|
||||
self.note.forget("a:1")
|
||||
self.assertEqual(sorted(json.loads(self.note.path().read_text(encoding="utf-8"))), ["b:2"])
|
||||
self.note.forget("b:2")
|
||||
self.assertFalse(self.note.path().exists())
|
||||
|
||||
def test_forget_without_a_note_writes_nothing(self):
|
||||
self.note.forget("a:1")
|
||||
self.assertFalse(self.note.path().parent.exists())
|
||||
|
||||
def test_a_damaged_or_unreadable_note_is_no_note_and_says_nothing(self):
|
||||
p = self.note.path()
|
||||
p.parent.mkdir(parents=True)
|
||||
for text in ("{not json", "[1, 2]", '{"a:1": "yesterday"}', '{"a:1": true}', "\xff\xfe".encode("latin-1").decode("latin-1")):
|
||||
p.write_text(text, encoding="latin-1")
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
self.assertFalse(self.note.refused_recently("a:1"), text)
|
||||
self.note.remember("c:3") # a damaged note is replaced by a good one
|
||||
self.assertTrue(self.note.refused_recently("c:3"))
|
||||
self.assertEqual((out.getvalue(), err.getvalue()), ("", ""))
|
||||
p.unlink()
|
||||
p.mkdir() # a folder where the note should be: cannot be read or written
|
||||
self.assertFalse(self.note.refused_recently("a:1"))
|
||||
self.note.remember("a:1") # silently not kept
|
||||
self.note.forget("a:1")
|
||||
self.assertFalse(self.note.refused_recently("a:1"))
|
||||
|
||||
|
||||
class OpenUrl(Base):
|
||||
def test_a_refusal_is_noted_and_the_next_automatic_read_does_not_connect(self):
|
||||
with self.assertRaises(netpolicy.NetFailure) as cm:
|
||||
netpolicy.open_url(refuse, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True)
|
||||
self.assertEqual(cm.exception.kind, "offline")
|
||||
self.assertTrue(self.note.refused_recently("feed.example:443"))
|
||||
calls = []
|
||||
|
||||
def counting(request, timeout):
|
||||
calls.append(1)
|
||||
return b"answer"
|
||||
with self.assertRaises(netpolicy.NetFailure) as cm:
|
||||
netpolicy.open_url(counting, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True)
|
||||
self.assertEqual((cm.exception.kind, calls), ("offline", []), "the automatic read failed at once, without a connection")
|
||||
self.assertIn("could not connect", str(cm.exception), "the same offline words as a refusal")
|
||||
|
||||
def test_a_read_asked_for_by_name_ignores_the_note_and_its_answer_removes_the_host(self):
|
||||
self.note.remember("feed.example:443")
|
||||
calls = []
|
||||
|
||||
def answer(request, timeout):
|
||||
calls.append(1)
|
||||
return b"answer"
|
||||
self.assertEqual(netpolicy.open_url(answer, "https://feed.example:443/strata-feed.json", refusals=self.note), b"answer")
|
||||
self.assertEqual(calls, [1])
|
||||
self.assertFalse(self.note.refused_recently("feed.example:443"), "the first success removes the host")
|
||||
self.assertEqual(netpolicy.open_url(answer, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True), b"answer")
|
||||
|
||||
def test_an_http_answer_also_removes_the_host(self):
|
||||
import urllib.error
|
||||
self.note.remember("feed.example:443")
|
||||
|
||||
def missing(request, timeout):
|
||||
raise urllib.error.HTTPError(str(request), 404, "Not Found", {}, None)
|
||||
with self.assertRaises(urllib.error.HTTPError):
|
||||
netpolicy.open_url(missing, "https://feed.example:443/x", refusals=self.note)
|
||||
self.assertFalse(self.note.refused_recently("feed.example:443"))
|
||||
|
||||
def test_only_a_refusal_is_noted(self):
|
||||
import socket
|
||||
|
||||
def no_name(request, timeout):
|
||||
raise socket.gaierror(-2, "Name or service not known")
|
||||
|
||||
def timeout(request, timeout):
|
||||
raise TimeoutError("timed out")
|
||||
for fn in (no_name, timeout):
|
||||
with self.assertRaises(netpolicy.NetFailure):
|
||||
netpolicy.open_url(fn, "https://feed.example:443/x", refusals=self.note, limits=(0.01,), gap=0, sleep=lambda s: None)
|
||||
self.assertFalse(self.note.path().exists(), "no DNS answer and a timeout are not refusals (the first fails at once anyway)")
|
||||
|
||||
def test_a_refusal_through_urllib_is_seen(self):
|
||||
import urllib.error
|
||||
self.assertTrue(netpolicy.refused(urllib.error.URLError(ConnectionRefusedError(111, "refused"))))
|
||||
self.assertFalse(netpolicy.refused(urllib.error.URLError("timed out")))
|
||||
|
||||
|
||||
class RealSocket(Base):
|
||||
def test_a_refused_loopback_port_costs_its_wait_once_then_nothing(self):
|
||||
url = f"http://127.0.0.1:{refused_port()}/strata-feed.json"
|
||||
with mock.patch.object(netpolicy, "REFUSALS", self.note):
|
||||
t0 = time.monotonic()
|
||||
with self.assertRaises(transfer.Unreachable):
|
||||
transfer.read_small(url, timeout=5, automatic=True)
|
||||
first = time.monotonic() - t0
|
||||
t0 = time.monotonic()
|
||||
with self.assertRaises(transfer.Unreachable):
|
||||
transfer.read_small(url, timeout=5, automatic=True)
|
||||
second = time.monotonic() - t0
|
||||
t0 = time.monotonic()
|
||||
with self.assertRaises(transfer.Unreachable):
|
||||
transfer.read_small(url, timeout=5) # asked for by name: it tries again
|
||||
explicit = time.monotonic() - t0
|
||||
print(f"refused loopback: first {first:.3f} s, second (noted) {second:.3f} s, explicit {explicit:.3f} s")
|
||||
self.assertLess(second, 0.2)
|
||||
if os.name == "nt": # Windows reports a refusal after about 2 s: the note saves exactly that
|
||||
self.assertGreater(first, 1.0)
|
||||
self.assertGreater(explicit, 1.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -548,6 +548,44 @@ class Update(Base):
|
||||
self.assertIsNone(shape_engine.ensure("q4_mid", dead, components=self.comp, hardware=self.hw, emit=lines.append))
|
||||
self.assertTrue(any("could not be downloaded" in line for line in lines), lines)
|
||||
|
||||
def test_a_refused_feed_is_asked_once_by_the_launch_check_then_not_for_six_hours(self):
|
||||
"""netpolicy rule 4b: `strata launch` (automatic=True) with an engine installed reads the refusal note; setup (no flag) and a shape
|
||||
with no engine yet always read the feed."""
|
||||
from strata_control import netpolicy, transfer
|
||||
from tests.terminal.test_netpolicy import refused_port
|
||||
self.installed("0.1.59")
|
||||
# the product's own windows (5 s with an engine installed), not net_dead's scaled 0.3 s: Windows reports a refusal only after about 2 s,
|
||||
# so a scaled window would see a timeout there, not a refusal
|
||||
dead = f"http://127.0.0.1:{refused_port()}/strata-feed.json"
|
||||
note = netpolicy.RefusalNote(path=self.root / "state" / "net" / netpolicy.REFUSED_NOTE_NAME)
|
||||
calls = []
|
||||
real = transfer._open_small
|
||||
|
||||
def counting(request, timeout, limit):
|
||||
calls.append(request.full_url)
|
||||
return real(request, timeout, limit)
|
||||
with mock.patch.object(netpolicy, "REFUSALS", note), mock.patch.object(transfer, "_open_small", counting):
|
||||
lines = []
|
||||
self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True).is_file())
|
||||
self.assertEqual(lines, [])
|
||||
self.assertEqual(len(calls), 1, "one try: a refusal is clear at once")
|
||||
port = dead.split("/")[2]
|
||||
self.assertEqual(list(json.loads(note.path().read_text(encoding="utf-8"))), [port], "host:port only")
|
||||
self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True).is_file())
|
||||
self.assertEqual((len(calls), lines), (1, []), "the next launch check does not connect and says nothing")
|
||||
self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append).is_file())
|
||||
self.assertEqual(len(calls), 2, "setup's call (no flag) reads the feed")
|
||||
self.assertIsNone(shape_engine.ensure("q4_mid", dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True))
|
||||
self.assertEqual(len(calls), 3, "no engine installed: the feed is always read")
|
||||
|
||||
def test_the_launch_asks_as_an_automatic_check_and_setup_does_not(self):
|
||||
runner_src = (ROOT / "strata_cli" / "launch" / "runner.py").read_text(encoding="utf-8")
|
||||
call = runner_src[runner_src.index("exe = shape_engine.ensure("):]
|
||||
self.assertIn("automatic=True", call[:call.index("\n\n")])
|
||||
setup_src = (ROOT / "setup.py").read_text(encoding="utf-8")
|
||||
call = setup_src[setup_src.index("exe = shape_engine.ensure("):]
|
||||
self.assertNotIn("automatic", call[:call.index("\n")])
|
||||
|
||||
def test_the_explicit_update_has_a_step_only_for_an_installed_shape(self):
|
||||
self.publish("0.1.59")
|
||||
ctx = updater.Context(components=self.comp, source=self.url, trusted=signing.load_trusted_keys(), hardware=self.hw)
|
||||
|
||||
Reference in new issue
Block a user