-
Notifications
You must be signed in to change notification settings - Fork 113
Part 5 - jsonrpc: replace jsonrpcserver/jsonrpcclient with custom implementation #971
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
Open
ping-ke
wants to merge
13
commits into
upgrade/py313-baseline
Choose a base branch
from
upgrade/jsonrpc
base: upgrade/py313-baseline
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.
+767
−235
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
81b9f3d
replace jsonrpcserver/jsonrpcclient packages with custom implementation
8fbf960
fix remaining jsonrpc_async usages and import issues in tools
9f603e6
fix jsonrpc test failures: params passing and websocket server shutdown
ping-ke 4ffeaa8
Revert "fix jsonrpc test failures: params passing and websocket serve…
ping-ke d67a44c
fix jsonrpc test failures: params passing and websocket server shutdown
ping-ke 0abbb30
move async related changes to update/asyncio branch
ping-ke 73eb7e6
Merge branch 'upgrade/jsonrpc' of https://github.com/QuarkChain/pyqua…
ping-ke f867cb3
add rationale comment for httpx dependency choice in jsonrpc_client
ping-ke cd2843d
rename jsonrpcserver to jsonrpc_server and fix related imports and is…
ping-ke 50ffeb2
fix tools compatibility with new JsonRpcClient
ping-ke d0ea0a4
add unit test for jsonrpc
ping-ke ca5c275
Merge branch 'master' into upgrade/jsonrpc
ping-ke 4496def
remove call_with_dict_params, unify call() for both param types, log …
ping-ke 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
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| import inspect | ||
| import logging | ||
| from typing import Any, Callable, Dict, Optional, Awaitable | ||
|
|
||
| from aiohttp import web | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class JsonRpcError(Exception): | ||
| code = -32000 | ||
| message = "Server error" | ||
|
|
||
| def __init__(self, message=None, data=None): | ||
| super().__init__(message or self.message) | ||
| self.message = message or self.message | ||
| self.data = data | ||
|
|
||
| def to_dict(self): | ||
| error = { | ||
| "code": self.code, | ||
| "message": self.message, | ||
| } | ||
| if self.data is not None: | ||
| error["data"] = self.data | ||
| return error | ||
|
|
||
| class InvalidRequest(JsonRpcError): | ||
| code = -32600 | ||
| message = "Invalid Request" | ||
|
|
||
| class MethodNotFound(JsonRpcError): | ||
| code = -32601 | ||
| message = "Method not found" | ||
|
|
||
| class InvalidParams(JsonRpcError): | ||
| code = -32602 | ||
| message = "Invalid params" | ||
|
|
||
| class ServerError(JsonRpcError): | ||
| code = -32000 | ||
| message = "Server error" | ||
|
|
||
|
|
||
| class RpcMethods: | ||
| def __init__(self): | ||
| self._methods: Dict[str, Callable[..., Awaitable[Any]]] = {} | ||
|
|
||
| # ========== dict ========== | ||
| def __iter__(self): | ||
| return iter(self._methods) | ||
|
|
||
| def __getitem__(self, key): | ||
| return self._methods[key] | ||
|
|
||
| def __setitem__(self, key, value): | ||
| self._methods[key] = value | ||
|
|
||
| def items(self): | ||
| return self._methods.items() | ||
|
|
||
| def keys(self): | ||
| return self._methods.keys() | ||
|
|
||
| def values(self): | ||
| return self._methods.values() | ||
|
|
||
| # ========== decorator ========== | ||
| def add(self, func: Callable[..., Awaitable[Any]] = None, *, name: str = None): | ||
| """ | ||
| Usage: | ||
|
|
||
| @methods.add | ||
| async def foo(...): | ||
|
|
||
| or: | ||
|
|
||
| @methods.add(name="customName") | ||
| async def foo(...): | ||
| """ | ||
| if func is None: | ||
| def wrapper(f): | ||
| method_name = name or f.__name__ | ||
| self._methods[method_name] = f | ||
| return f | ||
| return wrapper | ||
|
|
||
| method_name = name or func.__name__ | ||
| self._methods[method_name] = func | ||
| return func | ||
|
|
||
| async def dispatch(self, request_json: Dict[str, Any], context=None) -> Optional[Dict[str, Any]]: | ||
| req_id = None | ||
|
|
||
| try: | ||
| if not isinstance(request_json, dict): | ||
| raise InvalidRequest("Request must be object") | ||
|
|
||
| req_id = request_json.get("id") | ||
|
|
||
| if request_json.get("jsonrpc") != "2.0": | ||
| raise InvalidRequest("Invalid JSON-RPC version") | ||
|
|
||
| method = request_json.get("method") | ||
| if not isinstance(method, str): | ||
| raise InvalidRequest("Method must be string") | ||
|
|
||
| is_notification = "id" not in request_json | ||
|
|
||
| if method not in self._methods: | ||
| raise MethodNotFound() | ||
|
|
||
| handler = self._methods[method] | ||
| params = request_json.get("params", []) | ||
|
|
||
| # Check if handler accepts a context parameter | ||
| sig = inspect.signature(handler) | ||
| pass_context = context is not None and "context" in sig.parameters | ||
|
|
||
| if isinstance(params, list): | ||
| result = await handler(*params, context=context) if pass_context else await handler(*params) | ||
| elif isinstance(params, dict): | ||
| result = await handler(**params, context=context) if pass_context else await handler(**params) | ||
| else: | ||
| raise InvalidParams() | ||
|
|
||
| if is_notification: | ||
| return None | ||
|
|
||
| return { | ||
| "jsonrpc": "2.0", | ||
| "result": result, | ||
| "id": req_id, | ||
| } | ||
|
|
||
| except JsonRpcError as e: | ||
| return { | ||
| "jsonrpc": "2.0", | ||
| "error": e.to_dict(), | ||
| "id": req_id, | ||
| } | ||
|
|
||
| except TypeError as e: | ||
| # Could be missing/extra arguments → treat as invalid params | ||
| return { | ||
| "jsonrpc": "2.0", | ||
| "error": { | ||
| "code": -32602, | ||
| "message": str(e), | ||
| }, | ||
| "id": req_id, | ||
| } | ||
| except Exception: | ||
| logger.exception("Internal JSON-RPC error for method %s", method) | ||
| return { | ||
| "jsonrpc": "2.0", | ||
| "error": { | ||
| "code": -32603, | ||
| "message": "Internal error", | ||
ping-ke marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }, | ||
| "id": req_id, | ||
| } | ||
|
|
||
| async def aiohttp_handler(self, request: web.Request) -> web.Response: | ||
| body = await request.json() | ||
|
|
||
| # support batch | ||
| if isinstance(body, list): | ||
| responses = [await self.dispatch(item) for item in body] | ||
| return web.json_response(responses) | ||
|
|
||
| response = await self.dispatch(body) | ||
| return web.json_response(response) | ||
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.