web3-multi-provider 2.0.0__tar.gz → 2.2.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: web3-multi-provider
3
- Version: 2.0.0
3
+ Version: 2.2.0
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
@@ -9,7 +9,8 @@ Requires-Python: >=3.12,<4
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Programming Language :: Python :: 3
11
11
  Classifier: Programming Language :: Python :: 3.12
12
- Classifier: Programming Language :: Python :: 3.13
12
+ Provides-Extra: metrics
13
+ Requires-Dist: prometheus-client (>=0.21.1,<0.22.0) ; extra == "metrics"
13
14
  Requires-Dist: web3 (>=7,<8)
14
15
  Description-Content-Type: text/markdown
15
16
 
@@ -29,6 +30,10 @@ or
29
30
  ```bash
30
31
  $ poetry add web3-multi-provider
31
32
  ```
33
+ or with metrics:
34
+ ```bash
35
+ $ poetry add web3-multi-provider[metrics]
36
+ ```
32
37
 
33
38
  ## Usage
34
39
 
@@ -54,13 +59,32 @@ last_block = w3.eth.get_block('latest')
54
59
 
55
60
  ### `MultiProvider`
56
61
 
57
- This provider keeps track of the current endpoint and switches to the next one if an error occurs.
62
+ This provider keeps track of the current endpoint and switches to the next one if an error occurs.
58
63
  It fails if no endpoints are available.
59
64
 
60
65
  ### `FallbackProvider`
61
66
 
62
67
  This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
63
68
 
69
+ ### `AsyncMultiProvider` and `AsyncFallbackProvider`
70
+
71
+ These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
72
+ be used with instances of `AsyncWeb3`.
73
+
74
+ ```py
75
+ from web3 import AsyncWeb3
76
+ from web3_multi_provider import AsyncMultiProvider
77
+
78
+ w3 = AsyncWeb3(AsyncMultiProvider([ # RPC endpoints list
79
+ 'http://127.0.0.1:8000/',
80
+ 'https://mainnet.infura.io/v3/...',
81
+ ]))
82
+ ```
83
+
84
+ ### Metrics
85
+
86
+ Library has in-built prometheus metrics, to enable them run `metrics.init_metrics()`.
87
+
64
88
  ## For developers
65
89
 
66
90
  1. `poetry install` - to install deps
@@ -14,6 +14,10 @@ or
14
14
  ```bash
15
15
  $ poetry add web3-multi-provider
16
16
  ```
17
+ or with metrics:
18
+ ```bash
19
+ $ poetry add web3-multi-provider[metrics]
20
+ ```
17
21
 
18
22
  ## Usage
19
23
 
@@ -39,13 +43,32 @@ last_block = w3.eth.get_block('latest')
39
43
 
40
44
  ### `MultiProvider`
41
45
 
42
- This provider keeps track of the current endpoint and switches to the next one if an error occurs.
46
+ This provider keeps track of the current endpoint and switches to the next one if an error occurs.
43
47
  It fails if no endpoints are available.
44
48
 
45
49
  ### `FallbackProvider`
46
50
 
47
51
  This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
48
52
 
53
+ ### `AsyncMultiProvider` and `AsyncFallbackProvider`
54
+
55
+ These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
56
+ be used with instances of `AsyncWeb3`.
57
+
58
+ ```py
59
+ from web3 import AsyncWeb3
60
+ from web3_multi_provider import AsyncMultiProvider
61
+
62
+ w3 = AsyncWeb3(AsyncMultiProvider([ # RPC endpoints list
63
+ 'http://127.0.0.1:8000/',
64
+ 'https://mainnet.infura.io/v3/...',
65
+ ]))
66
+ ```
67
+
68
+ ### Metrics
69
+
70
+ Library has in-built prometheus metrics, to enable them run `metrics.init_metrics()`.
71
+
49
72
  ## For developers
50
73
 
51
74
  1. `poetry install` - to install deps
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "web3-multi-provider"
3
- version = "2.0.0"
3
+ version = "2.2.0"
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"
@@ -8,13 +8,22 @@ readme = "README.md"
8
8
  include = [
9
9
  "LICENSE",
10
10
  ]
11
+ packages = [
12
+ {include = "web3_multi_provider"},
13
+ {include = "web3_multi_provider/py.typed"},
14
+ ]
11
15
 
12
16
  [tool.poetry.dependencies]
13
17
  python = ">=3.12,<4"
14
18
  web3 = ">=7,<8"
19
+ prometheus-client = { version = "^0.21.1", optional = true }
20
+
21
+ [tool.poetry.extras]
22
+ metrics = ["prometheus-client"]
15
23
 
16
24
  [tool.poetry.group.dev.dependencies]
17
25
  pytest = "^8.3.3"
26
+ pytest-asyncio = "^0.24.0"
18
27
  pytest-cov = "^5.0.0"
19
28
  pre-commit = "^4.0.1"
20
29
  isort = "^5.13.2"
@@ -22,6 +31,13 @@ mypy = "^1.13.0"
22
31
  pylint = "^3.3.1"
23
32
  black = "^24.10.0"
24
33
  pytest-mock = "^3.14.0"
34
+ prometheus-client = "^0.21.1"
35
+ requests = "^2.32.3"
36
+ aiohttp = "^3.11.14"
37
+ responses = "^0.25.7"
25
38
 
26
39
  [tool.isort]
27
40
  profile = "black"
41
+
42
+ [tool.pytest.ini_options]
43
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,14 @@
1
+ from .async_multi_http_provider import AsyncFallbackProvider, AsyncMultiProvider
2
+ from .exceptions import NoActiveProviderError, ProtocolNotSupported
3
+ from .metrics import init_metrics
4
+ from .multi_http_provider import FallbackProvider, MultiProvider
5
+
6
+ __all__ = (
7
+ "FallbackProvider",
8
+ "MultiProvider",
9
+ "AsyncFallbackProvider",
10
+ "AsyncMultiProvider",
11
+ "NoActiveProviderError",
12
+ "ProtocolNotSupported",
13
+ "init_metrics"
14
+ )
@@ -0,0 +1,179 @@
1
+ import logging
2
+ from queue import Empty
3
+ from typing import Any, cast, List, Optional, override, Tuple, Union
4
+
5
+ from eth_typing import URI
6
+ from web3 import AsyncHTTPProvider, JSONBaseProvider
7
+ from web3._utils.batching import sort_batch_response_by_response_ids
8
+ from web3._utils.empty import empty
9
+ from web3.providers.rpc.utils import ExceptionRetryConfiguration
10
+ from web3.types import RPCEndpoint, RPCResponse
11
+
12
+ import web3_multi_provider.metrics as metrics
13
+ from web3_multi_provider.http_session_manager_proxy import HTTPSessionManagerProxy
14
+ from web3_multi_provider.metrics_decorator import observe_batch_size, observe_input_payload, observe_output_payload, record_rpc_call
15
+ from web3_multi_provider.util import normalize_provider
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
21
+ """
22
+ An asynchronous extension of Web3's AsyncHTTPProvider that adds Prometheus metrics tracking.
23
+
24
+ This proxy handles request success/failure tracking, request and response payload size observation,
25
+ and lazy chain ID initialization to tag metrics with network-specific labels.
26
+
27
+ Metrics collected include:
28
+ - RPC call success/failure counts
29
+ - Request payload sizes
30
+ - Response payload sizes
31
+ - Batch request sizes
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ endpoint_uri: Optional[Union[URI, str]] = None,
37
+ request_kwargs: Optional[Any] = None,
38
+ layer: str = 'el',
39
+ exception_retry_configuration: Optional[
40
+ Union[ExceptionRetryConfiguration, Empty]
41
+ ] = empty,
42
+ **kwargs: Any,
43
+ ) -> None:
44
+ """
45
+ Initializes the asynchronous provider with metric tagging metadata.
46
+
47
+ Args:
48
+ endpoint_uri (Optional[Union[URI, str]]): The Ethereum RPC endpoint URI.
49
+ request_kwargs (Optional[Any]): Extra request arguments.
50
+ layer (str): The blockchain layer (e.g., 'el' for Execution Layer).
51
+ exception_retry_configuration (Optional): Configuration for retry behavior.
52
+ **kwargs: Additional arguments passed to the base class.
53
+ """
54
+ super().__init__(endpoint_uri, request_kwargs, exception_retry_configuration, **kwargs)
55
+ self._chain_id: str = ''
56
+ self._network: str = '' # to pass fetching of the chain_id
57
+ self._uri: str = normalize_provider(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
+ chain_id=self._chain_id,
71
+ uri=self._uri,
72
+ network=self._network,
73
+ layer=self._layer
74
+ )
75
+
76
+ async def _fetch_chain_id(self) -> int:
77
+ """
78
+ Makes an RPC call to retrieve the Ethereum chain ID.
79
+
80
+ Returns:
81
+ int: The current chain ID.
82
+
83
+ Raises:
84
+ RuntimeError: If the call to `eth_chainId` fails.
85
+ """
86
+ try:
87
+ resp = await super().make_request(RPCEndpoint('eth_chainId'), [])
88
+ return int(resp['result'], 16)
89
+ except Exception as e:
90
+ raise RuntimeError('Failed to fetch chain ID') from e
91
+
92
+ @override
93
+ @record_rpc_call('_RPC_REQUEST')
94
+ async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
95
+ """
96
+ Makes an async JSON-RPC request, tagging metrics with status and error code.
97
+
98
+ Args:
99
+ method (RPCEndpoint): The RPC method to call.
100
+ params (Any): Parameters for the method.
101
+
102
+ Returns:
103
+ RPCResponse: The decoded response.
104
+ """
105
+ await self._ensure_chain_info_initialized()
106
+ return await super().make_request(method, params)
107
+
108
+ @override
109
+ @observe_output_payload('_RPC_SERVICE_REQUEST_PAYLOAD_BYTES')
110
+ def encode_rpc_request(self, method: RPCEndpoint, params: Any) -> bytes:
111
+ """
112
+ Encodes a single RPC request into bytes and observes its size.
113
+
114
+ Args:
115
+ method (RPCEndpoint): The method name.
116
+ params (Any): Parameters to encode.
117
+
118
+ Returns:
119
+ bytes: The encoded request.
120
+ """
121
+ return super().encode_rpc_request(method, params)
122
+
123
+ @override
124
+ @observe_output_payload('_RPC_SERVICE_REQUEST_PAYLOAD_BYTES')
125
+ def encode_batch_rpc_request(self, requests: List[Tuple[RPCEndpoint, Any]]) -> bytes:
126
+ """
127
+ Encodes a list of RPC requests into a batch payload and observes size.
128
+
129
+ Args:
130
+ requests (List[Tuple[RPCEndpoint, Any]]): RPC method/param pairs.
131
+
132
+ Returns:
133
+ bytes: Encoded batch request.
134
+ """
135
+ return super().encode_batch_rpc_request(requests)
136
+
137
+ @override
138
+ @observe_input_payload('_RPC_SERVICE_RESPONSE_PAYLOAD_BYTES')
139
+ def decode_rpc_response(self, raw_response: bytes) -> RPCResponse:
140
+ """
141
+ Decodes a raw byte response into a structured JSON-RPC response and records response size.
142
+
143
+ Args:
144
+ raw_response (bytes): Raw HTTP response content.
145
+
146
+ Returns:
147
+ RPCResponse: Parsed RPC response.
148
+ """
149
+ return JSONBaseProvider.decode_rpc_response(raw_response)
150
+
151
+ @override
152
+ @observe_batch_size('_HTTP_RPC_BATCH_SIZE')
153
+ async def make_batch_request(
154
+ self, batch_requests: List[Tuple[RPCEndpoint, Any]]
155
+ ) -> Union[List[RPCResponse], RPCResponse]:
156
+ """
157
+ Makes a batched RPC request and records batch size and metrics.
158
+
159
+ Args:
160
+ batch_requests (List[Tuple[RPCEndpoint, Any]]): A list of RPC method/param pairs.
161
+
162
+ Returns:
163
+ Union[List[RPCResponse], RPCResponse]: A sorted list of RPC responses or a single error response.
164
+ """
165
+ await self._ensure_chain_info_initialized()
166
+ logger.debug(f"Making batch request HTTP - uri: `{self.endpoint_uri}`")
167
+ request_data = self.encode_batch_rpc_request(batch_requests)
168
+ raw_response = await self._request_session_manager.async_make_post_request_batch(
169
+ self.endpoint_uri,
170
+ request_data,
171
+ **self.get_request_kwargs()
172
+ )
173
+ logger.debug("Received batch response HTTP.")
174
+ response = self.decode_rpc_response(raw_response)
175
+ if not isinstance(response, list):
176
+ return response
177
+ return sort_batch_response_by_response_ids(
178
+ cast(List[RPCResponse], response)
179
+ )
@@ -0,0 +1,114 @@
1
+ # pylint: disable=duplicate-code
2
+ import logging
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any, Iterable
5
+
6
+ from eth_typing import URI
7
+ from web3 import AsyncHTTPProvider
8
+ from web3._utils.empty import Empty, empty
9
+ from web3.providers.async_base import AsyncJSONBaseProvider
10
+ from web3.providers.rpc.utils import ExceptionRetryConfiguration
11
+ from web3.types import RPCEndpoint, RPCResponse
12
+
13
+ from web3_multi_provider.async_http_provider_proxy import AsyncHTTPProviderProxy
14
+ from web3_multi_provider.exceptions import NoActiveProviderError, ProtocolNotSupported
15
+ from web3_multi_provider.util import sanitize_poa_response
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
20
+ """Base async provider for multiple endpoint handling strategies."""
21
+
22
+ _providers: list[AsyncHTTPProvider]
23
+
24
+ def __init__( # pylint: disable=too-many-arguments
25
+ self,
26
+ endpoint_urls: list[URI | str],
27
+ request_kwargs: Any | None = None,
28
+ exception_retry_configuration: ExceptionRetryConfiguration | Empty | None = empty,
29
+ **kwargs: Any,
30
+ ):
31
+ logger.debug({"msg": f"Initialize {self.__class__.__name__}"})
32
+ self._hosts_uri = endpoint_urls
33
+ self._providers = []
34
+
35
+ if endpoint_urls:
36
+ self.endpoint_uri = endpoint_urls[0]
37
+
38
+ for endpoint_uri in endpoint_urls:
39
+ if not endpoint_uri.startswith("http"):
40
+ protocol = endpoint_uri.split("://")[0]
41
+ raise ProtocolNotSupported(f'Protocol "{protocol}" is not supported.')
42
+
43
+ provider = AsyncHTTPProviderProxy(
44
+ endpoint_uri=endpoint_uri,
45
+ request_kwargs=request_kwargs,
46
+ exception_retry_configuration=exception_retry_configuration,
47
+ **kwargs,
48
+ )
49
+ self._providers.append(provider)
50
+
51
+ super().__init__()
52
+
53
+ async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
54
+ return await self._make_request_with_failover(
55
+ method=method,
56
+ params=params,
57
+ provider_name=self.__class__.__name__,
58
+ provider_iter=self.get_providers(),
59
+ )
60
+
61
+ async def _make_request_with_failover(
62
+ self,
63
+ method: RPCEndpoint,
64
+ params: Any,
65
+ provider_name: str,
66
+ provider_iter: Iterable[AsyncHTTPProvider],
67
+ ) -> RPCResponse:
68
+ exceptions: list[Exception] = []
69
+
70
+ for provider in provider_iter:
71
+ try:
72
+ response = await provider.make_request(method, params)
73
+ except Exception as error: # pylint: disable=broad-except
74
+ exceptions.append(error)
75
+ logger.warning({
76
+ "msg": f"Provider not responding.",
77
+ "error": str(error).replace(str(provider.endpoint_uri), "****"),
78
+ })
79
+ else:
80
+ sanitize_poa_response(method, response)
81
+ logger.debug({
82
+ "msg": f"Send request using {provider_name}.",
83
+ "method": method,
84
+ "params": str(params),
85
+ })
86
+ return response
87
+
88
+ msg = f"No active provider available in {provider_name}."
89
+ logger.debug({"msg": msg})
90
+ raise NoActiveProviderError.from_exceptions(msg, exceptions)
91
+
92
+ @abstractmethod
93
+ def get_providers(self) -> Iterable[AsyncHTTPProvider]:
94
+ raise NotImplementedError
95
+
96
+
97
+ class AsyncMultiProvider(AsyncBaseMultiProvider):
98
+ """Round-robin failover: rotates provider on failure."""
99
+
100
+ _current_provider_index: int = 0
101
+
102
+ def get_providers(self) -> Iterable[AsyncHTTPProvider]:
103
+ count = len(self._providers)
104
+ for _ in range(count):
105
+ provider = self._providers[self._current_provider_index]
106
+ self._current_provider_index = (self._current_provider_index + 1) % count
107
+ yield provider
108
+
109
+
110
+ class AsyncFallbackProvider(AsyncBaseMultiProvider):
111
+ """Simple fallback: tries providers in order."""
112
+
113
+ def get_providers(self) -> Iterable[AsyncHTTPProvider]:
114
+ return iter(self._providers)
@@ -0,0 +1,97 @@
1
+ import sys
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ from typing_extensions import override
5
+ from web3.beacon import Beacon
6
+
7
+ import web3_multi_provider.metrics as metrics
8
+ from web3_multi_provider.http_session_manager_proxy import HTTPSessionManagerProxy
9
+ from web3_multi_provider.metrics_decorator import record_rpc_call
10
+ from web3_multi_provider.util import normalize_provider
11
+
12
+
13
+ class BeaconProxy(Beacon):
14
+ """
15
+ A proxy extension of the Web3 `Beacon` client that integrates Prometheus-based
16
+ metrics collection for GET and POST RPC requests on the consensus layer.
17
+
18
+ It tracks:
19
+ - Number of requests (success/failure)
20
+ - Request payload sizes (POST)
21
+ - Response payload sizes (GET & POST)
22
+ """
23
+
24
+ def __init__(self, base_url: str, request_timeout: float = 10.0):
25
+ """
26
+ Initialize the BeaconProxy instance.
27
+
28
+ Args:
29
+ base_url (str): The HTTP endpoint URL of the Beacon (Consensus Layer) node.
30
+ request_timeout (float, optional): Request timeout in seconds. Defaults to 10.0.
31
+ """
32
+ super().__init__(base_url, request_timeout)
33
+ self._network = 'ethereum'
34
+ self._layer = 'cl'
35
+ self._chain_id = ''
36
+ self._uri = normalize_provider(self.base_url)
37
+ self._request_session_manager = HTTPSessionManagerProxy(
38
+ chain_id='',
39
+ uri=normalize_provider(self.base_url),
40
+ network=self._network,
41
+ layer=self._layer,
42
+ )
43
+
44
+ @override
45
+ @record_rpc_call('_RPC_REQUEST')
46
+ def _make_get_request(
47
+ self, endpoint_url: str, params: Optional[Dict[str, str]] = None
48
+ ) -> Dict[str, Any]:
49
+ """
50
+ Make a GET request to the beacon node and record metrics.
51
+
52
+ Args:
53
+ endpoint_url (str): Full endpoint URL to query.
54
+ params (Optional[Dict[str, str]]): Query string parameters.
55
+
56
+ Returns:
57
+ Dict[str, Any]: Decoded JSON response from the node.
58
+
59
+ Metrics:
60
+ - Increments `_RPC_REQUEST` with status and error code (if any).
61
+ - Observes `_RPC_SERVICE_RESPONSE_PAYLOAD_BYTES` using `sys.getsizeof` on the response.
62
+ """
63
+ resp = super()._make_get_request(endpoint_url, params)
64
+ metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES.labels(
65
+ self._network, self._layer, self._chain_id, self._uri
66
+ ).observe(sys.getsizeof(resp))
67
+ return resp
68
+
69
+ @override
70
+ @record_rpc_call('_RPC_REQUEST')
71
+ def _make_post_request(
72
+ self, endpoint_url: str, body: Union[List[str], Dict[str, Any]]
73
+ ) -> Dict[str, Any]:
74
+ """
75
+ Make a POST request to the beacon node and record metrics.
76
+
77
+ Args:
78
+ endpoint_url (str): Full endpoint URL to post to.
79
+ body (Union[List[str], Dict[str, Any]]): JSON-serializable body of the request.
80
+
81
+ Returns:
82
+ Dict[str, Any]: Decoded JSON response from the node.
83
+
84
+ Metrics:
85
+ - Observes `_RPC_SERVICE_REQUEST_PAYLOAD_BYTES` using `sys.getsizeof` on the body.
86
+ - Observes `_RPC_SERVICE_RESPONSE_PAYLOAD_BYTES` using `sys.getsizeof` on the response.
87
+ - Increments `_RPC_REQUEST` with status and error code (if any).
88
+ """
89
+ payload_size = sys.getsizeof(body)
90
+ metrics._RPC_SERVICE_REQUEST_PAYLOAD_BYTES.labels(
91
+ self._network, self._layer, self._chain_id, self._uri
92
+ ).observe(payload_size)
93
+ resp = super()._make_post_request(endpoint_url, body)
94
+ metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES.labels(
95
+ self._network, self._layer, self._chain_id, self._uri
96
+ ).observe(sys.getsizeof(resp))
97
+ return resp
@@ -0,0 +1,18 @@
1
+ class NoActiveProviderError(ExceptionGroup):
2
+ """Raised when no provider is able to handle the request."""
3
+
4
+ @classmethod
5
+ def from_exceptions(cls, message: str, exceptions: list[BaseException]):
6
+ if exceptions:
7
+ return cls(message, exceptions)
8
+ else:
9
+ return RuntimeError("No providers were called") # or a fallback custom Exception
10
+
11
+
12
+
13
+ class ProtocolNotSupported(Exception):
14
+ """Supported protocols: http, https"""
15
+
16
+
17
+ class ProviderInitialization(Exception):
18
+ """Error during provider init"""