frequenz-client-base 0.10.0__tar.gz → 0.11.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.
Files changed (25) hide show
  1. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/PKG-INFO +11 -11
  2. frequenz_client_base-0.11.0/RELEASE_NOTES.md +42 -0
  3. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/pyproject.toml +12 -12
  4. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/authentication.py +6 -15
  5. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/channel.py +4 -31
  6. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/client.py +59 -5
  7. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/signing.py +6 -15
  8. frequenz_client_base-0.11.0/src/frequenz/client/base/streaming.py +333 -0
  9. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/PKG-INFO +11 -11
  10. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/requires.txt +10 -10
  11. frequenz_client_base-0.10.0/RELEASE_NOTES.md +0 -20
  12. frequenz_client_base-0.10.0/src/frequenz/client/base/streaming.py +0 -144
  13. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/LICENSE +0 -0
  14. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/MANIFEST.in +0 -0
  15. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/README.md +0 -0
  16. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/setup.cfg +0 -0
  17. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/__init__.py +0 -0
  18. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/conftest.py +0 -0
  19. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/conversion.py +0 -0
  20. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/exception.py +0 -0
  21. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/py.typed +0 -0
  22. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/retry.py +0 -0
  23. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/SOURCES.txt +0 -0
  24. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
  25. {frequenz_client_base-0.10.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: frequenz-client-base
3
- Version: 0.10.0
3
+ Version: 0.11.0
4
4
  Summary: Utilities for writing Frequenz API clients
5
5
  Author-email: Frequenz Energy-as-a-Service GmbH <floss@frequenz.com>
6
6
  License: MIT
@@ -41,30 +41,30 @@ Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
41
41
  Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
42
42
  Requires-Dist: mkdocs-literate-nav==0.6.2; extra == "dev-mkdocs"
43
43
  Requires-Dist: mkdocs-macros-plugin==1.3.7; extra == "dev-mkdocs"
44
- Requires-Dist: mkdocs-material==9.6.12; extra == "dev-mkdocs"
44
+ Requires-Dist: mkdocs-material==9.6.14; extra == "dev-mkdocs"
45
45
  Requires-Dist: mkdocstrings[python]==0.29.1; extra == "dev-mkdocs"
46
- Requires-Dist: mkdocstrings-python==1.16.10; extra == "dev-mkdocs"
47
- Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-mkdocs"
46
+ Requires-Dist: mkdocstrings-python==1.16.11; extra == "dev-mkdocs"
47
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-mkdocs"
48
48
  Requires-Dist: frequenz-client-base; extra == "dev-mkdocs"
49
49
  Provides-Extra: dev-mypy
50
- Requires-Dist: mypy==1.15.0; extra == "dev-mypy"
50
+ Requires-Dist: mypy==1.16.0; extra == "dev-mypy"
51
51
  Requires-Dist: types-Markdown==3.8.0.20250415; extra == "dev-mypy"
52
- Requires-Dist: types-protobuf==5.29.1.20250403; extra == "dev-mypy"
52
+ Requires-Dist: types-protobuf==6.30.2.20250516; extra == "dev-mypy"
53
53
  Requires-Dist: grpc-stubs==1.53.0.6; extra == "dev-mypy"
54
54
  Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-mypy"
55
55
  Provides-Extra: dev-noxfile
56
56
  Requires-Dist: nox==2025.5.1; extra == "dev-noxfile"
57
- Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-noxfile"
57
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-noxfile"
58
58
  Provides-Extra: dev-pylint
59
- Requires-Dist: pylint==3.3.6; extra == "dev-pylint"
59
+ Requires-Dist: pylint==3.3.7; extra == "dev-pylint"
60
60
  Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-pylint"
61
61
  Provides-Extra: dev-pytest
62
62
  Requires-Dist: pytest==8.3.5; extra == "dev-pytest"
63
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.3; extra == "dev-pytest"
64
- Requires-Dist: pytest-mock==3.14.0; extra == "dev-pytest"
63
+ Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.4; extra == "dev-pytest"
64
+ Requires-Dist: pytest-mock==3.14.1; extra == "dev-pytest"
65
65
  Requires-Dist: pytest-asyncio==0.26.0; extra == "dev-pytest"
66
66
  Requires-Dist: async-solipsism==0.7; extra == "dev-pytest"
67
- Requires-Dist: hypothesis==6.131.9; extra == "dev-pytest"
67
+ Requires-Dist: hypothesis==6.132.0; extra == "dev-pytest"
68
68
  Requires-Dist: frequenz-client-base; extra == "dev-pytest"
69
69
  Provides-Extra: dev
70
70
  Requires-Dist: frequenz-client-base[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]; extra == "dev"
@@ -0,0 +1,42 @@
1
+ # Frequenz Client Base Library Release Notes
2
+
3
+ ## Summary
4
+
5
+ <!-- Here goes a general summary of what this release is about -->
6
+
7
+ ## Upgrading
8
+
9
+ * Updated interface and behavior for HMAC
10
+
11
+ This introduces a new positional argument to `parse_grpc_uri`.
12
+ If calling this function manually and passing `ChannelOptions`, it is recommended
13
+ to switch to passing `ChannelOptions` via keyword argument.
14
+
15
+ * All parameters of the Streamers `new_receiver` method are now keyword-only arguments. This means that you must specify them by name when calling the method, e.g.:
16
+
17
+ ```python
18
+ recv = streamer.new_receiver(max_size=50, warn_on_overflow=True)
19
+ ```
20
+
21
+ ## New Features
22
+
23
+ * The streaming client, when using `new_receiver(include_events=True)`, will now return a receiver that yields stream notification events, such as `StreamStarted`, `StreamRetrying`, and `StreamFatalError`. This allows you to monitor the state of the stream:
24
+
25
+ ```python
26
+ recv = streamer.new_receiver(include_events=True)
27
+
28
+ for msg in recv:
29
+ match msg:
30
+ case StreamStarted():
31
+ print("Stream started")
32
+ case StreamRetrying(delay, error):
33
+ print(f"Stream stopped and will retry in {delay}: {error or 'closed'}")
34
+ case StreamFatalError(error):
35
+ print(f"Stream will stop because of a fatal error: {error}")
36
+ case int() as output:
37
+ print(f"Received message: {output}")
38
+ ```
39
+
40
+ ## Bug Fixes
41
+
42
+ <!-- Here goes notable bug fixes that are worth a special mention or explanation -->
@@ -3,9 +3,9 @@
3
3
 
4
4
  [build-system]
5
5
  requires = [
6
- "setuptools == 80.3.1",
6
+ "setuptools == 80.9.0",
7
7
  "setuptools_scm[toml] == 8.3.1",
8
- "frequenz-repo-config[lib] == 0.13.3",
8
+ "frequenz-repo-config[lib] == 0.13.4",
9
9
  ]
10
10
  build-backend = "setuptools.build_meta"
11
11
 
@@ -54,33 +54,33 @@ dev-mkdocs = [
54
54
  "mkdocs-gen-files == 0.5.0",
55
55
  "mkdocs-literate-nav == 0.6.2",
56
56
  "mkdocs-macros-plugin == 1.3.7",
57
- "mkdocs-material == 9.6.12",
57
+ "mkdocs-material == 9.6.14",
58
58
  "mkdocstrings[python] == 0.29.1",
59
- "mkdocstrings-python == 1.16.10",
60
- "frequenz-repo-config[lib] == 0.13.3",
59
+ "mkdocstrings-python == 1.16.11",
60
+ "frequenz-repo-config[lib] == 0.13.4",
61
61
  "frequenz-client-base",
62
62
  ]
63
63
  dev-mypy = [
64
- "mypy == 1.15.0",
64
+ "mypy == 1.16.0",
65
65
  "types-Markdown == 3.8.0.20250415",
66
- "types-protobuf == 5.29.1.20250403",
66
+ "types-protobuf == 6.30.2.20250516",
67
67
  "grpc-stubs == 1.53.0.6", # 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
- dev-noxfile = ["nox == 2025.5.1", "frequenz-repo-config[lib] == 0.13.3"]
71
+ dev-noxfile = ["nox == 2025.5.1", "frequenz-repo-config[lib] == 0.13.4"]
72
72
  dev-pylint = [
73
- "pylint == 3.3.6",
73
+ "pylint == 3.3.7",
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
78
  "pytest == 8.3.5",
79
- "frequenz-repo-config[extra-lint-examples] == 0.13.3",
80
- "pytest-mock == 3.14.0",
79
+ "frequenz-repo-config[extra-lint-examples] == 0.13.4",
80
+ "pytest-mock == 3.14.1",
81
81
  "pytest-asyncio == 0.26.0",
82
82
  "async-solipsism == 0.7",
83
- "hypothesis == 6.131.9",
83
+ "hypothesis == 6.132.0",
84
84
  "frequenz-client-base",
85
85
  ]
86
86
  dev = [
@@ -3,7 +3,6 @@
3
3
 
4
4
  """An Interceptor that adds the API key to a gRPC call."""
5
5
 
6
- import dataclasses
7
6
  from typing import AsyncIterable, Callable
8
7
 
9
8
  from grpc.aio import (
@@ -35,25 +34,17 @@ def _add_auth_header(
35
34
  client_call_details.metadata["key"] = key
36
35
 
37
36
 
38
- @dataclasses.dataclass(frozen=True)
39
- class AuthenticationOptions:
40
- """Options for authenticating to the endpoint."""
41
-
42
- api_key: str
43
- """The API key to authenticate with."""
44
-
45
-
46
37
  # There is an issue in gRPC which means the type can not be specified correctly here.
47
38
  class AuthenticationInterceptorUnaryUnary(UnaryUnaryClientInterceptor): # type: ignore[type-arg]
48
39
  """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
49
40
 
50
- def __init__(self, options: AuthenticationOptions):
41
+ def __init__(self, api_key: str):
51
42
  """Create an instance of the interceptor.
52
43
 
53
44
  Args:
54
- options: The options for authenticating to the endpoint.
45
+ api_key: The API key to send along for the request.
55
46
  """
56
- self._key = options.api_key
47
+ self._key = api_key
57
48
 
58
49
  async def intercept_unary_unary(
59
50
  self,
@@ -83,13 +74,13 @@ class AuthenticationInterceptorUnaryUnary(UnaryUnaryClientInterceptor): # type:
83
74
  class AuthenticationInterceptorUnaryStream(UnaryStreamClientInterceptor): # type: ignore[type-arg]
84
75
  """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
85
76
 
86
- def __init__(self, options: AuthenticationOptions):
77
+ def __init__(self, api_key: str):
87
78
  """Create an instance of the interceptor.
88
79
 
89
80
  Args:
90
- options: The options for authenticating to the endpoint.
81
+ api_key: The API key to send along for the request.
91
82
  """
92
- self._key = options.api_key
83
+ self._key = api_key
93
84
 
94
85
  async def intercept_unary_stream(
95
86
  self,
@@ -6,7 +6,7 @@
6
6
  import dataclasses
7
7
  import pathlib
8
8
  from datetime import timedelta
9
- from typing import assert_never
9
+ from typing import Sequence, assert_never
10
10
  from urllib.parse import parse_qs, urlparse
11
11
 
12
12
  from grpc import ssl_channel_credentials
@@ -17,17 +17,6 @@ from grpc.aio import (
17
17
  secure_channel,
18
18
  )
19
19
 
20
- from .authentication import (
21
- AuthenticationInterceptorUnaryStream,
22
- AuthenticationInterceptorUnaryUnary,
23
- AuthenticationOptions,
24
- )
25
- from .signing import (
26
- SigningInterceptorUnaryStream,
27
- SigningInterceptorUnaryUnary,
28
- SigningOptions,
29
- )
30
-
31
20
 
32
21
  @dataclasses.dataclass(frozen=True)
33
22
  class SslOptions:
@@ -85,15 +74,10 @@ class ChannelOptions:
85
74
  keep_alive: KeepAliveOptions = KeepAliveOptions()
86
75
  """HTTP2 keep-alive options for the channel."""
87
76
 
88
- sign: SigningOptions | None = None
89
- """Signing options for the channel."""
90
-
91
- auth: AuthenticationOptions | None = None
92
- """Authentication options for the channel."""
93
-
94
77
 
95
78
  def parse_grpc_uri(
96
79
  uri: str,
80
+ interceptors: Sequence[ClientInterceptor] = (),
97
81
  /,
98
82
  defaults: ChannelOptions = ChannelOptions(),
99
83
  ) -> Channel:
@@ -131,6 +115,8 @@ def parse_grpc_uri(
131
115
 
132
116
  Args:
133
117
  uri: The gRPC URI specifying the connection parameters.
118
+ interceptors: A list of interceptors to apply to the channel. They are applied
119
+ in the same order as they are passed in (see grpc interceptor docs for details)
134
120
  defaults: The default options use to create the channel when not specified in
135
121
  the URI.
136
122
 
@@ -199,19 +185,6 @@ def parse_grpc_uri(
199
185
  else None
200
186
  )
201
187
 
202
- interceptors: list[ClientInterceptor] = []
203
- if defaults.auth is not None:
204
- interceptors += [
205
- AuthenticationInterceptorUnaryUnary(options=defaults.auth), # type: ignore [list-item]
206
- AuthenticationInterceptorUnaryStream(options=defaults.auth), # type: ignore [list-item]
207
- ]
208
-
209
- if defaults.sign is not None:
210
- interceptors += [
211
- SigningInterceptorUnaryUnary(options=defaults.sign), # type: ignore [list-item]
212
- SigningInterceptorUnaryStream(options=defaults.sign), # type: ignore [list-item]
213
- ]
214
-
215
188
  ssl = defaults.ssl.enabled if options.ssl is None else options.ssl
216
189
  if ssl:
217
190
  return secure_channel(
@@ -6,15 +6,25 @@
6
6
  import abc
7
7
  import inspect
8
8
  from collections.abc import Awaitable, Callable
9
+ from types import EllipsisType
9
10
  from typing import Any, Generic, Self, TypeVar, overload
10
11
 
11
12
  from grpc.aio import (
12
13
  AioRpcError,
13
14
  Channel,
15
+ ClientInterceptor,
14
16
  )
15
17
 
18
+ from .authentication import (
19
+ AuthenticationInterceptorUnaryStream,
20
+ AuthenticationInterceptorUnaryUnary,
21
+ )
16
22
  from .channel import ChannelOptions, parse_grpc_uri
17
23
  from .exception import ApiClientError, ClientNotConnected
24
+ from .signing import (
25
+ SigningInterceptorUnaryStream,
26
+ SigningInterceptorUnaryUnary,
27
+ )
18
28
 
19
29
  StubT = TypeVar("StubT")
20
30
  """The type of the gRPC stub."""
@@ -153,13 +163,15 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
153
163
  instances.
154
164
  """
155
165
 
156
- def __init__(
166
+ def __init__( # pylint: disable=too-many-arguments
157
167
  self,
158
168
  server_url: str,
159
169
  create_stub: Callable[[Channel], StubT],
160
170
  *,
161
171
  connect: bool = True,
162
172
  channel_defaults: ChannelOptions = ChannelOptions(),
173
+ auth_key: str | None = None,
174
+ sign_secret: str | None = None,
163
175
  ) -> None:
164
176
  """Create an instance and connect to the server.
165
177
 
@@ -172,14 +184,21 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
172
184
  called.
173
185
  channel_defaults: The default options for the gRPC channel to create using
174
186
  the server URL.
187
+ auth_key: The API key to use when connecting to the service.
188
+ sign_secret: The secret to use when creating message HMAC.
189
+
175
190
  """
176
191
  self._server_url: str = server_url
177
192
  self._create_stub: Callable[[Channel], StubT] = create_stub
178
193
  self._channel_defaults: ChannelOptions = channel_defaults
194
+ self._auth_key = auth_key
195
+ self._sign_secret = sign_secret
179
196
  self._channel: Channel | None = None
180
197
  self._stub: StubT | None = None
181
198
  if connect:
182
- self.connect(server_url)
199
+ self.connect(
200
+ server_url=self._server_url, auth_key=auth_key, sign_secret=sign_secret
201
+ )
183
202
 
184
203
  @property
185
204
  def server_url(self) -> str:
@@ -212,7 +231,13 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
212
231
  """Whether the client is connected to the server."""
213
232
  return self._channel is not None
214
233
 
215
- def connect(self, server_url: str | None = None) -> None:
234
+ def connect(
235
+ self,
236
+ server_url: str | None = None,
237
+ *,
238
+ auth_key: str | None | EllipsisType = ...,
239
+ sign_secret: str | None | EllipsisType = ...,
240
+ ) -> None:
216
241
  """Connect to the server, possibly using a new URL.
217
242
 
218
243
  If the client is already connected and the URL is the same as the previous URL,
@@ -222,12 +247,41 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
222
247
  Args:
223
248
  server_url: The URL of the server to connect to. If not provided, the
224
249
  previously used URL is used.
250
+ auth_key: The API key to use when connecting to the service. If an Ellipsis
251
+ is provided, the previously used auth_key is used.
252
+ sign_secret: The secret to use when creating message HMAC. If an Ellipsis is
253
+ provided,
225
254
  """
255
+ reconnect = False
226
256
  if server_url is not None and server_url != self._server_url: # URL changed
227
257
  self._server_url = server_url
228
- elif self.is_connected:
258
+ reconnect = True
259
+ if auth_key is not ... and auth_key != self._auth_key:
260
+ self._auth_key = auth_key
261
+ reconnect = True
262
+ if sign_secret is not ... and sign_secret != self._sign_secret:
263
+ self._sign_secret = sign_secret
264
+ reconnect = True
265
+ if self.is_connected and not reconnect: # Desired connection already exists
229
266
  return
230
- self._channel = parse_grpc_uri(self._server_url, self._channel_defaults)
267
+
268
+ interceptors: list[ClientInterceptor] = []
269
+ if self._auth_key is not None:
270
+ interceptors += [
271
+ AuthenticationInterceptorUnaryUnary(self._auth_key), # type: ignore [list-item]
272
+ AuthenticationInterceptorUnaryStream(self._auth_key), # type: ignore [list-item]
273
+ ]
274
+ if self._sign_secret is not None:
275
+ interceptors += [
276
+ SigningInterceptorUnaryUnary(self._sign_secret), # type: ignore [list-item]
277
+ SigningInterceptorUnaryStream(self._sign_secret), # type: ignore [list-item]
278
+ ]
279
+
280
+ self._channel = parse_grpc_uri(
281
+ self._server_url,
282
+ interceptors,
283
+ defaults=self._channel_defaults,
284
+ )
231
285
  self._stub = self._create_stub(self._channel)
232
286
 
233
287
  async def disconnect(self) -> None:
@@ -3,7 +3,6 @@
3
3
 
4
4
  """An Interceptor that adds HMAC signature of the metadata fields to a gRPC call."""
5
5
 
6
- import dataclasses
7
6
  import hmac
8
7
  import logging
9
8
  import secrets
@@ -68,25 +67,17 @@ def _add_hmac(
68
67
  )
69
68
 
70
69
 
71
- @dataclasses.dataclass(frozen=True)
72
- class SigningOptions:
73
- """Options for message signing of messages."""
74
-
75
- secret: str
76
- """The secret to sign the message with."""
77
-
78
-
79
70
  # There is an issue in gRPC which means the type can not be specified correctly here.
80
71
  class SigningInterceptorUnaryUnary(UnaryUnaryClientInterceptor): # type: ignore[type-arg]
81
72
  """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
82
73
 
83
- def __init__(self, options: SigningOptions):
74
+ def __init__(self, secret: str):
84
75
  """Create an instance of the interceptor.
85
76
 
86
77
  Args:
87
- options: The options for signing the message.
78
+ secret: The secret used for signing the message.
88
79
  """
89
- self._secret = options.secret.encode()
80
+ self._secret = secret.encode()
90
81
 
91
82
  async def intercept_unary_unary(
92
83
  self,
@@ -121,13 +112,13 @@ class SigningInterceptorUnaryUnary(UnaryUnaryClientInterceptor): # type: ignore
121
112
  class SigningInterceptorUnaryStream(UnaryStreamClientInterceptor): # type: ignore[type-arg]
122
113
  """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
123
114
 
124
- def __init__(self, options: SigningOptions):
115
+ def __init__(self, secret: str):
125
116
  """Create an instance of the interceptor.
126
117
 
127
118
  Args:
128
- options: The options for signing the message.
119
+ secret: The secret used for signing the message.
129
120
  """
130
- self._secret = options.secret.encode()
121
+ self._secret = secret.encode()
131
122
 
132
123
  async def intercept_unary_stream(
133
124
  self,
@@ -0,0 +1,333 @@
1
+ # License: MIT
2
+ # Copyright © 2023 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Implementation of the grpc streaming helper."""
5
+
6
+ import asyncio
7
+ import logging
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from datetime import timedelta
11
+ from typing import AsyncIterable, Generic, Literal, TypeAlias, TypeVar, overload
12
+
13
+ import grpc.aio
14
+
15
+ from frequenz import channels
16
+
17
+ from . import retry
18
+
19
+ _logger = logging.getLogger(__name__)
20
+
21
+
22
+ InputT = TypeVar("InputT")
23
+ """The input type of the stream."""
24
+
25
+ OutputT = TypeVar("OutputT")
26
+ """The output type of the stream."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class StreamStarted:
31
+ """Event indicating that the stream has started."""
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class StreamRetrying:
36
+ """Event indicating that the stream has stopped."""
37
+
38
+ delay: timedelta
39
+ """Time to wait before retrying to start the stream again."""
40
+
41
+ exception: Exception | None = None
42
+ """The exception that caused the stream to stop, if any.
43
+
44
+ If `None`, the stream was stopped without an error, e.g. the server closed the
45
+ stream.
46
+ """
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class StreamFatalError:
51
+ """Event indicating that the stream has stopped due to an unrecoverable error."""
52
+
53
+ exception: Exception
54
+ """The exception that caused the stream to stop."""
55
+
56
+
57
+ StreamEvent: TypeAlias = StreamStarted | StreamRetrying | StreamFatalError
58
+ """Type alias for the events that can be sent over the stream."""
59
+
60
+
61
+ # pylint: disable-next=too-many-instance-attributes
62
+ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
63
+ """Helper class to handle grpc streaming methods.
64
+
65
+ This class handles the grpc streaming methods, automatically reconnecting
66
+ when the connection is lost, and broadcasting the received messages to
67
+ multiple receivers.
68
+
69
+ The stream is started when the class is initialized, and can be stopped
70
+ with the `stop` method. New receivers can be created with the
71
+ `new_receiver` method, which will receive the streamed messages.
72
+
73
+ If `include_events=True` is passed to `new_receiver`, the receiver will
74
+ also get state change messages (`StreamStarted`, `StreamRetrying`,
75
+ `StreamFatalError`) indicating the state of the stream.
76
+
77
+ Example:
78
+ ```python
79
+ from frequenz.client.base import (
80
+ GrpcStreamBroadcaster,
81
+ StreamFatalError,
82
+ StreamRetrying,
83
+ StreamStarted,
84
+ )
85
+ from frequenz.channels import Receiver # Assuming Receiver is available
86
+
87
+ # Dummy async iterable for demonstration
88
+ async def async_range(fail_after: int = -1) -> AsyncIterable[int]:
89
+ for i in range(10):
90
+ if fail_after != -1 and i >= fail_after:
91
+ raise grpc.aio.AioRpcError(
92
+ code=grpc.StatusCode.UNAVAILABLE,
93
+ initial_metadata=grpc.aio.Metadata(),
94
+ trailing_metadata=grpc.aio.Metadata(),
95
+ details="Simulated error"
96
+ )
97
+ yield i
98
+ await asyncio.sleep(0.1)
99
+
100
+ async def main():
101
+ streamer = GrpcStreamBroadcaster(
102
+ stream_name="example_stream",
103
+ stream_method=lambda: async_range(fail_after=3),
104
+ transform=lambda msg: msg * 2, # transform messages
105
+ retry_on_exhausted_stream=False,
106
+ )
107
+
108
+ # Receiver for data only
109
+ data_recv: Receiver[int] = streamer.new_receiver()
110
+
111
+ # Receiver for data and events
112
+ mixed_recv: Receiver[int | StreamEvent] = streamer.new_receiver(
113
+ include_events=True
114
+ )
115
+
116
+ async def consume_mixed():
117
+ async for msg in mixed_recv:
118
+ match msg:
119
+ case StreamStarted():
120
+ print("Mixed: Stream started")
121
+ case StreamRetrying(delay, error):
122
+ print(
123
+ "Mixed: Stream retrying in " +
124
+ f"{delay.total_seconds():.1f}s: {error or 'closed'}"
125
+ )
126
+ case StreamFatalError(error):
127
+ print(f"Mixed: Stream fatal error: {error}")
128
+ break # Stop consuming on fatal error
129
+ case int() as output:
130
+ print(f"Mixed: Received data: {output}")
131
+ if isinstance(msg, StreamFatalError):
132
+ break
133
+ print("Mixed: Consumer finished")
134
+
135
+
136
+ async def consume_data():
137
+ async for data_msg in data_recv:
138
+ print(f"DataOnly: Received data: {data_msg}")
139
+ print("DataOnly: Consumer finished")
140
+
141
+ mixed_consumer_task = asyncio.create_task(consume_mixed())
142
+ data_consumer_task = asyncio.create_task(consume_data())
143
+
144
+ await asyncio.sleep(5) # Let it run for a bit
145
+ print("Stopping streamer...")
146
+ await streamer.stop()
147
+ await mixed_consumer_task
148
+ await data_consumer_task
149
+ print("Streamer stopped.")
150
+
151
+ if __name__ == "__main__":
152
+ asyncio.run(main())
153
+ ```
154
+ """
155
+
156
+ def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
157
+ self,
158
+ stream_name: str,
159
+ stream_method: Callable[[], AsyncIterable[InputT]],
160
+ transform: Callable[[InputT], OutputT],
161
+ retry_strategy: retry.Strategy | None = None,
162
+ retry_on_exhausted_stream: bool = False,
163
+ ):
164
+ """Initialize the streaming helper.
165
+
166
+ Args:
167
+ stream_name: A name to identify the stream in the logs.
168
+ stream_method: A function that returns the grpc stream. This function is
169
+ called every time the connection is lost and we want to retry.
170
+ transform: A function to transform the input type to the output type.
171
+ retry_strategy: The retry strategy to use, when the connection is lost. Defaults
172
+ to retries every 3 seconds, with a jitter of 1 second, indefinitely.
173
+ retry_on_exhausted_stream: Whether to retry when the stream is exhausted, i.e.
174
+ when the server closes the stream. Defaults to False.
175
+ """
176
+ self._stream_name = stream_name
177
+ self._stream_method = stream_method
178
+ self._transform = transform
179
+ self._retry_strategy = (
180
+ retry.LinearBackoff() if retry_strategy is None else retry_strategy.copy()
181
+ )
182
+ self._retry_on_exhausted_stream = retry_on_exhausted_stream
183
+
184
+ # Channel for transformed data messages (OutputT)
185
+ self._data_channel: channels.Broadcast[OutputT] = channels.Broadcast(
186
+ name=f"GrpcStreamBroadcaster-{stream_name}-Data"
187
+ )
188
+
189
+ # Channel for stream events (StreamEvent), created on demand
190
+ self._event_channel: channels.Broadcast[StreamEvent] | None = None
191
+ self._event_sender: channels.Sender[StreamEvent] | None = None
192
+ self._task = asyncio.create_task(self._run())
193
+
194
+ @overload
195
+ def new_receiver(
196
+ self,
197
+ *,
198
+ maxsize: int = 50,
199
+ warn_on_overflow: bool = True,
200
+ include_events: Literal[False] = False,
201
+ ) -> channels.Receiver[OutputT]: ...
202
+
203
+ @overload
204
+ def new_receiver(
205
+ self,
206
+ *,
207
+ maxsize: int = 50,
208
+ warn_on_overflow: bool = True,
209
+ include_events: Literal[True],
210
+ ) -> channels.Receiver[StreamEvent | OutputT]: ...
211
+
212
+ def new_receiver(
213
+ self,
214
+ *,
215
+ maxsize: int = 50,
216
+ warn_on_overflow: bool = True,
217
+ include_events: bool = False,
218
+ ) -> channels.Receiver[OutputT] | channels.Receiver[StreamEvent | OutputT]:
219
+ """Create a new receiver for the stream.
220
+
221
+ Args:
222
+ maxsize: The maximum number of messages to buffer in underlying receivers.
223
+ warn_on_overflow: Whether to log a warning when a receiver's
224
+ buffer is full and a message is dropped.
225
+ include_events: Whether to include stream events (e.g. StreamStarted,
226
+ StreamRetrying, StreamFatalError) in the receiver. If `False` (default),
227
+ only transformed data messages will be received.
228
+
229
+ Returns:
230
+ A new receiver. If `include_events` is True, the receiver will yield
231
+ both `OutputT` and `StreamEvent` types. Otherwise, only `OutputT`.
232
+ """
233
+ if not include_events:
234
+ return self._data_channel.new_receiver(
235
+ limit=maxsize, warn_on_overflow=warn_on_overflow
236
+ )
237
+
238
+ if self._event_channel is None:
239
+ _logger.debug(
240
+ "%s: First request for events, creating event channel.",
241
+ self._stream_name,
242
+ )
243
+ self._event_channel = channels.Broadcast[StreamEvent](
244
+ name=f"GrpcStreamBroadcaster-{self._stream_name}-Events"
245
+ )
246
+ self._event_sender = self._event_channel.new_sender()
247
+
248
+ data_rx = self._data_channel.new_receiver(
249
+ limit=maxsize, warn_on_overflow=warn_on_overflow
250
+ )
251
+ event_rx = self._event_channel.new_receiver(
252
+ limit=maxsize, warn_on_overflow=warn_on_overflow
253
+ )
254
+ return channels.merge(data_rx, event_rx)
255
+
256
+ @property
257
+ def is_running(self) -> bool:
258
+ """Return whether the streaming helper is running.
259
+
260
+ Returns:
261
+ Whether the streaming helper is running.
262
+ """
263
+ return not self._task.done()
264
+
265
+ async def stop(self) -> None:
266
+ """Stop the streaming helper."""
267
+ _logger.info("%s: stopping the stream", self._stream_name)
268
+ if self._task.done():
269
+ return
270
+ self._task.cancel()
271
+ try:
272
+ await self._task
273
+ except asyncio.CancelledError:
274
+ pass
275
+ await self._data_channel.close()
276
+ if self._event_channel is not None:
277
+ await self._event_channel.close()
278
+
279
+ async def _run(self) -> None:
280
+ """Run the streaming helper."""
281
+ data_sender = self._data_channel.new_sender()
282
+
283
+ while True:
284
+ error: Exception | None = None
285
+ _logger.info("%s: starting to stream", self._stream_name)
286
+ try:
287
+ call = self._stream_method()
288
+
289
+ if self._event_sender:
290
+ await self._event_sender.send(StreamStarted())
291
+
292
+ async for msg in call:
293
+ await data_sender.send(self._transform(msg))
294
+ except grpc.aio.AioRpcError as err:
295
+ error = err
296
+
297
+ if error is None and not self._retry_on_exhausted_stream:
298
+ _logger.info(
299
+ "%s: connection closed, stream exhausted", self._stream_name
300
+ )
301
+ await self._data_channel.close()
302
+ if self._event_channel is not None:
303
+ await self._event_channel.close()
304
+ break
305
+
306
+ interval = self._retry_strategy.next_interval()
307
+ error_str = f"Error: {error}" if error else "Stream exhausted"
308
+ if interval is None:
309
+ _logger.error(
310
+ "%s: connection ended, retry limit exceeded (%s), giving up. %s.",
311
+ self._stream_name,
312
+ self._retry_strategy.get_progress(),
313
+ error_str,
314
+ )
315
+ if error is not None and self._event_sender:
316
+ await self._event_sender.send(StreamFatalError(error))
317
+ await self._data_channel.close()
318
+ if self._event_channel is not None:
319
+ await self._event_channel.close()
320
+ break
321
+ _logger.warning(
322
+ "%s: connection ended, retrying %s in %0.3f seconds. %s.",
323
+ self._stream_name,
324
+ self._retry_strategy.get_progress(),
325
+ interval,
326
+ error_str,
327
+ )
328
+
329
+ if self._event_sender:
330
+ await self._event_sender.send(
331
+ StreamRetrying(timedelta(seconds=interval), error)
332
+ )
333
+ await asyncio.sleep(interval)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: frequenz-client-base
3
- Version: 0.10.0
3
+ Version: 0.11.0
4
4
  Summary: Utilities for writing Frequenz API clients
5
5
  Author-email: Frequenz Energy-as-a-Service GmbH <floss@frequenz.com>
6
6
  License: MIT
@@ -41,30 +41,30 @@ Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
41
41
  Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
42
42
  Requires-Dist: mkdocs-literate-nav==0.6.2; extra == "dev-mkdocs"
43
43
  Requires-Dist: mkdocs-macros-plugin==1.3.7; extra == "dev-mkdocs"
44
- Requires-Dist: mkdocs-material==9.6.12; extra == "dev-mkdocs"
44
+ Requires-Dist: mkdocs-material==9.6.14; extra == "dev-mkdocs"
45
45
  Requires-Dist: mkdocstrings[python]==0.29.1; extra == "dev-mkdocs"
46
- Requires-Dist: mkdocstrings-python==1.16.10; extra == "dev-mkdocs"
47
- Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-mkdocs"
46
+ Requires-Dist: mkdocstrings-python==1.16.11; extra == "dev-mkdocs"
47
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-mkdocs"
48
48
  Requires-Dist: frequenz-client-base; extra == "dev-mkdocs"
49
49
  Provides-Extra: dev-mypy
50
- Requires-Dist: mypy==1.15.0; extra == "dev-mypy"
50
+ Requires-Dist: mypy==1.16.0; extra == "dev-mypy"
51
51
  Requires-Dist: types-Markdown==3.8.0.20250415; extra == "dev-mypy"
52
- Requires-Dist: types-protobuf==5.29.1.20250403; extra == "dev-mypy"
52
+ Requires-Dist: types-protobuf==6.30.2.20250516; extra == "dev-mypy"
53
53
  Requires-Dist: grpc-stubs==1.53.0.6; extra == "dev-mypy"
54
54
  Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-mypy"
55
55
  Provides-Extra: dev-noxfile
56
56
  Requires-Dist: nox==2025.5.1; extra == "dev-noxfile"
57
- Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-noxfile"
57
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-noxfile"
58
58
  Provides-Extra: dev-pylint
59
- Requires-Dist: pylint==3.3.6; extra == "dev-pylint"
59
+ Requires-Dist: pylint==3.3.7; extra == "dev-pylint"
60
60
  Requires-Dist: frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-pylint"
61
61
  Provides-Extra: dev-pytest
62
62
  Requires-Dist: pytest==8.3.5; extra == "dev-pytest"
63
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.3; extra == "dev-pytest"
64
- Requires-Dist: pytest-mock==3.14.0; extra == "dev-pytest"
63
+ Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.4; extra == "dev-pytest"
64
+ Requires-Dist: pytest-mock==3.14.1; extra == "dev-pytest"
65
65
  Requires-Dist: pytest-asyncio==0.26.0; extra == "dev-pytest"
66
66
  Requires-Dist: async-solipsism==0.7; extra == "dev-pytest"
67
- Requires-Dist: hypothesis==6.131.9; extra == "dev-pytest"
67
+ Requires-Dist: hypothesis==6.132.0; extra == "dev-pytest"
68
68
  Requires-Dist: frequenz-client-base; extra == "dev-pytest"
69
69
  Provides-Extra: dev
70
70
  Requires-Dist: frequenz-client-base[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]; extra == "dev"
@@ -25,32 +25,32 @@ mike==2.1.3
25
25
  mkdocs-gen-files==0.5.0
26
26
  mkdocs-literate-nav==0.6.2
27
27
  mkdocs-macros-plugin==1.3.7
28
- mkdocs-material==9.6.12
28
+ mkdocs-material==9.6.14
29
29
  mkdocstrings[python]==0.29.1
30
- mkdocstrings-python==1.16.10
31
- frequenz-repo-config[lib]==0.13.3
30
+ mkdocstrings-python==1.16.11
31
+ frequenz-repo-config[lib]==0.13.4
32
32
  frequenz-client-base
33
33
 
34
34
  [dev-mypy]
35
- mypy==1.15.0
35
+ mypy==1.16.0
36
36
  types-Markdown==3.8.0.20250415
37
- types-protobuf==5.29.1.20250403
37
+ types-protobuf==6.30.2.20250516
38
38
  grpc-stubs==1.53.0.6
39
39
  frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
40
40
 
41
41
  [dev-noxfile]
42
42
  nox==2025.5.1
43
- frequenz-repo-config[lib]==0.13.3
43
+ frequenz-repo-config[lib]==0.13.4
44
44
 
45
45
  [dev-pylint]
46
- pylint==3.3.6
46
+ pylint==3.3.7
47
47
  frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
48
48
 
49
49
  [dev-pytest]
50
50
  pytest==8.3.5
51
- frequenz-repo-config[extra-lint-examples]==0.13.3
52
- pytest-mock==3.14.0
51
+ frequenz-repo-config[extra-lint-examples]==0.13.4
52
+ pytest-mock==3.14.1
53
53
  pytest-asyncio==0.26.0
54
54
  async-solipsism==0.7
55
- hypothesis==6.131.9
55
+ hypothesis==6.132.0
56
56
  frequenz-client-base
@@ -1,20 +0,0 @@
1
- # Frequenz Client Base Library Release Notes
2
-
3
- ## Features
4
-
5
- * Added support for HMAC signing of `UnaryUnary` client messages
6
- * Added support for HMAC signing of `UnaryStream` client messages
7
-
8
- ## Upgrading
9
-
10
- * Updated `protobuf` dependency range: changed from `>=4.21.6, <6` to `>=5.29.2, <7`
11
- * The minimum dependency for `typing-extensions` is now `4.6.0` to be compatible with Python 3.12
12
- * The minimum dependency for `grpcio` is now `1.59` to be compatible with Python 3.12
13
-
14
- ## Bug Fixes
15
-
16
- * Fixed keys of signature to match what fuse-rs expects
17
- * `GrpcStreamBroadcaster` will now correctly try to restart on unexpected errors.
18
-
19
- Before if an unexpected exception was raised by the stream method, the
20
- internal task would silently finish and never start again.
@@ -1,144 +0,0 @@
1
- # License: MIT
2
- # Copyright © 2023 Frequenz Energy-as-a-Service GmbH
3
-
4
- """Implementation of the grpc streaming helper."""
5
-
6
- import asyncio
7
- import logging
8
- from collections.abc import Callable
9
- from typing import AsyncIterable, Generic, TypeVar
10
-
11
- import grpc.aio
12
-
13
- from frequenz import channels
14
-
15
- from . import retry
16
-
17
- _logger = logging.getLogger(__name__)
18
-
19
-
20
- InputT = TypeVar("InputT")
21
- """The input type of the stream."""
22
-
23
- OutputT = TypeVar("OutputT")
24
- """The output type of the stream."""
25
-
26
-
27
- class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
28
- """Helper class to handle grpc streaming methods."""
29
-
30
- def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments
31
- self,
32
- stream_name: str,
33
- stream_method: Callable[[], AsyncIterable[InputT]],
34
- transform: Callable[[InputT], OutputT],
35
- retry_strategy: retry.Strategy | None = None,
36
- retry_on_exhausted_stream: bool = False,
37
- ):
38
- """Initialize the streaming helper.
39
-
40
- Args:
41
- stream_name: A name to identify the stream in the logs.
42
- stream_method: A function that returns the grpc stream. This function is
43
- called everytime the connection is lost and we want to retry.
44
- transform: A function to transform the input type to the output type.
45
- retry_strategy: The retry strategy to use, when the connection is lost. Defaults
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.
49
- """
50
- self._stream_name = stream_name
51
- self._stream_method = stream_method
52
- self._transform = transform
53
- self._retry_strategy = (
54
- retry.LinearBackoff() if retry_strategy is None else retry_strategy.copy()
55
- )
56
- self._retry_on_exhausted_stream = retry_on_exhausted_stream
57
-
58
- self._channel: channels.Broadcast[OutputT] = channels.Broadcast(
59
- name=f"GrpcStreamBroadcaster-{stream_name}"
60
- )
61
- self._task = asyncio.create_task(self._run())
62
-
63
- def new_receiver(
64
- self, maxsize: int = 50, warn_on_overflow: bool = True
65
- ) -> channels.Receiver[OutputT]:
66
- """Create a new receiver for the stream.
67
-
68
- Args:
69
- maxsize: The maximum number of messages to buffer.
70
- warn_on_overflow: Whether to log a warning when the receiver's
71
- buffer is full and a message is dropped.
72
-
73
- Returns:
74
- A new receiver.
75
- """
76
- return self._channel.new_receiver(
77
- limit=maxsize, warn_on_overflow=warn_on_overflow
78
- )
79
-
80
- @property
81
- def is_running(self) -> bool:
82
- """Return whether the streaming helper is running.
83
-
84
- Returns:
85
- Whether the streaming helper is running.
86
- """
87
- return not self._task.done()
88
-
89
- async def stop(self) -> None:
90
- """Stop the streaming helper."""
91
- _logger.info("%s: stopping the stream", self._stream_name)
92
- if self._task.done():
93
- return
94
- self._task.cancel()
95
- try:
96
- await self._task
97
- except asyncio.CancelledError:
98
- pass
99
- await self._channel.close()
100
-
101
- async def _run(self) -> None:
102
- """Run the streaming helper."""
103
- sender = self._channel.new_sender()
104
-
105
- while True:
106
- error: Exception | None = None
107
- _logger.info("%s: starting to stream", self._stream_name)
108
- try:
109
- call = self._stream_method()
110
- async for msg in call:
111
- await sender.send(self._transform(msg))
112
- except grpc.aio.AioRpcError as err:
113
- error = err
114
- except Exception as err: # pylint: disable=broad-except
115
- _logger.exception(
116
- "%s: raise an unexpected exception",
117
- self._stream_name,
118
- )
119
- error = err
120
- if error is None and not self._retry_on_exhausted_stream:
121
- _logger.info(
122
- "%s: connection closed, stream exhausted", self._stream_name
123
- )
124
- await self._channel.close()
125
- break
126
- error_str = f"Error: {error}" if error else "Stream exhausted"
127
- interval = self._retry_strategy.next_interval()
128
- if interval is None:
129
- _logger.error(
130
- "%s: connection ended, retry limit exceeded (%s), giving up. %s.",
131
- self._stream_name,
132
- self._retry_strategy.get_progress(),
133
- error_str,
134
- )
135
- await self._channel.close()
136
- break
137
- _logger.warning(
138
- "%s: connection ended, retrying %s in %0.3f seconds. %s.",
139
- self._stream_name,
140
- self._retry_strategy.get_progress(),
141
- interval,
142
- error_str,
143
- )
144
- await asyncio.sleep(interval)