frequenz-client-base 0.6.1__tar.gz → 0.7.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.
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/PKG-INFO +1 -1
- frequenz-client-base-0.7.0/RELEASE_NOTES.md +49 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/pyproject.toml +9 -9
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/channel.py +111 -4
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/client.py +59 -37
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/retry.py +3 -2
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/streaming.py +23 -4
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz_client_base.egg-info/PKG-INFO +1 -1
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz_client_base.egg-info/requires.txt +9 -9
- frequenz-client-base-0.6.1/RELEASE_NOTES.md +0 -5
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/LICENSE +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/MANIFEST.in +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/README.md +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/setup.cfg +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/__init__.py +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/conftest.py +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/conversion.py +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/exception.py +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/py.typed +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz_client_base.egg-info/SOURCES.txt +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
- {frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Frequenz Client Base Library Release Notes
|
|
2
|
+
|
|
3
|
+
## Summary
|
|
4
|
+
|
|
5
|
+
This release improves the `BaseApiClient` interface and introduces HTTP2 keep-alive, among other changes.
|
|
6
|
+
|
|
7
|
+
## Upgrading
|
|
8
|
+
|
|
9
|
+
- `GrpcStreamBroadcaster` now takes a `AsyncIterable` instead of a `AsyncIterator` as the `stream_method`. This is to match the type of streaming methods generated by `grpc`, so no conversion to an `AsyncIterator` is needed.
|
|
10
|
+
|
|
11
|
+
- `GrpcStreamBroadcaster` no longer tries to reconnect when a server closes a connection. This behaviour can be overridden by passing `retry_on_exhausted_stream=True` when constructing `GrpcStreamBroadcaster` instances.
|
|
12
|
+
|
|
13
|
+
- gRPC URLs don't have a default port anymore, unless a default is set via `ChannelOptions`. If you want to set a default port for URLs, please pass custom `ChannelOptions` as `defaults` to `parse_grpc_uri` or as `channel_defaults` to `BaseApiClient`.
|
|
14
|
+
|
|
15
|
+
* The `ExponentialBackoff` and `LinearBackoff` classes now require keyword arguments for their constructor. This change was made to make the classes easier to use and to avoid confusion with the order of the arguments.
|
|
16
|
+
|
|
17
|
+
- HTTP2 keep-alive is now enabled by default, with an interval of 60 seconds between pings, and a 20 second timeout for responses from the service. These values are configurable and may be updated based on specific requirements.
|
|
18
|
+
|
|
19
|
+
* The `BaseApiClient` class is not generic anymore, and doesn't take a function to create the stub. Instead, subclasses should create their own stub right after calling the parent constructor. This enables subclasses to cast the stub to the generated `XxxAsyncStub` class, which have proper `async` type hints. To convert you client:
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
# Old
|
|
23
|
+
from my_service_pb2_grpc import MyServiceStub
|
|
24
|
+
class MyApiClient(BaseApiClient[MyServiceStub]):
|
|
25
|
+
def __init__(self, server_url: str, *, ...) -> None:
|
|
26
|
+
super().__init__(server_url, MyServiceStub, ...)
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
# New
|
|
30
|
+
from typing import cast
|
|
31
|
+
from my_service_pb2_grpc import MyServiceStub, MyServiceAsyncStub
|
|
32
|
+
class MyApiClient(BaseApiClient):
|
|
33
|
+
def __init__(self, server_url: str, *, ...) -> None:
|
|
34
|
+
super().__init__(server_url, connect=connect)
|
|
35
|
+
self._stub = cast(MyServiceAsyncStub, MyServiceStub(self.channel))
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def stub(self) -> MyServiceAsyncStub:
|
|
40
|
+
if self._channel is None:
|
|
41
|
+
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
42
|
+
return self._stub
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
After this, you should be able to remove a lot of `cast`s or `type: ignore` from the code when calling the stub `async` methods.
|
|
46
|
+
|
|
47
|
+
## New Features
|
|
48
|
+
|
|
49
|
+
- Added support for HTTP2 keep-alive.
|
|
@@ -42,7 +42,7 @@ dev-flake8 = [
|
|
|
42
42
|
"flake8 == 7.1.1",
|
|
43
43
|
"flake8-docstrings == 1.7.0",
|
|
44
44
|
"flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
|
|
45
|
-
"pydoclint == 0.5.
|
|
45
|
+
"pydoclint == 0.5.9",
|
|
46
46
|
"pydocstyle == 6.3.0",
|
|
47
47
|
"frequenz-client-base",
|
|
48
48
|
]
|
|
@@ -53,34 +53,34 @@ dev-mkdocs = [
|
|
|
53
53
|
"mike == 2.1.3",
|
|
54
54
|
"mkdocs-gen-files == 0.5.0",
|
|
55
55
|
"mkdocs-literate-nav == 0.6.1",
|
|
56
|
-
"mkdocs-macros-plugin == 1.0
|
|
57
|
-
"mkdocs-material == 9.5.
|
|
58
|
-
"mkdocstrings[python] == 0.
|
|
59
|
-
"mkdocstrings-python == 1.
|
|
56
|
+
"mkdocs-macros-plugin == 1.2.0",
|
|
57
|
+
"mkdocs-material == 9.5.39",
|
|
58
|
+
"mkdocstrings[python] == 0.26.1",
|
|
59
|
+
"mkdocstrings-python == 1.11.1",
|
|
60
60
|
"frequenz-repo-config[lib] == 0.10.0",
|
|
61
61
|
"frequenz-client-base",
|
|
62
62
|
]
|
|
63
63
|
dev-mypy = [
|
|
64
64
|
"mypy == 1.11.2",
|
|
65
65
|
"types-Markdown == 3.7.0.20240822",
|
|
66
|
-
"types-protobuf == 5.
|
|
66
|
+
"types-protobuf == 5.28.0.20240924",
|
|
67
67
|
"grpc-stubs == 1.53.0.5", # This dependency introduces breaking changes in patch releases
|
|
68
68
|
# For checking the noxfile, docs/ script, and tests
|
|
69
69
|
"frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]",
|
|
70
70
|
]
|
|
71
71
|
dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.10.0"]
|
|
72
72
|
dev-pylint = [
|
|
73
|
-
"pylint == 3.
|
|
73
|
+
"pylint == 3.3.1",
|
|
74
74
|
# For checking the noxfile, docs/ script, and tests
|
|
75
75
|
"frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]",
|
|
76
76
|
]
|
|
77
77
|
dev-pytest = [
|
|
78
|
-
"pytest == 8.3.
|
|
78
|
+
"pytest == 8.3.3",
|
|
79
79
|
"frequenz-repo-config[extra-lint-examples] == 0.10.0",
|
|
80
80
|
"pytest-mock == 3.14.0",
|
|
81
81
|
"pytest-asyncio == 0.24.0",
|
|
82
82
|
"async-solipsism == 0.7",
|
|
83
|
-
"hypothesis == 6.
|
|
83
|
+
"hypothesis == 6.112.2",
|
|
84
84
|
"frequenz-client-base",
|
|
85
85
|
]
|
|
86
86
|
dev = [
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/channel.py
RENAMED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import dataclasses
|
|
7
7
|
import pathlib
|
|
8
|
+
from datetime import timedelta
|
|
8
9
|
from typing import assert_never
|
|
9
10
|
from urllib.parse import parse_qs, urlparse
|
|
10
11
|
|
|
@@ -41,16 +42,33 @@ class SslOptions:
|
|
|
41
42
|
"""
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
@dataclasses.dataclass(frozen=True)
|
|
46
|
+
class KeepAliveOptions:
|
|
47
|
+
"""Options for HTTP2 keep-alive pings."""
|
|
48
|
+
|
|
49
|
+
enabled: bool = True
|
|
50
|
+
"""Whether HTTP2 keep-alive should be enabled."""
|
|
51
|
+
|
|
52
|
+
interval: timedelta = timedelta(seconds=60)
|
|
53
|
+
"""The interval between HTTP2 pings."""
|
|
54
|
+
|
|
55
|
+
timeout: timedelta = timedelta(seconds=20)
|
|
56
|
+
"""The time to wait for a HTTP2 keep-alive response."""
|
|
57
|
+
|
|
58
|
+
|
|
44
59
|
@dataclasses.dataclass(frozen=True)
|
|
45
60
|
class ChannelOptions:
|
|
46
61
|
"""Options for a gRPC channel."""
|
|
47
62
|
|
|
48
|
-
port: int =
|
|
63
|
+
port: int | None = None
|
|
49
64
|
"""The port number to connect to."""
|
|
50
65
|
|
|
51
66
|
ssl: SslOptions = SslOptions()
|
|
52
67
|
"""SSL options for the channel."""
|
|
53
68
|
|
|
69
|
+
keep_alive: KeepAliveOptions = KeepAliveOptions()
|
|
70
|
+
"""HTTP2 keep-alive options for the channel."""
|
|
71
|
+
|
|
54
72
|
|
|
55
73
|
def parse_grpc_uri(
|
|
56
74
|
uri: str,
|
|
@@ -68,7 +86,8 @@ def parse_grpc_uri(
|
|
|
68
86
|
A few things to consider about URI components:
|
|
69
87
|
|
|
70
88
|
- If any other components are present in the URI, a [`ValueError`][] is raised.
|
|
71
|
-
- If the port is omitted, the `default_port` is used
|
|
89
|
+
- If the port is omitted, the `default_port` is used unless it is `None`, in which
|
|
90
|
+
case a `ValueError` is raised
|
|
72
91
|
- If a query parameter is passed many times, the last value is used.
|
|
73
92
|
- Boolean query parameters can be specified with the following values
|
|
74
93
|
(case-insensitive): `true`, `1`, `on`, `false`, `0`, `off`.
|
|
@@ -110,10 +129,49 @@ def parse_grpc_uri(
|
|
|
110
129
|
|
|
111
130
|
options = _parse_query_params(uri, parsed_uri.query)
|
|
112
131
|
|
|
132
|
+
if parsed_uri.port is None and defaults.port is None:
|
|
133
|
+
raise ValueError(
|
|
134
|
+
f"The gRPC URI '{uri}' doesn't specify a port and there is no default."
|
|
135
|
+
)
|
|
136
|
+
|
|
113
137
|
target = (
|
|
114
138
|
parsed_uri.netloc if parsed_uri.port else f"{parsed_uri.netloc}:{defaults.port}"
|
|
115
139
|
)
|
|
116
140
|
|
|
141
|
+
keep_alive = (
|
|
142
|
+
defaults.keep_alive.enabled
|
|
143
|
+
if options.keep_alive is None
|
|
144
|
+
else options.keep_alive
|
|
145
|
+
)
|
|
146
|
+
channel_options = (
|
|
147
|
+
[
|
|
148
|
+
("grpc.http2.max_pings_without_data", 0),
|
|
149
|
+
("grpc.keepalive_permit_without_calls", 1),
|
|
150
|
+
(
|
|
151
|
+
"grpc.keepalive_time_ms",
|
|
152
|
+
(
|
|
153
|
+
(
|
|
154
|
+
defaults.keep_alive.interval
|
|
155
|
+
if options.keep_alive_interval is None
|
|
156
|
+
else options.keep_alive_interval
|
|
157
|
+
).total_seconds()
|
|
158
|
+
* 1000
|
|
159
|
+
),
|
|
160
|
+
),
|
|
161
|
+
(
|
|
162
|
+
"grpc.keepalive_timeout_ms",
|
|
163
|
+
(
|
|
164
|
+
defaults.keep_alive.timeout
|
|
165
|
+
if options.keep_alive_timeout is None
|
|
166
|
+
else options.keep_alive_timeout
|
|
167
|
+
).total_seconds()
|
|
168
|
+
* 1000,
|
|
169
|
+
),
|
|
170
|
+
]
|
|
171
|
+
if keep_alive
|
|
172
|
+
else None
|
|
173
|
+
)
|
|
174
|
+
|
|
117
175
|
ssl = defaults.ssl.enabled if options.ssl is None else options.ssl
|
|
118
176
|
if ssl:
|
|
119
177
|
return secure_channel(
|
|
@@ -135,8 +193,9 @@ def parse_grpc_uri(
|
|
|
135
193
|
defaults.ssl.certificate_chain,
|
|
136
194
|
),
|
|
137
195
|
),
|
|
196
|
+
channel_options,
|
|
138
197
|
)
|
|
139
|
-
return insecure_channel(target)
|
|
198
|
+
return insecure_channel(target, channel_options)
|
|
140
199
|
|
|
141
200
|
|
|
142
201
|
def _to_bool(value: str) -> bool:
|
|
@@ -154,6 +213,9 @@ class _QueryParams:
|
|
|
154
213
|
ssl_root_certificates_path: pathlib.Path | None
|
|
155
214
|
ssl_private_key_path: pathlib.Path | None
|
|
156
215
|
ssl_certificate_chain_path: pathlib.Path | None
|
|
216
|
+
keep_alive: bool | None
|
|
217
|
+
keep_alive_interval: timedelta | None
|
|
218
|
+
keep_alive_timeout: timedelta | None
|
|
157
219
|
|
|
158
220
|
|
|
159
221
|
def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
|
|
@@ -194,6 +256,26 @@ def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
|
|
|
194
256
|
f"Option(s) {', '.join(erros)} found in URI {uri!r}, but SSL is disabled",
|
|
195
257
|
)
|
|
196
258
|
|
|
259
|
+
keep_alive_option = options.pop("keep_alive", None)
|
|
260
|
+
keep_alive: bool | None = None
|
|
261
|
+
if keep_alive_option is not None:
|
|
262
|
+
keep_alive = _to_bool(keep_alive_option)
|
|
263
|
+
|
|
264
|
+
keep_alive_opts = {
|
|
265
|
+
k: options.pop(k, None)
|
|
266
|
+
for k in ("keep_alive_interval_s", "keep_alive_timeout_s")
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if keep_alive is False:
|
|
270
|
+
erros = []
|
|
271
|
+
for opt_name, opt in keep_alive_opts.items():
|
|
272
|
+
if opt is not None:
|
|
273
|
+
erros.append(opt_name)
|
|
274
|
+
if erros:
|
|
275
|
+
raise ValueError(
|
|
276
|
+
f"Option(s) {', '.join(erros)} found in URI {uri!r}, but keep_alive is disabled",
|
|
277
|
+
)
|
|
278
|
+
|
|
197
279
|
if options:
|
|
198
280
|
names = ", ".join(options)
|
|
199
281
|
raise ValueError(
|
|
@@ -203,7 +285,32 @@ def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
|
|
|
203
285
|
|
|
204
286
|
return _QueryParams(
|
|
205
287
|
ssl=ssl,
|
|
206
|
-
|
|
288
|
+
ssl_root_certificates_path=(
|
|
289
|
+
pathlib.Path(ssl_opts["ssl_root_certificates_path"])
|
|
290
|
+
if ssl_opts["ssl_root_certificates_path"] is not None
|
|
291
|
+
else None
|
|
292
|
+
),
|
|
293
|
+
ssl_private_key_path=(
|
|
294
|
+
pathlib.Path(ssl_opts["ssl_private_key_path"])
|
|
295
|
+
if ssl_opts["ssl_private_key_path"] is not None
|
|
296
|
+
else None
|
|
297
|
+
),
|
|
298
|
+
ssl_certificate_chain_path=(
|
|
299
|
+
pathlib.Path(ssl_opts["ssl_certificate_chain_path"])
|
|
300
|
+
if ssl_opts["ssl_certificate_chain_path"] is not None
|
|
301
|
+
else None
|
|
302
|
+
),
|
|
303
|
+
keep_alive=keep_alive,
|
|
304
|
+
keep_alive_interval=(
|
|
305
|
+
timedelta(seconds=float(keep_alive_opts["keep_alive_interval_s"]))
|
|
306
|
+
if keep_alive_opts["keep_alive_interval_s"] is not None
|
|
307
|
+
else None
|
|
308
|
+
),
|
|
309
|
+
keep_alive_timeout=(
|
|
310
|
+
timedelta(seconds=float(keep_alive_opts["keep_alive_timeout_s"]))
|
|
311
|
+
if keep_alive_opts["keep_alive_timeout_s"] is not None
|
|
312
|
+
else None
|
|
313
|
+
),
|
|
207
314
|
)
|
|
208
315
|
|
|
209
316
|
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/client.py
RENAMED
|
@@ -6,18 +6,15 @@
|
|
|
6
6
|
import abc
|
|
7
7
|
import inspect
|
|
8
8
|
from collections.abc import Awaitable, Callable
|
|
9
|
-
from typing import Any,
|
|
9
|
+
from typing import Any, Self, TypeVar, overload
|
|
10
10
|
|
|
11
11
|
from grpc.aio import AioRpcError, Channel
|
|
12
12
|
|
|
13
13
|
from .channel import ChannelOptions, parse_grpc_uri
|
|
14
14
|
from .exception import ApiClientError, ClientNotConnected
|
|
15
15
|
|
|
16
|
-
StubT = TypeVar("StubT")
|
|
17
|
-
"""The type of the gRPC stub."""
|
|
18
16
|
|
|
19
|
-
|
|
20
|
-
class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
17
|
+
class BaseApiClient(abc.ABC):
|
|
21
18
|
"""A base class for API clients.
|
|
22
19
|
|
|
23
20
|
This class provides a common interface for API clients that communicate with a API
|
|
@@ -32,12 +29,31 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
32
29
|
a class that helps sending messages from a gRPC stream to
|
|
33
30
|
a [Broadcast][frequenz.channels.Broadcast] channel.
|
|
34
31
|
|
|
32
|
+
Note:
|
|
33
|
+
Because grpcio doesn't provide proper type hints, a hack is needed to have
|
|
34
|
+
propepr async type hints for the stubs generated by protoc. When using
|
|
35
|
+
`mypy-protobuf`, a `XxxAsyncStub` class is generated for each `XxxStub` class
|
|
36
|
+
but in the `.pyi` file, so the type can be used to specify type hints, but
|
|
37
|
+
**not** in any other context, as the class doesn't really exist for the Python
|
|
38
|
+
interpreter. This include generics, and because of this, this class can't be
|
|
39
|
+
even parametrized using the async class, so the instantiation of the stub can't
|
|
40
|
+
be done in the base class.
|
|
41
|
+
|
|
42
|
+
Because of this, subclasses need to create the stubs by themselves, using the
|
|
43
|
+
real stub class and casting it to the `XxxAsyncStub` class, so `mypy` can use
|
|
44
|
+
the async version of the stubs.
|
|
45
|
+
|
|
46
|
+
It is recommended to define a `stub` property that returns the async stub, so
|
|
47
|
+
this hack is completely hidden from clients, even if they need to access the
|
|
48
|
+
stub for more advanced uses.
|
|
49
|
+
|
|
35
50
|
Example:
|
|
36
51
|
This example illustrates how to create a simple API client that connects to a
|
|
37
52
|
gRPC server and calls a method on a stub.
|
|
38
53
|
|
|
39
54
|
```python
|
|
40
55
|
from collections.abc import AsyncIterable
|
|
56
|
+
from typing import cast
|
|
41
57
|
from frequenz.client.base.client import BaseApiClient, call_stub_method
|
|
42
58
|
from frequenz.client.base.streaming import GrpcStreamBroadcaster
|
|
43
59
|
from frequenz.channels import Receiver
|
|
@@ -57,18 +73,38 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
57
73
|
) -> ExampleResponse:
|
|
58
74
|
...
|
|
59
75
|
|
|
60
|
-
def example_stream(self) -> AsyncIterable[ExampleResponse]:
|
|
76
|
+
def example_stream(self, _: ExampleRequest) -> AsyncIterable[ExampleResponse]:
|
|
77
|
+
...
|
|
78
|
+
|
|
79
|
+
class ExampleAsyncStub:
|
|
80
|
+
async def example_method(
|
|
81
|
+
self,
|
|
82
|
+
request: ExampleRequest # pylint: disable=unused-argument
|
|
83
|
+
) -> ExampleResponse:
|
|
84
|
+
...
|
|
85
|
+
|
|
86
|
+
def example_stream(self, _: ExampleRequest) -> AsyncIterable[ExampleResponse]:
|
|
61
87
|
...
|
|
62
88
|
# End of generated classes
|
|
63
89
|
|
|
64
90
|
class ExampleResponseWrapper:
|
|
65
|
-
def __init__(self, response: ExampleResponse):
|
|
91
|
+
def __init__(self, response: ExampleResponse) -> None:
|
|
66
92
|
self.transformed_value = f"{response.float_value:.2f}"
|
|
67
93
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
94
|
+
# Change defaults as needed
|
|
95
|
+
DEFAULT_CHANNEL_OPTIONS = ChannelOptions()
|
|
96
|
+
|
|
97
|
+
class MyApiClient(BaseApiClient):
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
server_url: str,
|
|
101
|
+
*,
|
|
102
|
+
connect: bool = True,
|
|
103
|
+
channel_defaults: ChannelOptions = DEFAULT_CHANNEL_OPTIONS,
|
|
104
|
+
) -> None:
|
|
105
|
+
super().__init__(server_url, connect=connect, channel_defaults=channel_defaults)
|
|
106
|
+
self._stub = cast(
|
|
107
|
+
ExampleAsyncStub, ExampleStub(self.channel)
|
|
72
108
|
)
|
|
73
109
|
self._broadcaster = GrpcStreamBroadcaster(
|
|
74
110
|
"stream",
|
|
@@ -76,6 +112,12 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
76
112
|
ExampleResponseWrapper,
|
|
77
113
|
)
|
|
78
114
|
|
|
115
|
+
@property
|
|
116
|
+
def stub(self) -> ExampleAsyncStub:
|
|
117
|
+
if self._channel is None:
|
|
118
|
+
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
119
|
+
return self._stub
|
|
120
|
+
|
|
79
121
|
async def example_method(
|
|
80
122
|
self, int_value: int, str_value: str
|
|
81
123
|
) -> ExampleResponseWrapper:
|
|
@@ -114,7 +156,6 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
114
156
|
def __init__(
|
|
115
157
|
self,
|
|
116
158
|
server_url: str,
|
|
117
|
-
create_stub: Callable[[Channel], StubT],
|
|
118
159
|
*,
|
|
119
160
|
connect: bool = True,
|
|
120
161
|
channel_defaults: ChannelOptions = ChannelOptions(),
|
|
@@ -123,7 +164,6 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
123
164
|
|
|
124
165
|
Args:
|
|
125
166
|
server_url: The URL of the server to connect to.
|
|
126
|
-
create_stub: A function that creates a stub from a channel.
|
|
127
167
|
connect: Whether to connect to the server as soon as a client instance is
|
|
128
168
|
created. If `False`, the client will not connect to the server until
|
|
129
169
|
[connect()][frequenz.client.base.client.BaseApiClient.connect] is
|
|
@@ -132,10 +172,8 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
132
172
|
the server URL.
|
|
133
173
|
"""
|
|
134
174
|
self._server_url: str = server_url
|
|
135
|
-
self._create_stub: Callable[[Channel], StubT] = create_stub
|
|
136
175
|
self._channel_defaults: ChannelOptions = channel_defaults
|
|
137
176
|
self._channel: Channel | None = None
|
|
138
|
-
self._stub: StubT | None = None
|
|
139
177
|
if connect:
|
|
140
178
|
self.connect(server_url)
|
|
141
179
|
|
|
@@ -165,22 +203,6 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
165
203
|
"""The default options for the gRPC channel."""
|
|
166
204
|
return self._channel_defaults
|
|
167
205
|
|
|
168
|
-
@property
|
|
169
|
-
def stub(self) -> StubT:
|
|
170
|
-
"""The underlying gRPC stub.
|
|
171
|
-
|
|
172
|
-
Warning:
|
|
173
|
-
This stub is provided as a last resort for advanced users. It is not
|
|
174
|
-
recommended to use this property directly unless you know what you are
|
|
175
|
-
doing and you don't care about being tied to a specific gRPC library.
|
|
176
|
-
|
|
177
|
-
Raises:
|
|
178
|
-
ClientNotConnected: If the client is not connected to the server.
|
|
179
|
-
"""
|
|
180
|
-
if self._stub is None:
|
|
181
|
-
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
182
|
-
return self._stub
|
|
183
|
-
|
|
184
206
|
@property
|
|
185
207
|
def is_connected(self) -> bool:
|
|
186
208
|
"""Whether the client is connected to the server."""
|
|
@@ -202,7 +224,6 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
202
224
|
elif self.is_connected:
|
|
203
225
|
return
|
|
204
226
|
self._channel = parse_grpc_uri(self._server_url, self._channel_defaults)
|
|
205
|
-
self._stub = self._create_stub(self._channel)
|
|
206
227
|
|
|
207
228
|
async def disconnect(self) -> None:
|
|
208
229
|
"""Disconnect from the server.
|
|
@@ -227,7 +248,6 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
|
227
248
|
return None
|
|
228
249
|
result = await self._channel.__aexit__(_exc_type, _exc_val, _exc_tb)
|
|
229
250
|
self._channel = None
|
|
230
|
-
self._stub = None
|
|
231
251
|
return result
|
|
232
252
|
|
|
233
253
|
|
|
@@ -240,7 +260,7 @@ TransformOutT_co = TypeVar("TransformOutT_co", covariant=True)
|
|
|
240
260
|
|
|
241
261
|
@overload
|
|
242
262
|
async def call_stub_method(
|
|
243
|
-
client: BaseApiClient
|
|
263
|
+
client: BaseApiClient,
|
|
244
264
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
245
265
|
*,
|
|
246
266
|
method_name: str | None = None,
|
|
@@ -250,7 +270,7 @@ async def call_stub_method(
|
|
|
250
270
|
|
|
251
271
|
@overload
|
|
252
272
|
async def call_stub_method(
|
|
253
|
-
client: BaseApiClient
|
|
273
|
+
client: BaseApiClient,
|
|
254
274
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
255
275
|
*,
|
|
256
276
|
method_name: str | None = None,
|
|
@@ -258,8 +278,10 @@ async def call_stub_method(
|
|
|
258
278
|
) -> StubOutT: ...
|
|
259
279
|
|
|
260
280
|
|
|
261
|
-
|
|
262
|
-
|
|
281
|
+
# We need the `noqa: DOC503` because `pydoclint` can't figure out that
|
|
282
|
+
# `ApiClientError.from_grpc_error()` returns a `GrpcError` instance.
|
|
283
|
+
async def call_stub_method( # noqa: DOC503
|
|
284
|
+
client: BaseApiClient,
|
|
263
285
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
264
286
|
*,
|
|
265
287
|
method_name: str | None = None,
|
|
@@ -79,6 +79,7 @@ class LinearBackoff(Strategy):
|
|
|
79
79
|
|
|
80
80
|
def __init__(
|
|
81
81
|
self,
|
|
82
|
+
*,
|
|
82
83
|
interval: float = DEFAULT_RETRY_INTERVAL,
|
|
83
84
|
jitter: float = DEFAULT_RETRY_JITTER,
|
|
84
85
|
limit: int | None = None,
|
|
@@ -124,9 +125,9 @@ class ExponentialBackoff(Strategy):
|
|
|
124
125
|
DEFAULT_MULTIPLIER = 2.0
|
|
125
126
|
"""Default multiplier for exponential increment."""
|
|
126
127
|
|
|
127
|
-
# pylint: disable=too-many-arguments
|
|
128
|
-
def __init__(
|
|
128
|
+
def __init__( # pylint: disable=too-many-arguments
|
|
129
129
|
self,
|
|
130
|
+
*,
|
|
130
131
|
initial_interval: float = DEFAULT_INTERVAL,
|
|
131
132
|
max_interval: float = DEFAULT_MAX_INTERVAL,
|
|
132
133
|
multiplier: float = DEFAULT_MULTIPLIER,
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/streaming.py
RENAMED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
|
|
6
6
|
import asyncio
|
|
7
7
|
import logging
|
|
8
|
-
from collections.abc import
|
|
9
|
-
from typing import Generic, TypeVar
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import AsyncIterable, Generic, TypeVar
|
|
10
10
|
|
|
11
11
|
import grpc.aio
|
|
12
12
|
|
|
@@ -27,12 +27,13 @@ OutputT = TypeVar("OutputT")
|
|
|
27
27
|
class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
28
28
|
"""Helper class to handle grpc streaming methods."""
|
|
29
29
|
|
|
30
|
-
def __init__(
|
|
30
|
+
def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
|
|
31
31
|
self,
|
|
32
32
|
stream_name: str,
|
|
33
|
-
stream_method: Callable[[],
|
|
33
|
+
stream_method: Callable[[], AsyncIterable[InputT]],
|
|
34
34
|
transform: Callable[[InputT], OutputT],
|
|
35
35
|
retry_strategy: retry.Strategy | None = None,
|
|
36
|
+
retry_on_exhausted_stream: bool = False,
|
|
36
37
|
):
|
|
37
38
|
"""Initialize the streaming helper.
|
|
38
39
|
|
|
@@ -43,6 +44,8 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
|
43
44
|
transform: A function to transform the input type to the output type.
|
|
44
45
|
retry_strategy: The retry strategy to use, when the connection is lost. Defaults
|
|
45
46
|
to retries every 3 seconds, with a jitter of 1 second, indefinitely.
|
|
47
|
+
retry_on_exhausted_stream: Whether to retry when the stream is exhausted, i.e.
|
|
48
|
+
when the server closes the stream. Defaults to False.
|
|
46
49
|
"""
|
|
47
50
|
self._stream_name = stream_name
|
|
48
51
|
self._stream_method = stream_method
|
|
@@ -50,6 +53,7 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
|
50
53
|
self._retry_strategy = (
|
|
51
54
|
retry.LinearBackoff() if retry_strategy is None else retry_strategy.copy()
|
|
52
55
|
)
|
|
56
|
+
self._retry_on_exhausted_stream = retry_on_exhausted_stream
|
|
53
57
|
|
|
54
58
|
self._channel: channels.Broadcast[OutputT] = channels.Broadcast(
|
|
55
59
|
name=f"GrpcStreamBroadcaster-{stream_name}"
|
|
@@ -67,6 +71,15 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
|
67
71
|
"""
|
|
68
72
|
return self._channel.new_receiver(limit=maxsize)
|
|
69
73
|
|
|
74
|
+
@property
|
|
75
|
+
def is_running(self) -> bool:
|
|
76
|
+
"""Return whether the streaming helper is running.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Whether the streaming helper is running.
|
|
80
|
+
"""
|
|
81
|
+
return not self._task.done()
|
|
82
|
+
|
|
70
83
|
async def stop(self) -> None:
|
|
71
84
|
"""Stop the streaming helper."""
|
|
72
85
|
if self._task.done():
|
|
@@ -91,6 +104,12 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
|
91
104
|
await sender.send(self._transform(msg))
|
|
92
105
|
except grpc.aio.AioRpcError as err:
|
|
93
106
|
error = err
|
|
107
|
+
if error is None and not self._retry_on_exhausted_stream:
|
|
108
|
+
_logger.info(
|
|
109
|
+
"%s: connection closed, stream exhausted", self._stream_name
|
|
110
|
+
)
|
|
111
|
+
await self._channel.close()
|
|
112
|
+
break
|
|
94
113
|
error_str = f"Error: {error}" if error else "Stream exhausted"
|
|
95
114
|
interval = self._retry_strategy.next_interval()
|
|
96
115
|
if interval is None:
|
|
@@ -10,7 +10,7 @@ frequenz-client-base[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,d
|
|
|
10
10
|
flake8==7.1.1
|
|
11
11
|
flake8-docstrings==1.7.0
|
|
12
12
|
flake8-pyproject==1.2.3
|
|
13
|
-
pydoclint==0.5.
|
|
13
|
+
pydoclint==0.5.9
|
|
14
14
|
pydocstyle==6.3.0
|
|
15
15
|
frequenz-client-base
|
|
16
16
|
|
|
@@ -24,17 +24,17 @@ Markdown==3.7
|
|
|
24
24
|
mike==2.1.3
|
|
25
25
|
mkdocs-gen-files==0.5.0
|
|
26
26
|
mkdocs-literate-nav==0.6.1
|
|
27
|
-
mkdocs-macros-plugin==1.0
|
|
28
|
-
mkdocs-material==9.5.
|
|
29
|
-
mkdocstrings[python]==0.
|
|
30
|
-
mkdocstrings-python==1.
|
|
27
|
+
mkdocs-macros-plugin==1.2.0
|
|
28
|
+
mkdocs-material==9.5.39
|
|
29
|
+
mkdocstrings[python]==0.26.1
|
|
30
|
+
mkdocstrings-python==1.11.1
|
|
31
31
|
frequenz-repo-config[lib]==0.10.0
|
|
32
32
|
frequenz-client-base
|
|
33
33
|
|
|
34
34
|
[dev-mypy]
|
|
35
35
|
mypy==1.11.2
|
|
36
36
|
types-Markdown==3.7.0.20240822
|
|
37
|
-
types-protobuf==5.
|
|
37
|
+
types-protobuf==5.28.0.20240924
|
|
38
38
|
grpc-stubs==1.53.0.5
|
|
39
39
|
frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
|
|
40
40
|
|
|
@@ -43,14 +43,14 @@ nox==2024.4.15
|
|
|
43
43
|
frequenz-repo-config[lib]==0.10.0
|
|
44
44
|
|
|
45
45
|
[dev-pylint]
|
|
46
|
-
pylint==3.
|
|
46
|
+
pylint==3.3.1
|
|
47
47
|
frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
|
|
48
48
|
|
|
49
49
|
[dev-pytest]
|
|
50
|
-
pytest==8.3.
|
|
50
|
+
pytest==8.3.3
|
|
51
51
|
frequenz-repo-config[extra-lint-examples]==0.10.0
|
|
52
52
|
pytest-mock==3.14.0
|
|
53
53
|
pytest-asyncio==0.24.0
|
|
54
54
|
async-solipsism==0.7
|
|
55
|
-
hypothesis==6.
|
|
55
|
+
hypothesis==6.112.2
|
|
56
56
|
frequenz-client-base
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/__init__.py
RENAMED
|
File without changes
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/conftest.py
RENAMED
|
File without changes
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/conversion.py
RENAMED
|
File without changes
|
{frequenz-client-base-0.6.1 → frequenz-client-base-0.7.0}/src/frequenz/client/base/exception.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|