frequenz-client-base 0.9.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.9.0/src/frequenz_client_base.egg-info → frequenz_client_base-0.11.0}/PKG-INFO +27 -26
  2. frequenz_client_base-0.11.0/RELEASE_NOTES.md +42 -0
  3. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/pyproject.toml +28 -27
  4. frequenz_client_base-0.11.0/src/frequenz/client/base/authentication.py +107 -0
  5. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/channel.py +20 -11
  6. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/client.py +63 -6
  7. frequenz_client_base-0.11.0/src/frequenz/client/base/signing.py +149 -0
  8. frequenz_client_base-0.11.0/src/frequenz/client/base/streaming.py +333 -0
  9. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0/src/frequenz_client_base.egg-info}/PKG-INFO +27 -26
  10. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/SOURCES.txt +2 -0
  11. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/requires.txt +24 -24
  12. frequenz_client_base-0.9.0/RELEASE_NOTES.md +0 -6
  13. frequenz_client_base-0.9.0/src/frequenz/client/base/streaming.py +0 -137
  14. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/LICENSE +0 -0
  15. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/MANIFEST.in +0 -0
  16. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/README.md +0 -0
  17. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/setup.cfg +0 -0
  18. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/__init__.py +0 -0
  19. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/conftest.py +0 -0
  20. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/conversion.py +0 -0
  21. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/exception.py +0 -0
  22. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/py.typed +0 -0
  23. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz/client/base/retry.py +0 -0
  24. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
  25. {frequenz_client_base-0.9.0 → frequenz_client_base-0.11.0}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: frequenz-client-base
3
- Version: 0.9.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
@@ -21,53 +21,54 @@ Requires-Python: <4,>=3.11
21
21
  Description-Content-Type: text/markdown
22
22
  License-File: LICENSE
23
23
  Requires-Dist: frequenz-channels<2,>=1.6.1
24
- Requires-Dist: grpcio<2,>=1.54.2
25
- Requires-Dist: protobuf<6,>=4.21.6
26
- Requires-Dist: typing-extensions<5,>=4.5.0
24
+ Requires-Dist: grpcio<2,>=1.59
25
+ Requires-Dist: protobuf<7,>=5.29.2
26
+ Requires-Dist: typing-extensions<5,>=4.6.0
27
27
  Provides-Extra: dev-flake8
28
- Requires-Dist: flake8==7.1.1; extra == "dev-flake8"
28
+ Requires-Dist: flake8==7.2.0; extra == "dev-flake8"
29
29
  Requires-Dist: flake8-docstrings==1.7.0; extra == "dev-flake8"
30
30
  Requires-Dist: flake8-pyproject==1.2.3; extra == "dev-flake8"
31
- Requires-Dist: pydoclint==0.6.0; extra == "dev-flake8"
31
+ Requires-Dist: pydoclint==0.6.6; extra == "dev-flake8"
32
32
  Requires-Dist: pydocstyle==6.3.0; extra == "dev-flake8"
33
33
  Requires-Dist: frequenz-client-base; extra == "dev-flake8"
34
34
  Provides-Extra: dev-formatting
35
35
  Requires-Dist: black==25.1.0; extra == "dev-formatting"
36
- Requires-Dist: isort==6.0.0; extra == "dev-formatting"
36
+ Requires-Dist: isort==6.0.1; extra == "dev-formatting"
37
37
  Provides-Extra: dev-mkdocs
38
38
  Requires-Dist: black==25.1.0; extra == "dev-mkdocs"
39
- Requires-Dist: Markdown==3.7; extra == "dev-mkdocs"
39
+ Requires-Dist: Markdown==3.8; extra == "dev-mkdocs"
40
40
  Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
41
41
  Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
42
- Requires-Dist: mkdocs-literate-nav==0.6.1; extra == "dev-mkdocs"
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.1; extra == "dev-mkdocs"
45
- Requires-Dist: mkdocstrings[python]==0.27.0; extra == "dev-mkdocs"
46
- Requires-Dist: mkdocstrings-python==1.13.0; extra == "dev-mkdocs"
47
- Requires-Dist: frequenz-repo-config[lib]==0.11.0; extra == "dev-mkdocs"
44
+ Requires-Dist: mkdocs-material==9.6.14; extra == "dev-mkdocs"
45
+ Requires-Dist: mkdocstrings[python]==0.29.1; 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.14.1; extra == "dev-mypy"
51
- Requires-Dist: types-Markdown==3.7.0.20241204; extra == "dev-mypy"
52
- Requires-Dist: types-protobuf==5.29.1.20241207; extra == "dev-mypy"
53
- Requires-Dist: grpc-stubs==1.53.0.5; extra == "dev-mypy"
50
+ Requires-Dist: mypy==1.16.0; extra == "dev-mypy"
51
+ Requires-Dist: types-Markdown==3.8.0.20250415; extra == "dev-mypy"
52
+ Requires-Dist: types-protobuf==6.30.2.20250516; extra == "dev-mypy"
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
- Requires-Dist: nox==2024.10.9; extra == "dev-noxfile"
57
- Requires-Dist: frequenz-repo-config[lib]==0.11.0; extra == "dev-noxfile"
56
+ Requires-Dist: nox==2025.5.1; 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.4; 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
- Requires-Dist: pytest==8.3.4; extra == "dev-pytest"
63
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.11.0; extra == "dev-pytest"
64
- Requires-Dist: pytest-mock==3.14.0; extra == "dev-pytest"
65
- Requires-Dist: pytest-asyncio==0.25.3; extra == "dev-pytest"
62
+ Requires-Dist: pytest==8.3.5; 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
+ 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.124.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"
71
+ Dynamic: license-file
71
72
 
72
73
  # Frequenz Client Base Library
73
74
 
@@ -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 == 75.8.0",
7
- "setuptools_scm[toml] == 8.1.0",
8
- "frequenz-repo-config[lib] == 0.11.0",
6
+ "setuptools == 80.9.0",
7
+ "setuptools_scm[toml] == 8.3.1",
8
+ "frequenz-repo-config[lib] == 0.13.4",
9
9
  ]
10
10
  build-backend = "setuptools.build_meta"
11
11
 
@@ -27,9 +27,9 @@ classifiers = [
27
27
  requires-python = ">= 3.11, < 4"
28
28
  dependencies = [
29
29
  "frequenz-channels >= 1.6.1, < 2",
30
- "grpcio >= 1.54.2, < 2",
31
- "protobuf >= 4.21.6, < 6",
32
- "typing-extensions >= 4.5.0, < 5",
30
+ "grpcio >= 1.59, < 2",
31
+ "protobuf >= 5.29.2, < 7",
32
+ "typing-extensions >= 4.6.0, < 5",
33
33
  ]
34
34
  dynamic = ["version"]
35
35
 
@@ -39,48 +39,48 @@ email = "floss@frequenz.com"
39
39
 
40
40
  [project.optional-dependencies]
41
41
  dev-flake8 = [
42
- "flake8 == 7.1.1",
42
+ "flake8 == 7.2.0",
43
43
  "flake8-docstrings == 1.7.0",
44
- "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
45
- "pydoclint == 0.6.0",
44
+ "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
45
+ "pydoclint == 0.6.6",
46
46
  "pydocstyle == 6.3.0",
47
47
  "frequenz-client-base",
48
48
  ]
49
- dev-formatting = ["black == 25.1.0", "isort == 6.0.0"]
49
+ dev-formatting = ["black == 25.1.0", "isort == 6.0.1"]
50
50
  dev-mkdocs = [
51
51
  "black == 25.1.0",
52
- "Markdown==3.7",
52
+ "Markdown==3.8",
53
53
  "mike == 2.1.3",
54
54
  "mkdocs-gen-files == 0.5.0",
55
- "mkdocs-literate-nav == 0.6.1",
55
+ "mkdocs-literate-nav == 0.6.2",
56
56
  "mkdocs-macros-plugin == 1.3.7",
57
- "mkdocs-material == 9.6.1",
58
- "mkdocstrings[python] == 0.27.0",
59
- "mkdocstrings-python == 1.13.0",
60
- "frequenz-repo-config[lib] == 0.11.0",
57
+ "mkdocs-material == 9.6.14",
58
+ "mkdocstrings[python] == 0.29.1",
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.14.1",
65
- "types-Markdown == 3.7.0.20241204",
66
- "types-protobuf == 5.29.1.20241207",
67
- "grpc-stubs == 1.53.0.5", # This dependency introduces breaking changes in patch releases
64
+ "mypy == 1.16.0",
65
+ "types-Markdown == 3.8.0.20250415",
66
+ "types-protobuf == 6.30.2.20250516",
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 == 2024.10.9", "frequenz-repo-config[lib] == 0.11.0"]
71
+ dev-noxfile = ["nox == 2025.5.1", "frequenz-repo-config[lib] == 0.13.4"]
72
72
  dev-pylint = [
73
- "pylint == 3.3.4",
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
- "pytest == 8.3.4",
79
- "frequenz-repo-config[extra-lint-examples] == 0.11.0",
80
- "pytest-mock == 3.14.0",
81
- "pytest-asyncio == 0.25.3",
78
+ "pytest == 8.3.5",
79
+ "frequenz-repo-config[extra-lint-examples] == 0.13.4",
80
+ "pytest-mock == 3.14.1",
81
+ "pytest-asyncio == 0.26.0",
82
82
  "async-solipsism == 0.7",
83
- "hypothesis == 6.124.9",
83
+ "hypothesis == 6.132.0",
84
84
  "frequenz-client-base",
85
85
  ]
86
86
  dev = [
@@ -155,6 +155,7 @@ disable = [
155
155
  ]
156
156
 
157
157
  [tool.pytest.ini_options]
158
+ addopts = "-W=all -Werror -Wdefault::DeprecationWarning -Wdefault::PendingDeprecationWarning -vv"
158
159
  testpaths = ["tests", "src"]
159
160
  asyncio_mode = "auto"
160
161
  asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,107 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """An Interceptor that adds the API key to a gRPC call."""
5
+
6
+ from typing import AsyncIterable, Callable
7
+
8
+ from grpc.aio import (
9
+ ClientCallDetails,
10
+ Metadata,
11
+ UnaryStreamCall,
12
+ UnaryStreamClientInterceptor,
13
+ UnaryUnaryCall,
14
+ UnaryUnaryClientInterceptor,
15
+ )
16
+
17
+
18
+ def _add_auth_header(
19
+ key: str,
20
+ client_call_details: ClientCallDetails,
21
+ ) -> None:
22
+ """Add the API key as a metadata field to the call.
23
+
24
+ The API key is used by the later sign interceptor to calculate the HMAC.
25
+ In addition it is used as a first layer of authentication by the server.
26
+
27
+ Args:
28
+ key: The API key to use for the service.
29
+ client_call_details: The call details.
30
+ """
31
+ if client_call_details.metadata is None:
32
+ client_call_details.metadata = Metadata()
33
+
34
+ client_call_details.metadata["key"] = key
35
+
36
+
37
+ # There is an issue in gRPC which means the type can not be specified correctly here.
38
+ class AuthenticationInterceptorUnaryUnary(UnaryUnaryClientInterceptor): # type: ignore[type-arg]
39
+ """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
40
+
41
+ def __init__(self, api_key: str):
42
+ """Create an instance of the interceptor.
43
+
44
+ Args:
45
+ api_key: The API key to send along for the request.
46
+ """
47
+ self._key = api_key
48
+
49
+ async def intercept_unary_unary(
50
+ self,
51
+ continuation: Callable[
52
+ [ClientCallDetails, object], UnaryUnaryCall[object, object]
53
+ ],
54
+ client_call_details: ClientCallDetails,
55
+ request: object,
56
+ ) -> object:
57
+ """Intercept the call to add HMAC authentication to the metadata fields.
58
+
59
+ This is a known method from the base class that is overridden.
60
+
61
+ Args:
62
+ continuation: The next interceptor in the chain.
63
+ client_call_details: The call details.
64
+ request: The request object.
65
+
66
+ Returns:
67
+ The response object (this implementation does not modify the response).
68
+ """
69
+ _add_auth_header(self._key, client_call_details)
70
+ return await continuation(client_call_details, request)
71
+
72
+
73
+ # There is an issue in gRPC which means the type can not be specified correctly here.
74
+ class AuthenticationInterceptorUnaryStream(UnaryStreamClientInterceptor): # type: ignore[type-arg]
75
+ """An Interceptor that adds HMAC authentication of the metadata fields to a gRPC call."""
76
+
77
+ def __init__(self, api_key: str):
78
+ """Create an instance of the interceptor.
79
+
80
+ Args:
81
+ api_key: The API key to send along for the request.
82
+ """
83
+ self._key = api_key
84
+
85
+ async def intercept_unary_stream(
86
+ self,
87
+ continuation: Callable[
88
+ [ClientCallDetails, object], UnaryStreamCall[object, object]
89
+ ],
90
+ client_call_details: ClientCallDetails,
91
+ request: object,
92
+ ) -> AsyncIterable[object] | UnaryStreamCall[object, object]:
93
+ """Intercept the call to add HMAC authentication to the metadata fields.
94
+
95
+ This is a known method from the base class that is overridden.
96
+
97
+ Args:
98
+ continuation: The next interceptor in the chain.
99
+ client_call_details: The call details.
100
+ request: The request object.
101
+
102
+ Returns:
103
+ The response object (this implementation does not modify the response).
104
+ """
105
+ _add_auth_header(self._key, client_call_details)
106
+
107
+ return await continuation(client_call_details, request) # type: ignore
@@ -6,11 +6,16 @@
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
13
- from grpc.aio import Channel, insecure_channel, secure_channel
13
+ from grpc.aio import (
14
+ Channel,
15
+ ClientInterceptor,
16
+ insecure_channel,
17
+ secure_channel,
18
+ )
14
19
 
15
20
 
16
21
  @dataclasses.dataclass(frozen=True)
@@ -72,6 +77,7 @@ class ChannelOptions:
72
77
 
73
78
  def parse_grpc_uri(
74
79
  uri: str,
80
+ interceptors: Sequence[ClientInterceptor] = (),
75
81
  /,
76
82
  defaults: ChannelOptions = ChannelOptions(),
77
83
  ) -> Channel:
@@ -109,6 +115,8 @@ def parse_grpc_uri(
109
115
 
110
116
  Args:
111
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)
112
120
  defaults: The default options use to create the channel when not specified in
113
121
  the URI.
114
122
 
@@ -199,8 +207,9 @@ def parse_grpc_uri(
199
207
  ),
200
208
  ),
201
209
  channel_options,
210
+ interceptors=interceptors,
202
211
  )
203
- return insecure_channel(target, channel_options)
212
+ return insecure_channel(target, channel_options, interceptors=interceptors)
204
213
 
205
214
 
206
215
  def _to_bool(value: str) -> bool:
@@ -252,13 +261,13 @@ def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
252
261
  }
253
262
 
254
263
  if ssl is False:
255
- erros = []
264
+ errors = []
256
265
  for opt_name, opt in ssl_opts.items():
257
266
  if opt is not None:
258
- erros.append(opt_name)
259
- if erros:
267
+ errors.append(opt_name)
268
+ if errors:
260
269
  raise ValueError(
261
- f"Option(s) {', '.join(erros)} found in URI {uri!r}, but SSL is disabled",
270
+ f"Option(s) {', '.join(errors)} found in URI {uri!r}, but SSL is disabled",
262
271
  )
263
272
 
264
273
  keep_alive_option = options.pop("keep_alive", None)
@@ -272,13 +281,13 @@ def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
272
281
  }
273
282
 
274
283
  if keep_alive is False:
275
- erros = []
284
+ errors = []
276
285
  for opt_name, opt in keep_alive_opts.items():
277
286
  if opt is not None:
278
- erros.append(opt_name)
279
- if erros:
287
+ errors.append(opt_name)
288
+ if errors:
280
289
  raise ValueError(
281
- f"Option(s) {', '.join(erros)} found in URI {uri!r}, but keep_alive is disabled",
290
+ f"Option(s) {', '.join(errors)} found in URI {uri!r}, but keep_alive is disabled",
282
291
  )
283
292
 
284
293
  if options:
@@ -6,12 +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
- from grpc.aio import AioRpcError, Channel
12
+ from grpc.aio import (
13
+ AioRpcError,
14
+ Channel,
15
+ ClientInterceptor,
16
+ )
12
17
 
18
+ from .authentication import (
19
+ AuthenticationInterceptorUnaryStream,
20
+ AuthenticationInterceptorUnaryUnary,
21
+ )
13
22
  from .channel import ChannelOptions, parse_grpc_uri
14
23
  from .exception import ApiClientError, ClientNotConnected
24
+ from .signing import (
25
+ SigningInterceptorUnaryStream,
26
+ SigningInterceptorUnaryUnary,
27
+ )
15
28
 
16
29
  StubT = TypeVar("StubT")
17
30
  """The type of the gRPC stub."""
@@ -150,13 +163,15 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
150
163
  instances.
151
164
  """
152
165
 
153
- def __init__(
166
+ def __init__( # pylint: disable=too-many-arguments
154
167
  self,
155
168
  server_url: str,
156
169
  create_stub: Callable[[Channel], StubT],
157
170
  *,
158
171
  connect: bool = True,
159
172
  channel_defaults: ChannelOptions = ChannelOptions(),
173
+ auth_key: str | None = None,
174
+ sign_secret: str | None = None,
160
175
  ) -> None:
161
176
  """Create an instance and connect to the server.
162
177
 
@@ -169,14 +184,21 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
169
184
  called.
170
185
  channel_defaults: The default options for the gRPC channel to create using
171
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
+
172
190
  """
173
191
  self._server_url: str = server_url
174
192
  self._create_stub: Callable[[Channel], StubT] = create_stub
175
193
  self._channel_defaults: ChannelOptions = channel_defaults
194
+ self._auth_key = auth_key
195
+ self._sign_secret = sign_secret
176
196
  self._channel: Channel | None = None
177
197
  self._stub: StubT | None = None
178
198
  if connect:
179
- self.connect(server_url)
199
+ self.connect(
200
+ server_url=self._server_url, auth_key=auth_key, sign_secret=sign_secret
201
+ )
180
202
 
181
203
  @property
182
204
  def server_url(self) -> str:
@@ -209,7 +231,13 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
209
231
  """Whether the client is connected to the server."""
210
232
  return self._channel is not None
211
233
 
212
- 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:
213
241
  """Connect to the server, possibly using a new URL.
214
242
 
215
243
  If the client is already connected and the URL is the same as the previous URL,
@@ -219,12 +247,41 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
219
247
  Args:
220
248
  server_url: The URL of the server to connect to. If not provided, the
221
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,
222
254
  """
255
+ reconnect = False
223
256
  if server_url is not None and server_url != self._server_url: # URL changed
224
257
  self._server_url = server_url
225
- 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
226
266
  return
227
- 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
+ )
228
285
  self._stub = self._create_stub(self._channel)
229
286
 
230
287
  async def disconnect(self) -> None: