-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix support for query cancellation #23
Open
mpetazzoni
wants to merge
4
commits into
main
Choose a base branch
from
max/query-cancel
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+90
−57
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9df6cad
feat: refactor state transitions to fix support for query cancellation
mpetazzoni 0fef38a
chore: add types-requests dependency for type checking
mpetazzoni 35ca532
chore: add function return type annotations
mpetazzoni b219e17
Release 0.9.1
mpetazzoni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
[tool.poetry] | ||
name = "wherobots-python-dbapi" | ||
version = "0.9.0" | ||
version = "0.9.1" | ||
description = "Python DB-API driver for Wherobots DB" | ||
authors = ["Maxime Petazzoni <[email protected]>"] | ||
license = "Apache 2.0" | ||
|
@@ -22,6 +22,7 @@ pandas = "^2.1.0" | |
StrEnum = "^0.4.15" | ||
# pyarrow 14.0.2 doesn't limit numpy < 2, but it should, we do it here | ||
numpy = "<2" | ||
types-requests = "^2.32.0.20241016" | ||
|
||
[tool.poetry.group.dev.dependencies] | ||
mypy = "^1.8.0" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,7 +22,11 @@ | |
GeometryRepresentation, | ||
) | ||
from wherobots.db.cursor import Cursor | ||
from wherobots.db.errors import NotSupportedError, OperationalError | ||
from wherobots.db.errors import ( | ||
NotSupportedError, | ||
OperationalError, | ||
QueryCancelledError, | ||
) | ||
|
||
|
||
@dataclass | ||
|
@@ -74,19 +78,19 @@ def __enter__(self): | |
def __exit__(self, exc_type, exc_val, exc_tb): | ||
self.close() | ||
|
||
def close(self): | ||
def close(self) -> None: | ||
self.__ws.close() | ||
|
||
def commit(self): | ||
def commit(self) -> None: | ||
raise NotSupportedError | ||
|
||
def rollback(self): | ||
def rollback(self) -> None: | ||
raise NotSupportedError | ||
|
||
def cursor(self) -> Cursor: | ||
return Cursor(self.__execute_sql, self.__cancel_query) | ||
|
||
def __main_loop(self): | ||
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: | ||
|
@@ -101,7 +105,7 @@ def __main_loop(self): | |
except Exception as e: | ||
logging.exception("Error handling message from SQL session", exc_info=e) | ||
|
||
def __listen(self): | ||
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. | ||
|
@@ -120,61 +124,67 @@ def __listen(self): | |
) | ||
return | ||
|
||
if kind == EventKind.STATE_UPDATED: | ||
# 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 | ||
|
||
# Incoming state transitions are handled here. | ||
if query.state == ExecutionState.SUCCEEDED: | ||
self.__request_results(execution_id) | ||
# On a state_updated event telling us the query succeeded, | ||
# ask for results. | ||
if kind == EventKind.STATE_UPDATED: | ||
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) | ||
return | ||
|
||
query.state = ExecutionState.COMPLETED | ||
query.handler(self._handle_results(execution_id, results)) | ||
elif query.state == ExecutionState.CANCELLED: | ||
logging.info("Query %s has been cancelled.", execution_id) | ||
query.handler(QueryCancelledError()) | ||
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.EXECUTION_RESULT: | ||
results = message.get("results") | ||
if not results or not isinstance(results, dict): | ||
logging.warning("Got no results back from %s.", execution_id) | ||
return | ||
|
||
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, | ||
) | ||
|
||
query.state = ExecutionState.COMPLETED | ||
if result_format == ResultsFormat.JSON: | ||
query.handler(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: | ||
query.handler(reader.read_pandas()) | ||
else: | ||
query.handler( | ||
OperationalError(f"Unsupported results format {result_format}") | ||
) | ||
elif kind == EventKind.ERROR: | ||
query.state = ExecutionState.FAILED | ||
error = message.get("message") | ||
query.handler(OperationalError(error)) | ||
else: | ||
logging.warning("Received unknown %s event!", kind) | ||
|
||
def _handle_results(self, execution_id: str, results: dict[str, Any]) -> Any: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hard +1 on this refactor |
||
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) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where is this used?