web3-multi-provider 2.2.1__tar.gz → 2.2.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/PKG-INFO +1 -1
  2. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/pyproject.toml +1 -1
  3. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/web3_multi_provider/__init__.py +9 -2
  4. web3_multi_provider-2.2.5/web3_multi_provider/async_http_provider_proxy.py +114 -0
  5. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/web3_multi_provider/async_multi_http_provider.py +53 -12
  6. web3_multi_provider-2.2.5/web3_multi_provider/exceptions.py +28 -0
  7. web3_multi_provider-2.2.5/web3_multi_provider/http_provider_proxy.py +130 -0
  8. web3_multi_provider-2.2.5/web3_multi_provider/http_session_manager_proxy.py +554 -0
  9. web3_multi_provider-2.2.5/web3_multi_provider/metrics.py +139 -0
  10. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/web3_multi_provider/multi_http_provider.py +52 -12
  11. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/web3_multi_provider/util.py +14 -8
  12. web3_multi_provider-2.2.1/web3_multi_provider/async_http_provider_proxy.py +0 -179
  13. web3_multi_provider-2.2.1/web3_multi_provider/cl_client_proxy.py +0 -97
  14. web3_multi_provider-2.2.1/web3_multi_provider/exceptions.py +0 -18
  15. web3_multi_provider-2.2.1/web3_multi_provider/http_provider_proxy.py +0 -182
  16. web3_multi_provider-2.2.1/web3_multi_provider/http_session_manager_proxy.py +0 -247
  17. web3_multi_provider-2.2.1/web3_multi_provider/metrics.py +0 -103
  18. web3_multi_provider-2.2.1/web3_multi_provider/metrics_decorator.py +0 -195
  19. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/LICENSE +0 -0
  20. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/README.md +0 -0
  21. {web3_multi_provider-2.2.1 → web3_multi_provider-2.2.5}/web3_multi_provider/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: web3-multi-provider
3
- Version: 2.2.1
3
+ Version: 2.2.5
4
4
  Summary: Web3py provider that makes it easy to switch between different blockchain nodes to make sure application will be be online if main blockchain node will be unavailable.
5
5
  License: MIT
6
6
  Author: Raman
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "web3-multi-provider"
3
- version = "2.2.1"
3
+ version = "2.2.5"
4
4
  description = "Web3py provider that makes it easy to switch between different blockchain nodes to make sure application will be be online if main blockchain node will be unavailable."
5
5
  authors = ["Raman <raman.s@lido.fi>"]
6
6
  license = "MIT License"
@@ -1,5 +1,10 @@
1
1
  from .async_multi_http_provider import AsyncFallbackProvider, AsyncMultiProvider
2
- from .exceptions import NoActiveProviderError, ProtocolNotSupported
2
+ from .exceptions import (
3
+ ChainIdMismatchError,
4
+ NoActiveProviderError,
5
+ ProtocolNotSupported,
6
+ )
7
+ from .http_session_manager_proxy import HTTPSessionManagerProxy
3
8
  from .metrics import init_metrics
4
9
  from .multi_http_provider import FallbackProvider, MultiProvider
5
10
 
@@ -8,7 +13,9 @@ __all__ = (
8
13
  "MultiProvider",
9
14
  "AsyncFallbackProvider",
10
15
  "AsyncMultiProvider",
16
+ "ChainIdMismatchError",
11
17
  "NoActiveProviderError",
12
18
  "ProtocolNotSupported",
13
- "init_metrics"
19
+ "HTTPSessionManagerProxy",
20
+ "init_metrics",
14
21
  )
@@ -0,0 +1,114 @@
1
+ import logging
2
+ from typing import Any, List, Optional, Tuple, Union, cast, override
3
+
4
+ from eth_typing import URI
5
+ from web3 import AsyncHTTPProvider
6
+ from web3._utils.batching import sort_batch_response_by_response_ids
7
+ from web3._utils.empty import Empty, empty
8
+ from web3.providers.rpc.utils import ExceptionRetryConfiguration
9
+ from web3.types import RPCEndpoint, RPCResponse
10
+
11
+ from web3_multi_provider import metrics
12
+ from web3_multi_provider.http_session_manager_proxy import HTTPSessionManagerProxy
13
+ from web3_multi_provider.util import normalize_provider
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
19
+ """
20
+ An asynchronous extension of Web3's AsyncHTTPProvider that adds Prometheus metrics tracking.
21
+
22
+ This proxy handles request success/failure tracking, request and response payload size observation,
23
+ and lazy chain ID initialization to tag metrics with network-specific labels.
24
+
25
+ Metrics collected include:
26
+ - RPC call success/failure counts
27
+ - Request payload sizes
28
+ - Response payload sizes
29
+ - Batch request sizes
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ endpoint_uri: Optional[Union[URI, str]] = None,
35
+ request_kwargs: Optional[Any] = None,
36
+ layer: str = "",
37
+ exception_retry_configuration: Optional[
38
+ Union[ExceptionRetryConfiguration, Empty]
39
+ ] = empty,
40
+ **kwargs: Any,
41
+ ) -> None:
42
+ """
43
+ Initializes the asynchronous provider with metric tagging metadata.
44
+
45
+ Args:
46
+ endpoint_uri (Optional[Union[URI, str]]): The Ethereum RPC endpoint URI.
47
+ request_kwargs (Optional[Any]): Extra request arguments.
48
+ layer (str): The blockchain layer (e.g., 'el' for Execution Layer).
49
+ exception_retry_configuration (Optional): Configuration for retry behavior.
50
+ **kwargs: Additional arguments passed to the base class.
51
+ """
52
+ super().__init__(
53
+ endpoint_uri, request_kwargs, exception_retry_configuration, **kwargs
54
+ )
55
+ self._chain_id: str = ""
56
+ self._network: str = "" # to pass fetching of the chain_id
57
+ self._uri: str = normalize_provider(str(self.endpoint_uri))
58
+ self._layer = layer
59
+
60
+ async def _ensure_chain_info_initialized(self) -> None:
61
+ """
62
+ Lazily fetches chain ID and maps it to a network name for metric labeling.
63
+ Also sets up the request session manager for batch requests.
64
+ """
65
+ if self._chain_id != "":
66
+ return
67
+ self._chain_id = str(await self._fetch_chain_id())
68
+ self._network = metrics._CHAIN_ID_TO_NAME.get(int(self._chain_id), "unknown")
69
+ self._request_session_manager: HTTPSessionManagerProxy = (
70
+ HTTPSessionManagerProxy(
71
+ chain_id=self._chain_id,
72
+ uri=self._uri,
73
+ network=self._network,
74
+ layer=self._layer,
75
+ )
76
+ )
77
+
78
+ async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
79
+ await self._ensure_chain_info_initialized()
80
+ return await super().make_request(method, params)
81
+
82
+ async def _fetch_chain_id(self) -> int:
83
+ """
84
+ Makes an RPC call to retrieve the Ethereum chain ID.
85
+
86
+ Returns:
87
+ int: The current chain ID.
88
+
89
+ Raises:
90
+ Exception: If the call to `eth_chainId` fails (any exception from the RPC call).
91
+ """
92
+ resp = await super().make_request(RPCEndpoint("eth_chainId"), [])
93
+ return int(resp["result"], 16)
94
+
95
+ async def make_batch_request(
96
+ self, batch_requests: List[Tuple[RPCEndpoint, Any]]
97
+ ) -> Union[List[RPCResponse], RPCResponse]:
98
+ await self._ensure_chain_info_initialized()
99
+ self.logger.debug(f"Making batch request HTTP - uri: `{self.endpoint_uri}`")
100
+ request_data = self.encode_batch_rpc_request(batch_requests)
101
+ raw_response = await self._request_session_manager.async_make_post_request(
102
+ self.endpoint_uri, # type: ignore
103
+ request_data,
104
+ _batch_size=len(batch_requests),
105
+ **self.get_request_kwargs(),
106
+ )
107
+ self.logger.debug("Received batch response HTTP.")
108
+ response = self.decode_rpc_response(raw_response)
109
+ if not isinstance(response, list):
110
+ # RPC errors return only one response with the error object
111
+ return response
112
+ return sort_batch_response_by_response_ids(
113
+ cast(List[RPCResponse], sort_batch_response_by_response_ids(response))
114
+ )
@@ -11,11 +11,16 @@ from web3.providers.rpc.utils import ExceptionRetryConfiguration
11
11
  from web3.types import RPCEndpoint, RPCResponse
12
12
 
13
13
  from web3_multi_provider.async_http_provider_proxy import AsyncHTTPProviderProxy
14
- from web3_multi_provider.exceptions import NoActiveProviderError, ProtocolNotSupported
14
+ from web3_multi_provider.exceptions import (
15
+ ChainIdMismatchError,
16
+ NoActiveProviderError,
17
+ ProtocolNotSupported,
18
+ )
15
19
  from web3_multi_provider.util import sanitize_poa_response
16
20
 
17
21
  logger = logging.getLogger(__name__)
18
22
 
23
+
19
24
  class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
20
25
  """Base async provider for multiple endpoint handling strategies."""
21
26
 
@@ -25,7 +30,9 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
25
30
  self,
26
31
  endpoint_urls: list[URI | str],
27
32
  request_kwargs: Any | None = None,
28
- exception_retry_configuration: ExceptionRetryConfiguration | Empty | None = empty,
33
+ exception_retry_configuration: (
34
+ ExceptionRetryConfiguration | Empty | None
35
+ ) = empty,
29
36
  **kwargs: Any,
30
37
  ):
31
38
  logger.debug({"msg": f"Initialize {self.__class__.__name__}"})
@@ -50,13 +57,42 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
50
57
 
51
58
  super().__init__()
52
59
 
60
+ def _validate_chain_ids(self) -> None:
61
+ """
62
+ Validates that all providers have the same chain ID.
63
+
64
+ Raises:
65
+ ChainIdMismatchError: If providers have different chain IDs.
66
+ """
67
+ chain_ids: dict[str, list[str]] = {}
68
+
69
+ for provider in self._providers:
70
+ if hasattr(provider, "_chain_id") and provider._chain_id:
71
+ chain_id = provider._chain_id
72
+ endpoint_uri = str(provider.endpoint_uri)
73
+
74
+ if chain_id not in chain_ids:
75
+ chain_ids[chain_id] = []
76
+ chain_ids[chain_id].append(endpoint_uri)
77
+
78
+ if len(chain_ids) > 1:
79
+ mismatches = []
80
+ for chain_id, endpoints in chain_ids.items():
81
+ mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
82
+
83
+ raise ChainIdMismatchError(
84
+ f"Providers have different chain IDs:\n" + "\n".join(mismatches)
85
+ )
86
+
53
87
  async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
54
- return await self._make_request_with_failover(
88
+ response = await self._make_request_with_failover(
55
89
  method=method,
56
90
  params=params,
57
91
  provider_name=self.__class__.__name__,
58
92
  provider_iter=self.get_providers(),
59
93
  )
94
+ self._validate_chain_ids()
95
+ return response
60
96
 
61
97
  async def _make_request_with_failover(
62
98
  self,
@@ -72,17 +108,21 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
72
108
  response = await provider.make_request(method, params)
73
109
  except Exception as error: # pylint: disable=broad-except
74
110
  exceptions.append(error)
75
- logger.warning({
76
- "msg": f"Provider not responding.",
77
- "error": str(error).replace(str(provider.endpoint_uri), "****"),
78
- })
111
+ logger.warning(
112
+ {
113
+ "msg": "Provider not responding.",
114
+ "error": str(error).replace(str(provider.endpoint_uri), "****"),
115
+ }
116
+ )
79
117
  else:
80
118
  sanitize_poa_response(method, response)
81
- logger.debug({
82
- "msg": f"Send request using {provider_name}.",
83
- "method": method,
84
- "params": str(params),
85
- })
119
+ logger.debug(
120
+ {
121
+ "msg": f"Send request using {provider_name}.",
122
+ "method": method,
123
+ "params": str(params),
124
+ }
125
+ )
86
126
  return response
87
127
 
88
128
  msg = f"No active provider available in {provider_name}."
@@ -111,4 +151,5 @@ class AsyncFallbackProvider(AsyncBaseMultiProvider):
111
151
  """Simple fallback: tries providers in order."""
112
152
 
113
153
  def get_providers(self) -> Iterable[AsyncHTTPProvider]:
154
+ """Return providers in order without rotation (fallback)."""
114
155
  return iter(self._providers)
@@ -0,0 +1,28 @@
1
+ from typing import Sequence
2
+
3
+
4
+ class NoActiveProviderError(ExceptionGroup):
5
+ """Raised when no provider is able to handle the request."""
6
+
7
+ @classmethod
8
+ def from_exceptions(
9
+ cls, message: str, exceptions: Sequence[Exception]
10
+ ) -> Exception:
11
+ if exceptions:
12
+ return cls(message, exceptions)
13
+ else:
14
+ return RuntimeError(
15
+ "No providers were called"
16
+ ) # or a fallback custom Exception
17
+
18
+
19
+ class ProtocolNotSupported(Exception):
20
+ """Supported protocols: http, https"""
21
+
22
+
23
+ class ProviderInitialization(Exception):
24
+ """Error during provider init"""
25
+
26
+
27
+ class ChainIdMismatchError(Exception):
28
+ """Raised when providers in a multi-provider have different chain IDs."""
@@ -0,0 +1,130 @@
1
+ import logging
2
+ from typing import Any, List, Optional, Tuple, Union, cast
3
+
4
+ from eth_typing import URI
5
+ from web3 import HTTPProvider
6
+ from web3._utils.batching import sort_batch_response_by_response_ids
7
+ from web3._utils.empty import Empty, empty
8
+ from web3.providers.rpc.utils import ExceptionRetryConfiguration
9
+ from web3.types import RPCEndpoint, RPCResponse
10
+
11
+ from web3_multi_provider import metrics
12
+ from web3_multi_provider.http_session_manager_proxy import HTTPSessionManagerProxy
13
+ from web3_multi_provider.util import normalize_provider
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class HTTPProviderProxy(HTTPProvider):
19
+ """
20
+ A metrics-aware HTTP JSON-RPC provider for Ethereum-like nodes.
21
+
22
+ This class extends `web3.HTTPProvider` and wraps core RPC functionality
23
+ to track performance and usage metrics via Prometheus. It adds support
24
+ for tracking request success/failure rates, payload sizes, and batch statistics.
25
+
26
+ Attributes:
27
+ _layer (str): Network layer (e.g. 'el' for Execution Layer).
28
+ _uri (str): Normalized provider URI.
29
+ _chain_id (str): Chain ID retrieved via `eth_chainId`.
30
+ _network (str): Human-readable network name based on chain ID.
31
+ _request_session_manager (HTTPSessionManagerProxy): Manages HTTP sessions per endpoint.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ endpoint_uri: Optional[Union[URI, str]] = None,
37
+ request_kwargs: Optional[Any] = None,
38
+ session: Optional[Any] = None,
39
+ layer: str = "el",
40
+ exception_retry_configuration: Optional[
41
+ Union[ExceptionRetryConfiguration, Empty]
42
+ ] = empty,
43
+ **kwargs: Any,
44
+ ) -> None:
45
+ """
46
+ Initializes the HTTPProviderProxy instance with lazy chain ID fetching.
47
+
48
+ Args:
49
+ endpoint_uri (Optional[Union[URI, str]]): URI of the Ethereum node.
50
+ request_kwargs (Optional[Any]): Additional request parameters.
51
+ session (Optional[Any]): Optional requests.Session object to reuse connections.
52
+ layer (str): Network layer label ('el' by default).
53
+ exception_retry_configuration (Optional[Union[ExceptionRetryConfiguration, Empty]]):
54
+ Configuration for retry logic.
55
+ **kwargs: Additional arguments passed to base class.
56
+ """
57
+ super().__init__(
58
+ endpoint_uri,
59
+ request_kwargs,
60
+ session,
61
+ exception_retry_configuration,
62
+ **kwargs,
63
+ )
64
+ self._layer = layer
65
+ self._uri = normalize_provider(str(self.endpoint_uri))
66
+ self._chain_id: str = ""
67
+ self._network: str = ""
68
+ self._session: Optional[Any] = session
69
+ self._request_session_manager: Optional[HTTPSessionManagerProxy] = None
70
+
71
+ def _ensure_chain_info_initialized(self) -> None:
72
+ """
73
+ Lazily fetches chain ID and maps it to a network name for metric labeling.
74
+ Also sets up the request session manager for batch requests.
75
+ """
76
+ if self._chain_id != "":
77
+ return
78
+ self._chain_id = str(self._fetch_chain_id())
79
+ self._network = metrics._CHAIN_ID_TO_NAME.get(int(self._chain_id), "unknown")
80
+ self._request_session_manager = HTTPSessionManagerProxy(
81
+ chain_id=self._chain_id,
82
+ uri=self._uri,
83
+ network=self._network,
84
+ layer=self._layer,
85
+ )
86
+ if self._session:
87
+ self._request_session_manager.cache_and_return_session(
88
+ cast(URI, self.endpoint_uri), self._session
89
+ )
90
+
91
+ def _fetch_chain_id(self) -> int:
92
+ """
93
+ Retrieves the chain ID from the connected Ethereum node.
94
+
95
+ Returns:
96
+ int: The chain ID as an integer.
97
+
98
+ Raises:
99
+ Exception: If the chain ID could not be retrieved (any exception from the RPC call).
100
+ """
101
+ resp = super().make_request(RPCEndpoint("eth_chainId"), [])
102
+ return int(resp["result"], 16)
103
+
104
+ def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
105
+ """
106
+ Makes an RPC request after ensuring chain info is initialized.
107
+ """
108
+ self._ensure_chain_info_initialized()
109
+ return super().make_request(method, params)
110
+
111
+ def make_batch_request(
112
+ self, batch_requests: List[Tuple[RPCEndpoint, Any]]
113
+ ) -> Union[List[RPCResponse], RPCResponse]:
114
+ self._ensure_chain_info_initialized()
115
+ self.logger.debug(f"Making batch request HTTP, uri: `{self.endpoint_uri}`")
116
+ request_data = self.encode_batch_rpc_request(batch_requests)
117
+ raw_response = self._request_session_manager.make_post_request(
118
+ self.endpoint_uri, # type: ignore
119
+ request_data,
120
+ _batch_size=len(batch_requests),
121
+ **self.get_request_kwargs(),
122
+ )
123
+ self.logger.debug("Received batch response HTTP.")
124
+ response = self.decode_rpc_response(raw_response)
125
+ if not isinstance(response, list):
126
+ # RPC errors return only one response with the error object
127
+ return response
128
+ return sort_batch_response_by_response_ids(
129
+ cast(List[RPCResponse], sort_batch_response_by_response_ids(response))
130
+ )