Skip to content

Commit

Permalink
Add httpx session in http.py (#475)
Browse files Browse the repository at this point in the history
  • Loading branch information
neochine authored Dec 1, 2024
1 parent 07acdac commit 2afacbd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/solana/rpc/providers/http.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""HTTP RPC Provider."""

from typing import Tuple, Type, overload
from typing import Optional, Tuple, Dict, Type, overload

import httpx
from solders.rpc.requests import Body
Expand All @@ -9,6 +9,7 @@
from ...exceptions import SolanaRpcException, handle_exceptions
from .base import BaseProvider
from .core import (
DEFAULT_TIMEOUT,
T,
_after_request_unparsed,
_BodiesTup,
Expand Down Expand Up @@ -39,6 +40,16 @@
class HTTPProvider(BaseProvider, _HTTPProviderCore):
"""HTTP provider to interact with the http rpc endpoint."""

def __init__(
self,
endpoint: Optional[str] = None,
extra_headers: Optional[Dict[str, str]] = None,
timeout: float = DEFAULT_TIMEOUT,
):
"""Init HTTPProvider."""
super().__init__(endpoint, extra_headers)
self.session = httpx.Client(timeout=timeout)

def __str__(self) -> str:
"""String definition for HTTPProvider."""
return f"HTTP RPC connection {self.endpoint_uri}"
Expand All @@ -52,13 +63,13 @@ def make_request(self, body: Body, parser: Type[T]) -> T:
def make_request_unparsed(self, body: Body) -> str:
"""Make an async HTTP request to an http rpc endpoint."""
request_kwargs = self._before_request(body=body)
raw_response = httpx.post(**request_kwargs)
raw_response = self.session.post(**request_kwargs)
return _after_request_unparsed(raw_response)

def make_batch_request_unparsed(self, reqs: Tuple[Body, ...]) -> str:
"""Make an async HTTP request to an http rpc endpoint."""
request_kwargs = self._before_batch_request(reqs)
raw_response = httpx.post(**request_kwargs)
raw_response = self.session.post(**request_kwargs)
return _after_request_unparsed(raw_response)

@overload
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_client_http_exception(unit_test_http_client):
with pytest.raises(SolanaRpcException) as exc_info:
unit_test_http_client.get_epoch_info()
assert exc_info.type == SolanaRpcException
assert exc_info.value.error_msg == "<class 'httpx.ReadTimeout'> raised in \"GetEpochInfo\" endpoint request"
assert exc_info.value.error_msg == "<class 'httpx.ConnectError'> raised in \"GetEpochInfo\" endpoint request"


def test_client_address_sig_args_no_commitment(unit_test_http_client):
Expand Down

0 comments on commit 2afacbd

Please sign in to comment.