frequenz-client-base 0.7.0__tar.gz → 0.8.1__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 (22) hide show
  1. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/PKG-INFO +1 -1
  2. frequenz-client-base-0.8.1/RELEASE_NOTES.md +17 -0
  3. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/pyproject.toml +10 -10
  4. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/channel.py +5 -0
  5. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/client.py +37 -34
  6. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz_client_base.egg-info/PKG-INFO +1 -1
  7. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz_client_base.egg-info/requires.txt +10 -10
  8. frequenz-client-base-0.7.0/RELEASE_NOTES.md +0 -49
  9. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/LICENSE +0 -0
  10. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/MANIFEST.in +0 -0
  11. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/README.md +0 -0
  12. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/setup.cfg +0 -0
  13. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/__init__.py +0 -0
  14. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/conftest.py +0 -0
  15. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/conversion.py +0 -0
  16. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/exception.py +0 -0
  17. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/py.typed +0 -0
  18. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/retry.py +0 -0
  19. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz/client/base/streaming.py +0 -0
  20. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz_client_base.egg-info/SOURCES.txt +0 -0
  21. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
  22. {frequenz-client-base-0.7.0 → frequenz-client-base-0.8.1}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: frequenz-client-base
3
- Version: 0.7.0
3
+ Version: 0.8.1
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
@@ -0,0 +1,17 @@
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
+ <!-- Here goes notes on how to upgrade from previous versions, including deprecations and what they should be replaced with -->
10
+
11
+ ## New Features
12
+
13
+ <!-- Here goes the main new features and examples or instructions on how to use them -->
14
+
15
+ ## Bug Fixes
16
+
17
+ <!-- Here goes notable bug fixes that are worth a special mention or explanation -->
@@ -46,29 +46,29 @@ dev-flake8 = [
46
46
  "pydocstyle == 6.3.0",
47
47
  "frequenz-client-base",
48
48
  ]
49
- dev-formatting = ["black == 24.8.0", "isort == 5.13.2"]
49
+ dev-formatting = ["black == 24.10.0", "isort == 5.13.2"]
50
50
  dev-mkdocs = [
51
- "black == 24.8.0",
51
+ "black == 24.10.0",
52
52
  "Markdown==3.7",
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.2.0",
57
- "mkdocs-material == 9.5.39",
58
- "mkdocstrings[python] == 0.26.1",
59
- "mkdocstrings-python == 1.11.1",
56
+ "mkdocs-macros-plugin == 1.3.7",
57
+ "mkdocs-material == 9.5.43",
58
+ "mkdocstrings[python] == 0.26.2",
59
+ "mkdocstrings-python == 1.12.2",
60
60
  "frequenz-repo-config[lib] == 0.10.0",
61
61
  "frequenz-client-base",
62
62
  ]
63
63
  dev-mypy = [
64
- "mypy == 1.11.2",
64
+ "mypy == 1.13.0",
65
65
  "types-Markdown == 3.7.0.20240822",
66
- "types-protobuf == 5.28.0.20240924",
66
+ "types-protobuf == 5.28.3.20241030",
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
- dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.10.0"]
71
+ dev-noxfile = ["nox == 2024.10.9", "frequenz-repo-config[lib] == 0.10.0"]
72
72
  dev-pylint = [
73
73
  "pylint == 3.3.1",
74
74
  # For checking the noxfile, docs/ script, and tests
@@ -80,7 +80,7 @@ dev-pytest = [
80
80
  "pytest-mock == 3.14.0",
81
81
  "pytest-asyncio == 0.24.0",
82
82
  "async-solipsism == 0.7",
83
- "hypothesis == 6.112.2",
83
+ "hypothesis == 6.116.0",
84
84
  "frequenz-client-base",
85
85
  ]
86
86
  dev = [
@@ -101,6 +101,11 @@ def parse_grpc_uri(
101
101
  enabled. Will raise a `ValueError` if the file cannot be read.
102
102
  - `ssl_certificate_chain_path` (str): Path to the certificate chain file. Only
103
103
  valid if SSL is enabled. Will raise a `ValueError` if the file cannot be read.
104
+ - `keep_alive` (bool): Enable or disable HTTP2 keep-alive. Defaults to `True`.
105
+ - `keep_alive_interval_s` (float): The interval between HTTP2 pings in seconds.
106
+ Defaults to 60.
107
+ - `keep_alive_timeout_s` (float): The time to wait for a HTTP2 keep-alive response
108
+ in seconds
104
109
 
105
110
  Args:
106
111
  uri: The gRPC URI specifying the connection parameters.
@@ -6,21 +6,34 @@
6
6
  import abc
7
7
  import inspect
8
8
  from collections.abc import Awaitable, Callable
9
- from typing import Any, Self, TypeVar, overload
9
+ from typing import Any, Generic, 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."""
16
18
 
17
- class BaseApiClient(abc.ABC):
19
+
20
+ class BaseApiClient(abc.ABC, Generic[StubT]):
18
21
  """A base class for API clients.
19
22
 
20
23
  This class provides a common interface for API clients that communicate with a API
21
24
  server. It is designed to be subclassed by specific API clients that provide a more
22
25
  specific interface.
23
26
 
27
+ Note:
28
+ It is recommended to add a `stub` property to the subclass that returns the gRPC
29
+ stub to use but using the *async stub* type instead of the *sync stub* type.
30
+ This is because the gRPC library provides async stubs that have proper async
31
+ type hints, but they only live in `.pyi` files, so they can be used in a very
32
+ limited way (only as type hints). Because of this, a `type: ignore` comment is
33
+ needed to cast the sync stub to the async stub.
34
+
35
+ Please see the example below for a recommended way to implement this property.
36
+
24
37
  Some extra tools are provided to make it easier to write API clients:
25
38
 
26
39
  - [call_stub_method()][frequenz.client.base.client.call_stub_method] is a function
@@ -29,31 +42,12 @@ class BaseApiClient(abc.ABC):
29
42
  a class that helps sending messages from a gRPC stream to
30
43
  a [Broadcast][frequenz.channels.Broadcast] channel.
31
44
 
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
-
50
45
  Example:
51
46
  This example illustrates how to create a simple API client that connects to a
52
47
  gRPC server and calls a method on a stub.
53
48
 
54
49
  ```python
55
50
  from collections.abc import AsyncIterable
56
- from typing import cast
57
51
  from frequenz.client.base.client import BaseApiClient, call_stub_method
58
52
  from frequenz.client.base.streaming import GrpcStreamBroadcaster
59
53
  from frequenz.channels import Receiver
@@ -67,13 +61,13 @@ class BaseApiClient(abc.ABC):
67
61
  float_value: float
68
62
 
69
63
  class ExampleStub:
70
- async def example_method(
64
+ def example_method(
71
65
  self,
72
66
  request: ExampleRequest # pylint: disable=unused-argument
73
67
  ) -> ExampleResponse:
74
68
  ...
75
69
 
76
- def example_stream(self, _: ExampleRequest) -> AsyncIterable[ExampleResponse]:
70
+ def example_stream(self) -> AsyncIterable[ExampleResponse]:
77
71
  ...
78
72
 
79
73
  class ExampleAsyncStub:
@@ -83,18 +77,18 @@ class BaseApiClient(abc.ABC):
83
77
  ) -> ExampleResponse:
84
78
  ...
85
79
 
86
- def example_stream(self, _: ExampleRequest) -> AsyncIterable[ExampleResponse]:
80
+ def example_stream(self) -> AsyncIterable[ExampleResponse]:
87
81
  ...
88
82
  # End of generated classes
89
83
 
90
84
  class ExampleResponseWrapper:
91
- def __init__(self, response: ExampleResponse) -> None:
85
+ def __init__(self, response: ExampleResponse):
92
86
  self.transformed_value = f"{response.float_value:.2f}"
93
87
 
94
88
  # Change defaults as needed
95
89
  DEFAULT_CHANNEL_OPTIONS = ChannelOptions()
96
90
 
97
- class MyApiClient(BaseApiClient):
91
+ class MyApiClient(BaseApiClient[ExampleStub]):
98
92
  def __init__(
99
93
  self,
100
94
  server_url: str,
@@ -102,9 +96,8 @@ class BaseApiClient(abc.ABC):
102
96
  connect: bool = True,
103
97
  channel_defaults: ChannelOptions = DEFAULT_CHANNEL_OPTIONS,
104
98
  ) -> None:
105
- super().__init__(server_url, connect=connect, channel_defaults=channel_defaults)
106
- self._stub = cast(
107
- ExampleAsyncStub, ExampleStub(self.channel)
99
+ super().__init__(
100
+ server_url, ExampleStub, connect=connect, channel_defaults=channel_defaults
108
101
  )
109
102
  self._broadcaster = GrpcStreamBroadcaster(
110
103
  "stream",
@@ -114,9 +107,13 @@ class BaseApiClient(abc.ABC):
114
107
 
115
108
  @property
116
109
  def stub(self) -> ExampleAsyncStub:
117
- if self._channel is None:
110
+ if self.channel is None or self._stub is None:
118
111
  raise ClientNotConnected(server_url=self.server_url, operation="stub")
119
- return self._stub
112
+ # This type: ignore is needed because we need to cast the sync stub to
113
+ # the async stub, but we can't use cast because the async stub doesn't
114
+ # actually exists to the eyes of the interpreter, it only exists for the
115
+ # type-checker, so it can only be used for type hints.
116
+ return self._stub # type: ignore
120
117
 
121
118
  async def example_method(
122
119
  self, int_value: int, str_value: str
@@ -156,6 +153,7 @@ class BaseApiClient(abc.ABC):
156
153
  def __init__(
157
154
  self,
158
155
  server_url: str,
156
+ create_stub: Callable[[Channel], StubT],
159
157
  *,
160
158
  connect: bool = True,
161
159
  channel_defaults: ChannelOptions = ChannelOptions(),
@@ -164,6 +162,7 @@ class BaseApiClient(abc.ABC):
164
162
 
165
163
  Args:
166
164
  server_url: The URL of the server to connect to.
165
+ create_stub: A function that creates a stub from a channel.
167
166
  connect: Whether to connect to the server as soon as a client instance is
168
167
  created. If `False`, the client will not connect to the server until
169
168
  [connect()][frequenz.client.base.client.BaseApiClient.connect] is
@@ -172,8 +171,10 @@ class BaseApiClient(abc.ABC):
172
171
  the server URL.
173
172
  """
174
173
  self._server_url: str = server_url
174
+ self._create_stub: Callable[[Channel], StubT] = create_stub
175
175
  self._channel_defaults: ChannelOptions = channel_defaults
176
176
  self._channel: Channel | None = None
177
+ self._stub: StubT | None = None
177
178
  if connect:
178
179
  self.connect(server_url)
179
180
 
@@ -224,6 +225,7 @@ class BaseApiClient(abc.ABC):
224
225
  elif self.is_connected:
225
226
  return
226
227
  self._channel = parse_grpc_uri(self._server_url, self._channel_defaults)
228
+ self._stub = self._create_stub(self._channel)
227
229
 
228
230
  async def disconnect(self) -> None:
229
231
  """Disconnect from the server.
@@ -248,6 +250,7 @@ class BaseApiClient(abc.ABC):
248
250
  return None
249
251
  result = await self._channel.__aexit__(_exc_type, _exc_val, _exc_tb)
250
252
  self._channel = None
253
+ self._stub = None
251
254
  return result
252
255
 
253
256
 
@@ -260,7 +263,7 @@ TransformOutT_co = TypeVar("TransformOutT_co", covariant=True)
260
263
 
261
264
  @overload
262
265
  async def call_stub_method(
263
- client: BaseApiClient,
266
+ client: BaseApiClient[StubT],
264
267
  stub_method: Callable[[], Awaitable[StubOutT]],
265
268
  *,
266
269
  method_name: str | None = None,
@@ -270,7 +273,7 @@ async def call_stub_method(
270
273
 
271
274
  @overload
272
275
  async def call_stub_method(
273
- client: BaseApiClient,
276
+ client: BaseApiClient[StubT],
274
277
  stub_method: Callable[[], Awaitable[StubOutT]],
275
278
  *,
276
279
  method_name: str | None = None,
@@ -281,7 +284,7 @@ async def call_stub_method(
281
284
  # We need the `noqa: DOC503` because `pydoclint` can't figure out that
282
285
  # `ApiClientError.from_grpc_error()` returns a `GrpcError` instance.
283
286
  async def call_stub_method( # noqa: DOC503
284
- client: BaseApiClient,
287
+ client: BaseApiClient[StubT],
285
288
  stub_method: Callable[[], Awaitable[StubOutT]],
286
289
  *,
287
290
  method_name: str | None = None,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: frequenz-client-base
3
- Version: 0.7.0
3
+ Version: 0.8.1
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
@@ -15,31 +15,31 @@ pydocstyle==6.3.0
15
15
  frequenz-client-base
16
16
 
17
17
  [dev-formatting]
18
- black==24.8.0
18
+ black==24.10.0
19
19
  isort==5.13.2
20
20
 
21
21
  [dev-mkdocs]
22
- black==24.8.0
22
+ black==24.10.0
23
23
  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.2.0
28
- mkdocs-material==9.5.39
29
- mkdocstrings[python]==0.26.1
30
- mkdocstrings-python==1.11.1
27
+ mkdocs-macros-plugin==1.3.7
28
+ mkdocs-material==9.5.43
29
+ mkdocstrings[python]==0.26.2
30
+ mkdocstrings-python==1.12.2
31
31
  frequenz-repo-config[lib]==0.10.0
32
32
  frequenz-client-base
33
33
 
34
34
  [dev-mypy]
35
- mypy==1.11.2
35
+ mypy==1.13.0
36
36
  types-Markdown==3.7.0.20240822
37
- types-protobuf==5.28.0.20240924
37
+ types-protobuf==5.28.3.20241030
38
38
  grpc-stubs==1.53.0.5
39
39
  frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
40
40
 
41
41
  [dev-noxfile]
42
- nox==2024.4.15
42
+ nox==2024.10.9
43
43
  frequenz-repo-config[lib]==0.10.0
44
44
 
45
45
  [dev-pylint]
@@ -52,5 +52,5 @@ 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.112.2
55
+ hypothesis==6.116.0
56
56
  frequenz-client-base
@@ -1,49 +0,0 @@
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.