frequenz-client-base 0.4.0__tar.gz → 0.6.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 (24) hide show
  1. {frequenz-client-base-0.4.0/src/frequenz_client_base.egg-info → frequenz-client-base-0.6.0}/PKG-INFO +1 -3
  2. frequenz-client-base-0.6.0/RELEASE_NOTES.md +23 -0
  3. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/pyproject.toml +27 -23
  4. frequenz-client-base-0.6.0/src/frequenz/client/base/channel.py +250 -0
  5. frequenz-client-base-0.6.0/src/frequenz/client/base/client.py +306 -0
  6. frequenz-client-base-0.6.0/src/frequenz/client/base/exception.py +646 -0
  7. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/streaming.py +3 -2
  8. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0/src/frequenz_client_base.egg-info}/PKG-INFO +1 -3
  9. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz_client_base.egg-info/SOURCES.txt +2 -1
  10. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz_client_base.egg-info/requires.txt +21 -25
  11. frequenz-client-base-0.4.0/RELEASE_NOTES.md +0 -18
  12. frequenz-client-base-0.4.0/src/frequenz/client/base/_grpchacks.py +0 -46
  13. frequenz-client-base-0.4.0/src/frequenz/client/base/channel.py +0 -75
  14. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/LICENSE +0 -0
  15. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/MANIFEST.in +0 -0
  16. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/README.md +0 -0
  17. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/setup.cfg +0 -0
  18. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/__init__.py +0 -0
  19. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/conftest.py +0 -0
  20. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/conversion.py +0 -0
  21. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/py.typed +0 -0
  22. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz/client/base/retry.py +0 -0
  23. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
  24. {frequenz-client-base-0.4.0 → frequenz-client-base-0.6.0}/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.4.0
3
+ Version: 0.6.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
@@ -19,8 +19,6 @@ Classifier: Topic :: Software Development :: Libraries
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: <4,>=3.11
21
21
  Description-Content-Type: text/markdown
22
- Provides-Extra: grpcio
23
- Provides-Extra: grpclib
24
22
  Provides-Extra: dev-flake8
25
23
  Provides-Extra: dev-formatting
26
24
  Provides-Extra: dev-mkdocs
@@ -0,0 +1,23 @@
1
+ # Frequenz Client Base Library Release Notes
2
+
3
+ ## Summary
4
+
5
+ This version removes `grpclib` support and adds new SSL options to the connection URI.
6
+
7
+ ## Upgrading
8
+
9
+ - `grpclib` was removed, if you used `grpclib` you should switch to `grpcio` instead.
10
+
11
+ You should also update your dependency to `frequenz-client-base` (without any `[grpclib]` or `[grpcio]` suffix). Also, now there is no need to pass around the channel type to the `BaseApiClient` or the `parse_grpc_uri` function.
12
+
13
+ - The `parse_grpc_uri` function (and `BaseApiClient` constructor) now enables SSL by default (`ssl=false` should be passed to disable it).
14
+
15
+ - The `parse_grpc_uri` and `BaseApiClient` function now accepts a set of defaults to use when the URI does not specify a value for a given option.
16
+
17
+ ## New Features
18
+
19
+ - The connection URI can now have a few new SSL options:
20
+
21
+ * `ssl_root_certificates_path` to specify the path to the root certificates file.
22
+ * `ssl_private_key_path` to specify the path to the private key file.
23
+ * `ssl_certificate_chain_path` to specify the path to the certificate chain file.
@@ -5,7 +5,7 @@
5
5
  requires = [
6
6
  "setuptools == 68.1.0",
7
7
  "setuptools_scm[toml] == 7.1.0",
8
- "frequenz-repo-config[lib] == 0.9.2",
8
+ "frequenz-repo-config[lib] == 0.10.0",
9
9
  ]
10
10
  build-backend = "setuptools.build_meta"
11
11
 
@@ -27,6 +27,7 @@ classifiers = [
27
27
  requires-python = ">= 3.11, < 4"
28
28
  dependencies = [
29
29
  "frequenz-channels >= v1.0.0-rc1, < 2",
30
+ "grpcio >= 1.54.2, < 2",
30
31
  "protobuf >= 4.21.6, < 6",
31
32
  "typing-extensions >= 4.5.0, < 5",
32
33
  ]
@@ -37,51 +38,50 @@ name = "Frequenz Energy-as-a-Service GmbH"
37
38
  email = "floss@frequenz.com"
38
39
 
39
40
  [project.optional-dependencies]
40
- grpcio = ["grpcio >= 1.54.2, < 2"]
41
- grpclib = ["grpclib >= 0.4.0, < 0.5"]
42
41
  dev-flake8 = [
43
- "flake8 == 7.0.0",
42
+ "flake8 == 7.1.1",
44
43
  "flake8-docstrings == 1.7.0",
45
- "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
46
- "pydoclint == 0.4.1",
44
+ "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
45
+ "pydoclint == 0.5.6",
47
46
  "pydocstyle == 6.3.0",
48
- "frequenz-client-base[grpclib,grpcio]",
47
+ "frequenz-client-base",
49
48
  ]
50
- dev-formatting = ["black == 24.4.2", "isort == 5.13.2"]
49
+ dev-formatting = ["black == 24.8.0", "isort == 5.13.2"]
51
50
  dev-mkdocs = [
52
- "black == 24.4.2",
51
+ "black == 24.8.0",
53
52
  "Markdown==3.6",
54
- "mike == 2.0.0",
53
+ "mike == 2.1.3",
55
54
  "mkdocs-gen-files == 0.5.0",
56
55
  "mkdocs-literate-nav == 0.6.1",
57
56
  "mkdocs-macros-plugin == 1.0.5",
58
- "mkdocs-material == 9.5.20",
59
- "mkdocstrings[python] == 0.25.0",
60
- "frequenz-repo-config[lib] == 0.9.2",
61
- "frequenz-client-base[grpclib,grpcio]",
57
+ "mkdocs-material == 9.5.31",
58
+ "mkdocstrings[python] == 0.25.2",
59
+ "mkdocstrings-python == 1.10.8",
60
+ "frequenz-repo-config[lib] == 0.10.0",
61
+ "frequenz-client-base",
62
62
  ]
63
63
  dev-mypy = [
64
- "mypy == 1.10.0",
64
+ "mypy == 1.11.1",
65
65
  "types-Markdown == 3.6.0.20240316",
66
- "types-protobuf == 5.26.0.20240422",
66
+ "types-protobuf == 5.27.0.20240626",
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.9.2"]
71
+ dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.10.0"]
72
72
  dev-pylint = [
73
- "pylint == 3.1.0",
73
+ "pylint == 3.2.6",
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.2.0",
79
- "frequenz-repo-config[extra-lint-examples] == 0.9.2",
78
+ "pytest == 8.3.2",
79
+ "frequenz-repo-config[extra-lint-examples] == 0.10.0",
80
80
  "pytest-mock == 3.14.0",
81
- "pytest-asyncio == 0.23.6",
81
+ "pytest-asyncio == 0.23.8",
82
82
  "async-solipsism == 0.6",
83
- "hypothesis == 6.100.2",
84
- "frequenz-client-base[grpclib,grpcio]",
83
+ "hypothesis == 6.111.0",
84
+ "frequenz-client-base",
85
85
  ]
86
86
  dev = [
87
87
  "frequenz-client-base[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]",
@@ -136,10 +136,14 @@ disable = [
136
136
  # pylint's unsubscriptable check is buggy and is not needed because
137
137
  # it is a type-check, for which we already have mypy.
138
138
  "unsubscriptable-object",
139
+ # Checked by mypy
140
+ "no-member",
139
141
  # Checked by flake8
142
+ "f-string-without-interpolation",
140
143
  "redefined-outer-name",
141
144
  "unused-import",
142
145
  "line-too-long",
146
+ "missing-function-docstring",
143
147
  "unused-variable",
144
148
  "unnecessary-lambda-assignment",
145
149
  # Checked by mypy
@@ -0,0 +1,250 @@
1
+ # License: MIT
2
+ # Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Handling of gRPC channels."""
5
+
6
+ import dataclasses
7
+ import pathlib
8
+ from typing import assert_never
9
+ from urllib.parse import parse_qs, urlparse
10
+
11
+ from grpc import ssl_channel_credentials
12
+ from grpc.aio import Channel, insecure_channel, secure_channel
13
+
14
+
15
+ @dataclasses.dataclass(frozen=True)
16
+ class SslOptions:
17
+ """SSL options for a gRPC channel."""
18
+
19
+ enabled: bool = True
20
+ """Whether SSL should be enabled."""
21
+
22
+ root_certificates: pathlib.Path | bytes | None = None
23
+ """The PEM-encoded root certificates.
24
+
25
+ This can be a path to a file containing the certificates, a byte string, or None to
26
+ retrieve them from a default location chosen by gRPC runtime.
27
+ """
28
+
29
+ private_key: pathlib.Path | bytes | None = None
30
+ """The PEM-encoded private key.
31
+
32
+ This can be a path to a file containing the key, a byte string, or None if no key
33
+ should be used.
34
+ """
35
+
36
+ certificate_chain: pathlib.Path | bytes | None = None
37
+ """The PEM-encoded certificate chain.
38
+
39
+ This can be a path to a file containing the chain, a byte string, or None if no
40
+ chain should be used.
41
+ """
42
+
43
+
44
+ @dataclasses.dataclass(frozen=True)
45
+ class ChannelOptions:
46
+ """Options for a gRPC channel."""
47
+
48
+ port: int = 9090
49
+ """The port number to connect to."""
50
+
51
+ ssl: SslOptions = SslOptions()
52
+ """SSL options for the channel."""
53
+
54
+
55
+ def parse_grpc_uri(
56
+ uri: str,
57
+ /,
58
+ defaults: ChannelOptions = ChannelOptions(),
59
+ ) -> Channel:
60
+ """Create a client channel from a URI.
61
+
62
+ The URI must have the following format:
63
+
64
+ ```
65
+ grpc://hostname[:port][?param=value&...]
66
+ ```
67
+
68
+ A few things to consider about URI components:
69
+
70
+ - If any other components are present in the URI, a [`ValueError`][] is raised.
71
+ - If the port is omitted, the `default_port` is used.
72
+ - If a query parameter is passed many times, the last value is used.
73
+ - Boolean query parameters can be specified with the following values
74
+ (case-insensitive): `true`, `1`, `on`, `false`, `0`, `off`.
75
+
76
+ Supported query parameters:
77
+
78
+ - `ssl` (bool): Enable or disable SSL. Defaults to `default_ssl`.
79
+ - `ssl_root_certificates_path` (str): Path to the root certificates file. Only
80
+ valid if SSL is enabled. Will raise a `ValueError` if the file cannot be read.
81
+ - `ssl_private_key_path` (str): Path to the private key file. Only valid if SSL is
82
+ enabled. Will raise a `ValueError` if the file cannot be read.
83
+ - `ssl_certificate_chain_path` (str): Path to the certificate chain file. Only
84
+ valid if SSL is enabled. Will raise a `ValueError` if the file cannot be read.
85
+
86
+ Args:
87
+ uri: The gRPC URI specifying the connection parameters.
88
+ defaults: The default options use to create the channel when not specified in
89
+ the URI.
90
+
91
+ Returns:
92
+ A client channel object.
93
+
94
+ Raises:
95
+ ValueError: If the URI is invalid or contains unexpected components.
96
+ """
97
+ parsed_uri = urlparse(uri)
98
+ if parsed_uri.scheme != "grpc":
99
+ raise ValueError(
100
+ f"Invalid scheme '{parsed_uri.scheme}' in the URI, expected 'grpc'", uri
101
+ )
102
+ if not parsed_uri.hostname:
103
+ raise ValueError(f"Host name is missing in URI '{uri}'", uri)
104
+ for attr in ("path", "fragment", "params", "username", "password"):
105
+ if getattr(parsed_uri, attr):
106
+ raise ValueError(
107
+ f"Unexpected {attr} '{getattr(parsed_uri, attr)}' in the URI '{uri}'",
108
+ uri,
109
+ )
110
+
111
+ options = _parse_query_params(uri, parsed_uri.query)
112
+
113
+ host = parsed_uri.hostname
114
+ port = parsed_uri.port or defaults.port
115
+ target = f"{host}:{port}"
116
+
117
+ ssl = defaults.ssl.enabled if options.ssl is None else options.ssl
118
+ if ssl:
119
+ return secure_channel(
120
+ target,
121
+ ssl_channel_credentials(
122
+ root_certificates=_get_contents(
123
+ "root certificates",
124
+ options.ssl_root_certificates_path,
125
+ defaults.ssl.root_certificates,
126
+ ),
127
+ private_key=_get_contents(
128
+ "private key",
129
+ options.ssl_private_key_path,
130
+ defaults.ssl.private_key,
131
+ ),
132
+ certificate_chain=_get_contents(
133
+ "certificate chain",
134
+ options.ssl_certificate_chain_path,
135
+ defaults.ssl.certificate_chain,
136
+ ),
137
+ ),
138
+ )
139
+ return insecure_channel(target)
140
+
141
+
142
+ def _to_bool(value: str) -> bool:
143
+ value = value.lower()
144
+ if value in ("true", "on", "1"):
145
+ return True
146
+ if value in ("false", "off", "0"):
147
+ return False
148
+ raise ValueError(f"Invalid boolean value '{value}'")
149
+
150
+
151
+ @dataclasses.dataclass(frozen=True)
152
+ class _QueryParams:
153
+ ssl: bool | None
154
+ ssl_root_certificates_path: pathlib.Path | None
155
+ ssl_private_key_path: pathlib.Path | None
156
+ ssl_certificate_chain_path: pathlib.Path | None
157
+
158
+
159
+ def _parse_query_params(uri: str, query_string: str) -> _QueryParams:
160
+ """Parse query parameters from a URI.
161
+
162
+ Args:
163
+ uri: The URI from which the query parameters were extracted.
164
+ query_string: The query string to parse.
165
+
166
+ Returns:
167
+ A `_QueryParams` object with the parsed query parameters.
168
+
169
+ Raises:
170
+ ValueError: If the query string contains unexpected components.
171
+ """
172
+ options = {k: v[-1] for k, v in parse_qs(query_string).items()}
173
+ ssl_option = options.pop("ssl", None)
174
+ ssl: bool | None = None
175
+ if ssl_option is not None:
176
+ ssl = _to_bool(ssl_option)
177
+
178
+ ssl_opts = {
179
+ k: options.pop(k, None)
180
+ for k in (
181
+ "ssl_root_certificates_path",
182
+ "ssl_private_key_path",
183
+ "ssl_certificate_chain_path",
184
+ )
185
+ }
186
+
187
+ if ssl is False:
188
+ erros = []
189
+ for opt_name, opt in ssl_opts.items():
190
+ if opt is not None:
191
+ erros.append(opt_name)
192
+ if erros:
193
+ raise ValueError(
194
+ f"Option(s) {', '.join(erros)} found in URI {uri!r}, but SSL is disabled",
195
+ )
196
+
197
+ if options:
198
+ names = ", ".join(options)
199
+ raise ValueError(
200
+ f"Unexpected query parameters [{names}] in the URI '{uri}'",
201
+ uri,
202
+ )
203
+
204
+ return _QueryParams(
205
+ ssl=ssl,
206
+ **{k: pathlib.Path(v) if v is not None else None for k, v in ssl_opts.items()},
207
+ )
208
+
209
+
210
+ def _get_contents(
211
+ name: str, source: pathlib.Path | None, default: pathlib.Path | bytes | None
212
+ ) -> bytes | None:
213
+ """Get the contents of a file or use a default value.
214
+
215
+ If the `source` is `None`, the `default` value is used instead. If the source (or
216
+ default) is a path, the contents of the file are returned. If the source is a byte
217
+ string (or default) the byte string is returned without doing any reading.
218
+
219
+ Args:
220
+ name: The name of the contents (used for error messages).
221
+ source: The source of the contents.
222
+ default: The default value to use if the source is None.
223
+
224
+ Returns:
225
+ The contents of the source file or the default value.
226
+ """
227
+ file_path: pathlib.Path
228
+ match source:
229
+ case None:
230
+ match default:
231
+ case None:
232
+ return None
233
+ case bytes() as default_bytes:
234
+ return default_bytes
235
+ case pathlib.Path() as file_path:
236
+ return _read_bytes(name, file_path)
237
+ case unexpected:
238
+ assert_never(unexpected)
239
+ case pathlib.Path() as file_path:
240
+ return _read_bytes(name, file_path)
241
+ case unexpected:
242
+ assert_never(unexpected)
243
+
244
+
245
+ def _read_bytes(name: str, source: pathlib.Path) -> bytes:
246
+ """Read the contents of a file as bytes."""
247
+ try:
248
+ return source.read_bytes()
249
+ except OSError as exc:
250
+ raise ValueError(f"Failed to read {name} from '{source}': {exc}") from exc