web3-multi-provider 2.2.8__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.
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/PKG-INFO +20 -1
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/README.md +19 -0
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/pyproject.toml +1 -1
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/async_http_provider_proxy.py +19 -7
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/async_multi_http_provider.py +70 -33
- web3_multi_provider-2.3.0/web3_multi_provider/cooldown.py +93 -0
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/exceptions.py +6 -4
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/http_provider_proxy.py +8 -3
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/http_session_manager_proxy.py +37 -13
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/metrics.py +22 -4
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/multi_http_provider.py +72 -34
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/LICENSE +0 -0
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/__init__.py +0 -0
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/py.typed +0 -0
- {web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/util.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: web3-multi-provider
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.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
|
|
@@ -66,6 +66,25 @@ It fails if no endpoints are available.
|
|
|
66
66
|
|
|
67
67
|
This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
|
|
68
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
|
+
|
|
69
88
|
### `AsyncMultiProvider` and `AsyncFallbackProvider`
|
|
70
89
|
|
|
71
90
|
These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
|
|
@@ -50,6 +50,25 @@ It fails if no endpoints are available.
|
|
|
50
50
|
|
|
51
51
|
This provider sends requests to the all endpoints in the sequence until response received or endpoints list exhausted.
|
|
52
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
|
+
|
|
53
72
|
### `AsyncMultiProvider` and `AsyncFallbackProvider`
|
|
54
73
|
|
|
55
74
|
These providers are async versions of `MultiProvider` and `FallbackProvider` respectively. They may
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "web3-multi-provider"
|
|
3
|
-
version = "2.
|
|
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"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import logging
|
|
2
|
-
from typing import Any, List, Optional, Tuple, Union, cast
|
|
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
|
-
|
|
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
|
|
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
|
|
23
|
-
and lazy chain ID initialization to tag metrics
|
|
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,6 +77,7 @@ 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
82
|
self._request_session_manager = HTTPSessionManagerProxy(
|
|
78
83
|
chain_id=self._chain_id,
|
|
@@ -82,6 +87,9 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
|
|
|
82
87
|
)
|
|
83
88
|
|
|
84
89
|
async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
|
|
90
|
+
"""
|
|
91
|
+
Makes an RPC request after ensuring chain info is initialized.
|
|
92
|
+
"""
|
|
85
93
|
await self._ensure_chain_info_initialized()
|
|
86
94
|
return await super().make_request(method, params)
|
|
87
95
|
|
|
@@ -101,14 +109,18 @@ class AsyncHTTPProviderProxy(AsyncHTTPProvider):
|
|
|
101
109
|
async def make_batch_request(
|
|
102
110
|
self, batch_requests: List[Tuple[RPCEndpoint, Any]]
|
|
103
111
|
) -> Union[List[RPCResponse], RPCResponse]:
|
|
112
|
+
"""
|
|
113
|
+
Makes a batch RPC request through the metrics-aware session manager.
|
|
114
|
+
"""
|
|
104
115
|
await self._ensure_chain_info_initialized()
|
|
105
|
-
self.logger.debug(
|
|
116
|
+
self.logger.debug("Making batch request HTTP - uri: `%s`", self.endpoint_uri)
|
|
106
117
|
request_data = self.encode_batch_rpc_request(batch_requests)
|
|
107
118
|
raw_response = await self._request_session_manager.async_make_post_request(
|
|
108
119
|
self.endpoint_uri, # type: ignore
|
|
109
120
|
request_data,
|
|
110
121
|
_batch_size=len(batch_requests),
|
|
111
|
-
|
|
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
|
|
112
124
|
)
|
|
113
125
|
self.logger.debug("Received batch response HTTP.")
|
|
114
126
|
response = self.decode_rpc_response(raw_response)
|
|
@@ -11,6 +11,7 @@ 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,
|
|
@@ -57,6 +58,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
|
|
|
57
58
|
)
|
|
58
59
|
self._providers.append(provider)
|
|
59
60
|
|
|
61
|
+
self._provider_indexes = {id(p): i for i, p in enumerate(self._providers)}
|
|
60
62
|
super().__init__()
|
|
61
63
|
|
|
62
64
|
def _validate_chain_ids(self) -> None:
|
|
@@ -69,8 +71,9 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
|
|
|
69
71
|
chain_ids: dict[str, list[str]] = {}
|
|
70
72
|
|
|
71
73
|
for provider in self._providers:
|
|
72
|
-
|
|
73
|
-
|
|
74
|
+
# Set lazily by the provider proxy on its first request.
|
|
75
|
+
chain_id = getattr(provider, "_chain_id", "")
|
|
76
|
+
if chain_id:
|
|
74
77
|
endpoint_uri = str(provider.endpoint_uri)
|
|
75
78
|
|
|
76
79
|
if chain_id not in chain_ids:
|
|
@@ -83,7 +86,7 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
|
|
|
83
86
|
mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
|
|
84
87
|
|
|
85
88
|
raise ChainIdMismatchError(
|
|
86
|
-
|
|
89
|
+
"Providers have different chain IDs:\n" + "\n".join(mismatches)
|
|
87
90
|
)
|
|
88
91
|
|
|
89
92
|
async def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
|
|
@@ -104,36 +107,55 @@ class AsyncBaseMultiProvider(AsyncJSONBaseProvider, ABC):
|
|
|
104
107
|
provider_iter: Iterable[AsyncHTTPProvider],
|
|
105
108
|
) -> RPCResponse:
|
|
106
109
|
exceptions: list[Exception] = []
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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."""
|
|
134
155
|
|
|
135
156
|
@abstractmethod
|
|
136
157
|
def get_providers(self) -> Iterable[AsyncHTTPProvider]:
|
|
158
|
+
"""Return the providers to try for one request, in order."""
|
|
137
159
|
raise NotImplementedError
|
|
138
160
|
|
|
139
161
|
|
|
@@ -151,8 +173,23 @@ class AsyncMultiProvider(AsyncBaseMultiProvider):
|
|
|
151
173
|
|
|
152
174
|
|
|
153
175
|
class AsyncFallbackProvider(AsyncBaseMultiProvider):
|
|
154
|
-
"""
|
|
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)
|
|
155
185
|
|
|
156
186
|
def get_providers(self) -> Iterable[AsyncHTTPProvider]:
|
|
157
|
-
|
|
158
|
-
|
|
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)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import math
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ProviderCooldown:
|
|
10
|
+
"""Remembers which endpoints failed recently.
|
|
11
|
+
|
|
12
|
+
A failed request costs web3's in-provider retries before failover moves on. Trying a recently
|
|
13
|
+
failed endpoint last pays that cost once per cooldown window instead of on every request.
|
|
14
|
+
|
|
15
|
+
When a cooldown ends, only one request probes the endpoint. The other requests keep it last
|
|
16
|
+
until the probe reports a result, so a still-failing endpoint does not slow down every
|
|
17
|
+
concurrent request at once.
|
|
18
|
+
|
|
19
|
+
All methods are thread-safe. They do no I/O, so the async providers can call them too.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, seconds: float):
|
|
23
|
+
if not math.isfinite(seconds) or seconds < 0:
|
|
24
|
+
raise ValueError(
|
|
25
|
+
"Cooldown must be a finite, non-negative number of seconds."
|
|
26
|
+
)
|
|
27
|
+
self._seconds = seconds
|
|
28
|
+
self._lock = threading.Lock()
|
|
29
|
+
self._until: dict[int, float] = {}
|
|
30
|
+
self._probing: set[int] = set()
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def enabled(self) -> bool:
|
|
34
|
+
"""Whether failed endpoints are moved back at all."""
|
|
35
|
+
return self._seconds > 0
|
|
36
|
+
|
|
37
|
+
def order(self, count: int) -> list[int]:
|
|
38
|
+
"""Endpoint indexes in configured order, with cooling endpoints moved to the end.
|
|
39
|
+
|
|
40
|
+
Cooling endpoints are kept, so a request never has fewer endpoints to try than without
|
|
41
|
+
a cooldown. Each index appears exactly once. Cooling endpoints are ordered by when their
|
|
42
|
+
cooldown ends: the endpoint that failed longest ago is the most likely to have recovered.
|
|
43
|
+
"""
|
|
44
|
+
with self._lock:
|
|
45
|
+
now = time.monotonic()
|
|
46
|
+
healthy: list[int] = []
|
|
47
|
+
cooling: list[tuple[float, int]] = []
|
|
48
|
+
for index in range(count):
|
|
49
|
+
until = self._until.get(index)
|
|
50
|
+
if until is None:
|
|
51
|
+
healthy.append(index)
|
|
52
|
+
elif until > now:
|
|
53
|
+
cooling.append((until, index))
|
|
54
|
+
else:
|
|
55
|
+
self._start_probe(index, now)
|
|
56
|
+
healthy.append(index)
|
|
57
|
+
return healthy + [index for _, index in sorted(cooling)]
|
|
58
|
+
|
|
59
|
+
def _start_probe(self, index: int, now: float) -> None:
|
|
60
|
+
# Re-arm the cooldown before the probe runs, so concurrent requests keep the endpoint
|
|
61
|
+
# last. A probe that never reports back (the request was cancelled, or an earlier
|
|
62
|
+
# endpoint answered first) only delays the next probe by one window. Because `order`
|
|
63
|
+
# sorts cooling endpoints by `_until`, such an endpoint still comes before endpoints
|
|
64
|
+
# that failed after it, so it is not stuck behind endpoints that are actually down.
|
|
65
|
+
self._until[index] = now + self._seconds
|
|
66
|
+
self._probing.add(index)
|
|
67
|
+
|
|
68
|
+
def mark_failed(self, index: int) -> None:
|
|
69
|
+
"""Start or extend the cooldown of the endpoint at `index`."""
|
|
70
|
+
if not self.enabled:
|
|
71
|
+
return
|
|
72
|
+
with self._lock:
|
|
73
|
+
now = time.monotonic()
|
|
74
|
+
if index in self._probing:
|
|
75
|
+
self._probing.discard(index)
|
|
76
|
+
self._log(
|
|
77
|
+
logging.WARNING, "Provider still failing after cooldown.", index
|
|
78
|
+
)
|
|
79
|
+
elif self._until.get(index, 0) <= now:
|
|
80
|
+
self._log(logging.WARNING, "Provider put on cooldown.", index)
|
|
81
|
+
self._until[index] = now + self._seconds
|
|
82
|
+
|
|
83
|
+
def mark_succeeded(self, index: int) -> None:
|
|
84
|
+
"""End the cooldown of the endpoint at `index`: it answered, so it is preferred again."""
|
|
85
|
+
if not self.enabled:
|
|
86
|
+
return
|
|
87
|
+
with self._lock:
|
|
88
|
+
self._probing.discard(index)
|
|
89
|
+
if self._until.pop(index, None) is not None:
|
|
90
|
+
self._log(logging.INFO, "Provider recovered from cooldown.", index)
|
|
91
|
+
|
|
92
|
+
def _log(self, level: int, msg: str, index: int) -> None:
|
|
93
|
+
logger.log(level, {"msg": msg, "index": index, "seconds": self._seconds})
|
|
@@ -8,12 +8,14 @@ class NoActiveProviderError(ExceptionGroup):
|
|
|
8
8
|
def from_exceptions(
|
|
9
9
|
cls, message: str, exceptions: Sequence[Exception]
|
|
10
10
|
) -> Exception:
|
|
11
|
+
"""Build the error to raise when every provider failed.
|
|
12
|
+
|
|
13
|
+
Returns a RuntimeError instead when no provider was called at all,
|
|
14
|
+
because an ExceptionGroup cannot be empty.
|
|
15
|
+
"""
|
|
11
16
|
if exceptions:
|
|
12
17
|
return cls(message, exceptions)
|
|
13
|
-
|
|
14
|
-
return RuntimeError(
|
|
15
|
-
"No providers were called"
|
|
16
|
-
) # or a fallback custom Exception
|
|
18
|
+
return RuntimeError("No providers were called")
|
|
17
19
|
|
|
18
20
|
|
|
19
21
|
class ProtocolNotSupported(Exception):
|
{web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/http_provider_proxy.py
RENAMED
|
@@ -31,7 +31,7 @@ class HTTPProviderProxy(HTTPProvider):
|
|
|
31
31
|
_request_session_manager (HTTPSessionManagerProxy): Manages HTTP sessions per endpoint.
|
|
32
32
|
"""
|
|
33
33
|
|
|
34
|
-
def __init__(
|
|
34
|
+
def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
|
|
35
35
|
self,
|
|
36
36
|
endpoint_uri: Optional[Union[URI, str]] = None,
|
|
37
37
|
request_kwargs: Optional[Any] = None,
|
|
@@ -81,6 +81,7 @@ class HTTPProviderProxy(HTTPProvider):
|
|
|
81
81
|
if self._chain_id != "":
|
|
82
82
|
return
|
|
83
83
|
self._chain_id = str(self._fetch_chain_id())
|
|
84
|
+
# pylint: disable-next=protected-access
|
|
84
85
|
self._network = metrics._CHAIN_ID_TO_NAME.get(int(self._chain_id), "unknown")
|
|
85
86
|
self._request_session_manager = HTTPSessionManagerProxy(
|
|
86
87
|
chain_id=self._chain_id,
|
|
@@ -116,14 +117,18 @@ class HTTPProviderProxy(HTTPProvider):
|
|
|
116
117
|
def make_batch_request(
|
|
117
118
|
self, batch_requests: List[Tuple[RPCEndpoint, Any]]
|
|
118
119
|
) -> Union[List[RPCResponse], RPCResponse]:
|
|
120
|
+
"""
|
|
121
|
+
Makes a batch RPC request through the metrics-aware session manager.
|
|
122
|
+
"""
|
|
119
123
|
self._ensure_chain_info_initialized()
|
|
120
|
-
self.logger.debug(
|
|
124
|
+
self.logger.debug("Making batch request HTTP, uri: `%s`", self.endpoint_uri)
|
|
121
125
|
request_data = self.encode_batch_rpc_request(batch_requests)
|
|
122
126
|
raw_response = self._request_session_manager.make_post_request(
|
|
123
127
|
self.endpoint_uri, # type: ignore
|
|
124
128
|
request_data,
|
|
125
129
|
_batch_size=len(batch_requests),
|
|
126
|
-
|
|
130
|
+
# get_request_kwargs() is wrapped in @to_dict upstream, as web3 itself uses it.
|
|
131
|
+
**self.get_request_kwargs(), # pylint: disable=not-a-mapping
|
|
127
132
|
)
|
|
128
133
|
self.logger.debug("Received batch response HTTP.")
|
|
129
134
|
response = self.decode_rpc_response(raw_response)
|
|
@@ -14,9 +14,30 @@ from web3._utils.http_session_manager import HTTPSessionManager
|
|
|
14
14
|
from web3_multi_provider import metrics
|
|
15
15
|
from web3_multi_provider.metrics import _DummyMetric
|
|
16
16
|
|
|
17
|
+
# The metric objects are package-private module globals in `metrics`, replaced
|
|
18
|
+
# by init_metrics(); they must be read through the module at call time.
|
|
19
|
+
# pylint: disable=protected-access
|
|
20
|
+
|
|
17
21
|
logger = logging.getLogger(__name__)
|
|
18
22
|
|
|
19
23
|
|
|
24
|
+
def _rpc_error_code(response: requests.Response) -> str:
|
|
25
|
+
"""JSON-RPC error code of a single response, for metric labels; "" if there is none.
|
|
26
|
+
|
|
27
|
+
Never raises. The body is read before web3 checks the HTTP status, so an exception
|
|
28
|
+
here would replace web3's `HTTPError` (and its status and retries) with a decode error.
|
|
29
|
+
Batch responses (JSON arrays) have no single code.
|
|
30
|
+
"""
|
|
31
|
+
try:
|
|
32
|
+
body = response.json()
|
|
33
|
+
except ValueError:
|
|
34
|
+
return ""
|
|
35
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
36
|
+
if isinstance(error, dict):
|
|
37
|
+
return str(error.get("code", ""))
|
|
38
|
+
return ""
|
|
39
|
+
|
|
40
|
+
|
|
20
41
|
class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
21
42
|
"""
|
|
22
43
|
A metrics-instrumented extension of `HTTPSessionManager` for monitoring and profiling
|
|
@@ -74,7 +95,8 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
74
95
|
),
|
|
75
96
|
# Rule: Peer identifiers
|
|
76
97
|
(lambda seg, prev_seg, prev2_seg: prev_seg == "peers", "{peer_id}"),
|
|
77
|
-
# Rule: Epoch numbers - duties, rewards, liveness endpoints
|
|
98
|
+
# Rule: Epoch numbers - duties, rewards, liveness endpoints
|
|
99
|
+
# (must come before validator check)
|
|
78
100
|
(
|
|
79
101
|
lambda seg, prev_seg, prev2_seg: (
|
|
80
102
|
prev_seg
|
|
@@ -134,7 +156,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
134
156
|
(lambda seg, prev_seg, prev2_seg: seg.isdigit(), "{id}"),
|
|
135
157
|
]
|
|
136
158
|
|
|
137
|
-
def __init__(
|
|
159
|
+
def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
|
|
138
160
|
self,
|
|
139
161
|
chain_id: int | str,
|
|
140
162
|
uri: str,
|
|
@@ -204,7 +226,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
204
226
|
|
|
205
227
|
return "/" + "/".join(normalized_segments)
|
|
206
228
|
|
|
207
|
-
except Exception as e:
|
|
229
|
+
except Exception as e: # pylint: disable=broad-exception-caught
|
|
208
230
|
logger.debug("Error normalizing CL path: %s", e, exc_info=True)
|
|
209
231
|
return None
|
|
210
232
|
|
|
@@ -238,12 +260,13 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
238
260
|
methods.append(item["method"])
|
|
239
261
|
elif isinstance(payload, dict) and isinstance(payload.get("method"), str):
|
|
240
262
|
methods.append(payload["method"])
|
|
241
|
-
except Exception:
|
|
263
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
242
264
|
if isinstance(metrics._RPC_REQUEST, _DummyMetric):
|
|
243
265
|
logger.debug("Error extracting methods", exc_info=True)
|
|
244
266
|
else:
|
|
245
267
|
logger.warning(
|
|
246
|
-
"Failed to extract methods for RPC request metrics
|
|
268
|
+
"Failed to extract methods for RPC request metrics "
|
|
269
|
+
"despite metrics being initialized",
|
|
247
270
|
exc_info=True,
|
|
248
271
|
)
|
|
249
272
|
|
|
@@ -266,7 +289,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
266
289
|
metrics._RPC_SERVICE_REQUEST_PAYLOAD_BYTES.labels(
|
|
267
290
|
self._network, self._layer, self._chain_id, self._uri
|
|
268
291
|
).observe(size)
|
|
269
|
-
except Exception:
|
|
292
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
270
293
|
if isinstance(metrics._RPC_SERVICE_REQUEST_PAYLOAD_BYTES, _DummyMetric):
|
|
271
294
|
logger.debug("Error observing request payload", exc_info=True)
|
|
272
295
|
else:
|
|
@@ -283,7 +306,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
283
306
|
metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES.labels(
|
|
284
307
|
self._network, self._layer, self._chain_id, self._uri
|
|
285
308
|
).observe(size)
|
|
286
|
-
except Exception:
|
|
309
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
287
310
|
if isinstance(metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES, _DummyMetric):
|
|
288
311
|
logger.debug("Error observing response payload", exc_info=True)
|
|
289
312
|
else:
|
|
@@ -298,7 +321,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
298
321
|
metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES.labels(
|
|
299
322
|
self._network, self._layer, self._chain_id, self._uri
|
|
300
323
|
).observe(int(response.content_length))
|
|
301
|
-
except Exception:
|
|
324
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
302
325
|
if isinstance(metrics._RPC_SERVICE_RESPONSE_PAYLOAD_BYTES, _DummyMetric):
|
|
303
326
|
logger.debug("Error observing response payload", exc_info=True)
|
|
304
327
|
else:
|
|
@@ -323,7 +346,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
323
346
|
http_success,
|
|
324
347
|
error_code,
|
|
325
348
|
).inc()
|
|
326
|
-
except Exception:
|
|
349
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
327
350
|
if isinstance(metrics._RPC_REQUEST, _DummyMetric):
|
|
328
351
|
logger.debug("Error recording RPC request", exc_info=True)
|
|
329
352
|
else:
|
|
@@ -360,9 +383,10 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
360
383
|
try:
|
|
361
384
|
response = func(*args, **kwargs)
|
|
362
385
|
code = str(response.status_code)
|
|
363
|
-
|
|
386
|
+
# Same meaning as the async path, where aiohttp raises on HTTP errors.
|
|
387
|
+
result = "success" if response.ok else "fail"
|
|
364
388
|
if self._layer == "el":
|
|
365
|
-
error_code = response
|
|
389
|
+
error_code = _rpc_error_code(response)
|
|
366
390
|
# Observe response payload size when available
|
|
367
391
|
self._observe_response_payload_sync(response)
|
|
368
392
|
return response
|
|
@@ -392,7 +416,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
392
416
|
metrics._HTTP_RPC_BATCH_SIZE.labels(
|
|
393
417
|
self._network, self._layer, self._chain_id, self._uri
|
|
394
418
|
).observe(int(batch_size_hint))
|
|
395
|
-
except Exception:
|
|
419
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
396
420
|
if isinstance(metrics._HTTP_RPC_BATCH_SIZE, _DummyMetric):
|
|
397
421
|
logger.debug("Error observing batch size", exc_info=True)
|
|
398
422
|
else:
|
|
@@ -460,7 +484,7 @@ class HTTPSessionManagerProxy(HTTPSessionManager):
|
|
|
460
484
|
metrics._HTTP_RPC_BATCH_SIZE.labels(
|
|
461
485
|
self._network, self._layer, self._chain_id, self._uri
|
|
462
486
|
).observe(int(batch_size_hint))
|
|
463
|
-
except Exception:
|
|
487
|
+
except Exception: # pylint: disable=broad-exception-caught
|
|
464
488
|
if isinstance(metrics._HTTP_RPC_BATCH_SIZE, _DummyMetric):
|
|
465
489
|
logger.debug("Error observing batch size", exc_info=True)
|
|
466
490
|
else:
|
|
@@ -26,6 +26,8 @@ _DEFAULT_CHAIN_ID_TO_NAME: Final = {
|
|
|
26
26
|
|
|
27
27
|
@dataclasses.dataclass
|
|
28
28
|
class MetricsConfig:
|
|
29
|
+
"""Settings for init_metrics(): metric name prefix and chain ID labels."""
|
|
30
|
+
|
|
29
31
|
namespace: str = ""
|
|
30
32
|
chain_id_to_name: dict[int, str] = dataclasses.field(
|
|
31
33
|
default_factory=_DEFAULT_CHAIN_ID_TO_NAME.copy,
|
|
@@ -35,18 +37,22 @@ class MetricsConfig:
|
|
|
35
37
|
class _DummyMetric:
|
|
36
38
|
"""No-op metric used before initialization or in tests."""
|
|
37
39
|
|
|
38
|
-
def labels(self, *
|
|
40
|
+
def labels(self, *_args: object, **_kwargs: object) -> "_DummyMetric":
|
|
41
|
+
"""Return self so that chained calls stay no-ops."""
|
|
39
42
|
return self
|
|
40
43
|
|
|
41
|
-
def inc(self, *
|
|
44
|
+
def inc(self, *_args: object, **_kwargs: object) -> None: # pragma: no cover
|
|
45
|
+
"""Do nothing."""
|
|
42
46
|
return None
|
|
43
47
|
|
|
44
|
-
def observe(self, *
|
|
48
|
+
def observe(self, *_args: object, **_kwargs: object) -> None: # pragma: no cover
|
|
49
|
+
"""Do nothing."""
|
|
45
50
|
return None
|
|
46
51
|
|
|
47
52
|
|
|
48
53
|
def _init_prometheus_metrics(registry=None) -> dict[str, Callable[..., Any]]:
|
|
49
54
|
# Import inside to avoid mandatory dependency at import time
|
|
55
|
+
# pylint: disable-next=import-outside-toplevel
|
|
50
56
|
from prometheus_client import REGISTRY, Counter, Histogram
|
|
51
57
|
|
|
52
58
|
reg = registry or REGISTRY
|
|
@@ -62,6 +68,8 @@ _metrics_initialized: bool = False
|
|
|
62
68
|
def warn_if_prometheus_not_initialized() -> None:
|
|
63
69
|
"""Warn if prometheus_client is installed but init_metrics() has not been called."""
|
|
64
70
|
try:
|
|
71
|
+
# Optional dependency: only probe whether it is installed.
|
|
72
|
+
# pylint: disable-next=import-outside-toplevel,unused-import
|
|
65
73
|
import prometheus_client # noqa: F401
|
|
66
74
|
except ImportError:
|
|
67
75
|
return
|
|
@@ -86,10 +94,20 @@ _RPC_SERVICE_RESPONSE_PAYLOAD_BYTES: Any = _DummyMetric()
|
|
|
86
94
|
def init_metrics(
|
|
87
95
|
metrics_config: MetricsConfig = MetricsConfig(), registry=None
|
|
88
96
|
) -> None:
|
|
97
|
+
"""Create the Prometheus metrics and replace the no-op placeholders.
|
|
98
|
+
|
|
99
|
+
Requires prometheus-client. Pass ``registry`` to register the metrics
|
|
100
|
+
somewhere other than the default prometheus_client registry.
|
|
101
|
+
"""
|
|
89
102
|
_prom = _init_prometheus_metrics(registry)
|
|
103
|
+
# The metrics are module-level singletons swapped in place, so that callers
|
|
104
|
+
# reading ``metrics.<NAME>`` at call time pick up the initialized objects.
|
|
105
|
+
# pylint: disable=global-statement
|
|
90
106
|
global _metrics_initialized, _HTTP_RPC_SERVICE_REQUESTS, _HTTP_RPC_BATCH_SIZE
|
|
91
|
-
global _RPC_REQUEST, _RPC_SERVICE_RESPONSE_SECONDS
|
|
107
|
+
global _RPC_REQUEST, _RPC_SERVICE_RESPONSE_SECONDS
|
|
108
|
+
global _RPC_SERVICE_REQUEST_PAYLOAD_BYTES, _RPC_SERVICE_RESPONSE_PAYLOAD_BYTES
|
|
92
109
|
global _CHAIN_ID_TO_NAME
|
|
110
|
+
# pylint: enable=global-statement
|
|
93
111
|
|
|
94
112
|
counter: Any = _prom["Counter"]
|
|
95
113
|
histogram: Any = _prom["Histogram"]
|
{web3_multi_provider-2.2.8 → web3_multi_provider-2.3.0}/web3_multi_provider/multi_http_provider.py
RENAMED
|
@@ -9,6 +9,7 @@ from web3.providers import JSONBaseProvider
|
|
|
9
9
|
from web3.providers.rpc.utils import ExceptionRetryConfiguration
|
|
10
10
|
from web3.types import RPCEndpoint, RPCResponse
|
|
11
11
|
|
|
12
|
+
from web3_multi_provider.cooldown import ProviderCooldown
|
|
12
13
|
from web3_multi_provider.exceptions import (
|
|
13
14
|
ChainIdMismatchError,
|
|
14
15
|
NoActiveProviderError,
|
|
@@ -58,6 +59,7 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
|
|
|
58
59
|
)
|
|
59
60
|
self._providers.append(provider)
|
|
60
61
|
|
|
62
|
+
self._provider_indexes = {id(p): i for i, p in enumerate(self._providers)}
|
|
61
63
|
super().__init__()
|
|
62
64
|
|
|
63
65
|
def _validate_chain_ids(self) -> None:
|
|
@@ -70,8 +72,9 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
|
|
|
70
72
|
chain_ids: dict[str, list[str]] = {}
|
|
71
73
|
|
|
72
74
|
for provider in self._providers:
|
|
73
|
-
|
|
74
|
-
|
|
75
|
+
# Set lazily by the provider proxy on its first request.
|
|
76
|
+
chain_id = getattr(provider, "_chain_id", "")
|
|
77
|
+
if chain_id:
|
|
75
78
|
endpoint_uri = str(provider.endpoint_uri)
|
|
76
79
|
|
|
77
80
|
if chain_id not in chain_ids:
|
|
@@ -84,7 +87,7 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
|
|
|
84
87
|
mismatches.append(f"Chain ID {chain_id}: {', '.join(endpoints)}")
|
|
85
88
|
|
|
86
89
|
raise ChainIdMismatchError(
|
|
87
|
-
|
|
90
|
+
"Providers have different chain IDs:\n" + "\n".join(mismatches)
|
|
88
91
|
)
|
|
89
92
|
|
|
90
93
|
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
|
|
@@ -97,44 +100,63 @@ class BaseMultiProvider(JSONBaseProvider, ABC):
|
|
|
97
100
|
self._validate_chain_ids()
|
|
98
101
|
return response
|
|
99
102
|
|
|
100
|
-
|
|
101
|
-
|
|
103
|
+
def _make_request_with_failover( # pylint: disable=inconsistent-return-statements
|
|
104
|
+
self,
|
|
102
105
|
method: RPCEndpoint,
|
|
103
106
|
params: Any,
|
|
104
107
|
provider_name: str,
|
|
105
108
|
provider_iter: Iterable[HTTPProvider],
|
|
106
109
|
) -> RPCResponse:
|
|
107
110
|
exceptions: list[Exception] = []
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
111
|
+
try:
|
|
112
|
+
for provider in provider_iter:
|
|
113
|
+
# None for an endpoint that a subclass yields from outside the configured
|
|
114
|
+
# list: it is still tried, but its cooldown is not tracked.
|
|
115
|
+
index = self._provider_indexes.get(id(provider))
|
|
116
|
+
try:
|
|
117
|
+
response = provider.make_request(method, params)
|
|
118
|
+
except Exception as error: # pylint: disable=broad-except
|
|
119
|
+
exceptions.append(error)
|
|
120
|
+
logger.warning(
|
|
121
|
+
{
|
|
122
|
+
"msg": "Provider not responding.",
|
|
123
|
+
"index": index,
|
|
124
|
+
"error": str(error).replace(
|
|
125
|
+
str(provider.endpoint_uri), "****"
|
|
126
|
+
),
|
|
127
|
+
}
|
|
128
|
+
)
|
|
129
|
+
if index is not None:
|
|
130
|
+
self._on_provider_failure(index)
|
|
131
|
+
else:
|
|
132
|
+
if index is not None:
|
|
133
|
+
self._on_provider_success(index)
|
|
134
|
+
sanitize_poa_response(method, response)
|
|
135
|
+
logger.debug(
|
|
136
|
+
{
|
|
137
|
+
"msg": f"Send request using {provider_name}.",
|
|
138
|
+
"method": method,
|
|
139
|
+
"params": str(params),
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
return response
|
|
143
|
+
|
|
144
|
+
msg = f"No active provider available in {provider_name}."
|
|
145
|
+
logger.debug({"msg": msg})
|
|
146
|
+
raise NoActiveProviderError.from_exceptions(msg, exceptions)
|
|
147
|
+
finally:
|
|
148
|
+
# Break explicitly a reference cycle, as socket.create_connection does
|
|
149
|
+
exceptions.clear()
|
|
150
|
+
|
|
151
|
+
def _on_provider_failure(self, index: int) -> None:
|
|
152
|
+
"""Called after the endpoint at `index` raised on a request."""
|
|
153
|
+
|
|
154
|
+
def _on_provider_success(self, index: int) -> None:
|
|
155
|
+
"""Called after the endpoint at `index` answered a request."""
|
|
135
156
|
|
|
136
157
|
@abstractmethod
|
|
137
158
|
def get_providers(self) -> Iterable[HTTPProvider]:
|
|
159
|
+
"""Return the providers to try for one request, in order."""
|
|
138
160
|
raise NotImplementedError
|
|
139
161
|
|
|
140
162
|
|
|
@@ -155,7 +177,23 @@ class MultiProvider(BaseMultiProvider):
|
|
|
155
177
|
|
|
156
178
|
|
|
157
179
|
class FallbackProvider(BaseMultiProvider):
|
|
158
|
-
"""
|
|
180
|
+
"""Fallback provider: tries each provider once, in order.
|
|
181
|
+
|
|
182
|
+
With `cooldown_seconds` > 0, a provider that failed is tried after the others until its
|
|
183
|
+
cooldown ends.
|
|
184
|
+
"""
|
|
185
|
+
|
|
186
|
+
def __init__(self, *args: Any, cooldown_seconds: float = 0, **kwargs: Any):
|
|
187
|
+
super().__init__(*args, **kwargs)
|
|
188
|
+
self._cooldown = ProviderCooldown(cooldown_seconds)
|
|
159
189
|
|
|
160
190
|
def get_providers(self) -> Iterable[HTTPProvider]:
|
|
161
|
-
|
|
191
|
+
if not self._cooldown.enabled:
|
|
192
|
+
return iter(self._providers)
|
|
193
|
+
return [self._providers[i] for i in self._cooldown.order(len(self._providers))]
|
|
194
|
+
|
|
195
|
+
def _on_provider_failure(self, index: int) -> None:
|
|
196
|
+
self._cooldown.mark_failed(index)
|
|
197
|
+
|
|
198
|
+
def _on_provider_success(self, index: int) -> None:
|
|
199
|
+
self._cooldown.mark_succeeded(index)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|