Skip to content

Commit 6bae3db

Browse files
committed
feat: create WebSocket connection from a daemon thread
This is required so the background listening thread of the WebSocket is itself a daemon thread and doesn't block the application from stopping.
1 parent 08b4ad8 commit 6bae3db

1 file changed

Lines changed: 29 additions & 9 deletions

File tree

wherobots/db/driver.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55

66
import logging
77
import urllib.parse
8+
import queue
89
import requests
910
import tenacity
11+
import threading
1012
import websockets.sync.client
1113

1214
from .constants import (
@@ -128,12 +130,30 @@ def connect_direct(
128130
headers: dict[str, str] = None,
129131
read_timeout: float = DEFAULT_READ_TIMEOUT_SECONDS,
130132
) -> Connection:
131-
logging.info("Connecting to SQL session at %s ...", uri)
132-
try:
133-
ws = websockets.sync.client.connect(
134-
uri=uri, additional_headers=headers, max_size=MAX_MESSAGE_SIZE
135-
)
136-
session = Connection(ws, read_timeout)
137-
return session
138-
except Exception as e:
139-
raise InterfaceError("Failed to connect to SQL session!") from e
133+
q = queue.SimpleQueue()
134+
135+
def create_ws_connection():
136+
try:
137+
logging.info("Connecting to SQL session at %s ...", uri)
138+
ws = websockets.sync.client.connect(
139+
uri=uri,
140+
additional_headers=headers,
141+
max_size=MAX_MESSAGE_SIZE,
142+
)
143+
q.put(ws)
144+
except Exception as e:
145+
q.put(e)
146+
147+
dt = threading.Thread(
148+
name="wherobots-ws-connector",
149+
target=create_ws_connection,
150+
daemon=True,
151+
)
152+
dt.start()
153+
dt.join()
154+
155+
result = q.get()
156+
if isinstance(result, Exception):
157+
raise InterfaceError("Failed to connect to SQL session!") from result
158+
159+
return Connection(result, read_timeout)

0 commit comments

Comments
 (0)