web3-multi-provider 2.2.7__tar.gz → 2.3.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.
@@ -0,0 +1,197 @@
1
+ Metadata-Version: 2.1
2
+ Name: web3-multi-provider
3
+ Version: 2.3.0
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
+ License: MIT
6
+ Author: Raman
7
+ Author-email: raman.s@lido.fi
8
+ Requires-Python: >=3.12,<4
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Provides-Extra: metrics
13
+ Requires-Dist: prometheus-client (>=0.21.1,<0.22.0) ; extra == "metrics"
14
+ Requires-Dist: web3 (>=7,<8)
15
+ Description-Content-Type: text/markdown
16
+
17
+ # <img src="https://docs.lido.fi/img/logo.svg" alt="Lido" width="46"/> Web3 Multi Provider
18
+
19
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
20
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
21
+
22
+ Provider that accepts multiple endpoints.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ $ pip install web3-multi-provider
28
+ ```
29
+ or
30
+ ```bash
31
+ $ poetry add web3-multi-provider
32
+ ```
33
+ or with metrics:
34
+ ```bash
35
+ $ poetry add web3-multi-provider[metrics]
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```py
41
+ from web3 import Web3
42
+ from web3_multi_provider import MultiProvider
43
+ from web3_multi_provider import FallbackProvider
44
+
45
+ w3 = Web3(MultiProvider([ # RPC endpoints list
46
+ 'http://127.0.0.1:8000/',
47
+ 'https://mainnet.infura.io/v3/...',
48
+ ]))
49
+
50
+ # or
51
+
52
+ w3 = Web3(FallbackProvider([ # RPC endpoints list
53
+ 'http://127.0.0.1:8000/',
54
+ 'https://mainnet.infura.io/v3/...',
55
+ ]))
56
+
57
+ last_block = w3.eth.get_block('latest')
58
+ ```
59
+
60
+ ### `MultiProvider`
61
+
62
+ This provider keeps track of the current endpoint and switches to the next one if an error occurs.
63
+ It fails if no endpoints are available.
64
+
65
+ ### `FallbackProvider`
66
+
67
+ This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
68
+
69
+ A failing endpoint is slow to fail over from: web3 retries it before the next endpoint is tried. Pass
70
+ `cooldown_seconds` to try an endpoint that failed after the other endpoints until its cooldown ends.
71
+ It is still tried if the other endpoints fail. When the cooldown ends, one request tries the endpoint
72
+ first again; concurrent requests keep it last until that request finishes. If it fails, a new
73
+ cooldown starts. An endpoint that answers, including one tried last, is first again at once. The
74
+ default `0` disables the cooldown.
75
+
76
+ Any exception from an endpoint starts its cooldown, including errors that the request itself
77
+ causes, such as a timeout or HTTP 413 on a heavy `eth_getLogs`. A JSON-RPC error in an HTTP 200
78
+ response (for example, a rate limit reported as error `-32005`) is a valid answer and does not start
79
+ a cooldown.
80
+
81
+ ```py
82
+ w3 = Web3(FallbackProvider([
83
+ 'http://127.0.0.1:8000/',
84
+ 'https://mainnet.infura.io/v3/...',
85
+ ], cooldown_seconds=60))
86
+ ```
87
+
88
+ ### `AsyncMultiProvider` and `AsyncFallbackProvider`
89
+
90
+ These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
91
+ be used with instances of `AsyncWeb3`.
92
+
93
+ ```py
94
+ from web3 import AsyncWeb3
95
+ from web3_multi_provider import AsyncMultiProvider
96
+
97
+ w3 = AsyncWeb3(AsyncMultiProvider([ # RPC endpoints list
98
+ 'http://127.0.0.1:8000/',
99
+ 'https://mainnet.infura.io/v3/...',
100
+ ]))
101
+ ```
102
+
103
+ ### Metrics
104
+
105
+ The library has built-in Prometheus metrics. They are disabled by default — install the extra and call `init_metrics()` before creating any provider.
106
+
107
+ ```bash
108
+ pip install web3-multi-provider[metrics]
109
+ ```
110
+
111
+ ```py
112
+ from web3 import Web3
113
+ from web3_multi_provider import MultiProvider, init_metrics
114
+
115
+ init_metrics() # must be called before creating a provider
116
+
117
+ w3 = Web3(MultiProvider([
118
+ 'http://127.0.0.1:8000/',
119
+ 'https://mainnet.infura.io/v3/...',
120
+ ]))
121
+ ```
122
+
123
+ `init_metrics()` registers the following metrics with the default Prometheus registry:
124
+
125
+ | Metric | Type | Description |
126
+ |---|---|---|
127
+ | `http_rpc_requests` | Counter | Total HTTP requests by network, provider, response code, result |
128
+ | `http_rpc_batch_size` | Histogram | Distribution of batch sizes |
129
+ | `http_rpc_response_seconds` | Histogram | RPC response time |
130
+ | `http_rpc_request_payload_bytes` | Histogram | Request payload size |
131
+ | `http_rpc_response_payload_bytes` | Histogram | Response payload size |
132
+ | `rpc_request` | Counter | RPC calls by method and result |
133
+
134
+ #### Custom configuration
135
+
136
+ Use `MetricsConfig` to set a namespace or override the chain ID → network name mapping:
137
+
138
+ ```py
139
+ from web3_multi_provider.metrics import MetricsConfig
140
+
141
+ init_metrics(MetricsConfig(
142
+ namespace="myapp",
143
+ chain_id_to_name={
144
+ 1: "ethereum",
145
+ 137: "polygon",
146
+ # add any custom chains here
147
+ },
148
+ ))
149
+ ```
150
+
151
+ #### Custom registry
152
+
153
+ Pass a custom Prometheus registry if you don't want to use the global one:
154
+
155
+ ```py
156
+ from prometheus_client import CollectorRegistry
157
+ from web3_multi_provider import init_metrics
158
+
159
+ registry = CollectorRegistry()
160
+ init_metrics(registry=registry)
161
+ ```
162
+
163
+ ## For developers
164
+
165
+ This project requires a specific Poetry version, pinned in `.poetry-version`. To install it:
166
+
167
+ ```bash
168
+ POETRY_VERSION=$(cat .poetry-version) curl -sSL https://install.python-poetry.org/ | python -
169
+ ```
170
+
171
+ ### Requirements
172
+
173
+ - [Docker](https://docs.docker.com/get-docker/)
174
+ - [Dev Container CLI](https://github.com/devcontainers/cli): `npm install -g @devcontainers/cli`
175
+ - VS Code: [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension
176
+ - JetBrains: [Dev Containers](https://plugins.jetbrains.com/plugin/21724-dev-containers) plugin
177
+
178
+ ### Setup
179
+
180
+ ```bash
181
+ devcontainer up --workspace-folder .
182
+ devcontainer exec --workspace-folder . bash
183
+ ```
184
+
185
+ This installs all dependencies and pre-commit hooks automatically via `postCreateCommand`.
186
+
187
+ Alternatively, without Docker:
188
+
189
+ 1. `poetry install` - to install deps
190
+ 2. `pre-commit install` - to install pre-commit hooks
191
+
192
+ ## Tests
193
+
194
+ ```bash
195
+ poetry run pytest tests
196
+ ```
197
+
@@ -0,0 +1,180 @@
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
+ A failing endpoint is slow to fail over from: web3 retries it before the next endpoint is tried. Pass
54
+ `cooldown_seconds` to try an endpoint that failed after the other endpoints until its cooldown ends.
55
+ It is still tried if the other endpoints fail. When the cooldown ends, one request tries the endpoint
56
+ first again; concurrent requests keep it last until that request finishes. If it fails, a new
57
+ cooldown starts. An endpoint that answers, including one tried last, is first again at once. The
58
+ default `0` disables the cooldown.
59
+
60
+ Any exception from an endpoint starts its cooldown, including errors that the request itself
61
+ causes, such as a timeout or HTTP 413 on a heavy `eth_getLogs`. A JSON-RPC error in an HTTP 200
62
+ response (for example, a rate limit reported as error `-32005`) is a valid answer and does not start
63
+ a cooldown.
64
+
65
+ ```py
66
+ w3 = Web3(FallbackProvider([
67
+ 'http://127.0.0.1:8000/',
68
+ 'https://mainnet.infura.io/v3/...',
69
+ ], cooldown_seconds=60))
70
+ ```
71
+
72
+ ### `AsyncMultiProvider` and `AsyncFallbackProvider`
73
+
74
+ These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
75
+ be used with instances of `AsyncWeb3`.
76
+
77
+ ```py
78
+ from web3 import AsyncWeb3
79
+ from web3_multi_provider import AsyncMultiProvider
80
+
81
+ w3 = AsyncWeb3(AsyncMultiProvider([ # RPC endpoints list
82
+ 'http://127.0.0.1:8000/',
83
+ 'https://mainnet.infura.io/v3/...',
84
+ ]))
85
+ ```
86
+
87
+ ### Metrics
88
+
89
+ The library has built-in Prometheus metrics. They are disabled by default — install the extra and call `init_metrics()` before creating any provider.
90
+
91
+ ```bash
92
+ pip install web3-multi-provider[metrics]
93
+ ```
94
+
95
+ ```py
96
+ from web3 import Web3
97
+ from web3_multi_provider import MultiProvider, init_metrics
98
+
99
+ init_metrics() # must be called before creating a provider
100
+
101
+ w3 = Web3(MultiProvider([
102
+ 'http://127.0.0.1:8000/',
103
+ 'https://mainnet.infura.io/v3/...',
104
+ ]))
105
+ ```
106
+
107
+ `init_metrics()` registers the following metrics with the default Prometheus registry:
108
+
109
+ | Metric | Type | Description |
110
+ |---|---|---|
111
+ | `http_rpc_requests` | Counter | Total HTTP requests by network, provider, response code, result |
112
+ | `http_rpc_batch_size` | Histogram | Distribution of batch sizes |
113
+ | `http_rpc_response_seconds` | Histogram | RPC response time |
114
+ | `http_rpc_request_payload_bytes` | Histogram | Request payload size |
115
+ | `http_rpc_response_payload_bytes` | Histogram | Response payload size |
116
+ | `rpc_request` | Counter | RPC calls by method and result |
117
+
118
+ #### Custom configuration
119
+
120
+ Use `MetricsConfig` to set a namespace or override the chain ID → network name mapping:
121
+
122
+ ```py
123
+ from web3_multi_provider.metrics import MetricsConfig
124
+
125
+ init_metrics(MetricsConfig(
126
+ namespace="myapp",
127
+ chain_id_to_name={
128
+ 1: "ethereum",
129
+ 137: "polygon",
130
+ # add any custom chains here
131
+ },
132
+ ))
133
+ ```
134
+
135
+ #### Custom registry
136
+
137
+ Pass a custom Prometheus registry if you don't want to use the global one:
138
+
139
+ ```py
140
+ from prometheus_client import CollectorRegistry
141
+ from web3_multi_provider import init_metrics
142
+
143
+ registry = CollectorRegistry()
144
+ init_metrics(registry=registry)
145
+ ```
146
+
147
+ ## For developers
148
+
149
+ This project requires a specific Poetry version, pinned in `.poetry-version`. To install it:
150
+
151
+ ```bash
152
+ POETRY_VERSION=$(cat .poetry-version) curl -sSL https://install.python-poetry.org/ | python -
153
+ ```
154
+
155
+ ### Requirements
156
+
157
+ - [Docker](https://docs.docker.com/get-docker/)
158
+ - [Dev Container CLI](https://github.com/devcontainers/cli): `npm install -g @devcontainers/cli`
159
+ - VS Code: [Dev Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension
160
+ - JetBrains: [Dev Containers](https://plugins.jetbrains.com/plugin/21724-dev-containers) plugin
161
+
162
+ ### Setup
163
+
164
+ ```bash
165
+ devcontainer up --workspace-folder .
166
+ devcontainer exec --workspace-folder . bash
167
+ ```
168
+
169
+ This installs all dependencies and pre-commit hooks automatically via `postCreateCommand`.
170
+
171
+ Alternatively, without Docker:
172
+
173
+ 1. `poetry install` - to install deps
174
+ 2. `pre-commit install` - to install pre-commit hooks
175
+
176
+ ## Tests
177
+
178
+ ```bash
179
+ poetry run pytest tests
180
+ ```
@@ -1,16 +1,16 @@
1
1
  [tool.poetry]
2
2
  name = "web3-multi-provider"
3
- version = "2.2.7"
3
+ version = "2.3.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"
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]
@@ -1,5 +1,5 @@
1
1
  import logging
2
- from typing import Any, List, Optional, Tuple, Union, cast, override
2
+ from typing import Any, List, Optional, Tuple, Union, cast
3
3
 
4
4
  from eth_typing import URI
5
5
  from web3 import AsyncHTTPProvider
@@ -15,12 +15,16 @@ from web3_multi_provider.util import normalize_provider
15
15
  logger = logging.getLogger(__name__)
16
16
 
17
17
 
18
- class AsyncHTTPProviderProxy(AsyncHTTPProvider):
18
+ # connect() is only for persistent-connection providers; AsyncHTTPProvider
19
+ # does not implement it either.
20
+ class AsyncHTTPProviderProxy(AsyncHTTPProvider): # pylint: disable=abstract-method
19
21
  """
20
- An asynchronous extension of Web3's AsyncHTTPProvider that adds Prometheus metrics tracking.
22
+ An asynchronous extension of Web3's AsyncHTTPProvider that adds Prometheus
23
+ metrics tracking.
21
24
 
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.
25
+ This proxy handles request success/failure tracking, request and response
26
+ payload size observation, and lazy chain ID initialization to tag metrics
27
+ with network-specific labels.
24
28
 
25
29
  Metrics collected include:
26
30
  - RPC call success/failure counts
@@ -73,17 +77,19 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
73
77
  if self._chain_id != "":
74
78
  return
75
79
  self._chain_id = str(await self._fetch_chain_id())
80
+ # pylint: disable-next=protected-access
76
81
  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
- )
82
+ self._request_session_manager = HTTPSessionManagerProxy(
83
+ chain_id=self._chain_id,
84
+ uri=self._uri,
85
+ network=self._network,
86
+ layer=self._layer,
84
87
  )
85
88
 
86
89
  async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
90
+ """
91
+ Makes an RPC request after ensuring chain info is initialized.
92
+ """
87
93
  await self._ensure_chain_info_initialized()
88
94
  return await super().make_request(method, params)
89
95
 
@@ -103,14 +109,18 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
103
109
  async def make_batch_request(
104
110
  self, batch_requests: List[Tuple[RPCEndpoint, Any]]
105
111
  ) -> Union[List[RPCResponse], RPCResponse]:
112
+ """
113
+ Makes a batch RPC request through the metrics-aware session manager.
114
+ """
106
115
  await self._ensure_chain_info_initialized()
107
- self.logger.debug(f"Making batch request HTTP - uri: `{self.endpoint_uri}`")
116
+ self.logger.debug("Making batch request HTTP - uri: `%s`", self.endpoint_uri)
108
117
  request_data = self.encode_batch_rpc_request(batch_requests)
109
118
  raw_response = await self._request_session_manager.async_make_post_request(
110
119
  self.endpoint_uri, # type: ignore
111
120
  request_data,
112
121
  _batch_size=len(batch_requests),
113
- **self.get_request_kwargs(),
122
+ # get_request_kwargs() is wrapped in @to_dict upstream, as web3 itself uses it.
123
+ **self.get_request_kwargs(), # pylint: disable=not-a-mapping
114
124
  )
115
125
  self.logger.debug("Received batch response HTTP.")
116
126
  response = self.decode_rpc_response(raw_response)
@@ -11,11 +11,13 @@ 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.cooldown import ProviderCooldown
14
15
  from web3_multi_provider.exceptions import (
15
16
  ChainIdMismatchError,
16
17
  NoActiveProviderError,
17
18
  ProtocolNotSupported,
18
19
  )
20
+ from web3_multi_provider.metrics import warn_if_prometheus_not_initialized
19
21
  from web3_multi_provider.util import sanitize_poa_response
20
22
 
21
23
  logger = logging.getLogger(__name__)
@@ -36,6 +38,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
36
38
  **kwargs: Any,
37
39
  ):
38
40
  logger.debug({"msg": f"Initialize {self.__class__.__name__}"})
41
+ warn_if_prometheus_not_initialized()
39
42
  self._hosts_uri = endpoint_urls
40
43
  self._providers = []
41
44
 
@@ -55,33 +58,35 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
55
58
  )
56
59
  self._providers.append(provider)
57
60
 
61
+ self._provider_indexes = {id(p): i for i, p in enumerate(self._providers)}
58
62
  super().__init__()
59
63
 
60
64
  def _validate_chain_ids(self) -> None:
61
65
  """
62
66
  Validates that all providers have the same chain ID.
63
-
67
+
64
68
  Raises:
65
69
  ChainIdMismatchError: If providers have different chain IDs.
66
70
  """
67
71
  chain_ids: dict[str, list[str]] = {}
68
-
72
+
69
73
  for provider in self._providers:
70
- if hasattr(provider, "_chain_id") and provider._chain_id:
71
- chain_id = provider._chain_id
74
+ # Set lazily by the provider proxy on its first request.
75
+ chain_id = getattr(provider, "_chain_id", "")
76
+ if chain_id:
72
77
  endpoint_uri = str(provider.endpoint_uri)
73
-
78
+
74
79
  if chain_id not in chain_ids:
75
80
  chain_ids[chain_id] = []
76
81
  chain_ids[chain_id].append(endpoint_uri)
77
-
82
+
78
83
  if len(chain_ids) > 1:
79
84
  mismatches = []
80
85
  for chain_id, endpoints in chain_ids.items():
81
86
  mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
82
-
87
+
83
88
  raise ChainIdMismatchError(
84
- f"Providers have different chain IDs:\n" + "\n".join(mismatches)
89
+ "Providers have different chain IDs:\n" + "\n".join(mismatches)
85
90
  )
86
91
 
87
92
  async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
@@ -102,36 +107,55 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
102
107
  provider_iter: Iterable[AsyncHTTPProvider],
103
108
  ) -> RPCResponse:
104
109
  exceptions: list[Exception] = []
105
-
106
- for index, provider in enumerate(provider_iter):
107
- try:
108
- response = await provider.make_request(method, params)
109
- except Exception as error: # pylint: disable=broad-except
110
- exceptions.append(error)
111
- logger.warning(
112
- {
113
- "msg": "Provider not responding.",
114
- "index": index,
115
- "error": str(error).replace(str(provider.endpoint_uri), "****"),
116
- }
117
- )
118
- else:
119
- sanitize_poa_response(method, response)
120
- logger.debug(
121
- {
122
- "msg": f"Send request using {provider_name}.",
123
- "method": method,
124
- "params": str(params),
125
- }
126
- )
127
- return response
128
-
129
- msg = f"No active provider available in {provider_name}."
130
- logger.debug({"msg": msg})
131
- raise NoActiveProviderError.from_exceptions(msg, exceptions)
110
+ try:
111
+ for provider in provider_iter:
112
+ # None for an endpoint that a subclass yields from outside the configured
113
+ # list: it is still tried, but its cooldown is not tracked.
114
+ index = self._provider_indexes.get(id(provider))
115
+ try:
116
+ response = await provider.make_request(method, params)
117
+ except Exception as error: # pylint: disable=broad-except
118
+ exceptions.append(error)
119
+ logger.warning(
120
+ {
121
+ "msg": "Provider not responding.",
122
+ "index": index,
123
+ "error": str(error).replace(
124
+ str(provider.endpoint_uri), "****"
125
+ ),
126
+ }
127
+ )
128
+ if index is not None:
129
+ self._on_provider_failure(index)
130
+ else:
131
+ if index is not None:
132
+ self._on_provider_success(index)
133
+ sanitize_poa_response(method, response)
134
+ logger.debug(
135
+ {
136
+ "msg": f"Send request using {provider_name}.",
137
+ "method": method,
138
+ "params": str(params),
139
+ }
140
+ )
141
+ return response
142
+
143
+ msg = f"No active provider available in {provider_name}."
144
+ logger.debug({"msg": msg})
145
+ raise NoActiveProviderError.from_exceptions(msg, exceptions)
146
+ finally:
147
+ # Break explicitly a reference cycle, as socket.create_connection does
148
+ exceptions.clear()
149
+
150
+ def _on_provider_failure(self, index: int) -> None:
151
+ """Called after the endpoint at `index` raised on a request."""
152
+
153
+ def _on_provider_success(self, index: int) -> None:
154
+ """Called after the endpoint at `index` answered a request."""
132
155
 
133
156
  @abstractmethod
134
157
  def get_providers(self) -> Iterable[AsyncHTTPProvider]:
158
+ """Return the providers to try for one request, in order."""
135
159
  raise NotImplementedError
136
160
 
137
161
 
@@ -149,8 +173,23 @@ class AsyncMultiProvider(AsyncBaseMultiProvider):
149
173
 
150
174
 
151
175
  class AsyncFallbackProvider(AsyncBaseMultiProvider):
152
- """Simple fallback: tries providers in order."""
176
+ """Fallback provider: tries each provider once, in order.
177
+
178
+ With `cooldown_seconds` > 0, a provider that failed is tried after the others until its
179
+ cooldown ends.
180
+ """
181
+
182
+ def __init__(self, *args: Any, cooldown_seconds: float = 0, **kwargs: Any):
183
+ super().__init__(*args, **kwargs)
184
+ self._cooldown = ProviderCooldown(cooldown_seconds)
153
185
 
154
186
  def get_providers(self) -> Iterable[AsyncHTTPProvider]:
155
- """Return providers in order without rotation (fallback)."""
156
- return iter(self._providers)
187
+ if not self._cooldown.enabled:
188
+ return iter(self._providers)
189
+ return [self._providers[i] for i in self._cooldown.order(len(self._providers))]
190
+
191
+ def _on_provider_failure(self, index: int) -> None:
192
+ self._cooldown.mark_failed(index)
193
+
194
+ def _on_provider_success(self, index: int) -> None:
195
+ self._cooldown.mark_succeeded(index)