|
| 1 | +"""Media server port stays fixed after logout -> InitializeApplication -> login.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import threading |
| 5 | +import time |
| 6 | + |
| 7 | +import pytest |
| 8 | +import requests |
| 9 | +import urllib3 |
| 10 | +import websocket |
| 11 | + |
| 12 | +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) |
| 13 | + |
| 14 | +HTTP_BASE = "http://127.0.0.1:8080/statusgo" |
| 15 | +WS_URL = "ws://127.0.0.1:8080/signals" |
| 16 | +DATA_DIR = "./data-dir" |
| 17 | +MEDIA_PORT = 8081 |
| 18 | +PASSWORD = "StatusSdkPortTest1" |
| 19 | + |
| 20 | + |
| 21 | +class SignalBuffer: |
| 22 | + def __init__(self, url: str): |
| 23 | + self.url = url |
| 24 | + self.by_type: dict[str, list[dict]] = {} |
| 25 | + self._cond = threading.Condition() |
| 26 | + self._stop = False |
| 27 | + self._thread = threading.Thread(target=self._run, daemon=True) |
| 28 | + self._thread.start() |
| 29 | + time.sleep(0.3) |
| 30 | + |
| 31 | + def _run(self): |
| 32 | + while not self._stop: |
| 33 | + |
| 34 | + def on_message(_ws, raw: str): |
| 35 | + try: |
| 36 | + msg = json.loads(raw) |
| 37 | + except json.JSONDecodeError: |
| 38 | + return |
| 39 | + typ = msg.get("type") |
| 40 | + if not typ: |
| 41 | + return |
| 42 | + with self._cond: |
| 43 | + self.by_type.setdefault(typ, []).append(msg) |
| 44 | + self._cond.notify_all() |
| 45 | + |
| 46 | + wsapp = websocket.WebSocketApp(self.url, on_message=on_message) |
| 47 | + wsapp.run_forever() |
| 48 | + if not self._stop: |
| 49 | + time.sleep(0.5) |
| 50 | + |
| 51 | + def count(self, signal_type: str) -> int: |
| 52 | + with self._cond: |
| 53 | + return len(self.by_type.get(signal_type, [])) |
| 54 | + |
| 55 | + def wait_for(self, signal_type: str, timeout: float = 90) -> dict: |
| 56 | + deadline = time.monotonic() + timeout |
| 57 | + with self._cond: |
| 58 | + while time.monotonic() < deadline: |
| 59 | + buf = self.by_type.get(signal_type, []) |
| 60 | + if buf: |
| 61 | + return buf[-1] |
| 62 | + self._cond.wait(timeout=0.5) |
| 63 | + raise TimeoutError(f"signal {signal_type!r} not received within {timeout}s") |
| 64 | + |
| 65 | + def latest_port(self, signal_type: str, since: int) -> int | None: |
| 66 | + with self._cond: |
| 67 | + signals = self.by_type.get(signal_type, [])[since:] |
| 68 | + for msg in reversed(signals): |
| 69 | + port = (msg.get("event") or {}).get("port") |
| 70 | + if port is not None: |
| 71 | + return int(port) |
| 72 | + return None |
| 73 | + |
| 74 | + def close(self): |
| 75 | + self._stop = True |
| 76 | + |
| 77 | + |
| 78 | +def post_json(path: str, payload: dict | None = None) -> dict: |
| 79 | + resp = requests.post(f"{HTTP_BASE}/{path}", json=payload or {}, timeout=60) |
| 80 | + resp.raise_for_status() |
| 81 | + if not resp.content: |
| 82 | + return {} |
| 83 | + return resp.json() |
| 84 | + |
| 85 | + |
| 86 | +def wait_backend_healthy(timeout: float = 180) -> None: |
| 87 | + deadline = time.monotonic() + timeout |
| 88 | + last_exc: Exception | None = None |
| 89 | + while time.monotonic() < deadline: |
| 90 | + try: |
| 91 | + if requests.get("http://127.0.0.1:8080/health", timeout=5).status_code == 200: |
| 92 | + return |
| 93 | + except requests.RequestException as exc: |
| 94 | + last_exc = exc |
| 95 | + time.sleep(2) |
| 96 | + raise RuntimeError(f"backend not healthy within {timeout}s: {last_exc}") |
| 97 | + |
| 98 | + |
| 99 | +def initialize() -> dict: |
| 100 | + return post_json( |
| 101 | + "InitializeApplication", |
| 102 | + { |
| 103 | + "dataDir": DATA_DIR, |
| 104 | + "apiLoggingEnabled": True, |
| 105 | + "mediaServerAddress": f"0.0.0.0:{MEDIA_PORT}", |
| 106 | + "mediaServerAdvertizeHost": "localhost", |
| 107 | + "mediaServerAdvertizePort": MEDIA_PORT, |
| 108 | + }, |
| 109 | + ) |
| 110 | + |
| 111 | + |
| 112 | +def logout(signals: SignalBuffer | None = None) -> None: |
| 113 | + try: |
| 114 | + post_json("Logout") |
| 115 | + if signals is not None: |
| 116 | + try: |
| 117 | + signals.wait_for("node.stopped", timeout=30) |
| 118 | + except TimeoutError: |
| 119 | + pass |
| 120 | + except requests.RequestException: |
| 121 | + pass |
| 122 | + |
| 123 | + |
| 124 | +def media_server_health_ok(port: int) -> bool: |
| 125 | + try: |
| 126 | + r = requests.get(f"https://127.0.0.1:{port}/health", timeout=10, verify=False) |
| 127 | + return r.status_code == 200 |
| 128 | + except requests.RequestException: |
| 129 | + return False |
| 130 | + |
| 131 | + |
| 132 | +def observed_port(signals: SignalBuffer, since: int) -> int | None: |
| 133 | + signal_port = signals.latest_port("mediaserver.started", since) |
| 134 | + if signal_port is not None: |
| 135 | + return signal_port |
| 136 | + if media_server_health_ok(MEDIA_PORT): |
| 137 | + return MEDIA_PORT |
| 138 | + return None |
| 139 | + |
| 140 | + |
| 141 | +def ensure_account(signals: SignalBuffer, init_data: dict) -> str: |
| 142 | + accounts = init_data.get("accounts") or [] |
| 143 | + if accounts: |
| 144 | + return accounts[0]["key-uid"] |
| 145 | + |
| 146 | + post_json( |
| 147 | + "CreateAccountAndLogin", |
| 148 | + { |
| 149 | + "rootDataDir": DATA_DIR, |
| 150 | + "kdfIterations": 256000, |
| 151 | + "displayName": "PortCheck", |
| 152 | + "password": PASSWORD, |
| 153 | + "customizationColor": "primary", |
| 154 | + "wakuV2LightClient": False, |
| 155 | + "thirdpartyServicesEnabled": True, |
| 156 | + "logEnabled": True, |
| 157 | + "logLevel": "INFO", |
| 158 | + }, |
| 159 | + ) |
| 160 | + signals.wait_for("node.login") |
| 161 | + init_data = initialize() |
| 162 | + accounts = init_data.get("accounts") or [] |
| 163 | + assert accounts, "no accounts after CreateAccountAndLogin" |
| 164 | + return accounts[0]["key-uid"] |
| 165 | + |
| 166 | + |
| 167 | +def login(key_uid: str, signals: SignalBuffer) -> None: |
| 168 | + post_json( |
| 169 | + "LoginAccount", |
| 170 | + { |
| 171 | + "keyUid": key_uid, |
| 172 | + "password": PASSWORD, |
| 173 | + "kdfIterations": 256000, |
| 174 | + "thirdpartyServicesEnabled": True, |
| 175 | + }, |
| 176 | + ) |
| 177 | + event = signals.wait_for("node.login") |
| 178 | + err = (event.get("event") or {}).get("error") |
| 179 | + if err: |
| 180 | + raise RuntimeError(f"login error: {err}") |
| 181 | + |
| 182 | + |
| 183 | +@pytest.fixture |
| 184 | +def signals(): |
| 185 | + buf = SignalBuffer(WS_URL) |
| 186 | + yield buf |
| 187 | + buf.close() |
| 188 | + logout(buf) |
| 189 | + |
| 190 | + |
| 191 | +def test_media_port_persists_across_logout_reinit(signals): |
| 192 | + wait_backend_healthy() |
| 193 | + logout(signals) |
| 194 | + since = signals.count("mediaserver.started") |
| 195 | + init_data = initialize() |
| 196 | + key_uid = ensure_account(signals, init_data) |
| 197 | + login(key_uid, signals) |
| 198 | + port1 = observed_port(signals, since) |
| 199 | + assert port1 == MEDIA_PORT, f"first login: expected {MEDIA_PORT}, got {port1}" |
| 200 | + |
| 201 | + logout(signals) |
| 202 | + since = signals.count("mediaserver.started") |
| 203 | + initialize() |
| 204 | + login(key_uid, signals) |
| 205 | + port2 = observed_port(signals, since) |
| 206 | + assert port2 == MEDIA_PORT, f"after re-init: expected {MEDIA_PORT}, got {port2}" |
0 commit comments