forked from wherobots/wherobots-python-dbapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.py
More file actions
341 lines (293 loc) · 12.5 KB
/
connection.py
File metadata and controls
341 lines (293 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import json
import logging
import textwrap
import threading
import uuid
from dataclasses import dataclass
from typing import Any, Callable, Dict
import pandas
import pyarrow
import cbor2
import websockets.exceptions
import websockets.protocol
import websockets.sync.client
from .constants import DEFAULT_READ_TIMEOUT_SECONDS
from .cursor import Cursor
from .errors import NotSupportedError, OperationalError
from .models import ExecutionResult, ProgressInfo, Store, StoreResult
from .types import (
RequestKind,
EventKind,
ExecutionState,
ResultsFormat,
DataCompression,
GeometryRepresentation,
)
ProgressHandler = Callable[[ProgressInfo], None]
"""A callable invoked with a :class:`ProgressInfo` on every progress event."""
@dataclass
class Query:
sql: str
execution_id: str
state: ExecutionState
handler: Callable[[Any], None]
store: Store | None = None
class Connection:
"""
A PEP-0249 compatible Connection object for Wherobots DB.
The connection is backed by the WebSocket connected to the Wherobots SQL session instance.
Transactions are not supported, so commit() and rollback() raise NotSupportedError.
This class handles all the interactions with the remote SQL session, and the details of the
Wherobots Spatial SQL API protocol. It supports multiple concurrent cursors, each one executing
a single query at a time.
A background thread listens for events from the SQL session, and handles update to the
corresponding query state. Queries are tracked by their unique execution ID.
"""
def __init__(
self,
ws: websockets.sync.client.ClientConnection,
read_timeout: float = DEFAULT_READ_TIMEOUT_SECONDS,
results_format: ResultsFormat | None = None,
data_compression: DataCompression | None = None,
geometry_representation: GeometryRepresentation | None = None,
):
self.__ws = ws
self.__read_timeout = read_timeout
self.__results_format = results_format
self.__data_compression = data_compression
self.__geometry_representation = geometry_representation
self.__progress_handler: ProgressHandler | None = None
self.__queries: dict[str, Query] = {}
self.__thread = threading.Thread(
target=self.__main_loop, daemon=True, name="wherobots-connection"
)
self.__thread.start()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self) -> None:
self.__ws.close()
def commit(self) -> None:
raise NotSupportedError
def rollback(self) -> None:
raise NotSupportedError
def cursor(self) -> Cursor:
return Cursor(self.__execute_sql, self.__cancel_query)
def set_progress_handler(self, handler: ProgressHandler | None) -> None:
"""Register a callback invoked for execution progress events.
When a handler is set, every ``execute_sql`` request automatically
includes ``enable_progress_events: true`` so the SQL session streams
progress updates for running queries.
Pass ``None`` to disable progress reporting.
This follows the `sqlite3 Connection.set_progress_handler()
<https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.set_progress_handler>`_
pattern (PEP 249 vendor extension).
"""
self.__progress_handler = handler
def __main_loop(self) -> None:
"""Main background loop listening for messages from the SQL session."""
logging.info("Starting background connection handling loop...")
while self.__ws.protocol.state < websockets.protocol.State.CLOSING:
try:
self.__listen()
except TimeoutError:
# Expected, retry next time
continue
except websockets.exceptions.ConnectionClosedOK:
logging.info("Connection closed; stopping main loop.")
return
except Exception as e:
logging.exception("Error handling message from SQL session", exc_info=e)
def __listen(self) -> None:
"""Waits for the next message from the SQL session and processes it.
The code in this method is purposefully defensive to avoid unexpected situations killing the thread.
"""
message = self.__recv()
kind = message.get("kind")
execution_id = message.get("execution_id")
if not kind or not execution_id:
# Invalid event.
return
# Progress events are independent of the query state machine and don't
# require a tracked query — the handler is connection-level.
if kind == EventKind.EXECUTION_PROGRESS:
handler = self.__progress_handler
if handler is None:
return
try:
handler(
ProgressInfo(
execution_id=execution_id,
tasks_total=message.get("tasks_total", 0),
tasks_completed=message.get("tasks_completed", 0),
tasks_active=message.get("tasks_active", 0),
)
)
except Exception:
logging.exception("Progress handler raised an exception")
return
query = self.__queries.get(execution_id)
if not query:
logging.warning(
"Received %s event for unknown execution ID %s", kind, execution_id
)
return
# Incoming state transitions are handled here.
if kind == EventKind.STATE_UPDATED or kind == EventKind.EXECUTION_RESULT:
try:
query.state = ExecutionState[message["state"].upper()]
logging.info("Query %s is now %s.", execution_id, query.state)
except KeyError:
logging.warning("Invalid state update message for %s", execution_id)
return
if query.state == ExecutionState.SUCCEEDED:
# On a state_updated event telling us the query succeeded,
# check if results are stored in cloud storage or need to be fetched.
if kind == EventKind.STATE_UPDATED:
result_uri = message.get("result_uri")
if result_uri:
# Results are stored in cloud storage
store_result = StoreResult(
result_uri=result_uri,
size=message.get("size"),
)
logging.info(
"Query %s results stored at: %s (size: %s)",
execution_id,
result_uri,
store_result.size,
)
query.state = ExecutionState.COMPLETED
query.handler(ExecutionResult(store_result=store_result))
return
if query.store is not None:
# Store was configured but produced no results (empty result set)
logging.info(
"Query %s completed with store configured but no results to store.",
execution_id,
)
query.state = ExecutionState.COMPLETED
query.handler(ExecutionResult())
return
# No store configured, request results normally
self.__request_results(execution_id)
return
# Otherwise, process the results from the execution_result event.
results = message.get("results")
if not results or not isinstance(results, dict):
logging.warning("Got no results back from %s.", execution_id)
query.state = ExecutionState.COMPLETED
query.handler(ExecutionResult())
return
query.state = ExecutionState.COMPLETED
query.handler(
ExecutionResult(results=self._handle_results(execution_id, results))
)
elif query.state == ExecutionState.CANCELLED:
logging.info(
"Query %s has been cancelled; returning empty results.",
execution_id,
)
query.handler(ExecutionResult(results=pandas.DataFrame()))
self.__queries.pop(execution_id)
elif query.state == ExecutionState.FAILED:
# Don't do anything here; the ERROR event is coming with more
# details.
pass
elif kind == EventKind.ERROR:
query.state = ExecutionState.FAILED
error = message.get("message")
query.handler(ExecutionResult(error=OperationalError(error)))
else:
logging.warning("Received unknown %s event!", kind)
def _handle_results(self, execution_id: str, results: Dict[str, Any]) -> Any:
result_bytes = results.get("result_bytes")
result_format = results.get("format")
result_compression = results.get("compression")
logging.info(
"Received %d bytes of %s-compressed %s results from %s.",
len(result_bytes),
result_compression,
result_format,
execution_id,
)
if result_format == ResultsFormat.JSON:
return json.loads(result_bytes.decode("utf-8"))
elif result_format == ResultsFormat.ARROW:
buffer = pyarrow.py_buffer(result_bytes)
stream = pyarrow.input_stream(buffer, result_compression)
with pyarrow.ipc.open_stream(stream) as reader:
return reader.read_pandas()
else:
return OperationalError(f"Unsupported results format {result_format}")
def __send(self, message: Dict[str, Any]) -> None:
request = json.dumps(message)
logging.debug("Request: %s", request)
self.__ws.send(request)
def __recv(self) -> Dict[str, Any]:
frame = self.__ws.recv(timeout=self.__read_timeout)
if isinstance(frame, str):
message = json.loads(frame)
elif isinstance(frame, bytes):
message = cbor2.loads(frame)
else:
raise ValueError("Unexpected frame type received")
return message
def __execute_sql(
self,
sql: str,
handler: Callable[[Any], None],
store: Store | None = None,
) -> str:
"""Triggers the execution of the given SQL query."""
execution_id = str(uuid.uuid4())
request = {
"kind": RequestKind.EXECUTE_SQL.value,
"execution_id": execution_id,
"statement": sql,
}
if self.__progress_handler is not None:
request["enable_progress_events"] = True
if store:
request["store"] = store.to_dict()
self.__queries[execution_id] = Query(
sql=sql,
execution_id=execution_id,
state=ExecutionState.EXECUTION_REQUESTED,
handler=handler,
store=store,
)
logging.info(
"Executing SQL query %s: %s", execution_id, textwrap.shorten(sql, width=60)
)
self.__send(request)
return execution_id
def __request_results(self, execution_id: str) -> None:
query = self.__queries.get(execution_id)
if not query:
return
request = {
"kind": RequestKind.RETRIEVE_RESULTS.value,
"execution_id": execution_id,
}
if self.__results_format:
request["format"] = self.__results_format.value
if self.__data_compression:
request["compression"] = self.__data_compression.value
if self.__geometry_representation:
request["geometry"] = self.__geometry_representation.value
query.state = ExecutionState.RESULTS_REQUESTED
logging.info("Requesting results from %s ...", execution_id)
self.__send(request)
def __cancel_query(self, execution_id: str) -> None:
"""Cancels the query with the given execution ID."""
query = self.__queries.get(execution_id)
if not query:
return
request = {
"kind": RequestKind.CANCEL.value,
"execution_id": execution_id,
}
logging.info("Cancelling query %s...", execution_id)
self.__send(request)