_app.py 24 KB

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