Debian Codegraph @

tests/functional_tests/test_ssh_recovery.py

raw
1 """A tunnel that drops mid-session, and the connection that died with it.
2
3 Restarting `ssh` is not enough on its own -- the adapter's TCP connection ran
4 *through* the old forward -- so the recovery is both halves, and it happens
5 lazily, before the next thing that needs the database.
6 """
7
8 from __future__ import annotations
9
10 import sys
11 from pathlib import Path
12 from typing import Awaitable, Callable, Iterator
13
14 import pytest
15 from textual.pilot import Pilot
16
17 from harlequin import Harlequin
18 from harlequin.app import QuerySubmitted
19 from harlequin.catalog import InteractiveCatalogItem
20 from harlequin.components.data_catalog.database_tree import DatabaseTree
21 from harlequin.components.text_modal import ErrorModal
22 from harlequin.ssh import Forward, SshTunnel
23 from tests.functional_tests.helpers import (
24 expand_catalog_node,
25 first_database_node,
26 rendered_catalog,
27 replaced_catalog,
28 )
29 from tests.tunnels import ssh_child_exited
30 from tests.waiting import POLL_INTERVAL, accepts, on_a_free_port, wait_for
31
32 pytestmark = pytest.mark.skipif(
33 sys.platform == "win32", reason="the fake client binds on a POSIX loopback"
34 )
35
36
37 def _modal_text(app: Harlequin) -> str:
38 """What the error modal on top of the stack is showing."""
39 modal = app.screen_stack[-1]
40 assert isinstance(modal, ErrorModal)
41 return modal.text
42
43
44 async def _wait_for_drop(pilot: Pilot, tunnel: SshTunnel) -> None:
45 """Wait for the watcher thread to notice the child let the forward go."""
46 await wait_for(
47 pilot,
48 lambda: tunnel.needs_restart,
49 description="the tunnel to be reported dropped",
50 interval=POLL_INTERVAL,
51 )
52
53
54 @pytest.fixture
55 def dropping_tunnel(drop_trigger: Path, fake_ssh_client: Path) -> Iterator[SshTunnel]:
56 """A tunnel whose child holds its forward until `drop_trigger` is touched."""
57
58 def start(port: int) -> SshTunnel:
59 tunnel = SshTunnel(
60 [
61 sys.executable,
62 str(fake_ssh_client),
63 "-N",
64 "-L",
65 f"{port}:db.internal:5432",
66 "web-1",
67 ],
68 forwards=(Forward(str(port), "[db.internal]:5432"),),
69 host="web-1",
70 )
71 tunnel.start()
72 return tunnel
73
74 tunnel = on_a_free_port(start, retry_on=ssh_child_exited)
75 try:
76 yield tunnel
77 finally:
78 tunnel.stop()
79
80
81 @pytest.mark.asyncio
82 async def test_a_dropped_tunnel_is_reopened_before_the_next_thing_that_needs_it(
83 app: Harlequin,
84 dropping_tunnel: SshTunnel,
85 drop_trigger: Path,
86 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
87 monkeypatch: pytest.MonkeyPatch,
88 ) -> None:
89 app.ssh_tunnel = dropping_tunnel
90 async with app.run_test() as pilot:
91 await wait_for_workers(app)
92 first_connection = app.connection
93 assert first_connection is not None
94
95 drop_trigger.touch()
96 await _wait_for_drop(pilot, dropping_tunnel)
97 # the child that comes back stays up
98 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
99
100 app.action_refresh_catalog()
101 await wait_for_workers(app)
102 await wait_for(
103 pilot,
104 lambda: (
105 app.connection is not None and app.connection is not first_connection
106 ),
107 description="the app to adopt the connection it reconnected with",
108 )
109
110 assert dropping_tunnel.running
111 # both halves: a new session, on a forward that is open again
112 assert accepts(dropping_tunnel.endpoints[0][1])
113
114
115 @pytest.fixture
116 def schema_updates(monkeypatch: pytest.MonkeyPatch) -> list[None]:
117 """Every call to `update_schema_data`, so a double refresh is visible."""
118 calls: list[None] = []
119 start_worker = Harlequin.update_schema_data
120
121 def counted(app: Harlequin) -> None:
122 calls.append(None)
123 start_worker(app)
124
125 monkeypatch.setattr(Harlequin, "update_schema_data", counted)
126 return calls
127
128
129 @pytest.mark.asyncio
130 async def test_a_reconnect_leaves_a_catalog_that_still_loads(
131 app_small_sqlite: Harlequin,
132 dropping_tunnel: SshTunnel,
133 drop_trigger: Path,
134 schema_updates: list[None],
135 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
136 monkeypatch: pytest.MonkeyPatch,
137 ) -> None:
138 """A query that reopens a dropped tunnel leaves a catalog that still loads.
139
140 sqlite is the adapter here because its `close()` really closes the driver
141 connection, so an item left on the old one fails deterministically rather
142 than by luck.
143 """
144 # the node under test has to still be unloaded when the tunnel drops, and
145 # the prefetch scan would have loaded it during start-up
146 monkeypatch.setattr(DatabaseTree, "_schedule_prefetch_scan", lambda _self: None)
147 app = app_small_sqlite
148 app.ssh_tunnel = dropping_tunnel
149 async with app.run_test() as pilot:
150 await wait_for_workers(app)
151 first_connection = app.connection
152 first_catalog = await rendered_catalog(pilot, app)
153 assert first_connection is not None
154 db_node = await first_database_node(pilot, app)
155 assert isinstance(db_node.data, InteractiveCatalogItem)
156 assert not db_node.data.loaded
157
158 drop_trigger.touch()
159 await _wait_for_drop(pilot, dropping_tunnel)
160 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
161
162 # a query is the recovery's other trigger; a refresh would rebuild
163 # the tree on its own, which is the workaround this replaces
164 schema_updates.clear()
165 app.post_message(QuerySubmitted(queries=["select 1"], limit=None))
166 await wait_for_workers(app)
167 rebuilt_catalog = await replaced_catalog(pilot, app, first_catalog)
168
169 assert len(schema_updates) == 1
170 assert rebuilt_catalog is not first_catalog
171 assert app.connection is not first_connection
172 db_node = await first_database_node(pilot, app)
173 assert isinstance(db_node.data, InteractiveCatalogItem)
174 assert db_node.data.connection is app.connection
175
176 # the symptom in #1127: expanding a node that had not loaded yet
177 await expand_catalog_node(pilot, db_node)
178 assert db_node.data.loaded
179 assert len(app.screen_stack) == 1 # no Catalog Error modal
180
181
182 @pytest.mark.asyncio
183 async def test_a_refresh_that_reconnects_does_not_ask_for_a_second_one(
184 app: Harlequin,
185 dropping_tunnel: SshTunnel,
186 drop_trigger: Path,
187 schema_updates: list[None],
188 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
189 monkeypatch: pytest.MonkeyPatch,
190 ) -> None:
191 app.ssh_tunnel = dropping_tunnel
192 async with app.run_test() as pilot:
193 await wait_for_workers(app)
194 first_catalog = await rendered_catalog(pilot, app)
195
196 drop_trigger.touch()
197 await _wait_for_drop(pilot, dropping_tunnel)
198 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
199
200 # the refresh builds the tree on the connection it recovered, so
201 # two `get_catalog()` calls would be two threads inside one adapter
202 schema_updates.clear()
203 app.action_refresh_catalog()
204 await wait_for_workers(app)
205 rebuilt_catalog = await replaced_catalog(pilot, app, first_catalog)
206
207 assert len(schema_updates) == 1
208 assert rebuilt_catalog is not first_catalog
209
210
211 @pytest.mark.asyncio
212 async def test_a_tunnel_that_will_not_come_back_is_not_tried_twice(
213 app: Harlequin,
214 dropping_tunnel: SshTunnel,
215 drop_trigger: Path,
216 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
217 monkeypatch: pytest.MonkeyPatch,
218 ) -> None:
219 app.ssh_tunnel = dropping_tunnel
220 async with app.run_test() as pilot:
221 await wait_for_workers(app)
222 drop_trigger.touch()
223 await _wait_for_drop(pilot, dropping_tunnel)
224 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
225 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
226
227 app.action_refresh_catalog()
228 await wait_for_workers(app)
229 # the error modal, once, quoting ssh
230 await wait_for(
231 pilot,
232 lambda: len(app.screen_stack) == 2,
233 description="the modal that says why the tunnel stayed down",
234 )
235 assert not dropping_tunnel.needs_restart
236 assert "Permission denied (publickey)." in _modal_text(app)
237 await pilot.press("escape")
238 await wait_for(
239 pilot,
240 lambda: len(app.screen_stack) == 1,
241 description="the error modal to be dismissed",
242 )
243
244 # and the worker aborts rather than running on the connection that
245 # died with the forward, which would raise a second modal
246 assert app._connection_for_worker() is None
247
248 app.action_refresh_catalog()
249 await wait_for_workers(app)
250 # no catalog is coming, so the refresh's spinner has to stop
251 await wait_for(
252 pilot,
253 lambda: not app.data_catalog.database_tree.loading,
254 description="the Data Catalog's spinner to stop",
255 )
256 assert not dropping_tunnel.running
257 assert len(app.screen_stack) == 1