okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
16.8 KiB361 linesraw
1"""The quiet line that says a newer engine is available, and the once-a-day check behind it (owner, 11-01).
2
3* the line comes from the last check's cached answer (a local file): one sentence, one next step, no network;
4* it is in the launch start screen and the launch monitor (and `strata update --check`), nowhere else;
5* the daily check is made by the launch monitor only, in a thread of its own, once a day, with a short timeout, and says NOTHING when it cannot reach
6  the feed: no internet, blocked DNS, a proxy that refuses, a captive portal that answers junk, a connection that never answers.  The attempt is
7  written before the network is touched, so a failure is not retried until tomorrow.  Offline, the launch, the monitor and the line behave exactly as
8  they do with a working network that has nothing new.
9"""
10from __future__ import annotations
11
12import asyncio
13import contextlib
14import datetime as dt
15import io
16import json
17import logging
18import os
19import socket
20import sys
21import threading
22import time
23import unittest
24from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
25from pathlib import Path
26from unittest import mock
27
28sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
29from strata_cli.launch import app as launch_app  # noqa: E402
30from strata_cli.launch.monitor_ext import LaunchMonitor  # noqa: E402
31from strata_control import engine_component as ec, engine_update, updater  # noqa: E402
32from tests.terminal import update_fixture as fx  # noqa: E402
33from tests.terminal.launch_support import text_of  # noqa: E402
34from tests.terminal.test_launch_monitor import INFO, flat  # noqa: E402
35from tests.terminal.test_launch_tui import Base as TuiBase, make_ctx  # noqa: E402
36from tests.terminal.test_overview import Source, metrics  # noqa: E402
37from tests.terminal.test_updater import UpdaterCase  # noqa: E402
38
39
40class Cached(UpdaterCase):
41    """The line is built from the cached check only."""
42
43    def remember(self, **offers):
44        state = self.components / ".updates" / "state.json"
45        state.parent.mkdir(parents=True, exist_ok=True)
46        last = {"at": dt.datetime.now(dt.timezone.utc).isoformat(), "engine": None, "app": None,
47                "control": ec.runtime_version(), "engine_installed": ec.newest_installed_version(self.components), **offers}
48        state.write_text(json.dumps({"schema_version": 1, "last_check": last}))
49
50    def test_nothing_cached_nothing_shown(self):
51        self.install_current("0.1.45")
52        self.assertIsNone(engine_update.notice(self.components))
53        self.assertIsNone(engine_update.notice_line(self.components))
54        self.assertIsNone(engine_update.monitor_note(self.components))
55
56    def test_a_newer_engine_is_one_sentence_and_one_next_step(self):
57        self.install_current("0.1.45")
58        self.remember(engine="0.1.56")
59        line = engine_update.notice_line(self.components)
60        self.assertEqual(line, "A new engine 0.1.56 (you have 0.1.45) is available. Update with `strata update`.")
61        self.assertEqual(engine_update.monitor_note(self.components), "New engine 0.1.56 is available. Press u to update.")
62        self.assertNotIn("\n", line)
63
64    def test_a_cached_engine_that_is_not_newer_is_never_shown(self):
65        self.install_current("0.1.56")
66        self.remember(engine="0.1.56", engine_installed="0.1.56")
67        self.assertIsNone(engine_update.notice(self.components))
68
69    def test_the_line_is_dropped_when_the_engine_changed_since_the_check(self):
70        self.install_current("0.1.45")
71        self.remember(engine="0.1.56", engine_installed="0.1.44")
72        self.assertIsNone(engine_update.notice(self.components))
73
74    def test_reading_the_line_touches_no_network(self):
75        self.install_current("0.1.45")
76        self.remember(engine="0.1.56")
77        with mock.patch("urllib.request.urlopen", side_effect=AssertionError("network")), mock.patch("socket.create_connection", side_effect=AssertionError("network")):
78            self.assertIsNotNone(engine_update.notice_line(self.components))
79
80    def test_a_check_writes_what_the_line_reads(self):
81        self.install_current("0.1.45")
82        self.publish(("0.1.56", fx.GOOD_ENGINE))
83        updater.check(self.ctx())
84        self.assertIn("0.1.56", engine_update.notice_line(self.components))
85        self.assertEqual(self.archive_requests(), [], "a check downloads no engine")
86
87
88class DailyCheck(UpdaterCase):
89    def setUp(self):
90        super().setUp()
91        self.install_current("0.1.45")
92        self.calls = 0
93
94    def check(self):
95        self.calls += 1
96
97    def attempt_file(self):
98        return self.components / ".updates" / engine_update.ATTEMPT_FILE
99
100    def test_it_runs_once_and_not_again_the_same_day(self):
101        self.assertTrue(engine_update.refresh_cache(self.check, self.components))
102        self.assertFalse(engine_update.refresh_cache(self.check, self.components))
103        self.assertEqual(self.calls, 1)
104
105    def test_a_failed_check_is_not_retried_until_tomorrow(self):
106        def broken():
107            self.calls += 1
108            raise OSError("no route to host")
109        self.assertFalse(engine_update.refresh_cache(broken, self.components))
110        self.assertFalse(engine_update.refresh_cache(broken, self.components))
111        self.assertEqual(self.calls, 1, "the attempt was written before the network was touched")
112        old = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(hours=25)).isoformat()
113        self.attempt_file().write_text(json.dumps({"at": old}))
114        self.assertTrue(engine_update.refresh_cache(self.check, self.components))
115        self.assertEqual(self.calls, 2)
116
117    def test_a_check_somebody_made_today_counts(self):
118        state = self.components / ".updates" / "state.json"
119        state.parent.mkdir(parents=True, exist_ok=True)
120        state.write_text(json.dumps({"last_check": {"at": dt.datetime.now(dt.timezone.utc).isoformat()}}))
121        self.assertFalse(engine_update.refresh_cache(self.check, self.components))
122        self.assertEqual(self.calls, 0)
123
124    def test_it_can_be_switched_off(self):
125        for value in ("0", "off", "never"):
126            with mock.patch.dict(os.environ, {engine_update.CHECK_ENV: value}):
127                self.assertFalse(engine_update.refresh_cache(self.check, self.components))
128        self.assertEqual(self.calls, 0)
129        self.assertFalse(self.attempt_file().exists())
130
131    def test_it_never_runs_in_a_process_that_forbids_acquiring(self):
132        with mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
133            self.assertIsNone(engine_update.start_daily_check(root=self.components))
134
135    def test_an_attempt_that_cannot_be_remembered_is_not_made(self):
136        with mock.patch.object(Path, "write_text", side_effect=OSError("read-only")):
137            self.assertFalse(engine_update.refresh_cache(self.check, self.components))
138        self.assertEqual(self.calls, 0)
139
140
141class Portal(BaseHTTPRequestHandler):
142    """A captive portal: 200 and a web page for every address."""
143
144    def do_GET(self):
145        body = b"<html><body>Please sign in to the hotel WiFi</body></html>"
146        self.send_response(200)
147        self.send_header("Content-Type", "text/html")
148        self.send_header("Content-Length", str(len(body)))
149        self.end_headers()
150        self.wfile.write(body)
151
152    def log_message(self, *a):
153        pass
154
155
156class Offline(UpdaterCase):
157    """The real daily check against a network that is not there.  Whatever is wrong, the thread ends without a word and the person sees nothing."""
158
159    def setUp(self):
160        super().setUp()
161        self.install_current("0.1.45")
162
163    def run_check(self, feed, join=60.0, env=None):
164        out, err = io.StringIO(), io.StringIO()
165        before = time.monotonic()
166        from tests.terminal import net_dead
167        with mock.patch.dict(os.environ, env or {}), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \
168                self.assertNoLogs(level=logging.INFO), net_dead.no_name_resolution():          # (no real name service: the offline PC is faked)
169            thread = engine_update.start_daily_check(root=self.components, feed=feed)
170            started_in = time.monotonic() - before
171            thread.join(join)
172        self.assertFalse(thread.is_alive(), "the check gave up by itself")
173        self.assertLess(started_in, 1.0, "starting the check does not wait for the network")
174        self.assertEqual((out.getvalue(), err.getvalue()), ("", ""), "nothing is printed")
175        self.assertIsNone(engine_update.notice(self.components))
176        self.assertTrue((self.components / ".updates" / engine_update.ATTEMPT_FILE).is_file(), "tomorrow, not in a minute")
177        self.assertEqual(self.archive_requests(), [])
178
179    def test_nothing_listens(self):
180        self.run_check("http://127.0.0.1:9/strata-feed.json")
181
182    def test_dns_is_blocked(self):
183        self.run_check("https://strata-feed.invalid/strata-feed.json")
184
185    def test_a_proxy_that_refuses(self):
186        self.run_check("https://example.invalid/strata-feed.json",
187                       env={"HTTPS_PROXY": "http://127.0.0.1:9", "https_proxy": "http://127.0.0.1:9", "HTTP_PROXY": "http://127.0.0.1:9"})
188
189    def test_a_captive_portal_that_answers_junk(self):
190        server = ThreadingHTTPServer(("127.0.0.1", 0), Portal)
191        threading.Thread(target=server.serve_forever, daemon=True).start()
192        self.addCleanup(server.server_close)
193        self.addCleanup(server.shutdown)
194        self.run_check(f"http://127.0.0.1:{server.server_address[1]}/strata-feed.json")
195
196    def test_a_connection_that_never_answers(self):
197        hang = socket.socket()
198        hang.bind(("127.0.0.1", 0))
199        hang.listen(5)
200        self.addCleanup(hang.close)
201        started = time.monotonic()
202        self.run_check(f"http://127.0.0.1:{hang.getsockname()[1]}/strata-feed.json", join=60.0)
203        self.assertLess(time.monotonic() - started, 30, "the short timeout ended it")
204
205    def test_a_second_try_the_same_day_makes_no_request_at_all(self):
206        server = ThreadingHTTPServer(("127.0.0.1", 0), Portal)
207        threading.Thread(target=server.serve_forever, daemon=True).start()
208        self.addCleanup(server.server_close)
209        self.addCleanup(server.shutdown)
210        seen = []
211        original = Portal.do_GET
212        Portal.do_GET = lambda handler: (seen.append(handler.path), original(handler))[1]
213        self.addCleanup(setattr, Portal, "do_GET", original)
214        feed = f"http://127.0.0.1:{server.server_address[1]}/strata-feed.json"
215        self.run_check(feed)
216        first = len(seen)
217        self.assertGreater(first, 0)
218        engine_update.start_daily_check(root=self.components, feed=feed).join(10)
219        self.assertEqual(len(seen), first)
220
221
222class OnTheScreens(TuiBase):
223    def note(self, text="A new engine 0.1.56 (you have 0.1.55) is available. Update with `strata update`."):
224        patch = mock.patch.object(engine_update, "notice_line", return_value=text)
225        patch.start()
226        self.addCleanup(patch.stop)
227
228    def test_the_start_screen_shows_the_line_once(self):
229        self.note()
230
231        async def case(app, pilot, ctx):
232            t = " ".join(text_of(app).split())
233            self.assertEqual(t.count("A new engine 0.1.56"), 1)
234            self.assertIn("Update with `strata update`", t)
235        self.run_app(case)
236
237    def test_the_start_screen_without_a_newer_engine_is_as_before(self):
238        async def case(app, pilot, ctx):
239            self.assertNotIn("new engine", text_of(app).lower())
240        self.run_app(case)
241
242
243class Monitor(unittest.TestCase):
244    def run_app(self, coro, info=None, note=None):
245        async def go():
246            app = LaunchMonitor(Source(metrics("idle")), None, info=info or dict(INFO), interval=30)
247            async with app.run_test(size=(120, 40)) as pilot:
248                await pilot.pause(0.5)
249                app.quiet_note = note
250                app._paint()
251                await pilot.pause(0.2)
252                return await coro(app, pilot)
253        return asyncio.run(go())
254
255    def test_the_line_and_the_key(self):
256        async def case(app, pilot):
257            t = flat(app)
258            self.assertIn("New engine 0.1.56 is available. Press u to update.", t)
259            self.assertEqual(t.count("is available"), 1)
260        self.run_app(case, note="New engine 0.1.56 is available. Press u to update.")
261
262    def test_no_line_when_nothing_is_new(self):
263        async def case(app, pilot):
264            self.assertNotIn("Press u", flat(app))
265        self.run_app(case)
266
267    def test_the_daily_check_is_started_by_the_launch_monitor_only(self):
268        with mock.patch.object(engine_update, "start_daily_check") as start:
269            self.run_app(lambda app, pilot: asyncio.sleep(0))
270            start.assert_not_called()                                        # (plain monitors, tests, `strata monitor --url`)
271            self.run_app(lambda app, pilot: asyncio.sleep(0), info={**INFO, "daily_check": True})
272            start.assert_called_once()
273
274    def test_run_monitor_asks_for_the_check(self):
275        seen = {}
276
277        class Stub:
278            def __init__(self, endpoint, snapshot, info, **kw):
279                seen.update(info)
280                self.stop_requested = False
281
282            def run(self):
283                return None
284        with mock.patch("strata_cli.launch.monitor_ext.LaunchMonitor", Stub):
285            launch_app.run_monitor({"url": "http://127.0.0.1:8080", "urls": ["http://127.0.0.1:8080"], "key": "", "profile": "launch-x"})
286        self.assertTrue(seen.get("daily_check"))
287
288    def test_a_monitor_beside_a_hanging_feed_is_not_slowed(self):
289        hang = socket.socket()
290        hang.bind(("127.0.0.1", 0))
291        hang.listen(5)
292        self.addCleanup(hang.close)
293        with tempfile_home() as home:
294            env = {"STRATA_COMPONENTS_DIR": home, "STRATA_UPDATE_FEED": f"http://127.0.0.1:{hang.getsockname()[1]}/strata-feed.json"}
295            with mock.patch.dict(os.environ, env):
296                started = time.monotonic()
297
298                async def case(app, pilot):
299                    self.assertNotIn("Press u", flat(app))
300                    return time.monotonic() - started
301                took = self.run_app(case, info={**INFO, "daily_check": True})
302        self.assertLess(took, 5.0, "the monitor drew and ran while the check was still waiting")
303
304    def test_u_asks_names_the_model_and_shows_what_happened(self):
305        def flow(*, ask, say, **kw):
306            say("Checking for a newer engine...")
307            if not ask("Stop Demo model (port 8080) for the update?", False):
308                raise engine_update.Declined("Nothing was changed. The model keeps running.")
309            return {"results": [{"component": "engine", "status": "updated", "installed_after": "0.1.56"}],
310                    "models": {"restarts": [{"name": "Demo model", "restarted": True, "message": "Demo model is serving again with the same settings."}]}}
311
312        async def case(app, pilot):
313            await pilot.press("u")
314            await pilot.pause(0.6)
315            t = flat(app)
316            self.assertIn("Stop Demo model (port 8080) for the update?", t)
317            await pilot.press("enter")                                       # Yes
318            await pilot.pause(0.8)
319            t = flat(app)
320            self.assertIn("Engine is now 0.1.56", t)
321            self.assertIn("serving again", t)
322            self.assertFalse(app.updating)
323        with mock.patch.object(engine_update, "run_flow", side_effect=flow):
324            self.run_app(case, note="New engine 0.1.56 is available. Press u to update.")
325
326    def test_u_and_no_changes_nothing(self):
327        def flow(*, ask, say, **kw):
328            if not ask("Stop Demo model for the update?", False):
329                raise engine_update.Declined("Nothing was changed. The model keeps running.")
330            raise AssertionError("must not get here")
331
332        async def case(app, pilot):
333            await pilot.press("u")
334            await pilot.pause(0.6)
335            await pilot.press("down", "enter")                               # No
336            await pilot.pause(0.8)
337            self.assertIn("Nothing was changed. The model keeps running.", flat(app))
338        with mock.patch.object(engine_update, "run_flow", side_effect=flow):
339            self.run_app(case)
340
341    def test_a_flow_that_breaks_is_a_sentence_not_a_trace(self):
342        async def case(app, pilot):
343            await pilot.press("u")
344            await pilot.pause(0.8)
345            self.assertIn("The update did not run: boom", flat(app))
346            self.assertTrue(app.is_running)
347        with mock.patch.object(engine_update, "run_flow", side_effect=RuntimeError("boom")):
348            self.run_app(case)
349
350
351@contextlib.contextmanager
352def tempfile_home():
353    import tempfile
354    # A check the app started in the background may still hold .updates/update.lock when the case ends (a file in use cannot be deleted on
355    # Windows); the folder is scratch, so a leftover is not a failure of the case.
356    with tempfile.TemporaryDirectory(prefix="strata-notice-", ignore_cleanup_errors=True) as d:
357        yield d
358
359
360if __name__ == "__main__":
361    unittest.main()