-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Async HTTP Provider #1978
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
Merged
Merged
Async HTTP Provider #1978
Changes from all commits
Commits
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
Add new AsyncHTTPProvider. No middleware or session caching support yet. | ||
|
||
Also adds async ``w3.eth.gas_price``, and async ``w3.isConnected()`` methods. |
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
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
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
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
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
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,71 @@ | ||
import itertools | ||
from typing import ( | ||
TYPE_CHECKING, | ||
Any, | ||
Callable, | ||
Coroutine, | ||
cast, | ||
) | ||
|
||
from eth_utils import ( | ||
to_bytes, | ||
to_text, | ||
) | ||
|
||
from web3._utils.encoding import ( | ||
FriendlyJsonSerde, | ||
) | ||
from web3.types import ( | ||
MiddlewareOnion, | ||
RPCEndpoint, | ||
RPCResponse, | ||
) | ||
|
||
if TYPE_CHECKING: | ||
from web3 import Web3 # noqa: F401 | ||
|
||
|
||
class AsyncBaseProvider: | ||
def request_func( | ||
self, web3: "Web3", outer_middlewares: MiddlewareOnion | ||
) -> Callable[[RPCEndpoint, Any], Coroutine[Any, Any, RPCResponse]]: | ||
# Placeholder - manager calls self.provider.request_func | ||
# Eventually this will handle caching and return make_request | ||
# along with all the middleware | ||
return self.make_request | ||
|
||
async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: | ||
raise NotImplementedError("Providers must implement this method") | ||
|
||
async def isConnected(self) -> bool: | ||
raise NotImplementedError("Providers must implement this method") | ||
|
||
|
||
class AsyncJSONBaseProvider(AsyncBaseProvider): | ||
def __init__(self) -> None: | ||
self.request_counter = itertools.count() | ||
|
||
async def encode_rpc_request(self, method: RPCEndpoint, params: Any) -> bytes: | ||
rpc_dict = { | ||
"jsonrpc": "2.0", | ||
"method": method, | ||
"params": params or [], | ||
"id": next(self.request_counter), | ||
} | ||
encoded = FriendlyJsonSerde().json_encode(rpc_dict) | ||
return to_bytes(text=encoded) | ||
|
||
async def decode_rpc_response(self, raw_response: bytes) -> RPCResponse: | ||
text_response = to_text(raw_response) | ||
return cast(RPCResponse, FriendlyJsonSerde().json_decode(text_response)) | ||
|
||
async def isConnected(self) -> bool: | ||
try: | ||
response = await self.make_request(RPCEndpoint('web3_clientVersion'), []) | ||
except IOError: | ||
return False | ||
|
||
assert response['jsonrpc'] == '2.0' | ||
assert 'error' not in response | ||
|
||
return True |
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,83 @@ | ||
import logging | ||
from typing import ( | ||
Any, | ||
Dict, | ||
Iterable, | ||
Optional, | ||
Tuple, | ||
Union, | ||
) | ||
|
||
from eth_typing import ( | ||
URI, | ||
) | ||
from eth_utils import ( | ||
to_dict, | ||
) | ||
|
||
from web3._utils.http import ( | ||
construct_user_agent, | ||
) | ||
from web3._utils.request import ( | ||
async_make_post_request, | ||
get_default_http_endpoint, | ||
) | ||
from web3.types import ( | ||
RPCEndpoint, | ||
RPCResponse, | ||
) | ||
|
||
from .async_base import ( | ||
AsyncJSONBaseProvider, | ||
) | ||
|
||
|
||
class AsyncHTTPProvider(AsyncJSONBaseProvider): | ||
logger = logging.getLogger("web3.providers.HTTPProvider") | ||
endpoint_uri = None | ||
_request_kwargs = None | ||
|
||
def __init__( | ||
self, endpoint_uri: Optional[Union[URI, str]] = None, | ||
request_kwargs: Optional[Any] = None, | ||
session: Optional[Any] = None | ||
) -> None: | ||
if endpoint_uri is None: | ||
self.endpoint_uri = get_default_http_endpoint() | ||
else: | ||
self.endpoint_uri = URI(endpoint_uri) | ||
|
||
self._request_kwargs = request_kwargs or {} | ||
|
||
super().__init__() | ||
|
||
def __str__(self) -> str: | ||
return "RPC connection {0}".format(self.endpoint_uri) | ||
|
||
@to_dict | ||
def get_request_kwargs(self) -> Iterable[Tuple[str, Any]]: | ||
if 'headers' not in self._request_kwargs: | ||
yield 'headers', self.get_request_headers() | ||
for key, value in self._request_kwargs.items(): | ||
yield key, value | ||
|
||
def get_request_headers(self) -> Dict[str, str]: | ||
return { | ||
'Content-Type': 'application/json', | ||
'User-Agent': construct_user_agent(str(type(self))), | ||
} | ||
|
||
async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse: | ||
self.logger.debug("Making request HTTP. URI: %s, Method: %s", | ||
self.endpoint_uri, method) | ||
request_data = await self.encode_rpc_request(method, params) | ||
raw_response = await async_make_post_request( | ||
self.endpoint_uri, | ||
request_data, | ||
**self.get_request_kwargs() | ||
) | ||
response = await self.decode_rpc_response(raw_response) | ||
self.logger.debug("Getting response HTTP. URI: %s, " | ||
"Method: %s, Response: %s", | ||
self.endpoint_uri, method, response) | ||
return response |
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.
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.
Yeah, this is unfortunate and would be nice to resolve... but I'm not sure what to suggest.