_app.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. import inspect
  2. import socket
  3. import threading
  4. import time
  5. from typing import Any, Callable, Optional, Union
  6. from . import _logging
  7. from ._abnf import ABNF
  8. from ._core import WebSocket, getdefaulttimeout
  9. from ._exceptions import (
  10. WebSocketConnectionClosedException,
  11. WebSocketException,
  12. WebSocketTimeoutException,
  13. )
  14. from ._ssl_compat import SSLEOFError
  15. from ._url import parse_url
  16. from ._dispatcher import Dispatcher, DispatcherBase, SSLDispatcher, WrappedDispatcher
  17. """
  18. _app.py
  19. websocket - WebSocket client library for Python
  20. Copyright 2025 engn33r
  21. Licensed under the Apache License, Version 2.0 (the "License");
  22. you may not use this file except in compliance with the License.
  23. You may obtain a copy of the License at
  24. http://www.apache.org/licenses/LICENSE-2.0
  25. Unless required by applicable law or agreed to in writing, software
  26. distributed under the License is distributed on an "AS IS" BASIS,
  27. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28. See the License for the specific language governing permissions and
  29. limitations under the License.
  30. """
  31. __all__ = ["WebSocketApp"]
  32. RECONNECT = 0
  33. def set_reconnect(reconnectInterval: int) -> None:
  34. global RECONNECT
  35. RECONNECT = reconnectInterval
  36. class WebSocketApp:
  37. """
  38. Higher level of APIs are provided. The interface is like JavaScript WebSocket object.
  39. """
  40. def __init__(
  41. self,
  42. url: str,
  43. header: Optional[
  44. Union[
  45. list[str],
  46. dict[str, str],
  47. Callable[[], Union[list[str], dict[str, str]]],
  48. ]
  49. ] = None,
  50. on_open: Optional[Callable[["WebSocketApp"], None]] = None,
  51. on_reconnect: Optional[Callable[["WebSocketApp"], None]] = None,
  52. on_message: Optional[Callable[["WebSocketApp", Any], None]] = None,
  53. on_error: Optional[Callable[["WebSocketApp", Any], None]] = None,
  54. on_close: Optional[Callable[["WebSocketApp", Any, Any], None]] = None,
  55. on_ping: Optional[Callable] = None,
  56. on_pong: Optional[Callable] = None,
  57. on_cont_message: Optional[Callable] = None,
  58. keep_running: bool = True,
  59. get_mask_key: Optional[Callable] = None,
  60. cookie: Optional[str] = None,
  61. subprotocols: Optional[list[str]] = None,
  62. on_data: Optional[Callable] = None,
  63. socket: Optional[socket.socket] = None,
  64. ) -> None:
  65. """
  66. WebSocketApp initialization
  67. Parameters
  68. ----------
  69. url: str
  70. Websocket url.
  71. header: list or dict or Callable
  72. Custom header for websocket handshake.
  73. If the parameter is a callable object, it is called just before the connection attempt.
  74. The returned dict or list is used as custom header value.
  75. This could be useful in order to properly setup timestamp dependent headers.
  76. on_open: function
  77. Callback object which is called at opening websocket.
  78. on_open has one argument.
  79. The 1st argument is this class object.
  80. on_reconnect: function
  81. Callback object which is called at reconnecting websocket.
  82. on_reconnect has one argument.
  83. The 1st argument is this class object.
  84. on_message: function
  85. Callback object which is called when received data.
  86. on_message has 2 arguments.
  87. The 1st argument is this class object.
  88. The 2nd argument is utf-8 data received from the server.
  89. on_error: function
  90. Callback object which is called when we get error.
  91. on_error has 2 arguments.
  92. The 1st argument is this class object.
  93. The 2nd argument is exception object.
  94. on_close: function
  95. Callback object which is called when connection is closed.
  96. on_close has 3 arguments.
  97. The 1st argument is this class object.
  98. The 2nd argument is close_status_code.
  99. The 3rd argument is close_msg.
  100. on_cont_message: function
  101. Callback object which is called when a continuation
  102. frame is received.
  103. on_cont_message has 3 arguments.
  104. The 1st argument is this class object.
  105. The 2nd argument is utf-8 string which we get from the server.
  106. The 3rd argument is continue flag. if 0, the data continue
  107. to next frame data
  108. on_data: function
  109. Callback object which is called when a message received.
  110. This is called before on_message or on_cont_message,
  111. and then on_message or on_cont_message is called.
  112. on_data has 4 argument.
  113. The 1st argument is this class object.
  114. The 2nd argument is utf-8 string which we get from the server.
  115. The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
  116. The 4th argument is continue flag. If 0, the data continue
  117. keep_running: bool
  118. This parameter is obsolete and ignored.
  119. get_mask_key: function
  120. A callable function to get new mask keys, see the
  121. WebSocket.set_mask_key's docstring for more information.
  122. cookie: str
  123. Cookie value.
  124. subprotocols: list
  125. List of available sub protocols. Default is None.
  126. socket: socket
  127. Pre-initialized stream socket.
  128. """
  129. self.url = url
  130. self.header = header if header is not None else []
  131. self.cookie = cookie
  132. self.on_open = on_open
  133. self.on_reconnect = on_reconnect
  134. self.on_message = on_message
  135. self.on_data = on_data
  136. self.on_error = on_error
  137. self.on_close = on_close
  138. self.on_ping = on_ping
  139. self.on_pong = on_pong
  140. self.on_cont_message = on_cont_message
  141. self.keep_running = False
  142. self.get_mask_key = get_mask_key
  143. self.sock: Optional[WebSocket] = None
  144. self.last_ping_tm = float(0)
  145. self.last_pong_tm = float(0)
  146. self.ping_thread: Optional[threading.Thread] = None
  147. self.stop_ping: Optional[threading.Event] = None
  148. self.ping_interval = float(0)
  149. self.ping_timeout: Optional[Union[float, int]] = None
  150. self.ping_payload = ""
  151. self.subprotocols = subprotocols
  152. self.prepared_socket = socket
  153. self.has_errored = False
  154. self.has_done_teardown = False
  155. self.has_done_teardown_lock = threading.Lock()
  156. def send(self, data: Union[bytes, str], opcode: int = ABNF.OPCODE_TEXT) -> None:
  157. """
  158. send message
  159. Parameters
  160. ----------
  161. data: str
  162. Message to send. If you set opcode to OPCODE_TEXT,
  163. data must be utf-8 string or unicode.
  164. opcode: int
  165. Operation code of data. Default is OPCODE_TEXT.
  166. """
  167. if not self.sock or self.sock.send(data, opcode) == 0:
  168. raise WebSocketConnectionClosedException("Connection is already closed.")
  169. def send_text(self, text_data: str) -> None:
  170. """
  171. Sends UTF-8 encoded text.
  172. """
  173. if not self.sock or self.sock.send(text_data, ABNF.OPCODE_TEXT) == 0:
  174. raise WebSocketConnectionClosedException("Connection is already closed.")
  175. def send_bytes(self, data: Union[bytes, bytearray]) -> None:
  176. """
  177. Sends a sequence of bytes.
  178. """
  179. if not self.sock or self.sock.send(data, ABNF.OPCODE_BINARY) == 0:
  180. raise WebSocketConnectionClosedException("Connection is already closed.")
  181. def close(self, **kwargs) -> None:
  182. """
  183. Close websocket connection.
  184. """
  185. self.keep_running = False
  186. if self.sock:
  187. self.sock.close(**kwargs)
  188. self.sock = None
  189. def _start_ping_thread(self) -> None:
  190. self.last_ping_tm = self.last_pong_tm = float(0)
  191. self.stop_ping = threading.Event()
  192. self.ping_thread = threading.Thread(target=self._send_ping)
  193. self.ping_thread.daemon = True
  194. self.ping_thread.start()
  195. def _stop_ping_thread(self) -> None:
  196. if self.stop_ping:
  197. self.stop_ping.set()
  198. if self.ping_thread and self.ping_thread.is_alive():
  199. self.ping_thread.join(3)
  200. # Handle thread leak - if thread doesn't terminate within timeout,
  201. # force cleanup and log warning instead of abandoning the thread
  202. if self.ping_thread.is_alive():
  203. _logging.warning(
  204. "Ping thread failed to terminate within 3 seconds, "
  205. "forcing cleanup. Thread may be blocked."
  206. )
  207. # Force cleanup by clearing references even if thread is still alive
  208. # The daemon thread will eventually be cleaned up by Python's GC
  209. # but we prevent resource leaks by not holding references
  210. # Always clean up references regardless of thread state
  211. self.ping_thread = None
  212. self.stop_ping = None
  213. self.last_ping_tm = self.last_pong_tm = float(0)
  214. def _send_ping(self) -> None:
  215. if self.stop_ping is None:
  216. return
  217. if self.stop_ping.wait(self.ping_interval) or self.keep_running is False:
  218. return
  219. while not self.stop_ping.wait(self.ping_interval) and self.keep_running is True:
  220. if self.sock:
  221. self.last_ping_tm = time.time()
  222. try:
  223. _logging.debug("Sending ping")
  224. self.sock.ping(self.ping_payload)
  225. except Exception as e:
  226. _logging.debug(f"Failed to send ping: {e}")
  227. def ready(self):
  228. return self.sock and self.sock.connected
  229. def run_forever(
  230. self,
  231. sockopt: tuple = None,
  232. sslopt: dict = None,
  233. ping_interval: Union[float, int] = 0,
  234. ping_timeout: Optional[Union[float, int]] = None,
  235. ping_payload: str = "",
  236. http_proxy_host: str = None,
  237. http_proxy_port: Union[int, str] = None,
  238. http_no_proxy: list = None,
  239. http_proxy_auth: tuple = None,
  240. http_proxy_timeout: Optional[float] = None,
  241. skip_utf8_validation: bool = False,
  242. host: str = None,
  243. origin: str = None,
  244. dispatcher=None,
  245. suppress_origin: bool = False,
  246. proxy_type: str = None,
  247. reconnect: int = None,
  248. ) -> bool:
  249. """
  250. Run event loop for WebSocket framework.
  251. This loop is an infinite loop and is alive while websocket is available.
  252. Parameters
  253. ----------
  254. sockopt: tuple
  255. Values for socket.setsockopt.
  256. sockopt must be tuple
  257. and each element is argument of sock.setsockopt.
  258. sslopt: dict
  259. Optional dict object for ssl socket option.
  260. ping_interval: int or float
  261. Automatically send "ping" command
  262. every specified period (in seconds).
  263. If set to 0, no ping is sent periodically.
  264. ping_timeout: int or float
  265. Timeout (in seconds) if the pong message is not received.
  266. ping_payload: str
  267. Payload message to send with each ping.
  268. http_proxy_host: str
  269. HTTP proxy host name.
  270. http_proxy_port: int or str
  271. HTTP proxy port. If not set, set to 80.
  272. http_no_proxy: list
  273. Whitelisted host names that don't use the proxy.
  274. http_proxy_timeout: int or float
  275. HTTP proxy timeout, default is 60 sec as per python-socks.
  276. http_proxy_auth: tuple
  277. HTTP proxy auth information. tuple of username and password. Default is None.
  278. skip_utf8_validation: bool
  279. skip utf8 validation.
  280. host: str
  281. update host header.
  282. origin: str
  283. update origin header.
  284. dispatcher: Dispatcher object
  285. customize reading data from socket.
  286. suppress_origin: bool
  287. suppress outputting origin header.
  288. proxy_type: str
  289. type of proxy from: http, socks4, socks4a, socks5, socks5h
  290. reconnect: int
  291. delay interval when reconnecting
  292. Returns
  293. -------
  294. teardown: bool
  295. False if the `WebSocketApp` is closed or caught KeyboardInterrupt,
  296. True if any other exception was raised during a loop.
  297. """
  298. if reconnect is None:
  299. reconnect = RECONNECT
  300. if ping_timeout is not None and ping_timeout <= 0:
  301. raise WebSocketException("Ensure ping_timeout > 0")
  302. if ping_interval is not None and ping_interval < 0:
  303. raise WebSocketException("Ensure ping_interval >= 0")
  304. if ping_timeout and ping_interval and ping_interval <= ping_timeout:
  305. raise WebSocketException("Ensure ping_interval > ping_timeout")
  306. if not sockopt:
  307. sockopt = ()
  308. if not sslopt:
  309. sslopt = {}
  310. if self.sock:
  311. raise WebSocketException("socket is already opened")
  312. self.ping_interval = ping_interval
  313. self.ping_timeout = ping_timeout
  314. self.ping_payload = ping_payload
  315. self.has_done_teardown = False
  316. self.keep_running = True
  317. def teardown(close_frame: ABNF = None):
  318. """
  319. Tears down the connection.
  320. Parameters
  321. ----------
  322. close_frame: ABNF frame
  323. If close_frame is set, the on_close handler is invoked
  324. with the statusCode and reason from the provided frame.
  325. """
  326. # teardown() is called in many code paths to ensure resources are cleaned up and on_close is fired.
  327. # To ensure the work is only done once, we use this bool and lock.
  328. with self.has_done_teardown_lock:
  329. if self.has_done_teardown:
  330. return
  331. self.has_done_teardown = True
  332. self._stop_ping_thread()
  333. self.keep_running = False
  334. if self.sock:
  335. # in cases like handleDisconnect, the "on_error" callback is called first. If the WebSocketApp
  336. # is being used in a multithreaded application, we nee to make sure that "self.sock" is cleared
  337. # before calling close, otherwise logic built around the sock being set can cause issues -
  338. # specifically calling "run_forever" again, since is checks if "self.sock" is set.
  339. current_sock = self.sock
  340. self.sock = None
  341. current_sock.close()
  342. close_status_code, close_reason = self._get_close_args(
  343. close_frame if close_frame else None
  344. )
  345. # Finally call the callback AFTER all teardown is complete
  346. self._callback(self.on_close, close_status_code, close_reason)
  347. def initialize_socket(reconnecting: bool = False) -> None:
  348. if reconnecting and self.sock:
  349. self.sock.shutdown()
  350. self.sock = WebSocket(
  351. self.get_mask_key,
  352. sockopt=sockopt,
  353. sslopt=sslopt,
  354. fire_cont_frame=self.on_cont_message is not None,
  355. skip_utf8_validation=skip_utf8_validation,
  356. enable_multithread=True,
  357. dispatcher=dispatcher,
  358. )
  359. self.sock.settimeout(getdefaulttimeout())
  360. try:
  361. header = self.header() if callable(self.header) else self.header
  362. self.sock.connect(
  363. self.url,
  364. header=header,
  365. cookie=self.cookie,
  366. http_proxy_host=http_proxy_host,
  367. http_proxy_port=http_proxy_port,
  368. http_no_proxy=http_no_proxy,
  369. http_proxy_auth=http_proxy_auth,
  370. http_proxy_timeout=http_proxy_timeout,
  371. subprotocols=self.subprotocols,
  372. host=host,
  373. origin=origin,
  374. suppress_origin=suppress_origin,
  375. proxy_type=proxy_type,
  376. socket=self.prepared_socket,
  377. )
  378. _logging.info("Websocket connected")
  379. if self.ping_interval:
  380. self._start_ping_thread()
  381. if reconnecting and self.on_reconnect:
  382. self._callback(self.on_reconnect)
  383. else:
  384. self._callback(self.on_open)
  385. dispatcher.read(self.sock.sock, read, check)
  386. except (
  387. WebSocketConnectionClosedException,
  388. ConnectionRefusedError,
  389. KeyboardInterrupt,
  390. SystemExit,
  391. Exception,
  392. ) as e:
  393. handleDisconnect(e, reconnecting)
  394. def read() -> bool:
  395. if not self.keep_running:
  396. teardown()
  397. return False
  398. if self.sock is None:
  399. return False
  400. try:
  401. op_code, frame = self.sock.recv_data_frame(True)
  402. except (
  403. WebSocketConnectionClosedException,
  404. KeyboardInterrupt,
  405. SSLEOFError,
  406. ) as e:
  407. if custom_dispatcher:
  408. return closed(e)
  409. else:
  410. raise e
  411. if op_code == ABNF.OPCODE_CLOSE:
  412. return closed(frame)
  413. elif op_code == ABNF.OPCODE_PING:
  414. self._callback(self.on_ping, frame.data)
  415. elif op_code == ABNF.OPCODE_PONG:
  416. self.last_pong_tm = time.time()
  417. self._callback(self.on_pong, frame.data)
  418. elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:
  419. self._callback(self.on_data, frame.data, frame.opcode, frame.fin)
  420. self._callback(self.on_cont_message, frame.data, frame.fin)
  421. else:
  422. data = frame.data
  423. if op_code == ABNF.OPCODE_TEXT and not skip_utf8_validation:
  424. data = data.decode("utf-8")
  425. self._callback(self.on_data, data, frame.opcode, True)
  426. self._callback(self.on_message, data)
  427. return True
  428. def check() -> bool:
  429. if self.ping_timeout:
  430. has_timeout_expired = (
  431. time.time() - self.last_ping_tm > self.ping_timeout
  432. )
  433. has_pong_not_arrived_after_last_ping = (
  434. self.last_pong_tm - self.last_ping_tm < 0
  435. )
  436. has_pong_arrived_too_late = (
  437. self.last_pong_tm - self.last_ping_tm > self.ping_timeout
  438. )
  439. if (
  440. self.last_ping_tm
  441. and has_timeout_expired
  442. and (
  443. has_pong_not_arrived_after_last_ping
  444. or has_pong_arrived_too_late
  445. )
  446. ):
  447. raise WebSocketTimeoutException("ping/pong timed out")
  448. return True
  449. def closed(
  450. e: Union[
  451. WebSocketConnectionClosedException,
  452. ConnectionRefusedError,
  453. KeyboardInterrupt,
  454. SystemExit,
  455. Exception,
  456. str,
  457. ] = "closed unexpectedly",
  458. ) -> bool:
  459. if type(e) is str:
  460. e = WebSocketConnectionClosedException(e)
  461. return handleDisconnect(e, bool(reconnect)) # type: ignore[arg-type]
  462. def handleDisconnect(
  463. e: Union[
  464. WebSocketConnectionClosedException,
  465. ConnectionRefusedError,
  466. KeyboardInterrupt,
  467. SystemExit,
  468. Exception,
  469. ],
  470. reconnecting: bool = False,
  471. ) -> bool:
  472. self.has_errored = True
  473. self._stop_ping_thread()
  474. if not reconnecting:
  475. self._callback(self.on_error, e)
  476. if isinstance(e, (KeyboardInterrupt, SystemExit)):
  477. teardown()
  478. # Propagate further
  479. raise
  480. if reconnect:
  481. _logging.info(f"{e} - reconnect")
  482. if custom_dispatcher:
  483. _logging.debug(
  484. f"Calling custom dispatcher reconnect [{len(inspect.stack())} frames in stack]"
  485. )
  486. dispatcher.reconnect(reconnect, initialize_socket)
  487. else:
  488. _logging.error(f"{e} - goodbye")
  489. teardown()
  490. return self.has_errored
  491. custom_dispatcher = bool(dispatcher)
  492. dispatcher = self.create_dispatcher(
  493. ping_timeout, dispatcher, parse_url(self.url)[3], closed
  494. )
  495. try:
  496. initialize_socket()
  497. if not custom_dispatcher and reconnect:
  498. while self.keep_running:
  499. _logging.debug(
  500. f"Calling dispatcher reconnect [{len(inspect.stack())} frames in stack]"
  501. )
  502. dispatcher.reconnect(reconnect, initialize_socket)
  503. except (KeyboardInterrupt, Exception) as e:
  504. _logging.info(f"tearing down on exception {e}")
  505. teardown()
  506. finally:
  507. if not custom_dispatcher:
  508. # Ensure teardown was called before returning from run_forever
  509. teardown()
  510. return self.has_errored
  511. def create_dispatcher(
  512. self,
  513. ping_timeout: Optional[Union[float, int]],
  514. dispatcher: Optional[DispatcherBase] = None,
  515. is_ssl: bool = False,
  516. handleDisconnect: Callable = None,
  517. ) -> Union[Dispatcher, SSLDispatcher, WrappedDispatcher]:
  518. if dispatcher: # If custom dispatcher is set, use WrappedDispatcher
  519. return WrappedDispatcher(self, ping_timeout, dispatcher, handleDisconnect)
  520. timeout = ping_timeout or 10
  521. if is_ssl:
  522. return SSLDispatcher(self, timeout)
  523. return Dispatcher(self, timeout)
  524. def _get_close_args(self, close_frame: ABNF) -> list:
  525. """
  526. _get_close_args extracts the close code and reason from the close body
  527. if it exists (RFC6455 says WebSocket Connection Close Code is optional)
  528. """
  529. # Need to catch the case where close_frame is None
  530. # Otherwise the following if statement causes an error
  531. if not self.on_close or not close_frame:
  532. return [None, None]
  533. # Extract close frame status code
  534. if close_frame.data and len(close_frame.data) >= 2:
  535. close_status_code = 256 * int(close_frame.data[0]) + int(
  536. close_frame.data[1]
  537. )
  538. reason = close_frame.data[2:]
  539. if isinstance(reason, bytes):
  540. reason = reason.decode("utf-8")
  541. return [close_status_code, reason]
  542. else:
  543. # Most likely reached this because len(close_frame_data.data) < 2
  544. return [None, None]
  545. def _callback(self, callback, *args) -> None:
  546. if callback:
  547. try:
  548. callback(self, *args)
  549. except Exception as e:
  550. _logging.error(f"error from callback {callback}: {e}")
  551. # Bug fix: Prevent infinite recursion by not calling on_error
  552. # when the failing callback IS on_error itself
  553. if self.on_error and callback is not self.on_error:
  554. self.on_error(self, e)