web3-multi-provider 2.2.7__tar.gz → 2.2.8__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.2.7
3
+ Version: 2.2.8
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
@@ -83,10 +83,90 @@ w3 = AsyncWeb3(AsyncMultiProvider([ # RPC endpoints list
83
83
 
84
84
  ### Metrics
85
85
 
86
- Library has in-built prometheus metrics, to enable them run `metrics.init_metrics()`.
86
+ The library has built-in Prometheus metrics. They are disabled by default — install the extra and call `init_metrics()` before creating any provider.
87
+
88
+ ```bash
89
+ pip install web3-multi-provider[metrics]
90
+ ```
91
+
92
+ ```py
93
+ from web3 import Web3
94
+ from web3_multi_provider import MultiProvider, init_metrics
95
+
96
+ init_metrics() # must be called before creating a provider
97
+
98
+ w3 = Web3(MultiProvider([
99
+ 'http://127.0.0.1:8000/',
100
+ 'https://mainnet.infura.io/v3/...',
101
+ ]))
102
+ ```
103
+
104
+ `init_metrics()` registers the following metrics with the default Prometheus registry:
105
+
106
+ | Metric | Type | Description |
107
+ |---|---|---|
108
+ | `http_rpc_requests` | Counter | Total HTTP requests by network, provider, response code, result |
109
+ | `http_rpc_batch_size` | Histogram | Distribution of batch sizes |
110
+ | `http_rpc_response_seconds` | Histogram | RPC response time |
111
+ | `http_rpc_request_payload_bytes` | Histogram | Request payload size |
112
+ | `http_rpc_response_payload_bytes` | Histogram | Response payload size |
113
+ | `rpc_request` | Counter | RPC calls by method and result |
114
+
115
+ #### Custom configuration
116
+
117
+ Use `MetricsConfig` to set a namespace or override the chain ID → network name mapping:
118
+
119
+ ```py
120
+ from web3_multi_provider.metrics import MetricsConfig
121
+
122
+ init_metrics(MetricsConfig(
123
+ namespace="myapp",
124
+ chain_id_to_name={
125
+ 1: "ethereum",
126
+ 137: "polygon",
127
+ # add any custom chains here
128
+ },
129
+ ))
130
+ ```
131
+
132
+ #### Custom registry
133
+
134
+ Pass a custom Prometheus registry if you don't want to use the global one:
135
+
136
+ ```py
137
+ from prometheus_client import CollectorRegistry
138
+ from web3_multi_provider import init_metrics
139
+
140
+ registry = CollectorRegistry()
141
+ init_metrics(registry=registry)
142
+ ```
87
143
 
88
144
  ## For developers
89
145
 
146
+ This project requires a specific Poetry version, pinned in `.poetry-version`. To install it:
147
+
148
+ ```bash
149
+ POETRY_VERSION=$(cat .poetry-version) curl -sSL https://install.python-poetry.org/ | python -
150
+ ```
151
+
152
+ ### Requirements
153
+
154
+ - [Docker](https://docs.docker.com/get-docker/)
155
+ - [Dev Container CLI](https://github.com/devcontainers/cli): `npm install -g @devcontainers/cli`
156
+ - VS Code: [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension
157
+ - JetBrains: [Dev Containers](https://plugins.jetbrains.com/plugin/21724-dev-containers) plugin
158
+
159
+ ### Setup
160
+
161
+ ```bash
162
+ devcontainer up --workspace-folder .
163
+ devcontainer exec --workspace-folder . bash
164
+ ```
165
+
166
+ This installs all dependencies and pre-commit hooks automatically via `postCreateCommand`.
167
+
168
+ Alternatively, without Docker:
169
+
90
170
  1. `poetry install` - to install deps
91
171
  2. `pre-commit install` - to install pre-commit hooks
92
172
 
@@ -0,0 +1,161 @@
1
+ # <img src="https://docs.lido.fi/img/logo.svg" alt="Lido" width="46"/> Web3 Multi Provider
2
+
3
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ Provider that accepts multiple endpoints.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ $ pip install web3-multi-provider
12
+ ```
13
+ or
14
+ ```bash
15
+ $ poetry add web3-multi-provider
16
+ ```
17
+ or with metrics:
18
+ ```bash
19
+ $ poetry add web3-multi-provider[metrics]
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```py
25
+ from web3 import Web3
26
+ from web3_multi_provider import MultiProvider
27
+ from web3_multi_provider import FallbackProvider
28
+
29
+ w3 = Web3(MultiProvider([ # RPC endpoints list
30
+ 'http://127.0.0.1:8000/',
31
+ 'https://mainnet.infura.io/v3/...',
32
+ ]))
33
+
34
+ # or
35
+
36
+ w3 = Web3(FallbackProvider([ # RPC endpoints list
37
+ 'http://127.0.0.1:8000/',
38
+ 'https://mainnet.infura.io/v3/...',
39
+ ]))
40
+
41
+ last_block = w3.eth.get_block('latest')
42
+ ```
43
+
44
+ ### `MultiProvider`
45
+
46
+ This provider keeps track of the current endpoint and switches to the next one if an error occurs.
47
+ It fails if no endpoints are available.
48
+
49
+ ### `FallbackProvider`
50
+
51
+ This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
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
+ The library has built-in Prometheus metrics. They are disabled by default — install the extra and call `init_metrics()` before creating any provider.
71
+
72
+ ```bash
73
+ pip install web3-multi-provider[metrics]
74
+ ```
75
+
76
+ ```py
77
+ from web3 import Web3
78
+ from web3_multi_provider import MultiProvider, init_metrics
79
+
80
+ init_metrics() # must be called before creating a provider
81
+
82
+ w3 = Web3(MultiProvider([
83
+ 'http://127.0.0.1:8000/',
84
+ 'https://mainnet.infura.io/v3/...',
85
+ ]))
86
+ ```
87
+
88
+ `init_metrics()` registers the following metrics with the default Prometheus registry:
89
+
90
+ | Metric | Type | Description |
91
+ |---|---|---|
92
+ | `http_rpc_requests` | Counter | Total HTTP requests by network, provider, response code, result |
93
+ | `http_rpc_batch_size` | Histogram | Distribution of batch sizes |
94
+ | `http_rpc_response_seconds` | Histogram | RPC response time |
95
+ | `http_rpc_request_payload_bytes` | Histogram | Request payload size |
96
+ | `http_rpc_response_payload_bytes` | Histogram | Response payload size |
97
+ | `rpc_request` | Counter | RPC calls by method and result |
98
+
99
+ #### Custom configuration
100
+
101
+ Use `MetricsConfig` to set a namespace or override the chain ID → network name mapping:
102
+
103
+ ```py
104
+ from web3_multi_provider.metrics import MetricsConfig
105
+
106
+ init_metrics(MetricsConfig(
107
+ namespace="myapp",
108
+ chain_id_to_name={
109
+ 1: "ethereum",
110
+ 137: "polygon",
111
+ # add any custom chains here
112
+ },
113
+ ))
114
+ ```
115
+
116
+ #### Custom registry
117
+
118
+ Pass a custom Prometheus registry if you don't want to use the global one:
119
+
120
+ ```py
121
+ from prometheus_client import CollectorRegistry
122
+ from web3_multi_provider import init_metrics
123
+
124
+ registry = CollectorRegistry()
125
+ init_metrics(registry=registry)
126
+ ```
127
+
128
+ ## For developers
129
+
130
+ This project requires a specific Poetry version, pinned in `.poetry-version`. To install it:
131
+
132
+ ```bash
133
+ POETRY_VERSION=$(cat .poetry-version) curl -sSL https://install.python-poetry.org/ | python -
134
+ ```
135
+
136
+ ### Requirements
137
+
138
+ - [Docker](https://docs.docker.com/get-docker/)
139
+ - [Dev Container CLI](https://github.com/devcontainers/cli): `npm install -g @devcontainers/cli`
140
+ - VS Code: [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension
141
+ - JetBrains: [Dev Containers](https://plugins.jetbrains.com/plugin/21724-dev-containers) plugin
142
+
143
+ ### Setup
144
+
145
+ ```bash
146
+ devcontainer up --workspace-folder .
147
+ devcontainer exec --workspace-folder . bash
148
+ ```
149
+
150
+ This installs all dependencies and pre-commit hooks automatically via `postCreateCommand`.
151
+
152
+ Alternatively, without Docker:
153
+
154
+ 1. `poetry install` - to install deps
155
+ 2. `pre-commit install` - to install pre-commit hooks
156
+
157
+ ## Tests
158
+
159
+ ```bash
160
+ poetry run pytest tests
161
+ ```
@@ -1,16 +1,16 @@
1
1
  [tool.poetry]
2
2
  name = "web3-multi-provider"
3
- version = "2.2.7"
3
+ version = "2.2.8"
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"
7
7
  readme = "README.md"
8
8
  include = [
9
9
  "LICENSE",
10
+ "web3_multi_provider/py.typed",
10
11
  ]
11
12
  packages = [
12
13
  {include = "web3_multi_provider"},
13
- {include = "web3_multi_provider/py.typed"},
14
14
  ]
15
15
 
16
16
  [tool.poetry.dependencies]
@@ -74,13 +74,11 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
74
74
  return
75
75
  self._chain_id = str(await self._fetch_chain_id())
76
76
  self._network = metrics._CHAIN_ID_TO_NAME.get(int(self._chain_id), "unknown")
77
- self._request_session_manager: HTTPSessionManagerProxy = (
78
- HTTPSessionManagerProxy(
79
- chain_id=self._chain_id,
80
- uri=self._uri,
81
- network=self._network,
82
- layer=self._layer,
83
- )
77
+ self._request_session_manager = HTTPSessionManagerProxy(
78
+ chain_id=self._chain_id,
79
+ uri=self._uri,
80
+ network=self._network,
81
+ layer=self._layer,
84
82
  )
85
83
 
86
84
  async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
@@ -16,6 +16,7 @@ from web3_multi_provider.exceptions import (
16
16
  NoActiveProviderError,
17
17
  ProtocolNotSupported,
18
18
  )
19
+ from web3_multi_provider.metrics import warn_if_prometheus_not_initialized
19
20
  from web3_multi_provider.util import sanitize_poa_response
20
21
 
21
22
  logger = logging.getLogger(__name__)
@@ -36,6 +37,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
36
37
  **kwargs: Any,
37
38
  ):
38
39
  logger.debug({"msg": f"Initialize {self.__class__.__name__}"})
40
+ warn_if_prometheus_not_initialized()
39
41
  self._hosts_uri = endpoint_urls
40
42
  self._providers = []
41
43
 
@@ -60,26 +62,26 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
60
62
  def _validate_chain_ids(self) -> None:
61
63
  """
62
64
  Validates that all providers have the same chain ID.
63
-
65
+
64
66
  Raises:
65
67
  ChainIdMismatchError: If providers have different chain IDs.
66
68
  """
67
69
  chain_ids: dict[str, list[str]] = {}
68
-
70
+
69
71
  for provider in self._providers:
70
72
  if hasattr(provider, "_chain_id") and provider._chain_id:
71
73
  chain_id = provider._chain_id
72
74
  endpoint_uri = str(provider.endpoint_uri)
73
-
75
+
74
76
  if chain_id not in chain_ids:
75
77
  chain_ids[chain_id] = []
76
78
  chain_ids[chain_id].append(endpoint_uri)
77
-
79
+
78
80
  if len(chain_ids) > 1:
79
81
  mismatches = []
80
82
  for chain_id, endpoints in chain_ids.items():
81
83
  mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
82
-
84
+
83
85
  raise ChainIdMismatchError(
84
86
  f"Providers have different chain IDs:\n" + "\n".join(mismatches)
85
87
  )
@@ -20,9 +20,5 @@ class ProtocolNotSupported(Exception):
20
20
  """Supported protocols: http, https"""
21
21
 
22
22
 
23
- class ProviderInitialization(Exception):
24
- """Error during provider init"""
25
-
26
-
27
23
  class ChainIdMismatchError(Exception):
28
24
  """Raised when providers in a multi-provider have different chain IDs."""
@@ -65,7 +65,7 @@ class HTTPProviderProxy(HTTPProvider):
65
65
  self._uri = normalize_provider(str(self.endpoint_uri))
66
66
  self._chain_id: str = ""
67
67
  self._network: str = ""
68
- self._session: Optional[Any] = session
68
+ self._session: Optional[Any] = session
69
69
  self._request_session_manager = HTTPSessionManagerProxy(
70
70
  chain_id=self._chain_id,
71
71
  uri=self._uri,
@@ -130,6 +130,4 @@ class HTTPProviderProxy(HTTPProvider):
130
130
  if not isinstance(response, list):
131
131
  # RPC errors return only one response with the error object
132
132
  return response
133
- return sort_batch_response_by_response_ids(
134
- cast(List[RPCResponse], sort_batch_response_by_response_ids(response))
135
- )
133
+ return sort_batch_response_by_response_ids(cast(List[RPCResponse], response))
@@ -5,6 +5,7 @@ provides dummy metrics for environments where Prometheus isn't configured.
5
5
  """
6
6
 
7
7
  import dataclasses
8
+ import warnings
8
9
  from functools import partial
9
10
  from typing import Any, Callable, Final
10
11
 
@@ -55,6 +56,24 @@ def _init_prometheus_metrics(registry=None) -> dict[str, Callable[..., Any]]:
55
56
  }
56
57
 
57
58
 
59
+ _metrics_initialized: bool = False
60
+
61
+
62
+ def warn_if_prometheus_not_initialized() -> None:
63
+ """Warn if prometheus_client is installed but init_metrics() has not been called."""
64
+ try:
65
+ import prometheus_client # noqa: F401
66
+ except ImportError:
67
+ return
68
+ if not _metrics_initialized:
69
+ warnings.warn(
70
+ "prometheus_client is installed but init_metrics() has not been called. "
71
+ "Metrics will not be recorded. Call init_metrics() to enable them.",
72
+ UserWarning,
73
+ stacklevel=3,
74
+ )
75
+
76
+
58
77
  _HTTP_RPC_SERVICE_REQUESTS: Any = _DummyMetric()
59
78
  _HTTP_RPC_BATCH_SIZE: Any = _DummyMetric()
60
79
 
@@ -68,7 +87,7 @@ def init_metrics(
68
87
  metrics_config: MetricsConfig = MetricsConfig(), registry=None
69
88
  ) -> None:
70
89
  _prom = _init_prometheus_metrics(registry)
71
- global _HTTP_RPC_SERVICE_REQUESTS, _HTTP_RPC_BATCH_SIZE
90
+ global _metrics_initialized, _HTTP_RPC_SERVICE_REQUESTS, _HTTP_RPC_BATCH_SIZE
72
91
  global _RPC_REQUEST, _RPC_SERVICE_RESPONSE_SECONDS, _RPC_SERVICE_REQUEST_PAYLOAD_BYTES, _RPC_SERVICE_RESPONSE_PAYLOAD_BYTES
73
92
  global _CHAIN_ID_TO_NAME
74
93
 
@@ -137,3 +156,5 @@ def init_metrics(
137
156
  ["network", "layer", "chain_id", "provider"],
138
157
  namespace=metrics_config.namespace,
139
158
  )
159
+
160
+ _metrics_initialized = True
@@ -15,6 +15,7 @@ from web3_multi_provider.exceptions import (
15
15
  ProtocolNotSupported,
16
16
  )
17
17
  from web3_multi_provider.http_provider_proxy import HTTPProviderProxy
18
+ from web3_multi_provider.metrics import warn_if_prometheus_not_initialized
18
19
  from web3_multi_provider.util import sanitize_poa_response
19
20
 
20
21
  logger = logging.getLogger(__name__)
@@ -36,6 +37,7 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
36
37
  **kwargs: Any,
37
38
  ):
38
39
  logger.debug({"msg": f"Initialize {self.__class__.__name__}"})
40
+ warn_if_prometheus_not_initialized()
39
41
  self._hosts_uri = endpoint_urls
40
42
  self._providers = []
41
43
 
@@ -61,26 +63,26 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
61
63
  def _validate_chain_ids(self) -> None:
62
64
  """
63
65
  Validates that all providers have the same chain ID.
64
-
66
+
65
67
  Raises:
66
68
  ChainIdMismatchError: If providers have different chain IDs.
67
69
  """
68
70
  chain_ids: dict[str, list[str]] = {}
69
-
71
+
70
72
  for provider in self._providers:
71
73
  if hasattr(provider, "_chain_id") and provider._chain_id:
72
74
  chain_id = provider._chain_id
73
75
  endpoint_uri = str(provider.endpoint_uri)
74
-
76
+
75
77
  if chain_id not in chain_ids:
76
78
  chain_ids[chain_id] = []
77
79
  chain_ids[chain_id].append(endpoint_uri)
78
-
80
+
79
81
  if len(chain_ids) > 1:
80
82
  mismatches = []
81
83
  for chain_id, endpoints in chain_ids.items():
82
84
  mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
83
-
85
+
84
86
  raise ChainIdMismatchError(
85
87
  f"Providers have different chain IDs:\n" + "\n".join(mismatches)
86
88
  )
@@ -1,81 +0,0 @@
1
- # <img src="https://docs.lido.fi/img/logo.svg" alt="Lido" width="46"/> Web3 Multi Provider
2
-
3
- [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
-
6
- Provider that accepts multiple endpoints.
7
-
8
- ## Install
9
-
10
- ```bash
11
- $ pip install web3-multi-provider
12
- ```
13
- or
14
- ```bash
15
- $ poetry add web3-multi-provider
16
- ```
17
- or with metrics:
18
- ```bash
19
- $ poetry add web3-multi-provider[metrics]
20
- ```
21
-
22
- ## Usage
23
-
24
- ```py
25
- from web3 import Web3
26
- from web3_multi_provider import MultiProvider
27
- from web3_multi_provider import FallbackProvider
28
-
29
- w3 = Web3(MultiProvider([ # RPC endpoints list
30
- 'http://127.0.0.1:8000/',
31
- 'https://mainnet.infura.io/v3/...',
32
- ]))
33
-
34
- # or
35
-
36
- w3 = Web3(FallbackProvider([ # RPC endpoints list
37
- 'http://127.0.0.1:8000/',
38
- 'https://mainnet.infura.io/v3/...',
39
- ]))
40
-
41
- last_block = w3.eth.get_block('latest')
42
- ```
43
-
44
- ### `MultiProvider`
45
-
46
- This provider keeps track of the current endpoint and switches to the next one if an error occurs.
47
- It fails if no endpoints are available.
48
-
49
- ### `FallbackProvider`
50
-
51
- This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
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
-
72
- ## For developers
73
-
74
- 1. `poetry install` - to install deps
75
- 2. `pre-commit install` - to install pre-commit hooks
76
-
77
- ## Tests
78
-
79
- ```bash
80
- poetry run pytest tests
81
- ```