Coverage for custom_components/ha_repl_server/websocket_api.py: 84%

147 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""Websocket commands: ha_repl_server/exec, ha_repl_server/cancel, 

2ha_repl_server/complete, ha_repl_server/reset, ha_repl_server/sessions, ha_repl_server/info, 

3ha_repl_server/sql and ha_repl_server/sql_tables (all admin only). 

4 

5Every command that runs or stops something - exec, cancel, reset and sql - is 

6logged at WARNING, so it shows in Home Assistant's log by default, with the 

7user who sent it, and how it went with its timing - on its own logger, 

8COMMAND_LOG, to be quietened without hiding the integration's other warnings. 

9complete runs nothing, so is logged at DEBUG only. 

10""" 

11 

12from __future__ import annotations 

13 

14import asyncio 

15import base64 

16import contextlib 

17import logging 

18import time 

19from typing import TYPE_CHECKING, Any, cast 

20 

21from homeassistant.components import websocket_api 

22from homeassistant.core import HomeAssistant, callback 

23from homeassistant.loader import async_get_integration 

24 

25from .complete import complete, describe, signature, source 

26from .const import DEFAULT_MAX_ROWS, DEFAULT_SESSION, DOMAIN 

27from .objtree import async_load_action_descriptions 

28from .session import SessionManager 

29 

30if TYPE_CHECKING: 

31 import probatio as vol 

32else: 

33 # From 2026.9 Home Assistant installs probatio as `voluptuous`, so this is 

34 # probatio there; 2026.8, still supported, has only voluptuous. 

35 import voluptuous as vol 

36 

37_LOGGER = logging.getLogger(__package__) 

38COMMAND_LOG = logging.getLogger(f"{__package__}.commands") 

39 

40 

41# What a client can ask this server for, given in ha_repl_server/info so a 

42# newer client can tell what an older server lacks. 

43COMMANDS = frozenset({ 

44 "exec", 

45 "cancel", 

46 "complete", 

47 "reset", 

48 "sessions", 

49 "info", 

50 "sql", 

51 "sql_tables", 

52}) 

53 

54 

55@callback 

56def async_register(hass: HomeAssistant) -> None: 

57 websocket_api.async_register_command(hass, ws_exec) 

58 websocket_api.async_register_command(hass, ws_cancel) 

59 websocket_api.async_register_command(hass, ws_complete) 

60 websocket_api.async_register_command(hass, ws_reset) 

61 websocket_api.async_register_command(hass, ws_sessions) 

62 websocket_api.async_register_command(hass, ws_info) 

63 websocket_api.async_register_command(hass, ws_sql) 

64 websocket_api.async_register_command(hass, ws_sql_tables) 

65 

66 

67def _manager( 

68 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

69) -> SessionManager | None: 

70 if (manager := hass.data.get(DOMAIN)) is None: 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true

71 connection.send_error( 

72 msg["id"], "not_loaded", "Home Assistant REPL integration is not loaded" 

73 ) 

74 return manager 

75 

76 

77def _who(connection: websocket_api.ActiveConnection) -> str: 

78 user = connection.user 

79 return user.name or user.id if user else "unknown user" 

80 

81 

82@websocket_api.require_admin 

83# Home Assistant installs probatio as the `voluptuous` module itself 

84# (probatio.compat.install_as_voluptuous(), called from homeassistant's own 

85# __init__.py) - this schema and websocket_command()'s internal 

86# BASE_COMMAND_MESSAGE_SCHEMA.extend() both end up using the same probatio 

87# Marker classes at runtime, so this works. Static checkers don't know that: 

88# websocket_command()'s own signature is still annotated against real 

89# voluptuous's Marker/VolDictType, a type unrelated to probatio's from 

90# mypy/ty's point of view - hence the cast. 

91@websocket_api.websocket_command( 

92 cast( 

93 Any, 

94 { 

95 vol.Required("type"): "ha_repl_server/exec", 

96 vol.Required("code"): str, 

97 vol.Optional("session", default=DEFAULT_SESSION): str, 

98 vol.Optional("timeout"): vol.Coerce(float), 

99 vol.Optional("color", default=False): bool, 

100 vol.Optional("width", default=88): vol.Coerce(int), 

101 vol.Optional("auto_await", default=True): bool, 

102 vol.Optional("fetch", default=list): [str], 

103 }, 

104 ) 

105) 

106@websocket_api.async_response 

107async def ws_exec( 

108 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

109) -> None: 

110 if (manager := _manager(hass, connection, msg)) is None: 110 ↛ 111line 110 didn't jump to line 111 because the condition on line 110 was never true

111 return 

112 # So an action in `obj` has its description, which is read where nothing 

113 # can be waited for. The code runs without it, just less well described. 

114 with contextlib.suppress(Exception): 

115 await async_load_action_descriptions(hass) 

116 who, session = _who(connection), msg["session"] 

117 COMMAND_LOG.warning("%s runs in session %r:\n%s", who, session, msg["code"]) 

118 try: 

119 result = await manager.get(session).run( 

120 msg["code"], 

121 msg.get("timeout"), 

122 color=msg["color"], 

123 width=msg["width"], 

124 auto_await=msg["auto_await"], 

125 fetch=msg["fetch"], 

126 ) 

127 except asyncio.CancelledError: 

128 COMMAND_LOG.warning( 

129 "%s's run in session %r stopped: connection closed", who, session 

130 ) 

131 raise 

132 COMMAND_LOG.warning("%s's run in session %r %s", who, session, result.summary()) 

133 connection.send_result(msg["id"], result.as_dict()) 

134 

135 

136@websocket_api.require_admin 

137@websocket_api.websocket_command( 

138 cast( 

139 Any, 

140 { 

141 vol.Required("type"): "ha_repl_server/cancel", 

142 vol.Optional("session"): str, 

143 }, 

144 ) 

145) 

146@callback 

147def ws_cancel( 

148 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

149) -> None: 

150 """Stop the code running in a session, or in every session if none is 

151 given - what the shell sends on Ctrl-C. The stopped run still answers its 

152 own exec, with a CancelledError.""" 

153 if (manager := _manager(hass, connection, msg)) is None: 153 ↛ 154line 153 didn't jump to line 154 because the condition on line 153 was never true

154 return 

155 who = _who(connection) 

156 stopped = manager.cancel(msg.get("session"), f"Stopped by {who}") 

157 COMMAND_LOG.warning( 

158 "%s stopped %s", 

159 who, 

160 ", ".join(f"session {name!r}" for name in stopped) or "nothing (none running)", 

161 ) 

162 connection.send_result(msg["id"], {"stopped": stopped}) 

163 

164 

165@websocket_api.require_admin 

166@websocket_api.websocket_command( 

167 cast( 

168 Any, 

169 { 

170 vol.Required("type"): "ha_repl_server/complete", 

171 vol.Required("source"): str, 

172 vol.Required("cursor"): vol.Coerce(int), 

173 vol.Optional("session", default=DEFAULT_SESSION): str, 

174 vol.Optional("kind", default="completions"): vol.In([ 

175 "completions", 

176 "signature", 

177 "source", 

178 "doc", 

179 ]), 

180 }, 

181 ) 

182) 

183@websocket_api.async_response 

184async def ws_complete( 

185 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

186) -> None: 

187 """What can go at the cursor, from the session's own namespace - see 

188 complete.py. Runs nothing, so it takes no lock and answers while an 

189 exec is running, and on the event loop, where the registries the 

190 object tree reads can be read. `resolved` is False when the expression 

191 before the cursor couldn't be followed without running something. 

192 

193 With `kind: "signature"`, the signature of the call the cursor is in 

194 instead, or None. With `kind: "source"`, where the source of what 

195 `source` names is, with a GitHub link at the version running, or None - 

196 for `thing??`. With `kind: "doc"`, what `source` names: its type, 

197 signature and docstring - for Ctrl-Space and `ha-repl inspect`.""" 

198 if (manager := _manager(hass, connection, msg)) is None: 198 ↛ 199line 198 didn't jump to line 199 because the condition on line 198 was never true

199 return 

200 namespace = manager.namespace(msg["session"]) 

201 if msg["kind"] == "source": 

202 integration = await async_get_integration(hass, DOMAIN) 

203 versions = {"custom_components.ha_repl_server": str(integration.version)} 

204 found_source = source(msg["source"], namespace, versions) 

205 connection.send_result( 

206 msg["id"], {"source": found_source.as_dict() if found_source else None} 

207 ) 

208 return 

209 if msg["kind"] == "doc": 

210 found_doc = describe(msg["source"], namespace) 

211 connection.send_result( 

212 msg["id"], {"doc": found_doc.as_dict() if found_doc else None} 

213 ) 

214 return 

215 if msg["kind"] == "signature": 

216 found = signature(msg["source"], msg["cursor"], namespace) 

217 connection.send_result( 

218 msg["id"], {"signature": found.as_dict() if found else None} 

219 ) 

220 return 

221 result = complete( 

222 msg["source"], 

223 msg["cursor"], 

224 namespace, 

225 limit=manager.complete_limit, 

226 budget=manager.complete_budget, 

227 ) 

228 _LOGGER.debug("%s completes %r", _who(connection), msg["source"][: msg["cursor"]]) 

229 if result is None: 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 connection.send_result( 

231 msg["id"], {"items": [], "replace": 0, "resolved": False} 

232 ) 

233 return 

234 connection.send_result(msg["id"], {**result.as_dict(), "resolved": True}) 

235 

236 

237@websocket_api.require_admin 

238@websocket_api.websocket_command( 

239 cast( 

240 Any, 

241 { 

242 vol.Required("type"): "ha_repl_server/reset", 

243 vol.Optional("session", default=DEFAULT_SESSION): str, 

244 }, 

245 ) 

246) 

247@callback 

248def ws_reset( 

249 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

250) -> None: 

251 if (manager := _manager(hass, connection, msg)) is None: 

252 return 

253 reset = manager.reset(msg["session"]) 

254 COMMAND_LOG.warning("%s reset session %r", _who(connection), msg["session"]) 

255 connection.send_result(msg["id"], {"reset": reset}) 

256 

257 

258@websocket_api.require_admin 

259@websocket_api.websocket_command( 

260 cast(Any, {vol.Required("type"): "ha_repl_server/sessions"}) 

261) 

262@callback 

263def ws_sessions( 

264 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

265) -> None: 

266 if (manager := _manager(hass, connection, msg)) is None: 

267 return 

268 connection.send_result(msg["id"], {"sessions": manager.describe()}) 

269 

270 

271@websocket_api.require_admin 

272@websocket_api.websocket_command( 

273 cast(Any, {vol.Required("type"): "ha_repl_server/info"}) 

274) 

275@websocket_api.async_response 

276async def ws_info( 

277 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

278) -> None: 

279 """The server-side component's own version - compared against the 

280 client's own package version in the live-mode shell's startup banner, 

281 since the two are versioned and deployed independently (PyPI package vs 

282 Marketplace component) and can drift out of sync.""" 

283 integration = await async_get_integration(hass, DOMAIN) 

284 connection.send_result( 

285 msg["id"], {"version": integration.version, "commands": sorted(COMMANDS)} 

286 ) 

287 

288 

289def _sql_manager( 

290 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

291) -> SessionManager | None: 

292 """_manager(), plus the integration's own expose_sql switch.""" 

293 if (manager := _manager(hass, connection, msg)) is None: 293 ↛ 294line 293 didn't jump to line 294 because the condition on line 293 was never true

294 return None 

295 if not manager.has_feature("sql"): 

296 if reason := manager.unavailable.get("sql"): 

297 connection.send_error( 

298 msg["id"], "sql_unavailable", f"sql couldn't be loaded: {reason}" 

299 ) 

300 else: 

301 connection.send_error( 

302 msg["id"], 

303 "sql_disabled", 

304 "sql is switched off in this integration's options", 

305 ) 

306 return None 

307 return manager 

308 

309 

310@websocket_api.require_admin 

311@websocket_api.websocket_command( 

312 cast( 

313 Any, 

314 { 

315 vol.Required("type"): "ha_repl_server/sql", 

316 vol.Required("query"): str, 

317 vol.Optional("max_rows", default=DEFAULT_MAX_ROWS): vol.Any( 

318 None, vol.Coerce(int) 

319 ), 

320 vol.Optional("raw", default=False): bool, 

321 }, 

322 ) 

323) 

324@websocket_api.async_response 

325async def ws_sql( 

326 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

327) -> None: 

328 """Run one query and send the result back as Arrow IPC bytes (base64, 

329 since the websocket API is JSON) - the client's own `sql` is a local 

330 object calling this, not code exec'd here, so everything past the 

331 download (show(), dataframes, CSV) happens on the client's machine.""" 

332 if _sql_manager(hass, connection, msg) is None: 

333 return 

334 # Imported only once _load_sql has, so only if it could be. 

335 from .sql import SqlError, sql 

336 

337 who = _who(connection) 

338 COMMAND_LOG.warning("%s queries:\n%s", who, msg["query"]) 

339 start = time.perf_counter() 

340 try: 

341 result = await sql(hass, msg["query"], max_rows=msg["max_rows"], raw=msg["raw"]) 

342 except Exception as err: # noqa: BLE001 - a bad query is the caller's to see, whatever the driver raised 

343 message = ( 

344 str(err) if isinstance(err, SqlError) else f"{type(err).__name__}: {err}" 

345 ) 

346 COMMAND_LOG.warning( 

347 "%s's query failed in %.3fs: %s", who, time.perf_counter() - start, message 

348 ) 

349 connection.send_error(msg["id"], "sql_error", message) 

350 return 

351 COMMAND_LOG.warning( 

352 "%s's query returned %d rows in %.3fs%s", 

353 who, 

354 result.rowcount, 

355 time.perf_counter() - start, 

356 ", truncated" if result.truncated else "", 

357 ) 

358 connection.send_result( 

359 msg["id"], 

360 { 

361 "arrow": base64.b64encode(result.data).decode("ascii"), 

362 "truncated": result.truncated, 

363 }, 

364 ) 

365 

366 

367@websocket_api.require_admin 

368@websocket_api.websocket_command( 

369 cast(Any, {vol.Required("type"): "ha_repl_server/sql_tables"}) 

370) 

371@callback 

372def ws_sql_tables( 

373 hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] 

374) -> None: 

375 """The recorder's tables and their columns, as plain data for the 

376 client's own `sql.tables`.""" 

377 if _sql_manager(hass, connection, msg) is None: 

378 return 

379 from .sql import table_schemas 

380 

381 connection.send_result(msg["id"], {"tables": table_schemas()})