frequenz-client-base 0.5.0__tar.gz → 0.6.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.
- {frequenz-client-base-0.5.0/src/frequenz_client_base.egg-info → frequenz-client-base-0.6.1}/PKG-INFO +1 -3
- frequenz-client-base-0.6.1/RELEASE_NOTES.md +5 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/pyproject.toml +29 -25
- frequenz-client-base-0.6.1/src/frequenz/client/base/channel.py +250 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/client.py +27 -33
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/exception.py +52 -122
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/streaming.py +3 -2
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1/src/frequenz_client_base.egg-info}/PKG-INFO +1 -3
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz_client_base.egg-info/SOURCES.txt +0 -1
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz_client_base.egg-info/requires.txt +23 -27
- frequenz-client-base-0.5.0/RELEASE_NOTES.md +0 -16
- frequenz-client-base-0.5.0/src/frequenz/client/base/_grpchacks.py +0 -138
- frequenz-client-base-0.5.0/src/frequenz/client/base/channel.py +0 -86
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/LICENSE +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/MANIFEST.in +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/README.md +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/setup.cfg +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/__init__.py +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/conftest.py +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/conversion.py +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/py.typed +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/retry.py +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
- {frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz_client_base.egg-info/top_level.txt +0 -0
{frequenz-client-base-0.5.0/src/frequenz_client_base.egg-info → frequenz-client-base-0.6.1}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: frequenz-client-base
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.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
|
|
@@ -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
|
|
@@ -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.
|
|
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.1.
|
|
42
|
+
"flake8 == 7.1.1",
|
|
44
43
|
"flake8-docstrings == 1.7.0",
|
|
45
|
-
"flake8-pyproject == 1.2.3",
|
|
46
|
-
"pydoclint == 0.5.
|
|
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
|
|
47
|
+
"frequenz-client-base",
|
|
49
48
|
]
|
|
50
|
-
dev-formatting = ["black == 24.
|
|
49
|
+
dev-formatting = ["black == 24.8.0", "isort == 5.13.2"]
|
|
51
50
|
dev-mkdocs = [
|
|
52
|
-
"black == 24.
|
|
53
|
-
"Markdown==3.
|
|
54
|
-
"mike == 2.1.
|
|
51
|
+
"black == 24.8.0",
|
|
52
|
+
"Markdown==3.7",
|
|
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.
|
|
59
|
-
"mkdocstrings[python] == 0.25.
|
|
60
|
-
"
|
|
61
|
-
"frequenz-
|
|
57
|
+
"mkdocs-material == 9.5.34",
|
|
58
|
+
"mkdocstrings[python] == 0.25.2",
|
|
59
|
+
"mkdocstrings-python == 1.10.9",
|
|
60
|
+
"frequenz-repo-config[lib] == 0.10.0",
|
|
61
|
+
"frequenz-client-base",
|
|
62
62
|
]
|
|
63
63
|
dev-mypy = [
|
|
64
|
-
"mypy == 1.
|
|
65
|
-
"types-Markdown == 3.
|
|
64
|
+
"mypy == 1.11.2",
|
|
65
|
+
"types-Markdown == 3.7.0.20240822",
|
|
66
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.
|
|
71
|
+
dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.10.0"]
|
|
72
72
|
dev-pylint = [
|
|
73
|
-
"pylint == 3.2.
|
|
73
|
+
"pylint == 3.2.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.
|
|
79
|
-
"frequenz-repo-config[extra-lint-examples] == 0.
|
|
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.
|
|
82
|
-
"async-solipsism == 0.
|
|
83
|
-
"hypothesis == 6.
|
|
84
|
-
"frequenz-client-base
|
|
81
|
+
"pytest-asyncio == 0.24.0",
|
|
82
|
+
"async-solipsism == 0.7",
|
|
83
|
+
"hypothesis == 6.111.2",
|
|
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
|
+
target = (
|
|
114
|
+
parsed_uri.netloc if parsed_uri.port else f"{parsed_uri.netloc}:{defaults.port}"
|
|
115
|
+
)
|
|
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
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/client.py
RENAMED
|
@@ -8,15 +8,16 @@ import inspect
|
|
|
8
8
|
from collections.abc import Awaitable, Callable
|
|
9
9
|
from typing import Any, Generic, Self, TypeVar, overload
|
|
10
10
|
|
|
11
|
-
from . import
|
|
12
|
-
|
|
11
|
+
from grpc.aio import AioRpcError, Channel
|
|
12
|
+
|
|
13
|
+
from .channel import ChannelOptions, parse_grpc_uri
|
|
13
14
|
from .exception import ApiClientError, ClientNotConnected
|
|
14
15
|
|
|
15
16
|
StubT = TypeVar("StubT")
|
|
16
17
|
"""The type of the gRPC stub."""
|
|
17
18
|
|
|
18
19
|
|
|
19
|
-
class BaseApiClient(abc.ABC, Generic[StubT
|
|
20
|
+
class BaseApiClient(abc.ABC, Generic[StubT]):
|
|
20
21
|
"""A base class for API clients.
|
|
21
22
|
|
|
22
23
|
This class provides a common interface for API clients that communicate with a API
|
|
@@ -37,7 +38,6 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
37
38
|
|
|
38
39
|
```python
|
|
39
40
|
from collections.abc import AsyncIterable
|
|
40
|
-
import grpc
|
|
41
41
|
from frequenz.client.base.client import BaseApiClient, call_stub_method
|
|
42
42
|
from frequenz.client.base.streaming import GrpcStreamBroadcaster
|
|
43
43
|
from frequenz.channels import Receiver
|
|
@@ -65,10 +65,10 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
65
65
|
def __init__(self, response: ExampleResponse):
|
|
66
66
|
self.transformed_value = f"{response.float_value:.2f}"
|
|
67
67
|
|
|
68
|
-
class MyApiClient(BaseApiClient[ExampleStub
|
|
68
|
+
class MyApiClient(BaseApiClient[ExampleStub]):
|
|
69
69
|
def __init__(self, server_url: str, *, connect: bool = True):
|
|
70
70
|
super().__init__(
|
|
71
|
-
server_url, ExampleStub,
|
|
71
|
+
server_url, ExampleStub, connect=connect
|
|
72
72
|
)
|
|
73
73
|
self._broadcaster = GrpcStreamBroadcaster(
|
|
74
74
|
"stream",
|
|
@@ -103,9 +103,7 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
103
103
|
break
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
* This example uses `grpcio` as the underlaying gRPC library, but `grpclib`
|
|
108
|
-
can be used as well.
|
|
106
|
+
Note:
|
|
109
107
|
* In this case a very simple `GrpcStreamBroadcaster` is used, asuming that
|
|
110
108
|
each call to `example_stream` will stream the same data. If the request
|
|
111
109
|
is more complex, you will probably need to have some kind of map from
|
|
@@ -116,26 +114,27 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
116
114
|
def __init__(
|
|
117
115
|
self,
|
|
118
116
|
server_url: str,
|
|
119
|
-
create_stub: Callable[[
|
|
120
|
-
channel_type: type[ChannelT],
|
|
117
|
+
create_stub: Callable[[Channel], StubT],
|
|
121
118
|
*,
|
|
122
119
|
connect: bool = True,
|
|
120
|
+
channel_defaults: ChannelOptions = ChannelOptions(),
|
|
123
121
|
) -> None:
|
|
124
122
|
"""Create an instance and connect to the server.
|
|
125
123
|
|
|
126
124
|
Args:
|
|
127
125
|
server_url: The URL of the server to connect to.
|
|
128
126
|
create_stub: A function that creates a stub from a channel.
|
|
129
|
-
channel_type: The type of channel to use.
|
|
130
127
|
connect: Whether to connect to the server as soon as a client instance is
|
|
131
128
|
created. If `False`, the client will not connect to the server until
|
|
132
129
|
[connect()][frequenz.client.base.client.BaseApiClient.connect] is
|
|
133
130
|
called.
|
|
131
|
+
channel_defaults: The default options for the gRPC channel to create using
|
|
132
|
+
the server URL.
|
|
134
133
|
"""
|
|
135
134
|
self._server_url: str = server_url
|
|
136
|
-
self._create_stub: Callable[[
|
|
137
|
-
self.
|
|
138
|
-
self._channel:
|
|
135
|
+
self._create_stub: Callable[[Channel], StubT] = create_stub
|
|
136
|
+
self._channel_defaults: ChannelOptions = channel_defaults
|
|
137
|
+
self._channel: Channel | None = None
|
|
139
138
|
self._stub: StubT | None = None
|
|
140
139
|
if connect:
|
|
141
140
|
self.connect(server_url)
|
|
@@ -146,7 +145,7 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
146
145
|
return self._server_url
|
|
147
146
|
|
|
148
147
|
@property
|
|
149
|
-
def channel(self) ->
|
|
148
|
+
def channel(self) -> Channel:
|
|
150
149
|
"""The underlying gRPC channel used to communicate with the server.
|
|
151
150
|
|
|
152
151
|
Warning:
|
|
@@ -161,6 +160,11 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
161
160
|
raise ClientNotConnected(server_url=self.server_url, operation="channel")
|
|
162
161
|
return self._channel
|
|
163
162
|
|
|
163
|
+
@property
|
|
164
|
+
def channel_defaults(self) -> ChannelOptions:
|
|
165
|
+
"""The default options for the gRPC channel."""
|
|
166
|
+
return self._channel_defaults
|
|
167
|
+
|
|
164
168
|
@property
|
|
165
169
|
def stub(self) -> StubT:
|
|
166
170
|
"""The underlying gRPC stub.
|
|
@@ -197,7 +201,7 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
197
201
|
self._server_url = server_url
|
|
198
202
|
elif self.is_connected:
|
|
199
203
|
return
|
|
200
|
-
self._channel = parse_grpc_uri(self._server_url, self.
|
|
204
|
+
self._channel = parse_grpc_uri(self._server_url, self._channel_defaults)
|
|
201
205
|
self._stub = self._create_stub(self._channel)
|
|
202
206
|
|
|
203
207
|
async def disconnect(self) -> None:
|
|
@@ -221,14 +225,6 @@ class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
|
221
225
|
"""Exit a context manager."""
|
|
222
226
|
if self._channel is None:
|
|
223
227
|
return None
|
|
224
|
-
# We need to ignore the return type here because the __aexit__ method of grpclib
|
|
225
|
-
# is not annotated correctly, it is annotated to return None but __aexit__
|
|
226
|
-
# should return a bool | None. This should be harmless if grpclib never handle
|
|
227
|
-
# any exceptions in __aexit__, so it is just a type checker issue. This is the
|
|
228
|
-
# error produced by mypy:
|
|
229
|
-
# Function does not return a value (it only ever returns None)
|
|
230
|
-
# [func-returns-value]
|
|
231
|
-
# See https://github.com/vmagamedov/grpclib/issues/193 for more details.
|
|
232
228
|
result = await self._channel.__aexit__(_exc_type, _exc_val, _exc_tb)
|
|
233
229
|
self._channel = None
|
|
234
230
|
self._stub = None
|
|
@@ -244,7 +240,7 @@ TransformOutT_co = TypeVar("TransformOutT_co", covariant=True)
|
|
|
244
240
|
|
|
245
241
|
@overload
|
|
246
242
|
async def call_stub_method(
|
|
247
|
-
client: BaseApiClient[StubT
|
|
243
|
+
client: BaseApiClient[StubT],
|
|
248
244
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
249
245
|
*,
|
|
250
246
|
method_name: str | None = None,
|
|
@@ -254,7 +250,7 @@ async def call_stub_method(
|
|
|
254
250
|
|
|
255
251
|
@overload
|
|
256
252
|
async def call_stub_method(
|
|
257
|
-
client: BaseApiClient[StubT
|
|
253
|
+
client: BaseApiClient[StubT],
|
|
258
254
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
259
255
|
*,
|
|
260
256
|
method_name: str | None = None,
|
|
@@ -263,7 +259,7 @@ async def call_stub_method(
|
|
|
263
259
|
|
|
264
260
|
|
|
265
261
|
async def call_stub_method(
|
|
266
|
-
client: BaseApiClient[StubT
|
|
262
|
+
client: BaseApiClient[StubT],
|
|
267
263
|
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
268
264
|
*,
|
|
269
265
|
method_name: str | None = None,
|
|
@@ -302,11 +298,9 @@ async def call_stub_method(
|
|
|
302
298
|
|
|
303
299
|
try:
|
|
304
300
|
response = await stub_method()
|
|
305
|
-
except
|
|
301
|
+
except AioRpcError as grpc_error:
|
|
306
302
|
raise ApiClientError.from_grpc_error(
|
|
307
|
-
server_url=client.server_url,
|
|
308
|
-
|
|
309
|
-
grpc_error=grpclib_error,
|
|
310
|
-
) from grpclib_error
|
|
303
|
+
server_url=client.server_url, operation=method_name, grpc_error=grpc_error
|
|
304
|
+
) from grpc_error
|
|
311
305
|
|
|
312
306
|
return response if transform is None else transform(response)
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/exception.py
RENAMED
|
@@ -7,7 +7,8 @@ from __future__ import annotations
|
|
|
7
7
|
|
|
8
8
|
from typing import Protocol
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
import grpc
|
|
11
|
+
from grpc.aio import AioRpcError
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
class ApiClientError(Exception):
|
|
@@ -61,7 +62,7 @@ class ApiClientError(Exception):
|
|
|
61
62
|
*,
|
|
62
63
|
server_url: str,
|
|
63
64
|
operation: str,
|
|
64
|
-
grpc_error:
|
|
65
|
+
grpc_error: AioRpcError,
|
|
65
66
|
) -> GrpcError:
|
|
66
67
|
"""Create an instance of the appropriate subclass from a gRPC error.
|
|
67
68
|
|
|
@@ -80,61 +81,32 @@ class ApiClientError(Exception):
|
|
|
80
81
|
"""A protocol for the constructor of a subclass of `GrpcError`."""
|
|
81
82
|
|
|
82
83
|
def __call__(
|
|
83
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
84
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
84
85
|
) -> GrpcError: ...
|
|
85
86
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return ctor(
|
|
110
|
-
server_url=server_url, operation=operation, grpc_error=grpc_error
|
|
111
|
-
)
|
|
112
|
-
elif isinstance(grpc_error, _grpchacks.GrpcioError):
|
|
113
|
-
import grpc # pylint: disable=import-outside-toplevel
|
|
114
|
-
|
|
115
|
-
grpc_status_map: dict[grpc.StatusCode, Ctor] = {
|
|
116
|
-
grpc.StatusCode.CANCELLED: OperationCancelled,
|
|
117
|
-
grpc.StatusCode.UNKNOWN: UnknownError,
|
|
118
|
-
grpc.StatusCode.INVALID_ARGUMENT: InvalidArgument,
|
|
119
|
-
grpc.StatusCode.DEADLINE_EXCEEDED: OperationTimedOut,
|
|
120
|
-
grpc.StatusCode.NOT_FOUND: EntityNotFound,
|
|
121
|
-
grpc.StatusCode.ALREADY_EXISTS: EntityAlreadyExists,
|
|
122
|
-
grpc.StatusCode.PERMISSION_DENIED: PermissionDenied,
|
|
123
|
-
grpc.StatusCode.RESOURCE_EXHAUSTED: ResourceExhausted,
|
|
124
|
-
grpc.StatusCode.FAILED_PRECONDITION: OperationPreconditionFailed,
|
|
125
|
-
grpc.StatusCode.ABORTED: OperationAborted,
|
|
126
|
-
grpc.StatusCode.OUT_OF_RANGE: OperationOutOfRange,
|
|
127
|
-
grpc.StatusCode.UNIMPLEMENTED: OperationNotImplemented,
|
|
128
|
-
grpc.StatusCode.INTERNAL: InternalError,
|
|
129
|
-
grpc.StatusCode.UNAVAILABLE: ServiceUnavailable,
|
|
130
|
-
grpc.StatusCode.DATA_LOSS: DataLoss,
|
|
131
|
-
grpc.StatusCode.UNAUTHENTICATED: OperationUnauthenticated,
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
if ctor := grpc_status_map.get(grpc_error.code()):
|
|
135
|
-
return ctor(
|
|
136
|
-
server_url=server_url, operation=operation, grpc_error=grpc_error
|
|
137
|
-
)
|
|
87
|
+
grpc_status_map: dict[grpc.StatusCode, Ctor] = {
|
|
88
|
+
grpc.StatusCode.CANCELLED: OperationCancelled,
|
|
89
|
+
grpc.StatusCode.UNKNOWN: UnknownError,
|
|
90
|
+
grpc.StatusCode.INVALID_ARGUMENT: InvalidArgument,
|
|
91
|
+
grpc.StatusCode.DEADLINE_EXCEEDED: OperationTimedOut,
|
|
92
|
+
grpc.StatusCode.NOT_FOUND: EntityNotFound,
|
|
93
|
+
grpc.StatusCode.ALREADY_EXISTS: EntityAlreadyExists,
|
|
94
|
+
grpc.StatusCode.PERMISSION_DENIED: PermissionDenied,
|
|
95
|
+
grpc.StatusCode.RESOURCE_EXHAUSTED: ResourceExhausted,
|
|
96
|
+
grpc.StatusCode.FAILED_PRECONDITION: OperationPreconditionFailed,
|
|
97
|
+
grpc.StatusCode.ABORTED: OperationAborted,
|
|
98
|
+
grpc.StatusCode.OUT_OF_RANGE: OperationOutOfRange,
|
|
99
|
+
grpc.StatusCode.UNIMPLEMENTED: OperationNotImplemented,
|
|
100
|
+
grpc.StatusCode.INTERNAL: InternalError,
|
|
101
|
+
grpc.StatusCode.UNAVAILABLE: ServiceUnavailable,
|
|
102
|
+
grpc.StatusCode.DATA_LOSS: DataLoss,
|
|
103
|
+
grpc.StatusCode.UNAUTHENTICATED: OperationUnauthenticated,
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if ctor := grpc_status_map.get(grpc_error.code()):
|
|
107
|
+
return ctor(
|
|
108
|
+
server_url=server_url, operation=operation, grpc_error=grpc_error
|
|
109
|
+
)
|
|
138
110
|
return UnrecognizedGrpcStatus(
|
|
139
111
|
server_url=server_url,
|
|
140
112
|
operation=operation,
|
|
@@ -215,7 +187,7 @@ class GrpcError(ApiClientError):
|
|
|
215
187
|
server_url: str,
|
|
216
188
|
operation: str,
|
|
217
189
|
description: str,
|
|
218
|
-
grpc_error:
|
|
190
|
+
grpc_error: AioRpcError,
|
|
219
191
|
retryable: bool,
|
|
220
192
|
) -> None:
|
|
221
193
|
"""Create a new instance.
|
|
@@ -224,24 +196,12 @@ class GrpcError(ApiClientError):
|
|
|
224
196
|
server_url: The URL of the server that returned the error.
|
|
225
197
|
operation: The operation that caused the error.
|
|
226
198
|
description: A human-readable description of the error.
|
|
227
|
-
grpc_error: The gRPC error originating this exception.
|
|
228
|
-
a `grpclib.GRPCError` or a `grpc.aio.AioRpcError` depending on which
|
|
229
|
-
library is used.
|
|
199
|
+
grpc_error: The gRPC error originating this exception.
|
|
230
200
|
retryable: Whether retrying the operation might succeed.
|
|
231
201
|
"""
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
details = grpc_error.debug_error_string()
|
|
236
|
-
elif isinstance(grpc_error, _grpchacks.GrpclibError):
|
|
237
|
-
status_name = grpc_error.status.name
|
|
238
|
-
message = grpc_error.message
|
|
239
|
-
details = grpc_error.details
|
|
240
|
-
else:
|
|
241
|
-
assert False, (
|
|
242
|
-
"GrpcError should only be instantiated with a gRPC error: "
|
|
243
|
-
"grpclib.GRPCError or grpc.aio.AioRpcError"
|
|
244
|
-
)
|
|
202
|
+
status_name = grpc_error.code().name
|
|
203
|
+
message = grpc_error.details()
|
|
204
|
+
details = grpc_error.debug_error_string()
|
|
245
205
|
message = f": {message}" if message else ""
|
|
246
206
|
details = f" ({details})" if details else ""
|
|
247
207
|
super().__init__(
|
|
@@ -250,48 +210,18 @@ class GrpcError(ApiClientError):
|
|
|
250
210
|
description=f"{description} <status={status_name}>{message}{details}",
|
|
251
211
|
retryable=retryable,
|
|
252
212
|
)
|
|
253
|
-
self.description = description
|
|
213
|
+
self.description: str = description
|
|
254
214
|
"""The human-readable description of the error."""
|
|
255
215
|
|
|
256
|
-
self.grpc_error = grpc_error
|
|
257
|
-
"""The original gRPC error.
|
|
258
|
-
|
|
259
|
-
This is either a `grpclib.GRPCError` or a `grpc.aio.AioRpcError` depending on
|
|
260
|
-
which library is used. We can't type this correctly if we want this library to
|
|
261
|
-
work when only one of the libraries is installed.
|
|
262
|
-
|
|
263
|
-
Tip:
|
|
264
|
-
If you need to get this error for a particular library, use the appropriate
|
|
265
|
-
property:
|
|
266
|
-
|
|
267
|
-
- [grpclib_error][frequenz.client.base.exception.GrpcError.grpclib_error]
|
|
268
|
-
for `grpclib.GRPCError`
|
|
269
|
-
- [grpcio_error][frequenz.client.base.exception.GrpcError.grpcio_error] for
|
|
270
|
-
`grpc.aio.AioRpcError`
|
|
271
|
-
"""
|
|
272
|
-
|
|
273
|
-
@property
|
|
274
|
-
def grpclib_error(self) -> _grpchacks.GrpclibError:
|
|
275
|
-
"""The original `grpclib.GRPCError`."""
|
|
276
|
-
assert isinstance(
|
|
277
|
-
self.grpc_error, _grpchacks.GrpclibError
|
|
278
|
-
), "This property is only available when using the grpclib library"
|
|
279
|
-
return self.grpc_error
|
|
280
|
-
|
|
281
|
-
@property
|
|
282
|
-
def grpcio_error(self) -> _grpchacks.GrpcioError:
|
|
283
|
-
"""The original `grpc.aio.AioRpcError`."""
|
|
284
|
-
assert isinstance(
|
|
285
|
-
self.grpc_error, _grpchacks.GrpcioError
|
|
286
|
-
), "This property is only available when using the grpcio library"
|
|
287
|
-
return self.grpc_error
|
|
216
|
+
self.grpc_error: AioRpcError = grpc_error
|
|
217
|
+
"""The original gRPC error."""
|
|
288
218
|
|
|
289
219
|
|
|
290
220
|
class UnrecognizedGrpcStatus(GrpcError):
|
|
291
221
|
"""The gRPC server returned an unrecognized status code."""
|
|
292
222
|
|
|
293
223
|
def __init__(
|
|
294
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
224
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
295
225
|
) -> None:
|
|
296
226
|
"""Create a new instance.
|
|
297
227
|
|
|
@@ -313,7 +243,7 @@ class OperationCancelled(GrpcError):
|
|
|
313
243
|
"""The operation was cancelled."""
|
|
314
244
|
|
|
315
245
|
def __init__(
|
|
316
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
246
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
317
247
|
) -> None:
|
|
318
248
|
"""Create a new instance.
|
|
319
249
|
|
|
@@ -335,7 +265,7 @@ class UnknownError(GrpcError):
|
|
|
335
265
|
"""There was an error that can't be described using other statuses."""
|
|
336
266
|
|
|
337
267
|
def __init__(
|
|
338
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
268
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
339
269
|
) -> None:
|
|
340
270
|
"""Create a new instance.
|
|
341
271
|
|
|
@@ -363,7 +293,7 @@ class InvalidArgument(GrpcError, ValueError):
|
|
|
363
293
|
"""
|
|
364
294
|
|
|
365
295
|
def __init__(
|
|
366
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
296
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
367
297
|
) -> None:
|
|
368
298
|
"""Create a new instance.
|
|
369
299
|
|
|
@@ -390,7 +320,7 @@ class OperationTimedOut(GrpcError):
|
|
|
390
320
|
"""
|
|
391
321
|
|
|
392
322
|
def __init__(
|
|
393
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
323
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
394
324
|
) -> None:
|
|
395
325
|
"""Create a new instance.
|
|
396
326
|
|
|
@@ -418,7 +348,7 @@ class EntityNotFound(GrpcError):
|
|
|
418
348
|
"""
|
|
419
349
|
|
|
420
350
|
def __init__(
|
|
421
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
351
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
422
352
|
) -> None:
|
|
423
353
|
"""Create a new instance.
|
|
424
354
|
|
|
@@ -440,7 +370,7 @@ class EntityAlreadyExists(GrpcError):
|
|
|
440
370
|
"""The entity that we attempted to create already exists."""
|
|
441
371
|
|
|
442
372
|
def __init__(
|
|
443
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
373
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
444
374
|
) -> None:
|
|
445
375
|
"""Create a new instance.
|
|
446
376
|
|
|
@@ -470,7 +400,7 @@ class PermissionDenied(GrpcError):
|
|
|
470
400
|
"""
|
|
471
401
|
|
|
472
402
|
def __init__(
|
|
473
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
403
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
474
404
|
) -> None:
|
|
475
405
|
"""Create a new instance.
|
|
476
406
|
|
|
@@ -493,7 +423,7 @@ class ResourceExhausted(GrpcError):
|
|
|
493
423
|
"""Some resource has been exhausted (for example per-user quota, disk space, etc.)."""
|
|
494
424
|
|
|
495
425
|
def __init__(
|
|
496
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
426
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
497
427
|
) -> None:
|
|
498
428
|
"""Create a new instance.
|
|
499
429
|
|
|
@@ -521,7 +451,7 @@ class OperationPreconditionFailed(GrpcError):
|
|
|
521
451
|
"""
|
|
522
452
|
|
|
523
453
|
def __init__(
|
|
524
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
454
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
525
455
|
) -> None:
|
|
526
456
|
"""Create a new instance.
|
|
527
457
|
|
|
@@ -547,7 +477,7 @@ class OperationAborted(GrpcError):
|
|
|
547
477
|
"""
|
|
548
478
|
|
|
549
479
|
def __init__(
|
|
550
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
480
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
551
481
|
) -> None:
|
|
552
482
|
"""Create a new instance.
|
|
553
483
|
|
|
@@ -578,7 +508,7 @@ class OperationOutOfRange(GrpcError):
|
|
|
578
508
|
"""
|
|
579
509
|
|
|
580
510
|
def __init__(
|
|
581
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
511
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
582
512
|
) -> None:
|
|
583
513
|
"""Create a new instance.
|
|
584
514
|
|
|
@@ -600,7 +530,7 @@ class OperationNotImplemented(GrpcError):
|
|
|
600
530
|
"""The operation is not implemented or not supported/enabled in this service."""
|
|
601
531
|
|
|
602
532
|
def __init__(
|
|
603
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
533
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
604
534
|
) -> None:
|
|
605
535
|
"""Create a new instance.
|
|
606
536
|
|
|
@@ -626,7 +556,7 @@ class InternalError(GrpcError):
|
|
|
626
556
|
"""
|
|
627
557
|
|
|
628
558
|
def __init__(
|
|
629
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
559
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
630
560
|
) -> None:
|
|
631
561
|
"""Create a new instance.
|
|
632
562
|
|
|
@@ -653,7 +583,7 @@ class ServiceUnavailable(GrpcError):
|
|
|
653
583
|
"""
|
|
654
584
|
|
|
655
585
|
def __init__(
|
|
656
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
586
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
657
587
|
) -> None:
|
|
658
588
|
"""Create a new instance.
|
|
659
589
|
|
|
@@ -675,7 +605,7 @@ class DataLoss(GrpcError):
|
|
|
675
605
|
"""Unrecoverable data loss or corruption."""
|
|
676
606
|
|
|
677
607
|
def __init__(
|
|
678
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
608
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
679
609
|
) -> None:
|
|
680
610
|
"""Create a new instance.
|
|
681
611
|
|
|
@@ -697,7 +627,7 @@ class OperationUnauthenticated(GrpcError):
|
|
|
697
627
|
"""The request does not have valid authentication credentials for the operation."""
|
|
698
628
|
|
|
699
629
|
def __init__(
|
|
700
|
-
self, *, server_url: str, operation: str, grpc_error:
|
|
630
|
+
self, *, server_url: str, operation: str, grpc_error: AioRpcError
|
|
701
631
|
) -> None:
|
|
702
632
|
"""Create a new instance.
|
|
703
633
|
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/streaming.py
RENAMED
|
@@ -8,10 +8,11 @@ import logging
|
|
|
8
8
|
from collections.abc import AsyncIterator, Callable
|
|
9
9
|
from typing import Generic, TypeVar
|
|
10
10
|
|
|
11
|
+
import grpc.aio
|
|
12
|
+
|
|
11
13
|
from frequenz import channels
|
|
12
14
|
|
|
13
15
|
from . import retry
|
|
14
|
-
from ._grpchacks import GrpcioError, GrpclibError
|
|
15
16
|
|
|
16
17
|
_logger = logging.getLogger(__name__)
|
|
17
18
|
|
|
@@ -88,7 +89,7 @@ class GrpcStreamBroadcaster(Generic[InputT, OutputT]):
|
|
|
88
89
|
call = self._stream_method()
|
|
89
90
|
async for msg in call:
|
|
90
91
|
await sender.send(self._transform(msg))
|
|
91
|
-
except
|
|
92
|
+
except grpc.aio.AioRpcError as err:
|
|
92
93
|
error = err
|
|
93
94
|
error_str = f"Error: {error}" if error else "Stream exhausted"
|
|
94
95
|
interval = self._retry_strategy.next_interval()
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1/src/frequenz_client_base.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: frequenz-client-base
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.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
|
|
@@ -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
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
frequenz-channels<2,>=v1.0.0-rc1
|
|
2
|
+
grpcio<2,>=1.54.2
|
|
2
3
|
protobuf<6,>=4.21.6
|
|
3
4
|
typing-extensions<5,>=4.5.0
|
|
4
5
|
|
|
@@ -6,55 +7,50 @@ typing-extensions<5,>=4.5.0
|
|
|
6
7
|
frequenz-client-base[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]
|
|
7
8
|
|
|
8
9
|
[dev-flake8]
|
|
9
|
-
flake8==7.1.
|
|
10
|
+
flake8==7.1.1
|
|
10
11
|
flake8-docstrings==1.7.0
|
|
11
12
|
flake8-pyproject==1.2.3
|
|
12
|
-
pydoclint==0.5.
|
|
13
|
+
pydoclint==0.5.6
|
|
13
14
|
pydocstyle==6.3.0
|
|
14
|
-
frequenz-client-base
|
|
15
|
+
frequenz-client-base
|
|
15
16
|
|
|
16
17
|
[dev-formatting]
|
|
17
|
-
black==24.
|
|
18
|
+
black==24.8.0
|
|
18
19
|
isort==5.13.2
|
|
19
20
|
|
|
20
21
|
[dev-mkdocs]
|
|
21
|
-
black==24.
|
|
22
|
-
Markdown==3.
|
|
23
|
-
mike==2.1.
|
|
22
|
+
black==24.8.0
|
|
23
|
+
Markdown==3.7
|
|
24
|
+
mike==2.1.3
|
|
24
25
|
mkdocs-gen-files==0.5.0
|
|
25
26
|
mkdocs-literate-nav==0.6.1
|
|
26
27
|
mkdocs-macros-plugin==1.0.5
|
|
27
|
-
mkdocs-material==9.5.
|
|
28
|
-
mkdocstrings[python]==0.25.
|
|
29
|
-
|
|
30
|
-
frequenz-
|
|
28
|
+
mkdocs-material==9.5.34
|
|
29
|
+
mkdocstrings[python]==0.25.2
|
|
30
|
+
mkdocstrings-python==1.10.9
|
|
31
|
+
frequenz-repo-config[lib]==0.10.0
|
|
32
|
+
frequenz-client-base
|
|
31
33
|
|
|
32
34
|
[dev-mypy]
|
|
33
|
-
mypy==1.
|
|
34
|
-
types-Markdown==3.
|
|
35
|
+
mypy==1.11.2
|
|
36
|
+
types-Markdown==3.7.0.20240822
|
|
35
37
|
types-protobuf==5.27.0.20240626
|
|
36
38
|
grpc-stubs==1.53.0.5
|
|
37
39
|
frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
|
|
38
40
|
|
|
39
41
|
[dev-noxfile]
|
|
40
42
|
nox==2024.4.15
|
|
41
|
-
frequenz-repo-config[lib]==0.
|
|
43
|
+
frequenz-repo-config[lib]==0.10.0
|
|
42
44
|
|
|
43
45
|
[dev-pylint]
|
|
44
|
-
pylint==3.2.
|
|
46
|
+
pylint==3.2.7
|
|
45
47
|
frequenz-client-base[dev-mkdocs,dev-noxfile,dev-pytest]
|
|
46
48
|
|
|
47
49
|
[dev-pytest]
|
|
48
|
-
pytest==8.
|
|
49
|
-
frequenz-repo-config[extra-lint-examples]==0.
|
|
50
|
+
pytest==8.3.2
|
|
51
|
+
frequenz-repo-config[extra-lint-examples]==0.10.0
|
|
50
52
|
pytest-mock==3.14.0
|
|
51
|
-
pytest-asyncio==0.
|
|
52
|
-
async-solipsism==0.
|
|
53
|
-
hypothesis==6.
|
|
54
|
-
frequenz-client-base
|
|
55
|
-
|
|
56
|
-
[grpcio]
|
|
57
|
-
grpcio<2,>=1.54.2
|
|
58
|
-
|
|
59
|
-
[grpclib]
|
|
60
|
-
grpclib<0.5,>=0.4.0
|
|
53
|
+
pytest-asyncio==0.24.0
|
|
54
|
+
async-solipsism==0.7
|
|
55
|
+
hypothesis==6.111.2
|
|
56
|
+
frequenz-client-base
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
# Frequenz Client Base Library Release Notes
|
|
2
|
-
|
|
3
|
-
## Summary
|
|
4
|
-
|
|
5
|
-
The main features of this release is the new base class for API clients, gRPC exception wrappers and a new utility function to call stub methods.
|
|
6
|
-
|
|
7
|
-
## Upgrading
|
|
8
|
-
|
|
9
|
-
- `channel.parse_grpc_uri()` takes an extra argument, the channel type (which can be either `grpclib.client.Channel` or `grpcio.aio.Channel`).
|
|
10
|
-
|
|
11
|
-
## New Features
|
|
12
|
-
|
|
13
|
-
- Add a `exception` module to provide client exceptions, including gRPC errors with one subclass per gRPC error status code.
|
|
14
|
-
- `channel.parse_grpc_uri()` can now be used with `grpcio` too.
|
|
15
|
-
- A new `BaseApiClient` class is introduced to provide a base class for API clients. It is strongly recommended to use this class as a base class for all API clients.
|
|
16
|
-
- A new `call_stub_method()` function to simplify calling stub methods, converting gRPC errors to `ApiClientError`s, checking if the client is connected and optionally wrapping the response.
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
# License: MIT
|
|
2
|
-
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
|
|
3
|
-
|
|
4
|
-
"""Hacks to deal with multiple grpc libraries.
|
|
5
|
-
|
|
6
|
-
This module conditionally imports symbols from the `grpclib` and `grpcio` libraries,
|
|
7
|
-
assigning them a new name.
|
|
8
|
-
|
|
9
|
-
for `grpclib`:
|
|
10
|
-
|
|
11
|
-
- `GrpclibError` for `grpclib.GRPCError`
|
|
12
|
-
- `GrpclibChannel` for `grpclib.client.Channel`
|
|
13
|
-
|
|
14
|
-
For `grpcio`:
|
|
15
|
-
|
|
16
|
-
- `GrpcioError` for `grpc.aio.AioRpcError`
|
|
17
|
-
- `GrpcioChannel` for `grpc.aio.Channel`
|
|
18
|
-
- `GrpcioSslChannelCredentials` for `grpc.ssl_channel_credentials`
|
|
19
|
-
- `grpcio_insecure_channel` for `grpc.aio.insecure_channel`
|
|
20
|
-
- `grpcio_secure_channel` for `grpc.aio.secure_channel`
|
|
21
|
-
|
|
22
|
-
If the libraries are not installed, the module defines dummy symbols with the same names
|
|
23
|
-
to avoid import errors.
|
|
24
|
-
|
|
25
|
-
This way exceptions code can be written to work with both libraries assuming both are
|
|
26
|
-
aviailable, and the correct symbols will be imported at runtime.
|
|
27
|
-
"""
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
from typing import Any, AsyncContextManager, Self
|
|
31
|
-
|
|
32
|
-
__all__ = [
|
|
33
|
-
"GrpcioChannel",
|
|
34
|
-
"GrpcioChannelCredentials",
|
|
35
|
-
"GrpcioError",
|
|
36
|
-
"GrpclibChannel",
|
|
37
|
-
"GrpclibError",
|
|
38
|
-
"grpcio_insecure_channel",
|
|
39
|
-
"grpcio_secure_channel",
|
|
40
|
-
"grpcio_ssl_channel_credentials",
|
|
41
|
-
]
|
|
42
|
-
|
|
43
|
-
try:
|
|
44
|
-
import grpclib.client
|
|
45
|
-
from grpclib import GRPCError as GrpclibError
|
|
46
|
-
from grpclib.client import Channel as GrpclibChannel
|
|
47
|
-
|
|
48
|
-
def grpclib_create_channel(host: str, port: int, ssl: bool) -> Any:
|
|
49
|
-
"""Create a channel."""
|
|
50
|
-
return grpclib.client.Channel(host=host, port=port, ssl=ssl)
|
|
51
|
-
|
|
52
|
-
except ImportError:
|
|
53
|
-
|
|
54
|
-
class GrpclibError(Exception): # type: ignore[no-redef]
|
|
55
|
-
"""A dummy class to avoid import errors.
|
|
56
|
-
|
|
57
|
-
This class will never be actually used, as it is only used for catching
|
|
58
|
-
exceptions from the grpclib library. If the grpclib library is not installed,
|
|
59
|
-
this class will never be instantiated.
|
|
60
|
-
"""
|
|
61
|
-
|
|
62
|
-
class GrpclibChannel: # type: ignore[no-redef]
|
|
63
|
-
"""A dummy class to avoid import errors.
|
|
64
|
-
|
|
65
|
-
This class will never be actually used, as it is only used for catching
|
|
66
|
-
exceptions from the grpclib library. If the grpclib library is not installed,
|
|
67
|
-
this class will never be instantiated.
|
|
68
|
-
"""
|
|
69
|
-
|
|
70
|
-
def __init__(self, target: str):
|
|
71
|
-
"""Create an instance."""
|
|
72
|
-
|
|
73
|
-
async def __aenter__(self) -> Self:
|
|
74
|
-
"""Enter a context manager."""
|
|
75
|
-
return self
|
|
76
|
-
|
|
77
|
-
async def __aexit__(
|
|
78
|
-
self,
|
|
79
|
-
_exc_type: type[BaseException] | None,
|
|
80
|
-
_exc_val: BaseException | None,
|
|
81
|
-
_exc_tb: Any | None,
|
|
82
|
-
) -> bool | None:
|
|
83
|
-
"""Exit a context manager."""
|
|
84
|
-
return None
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
try:
|
|
88
|
-
from grpc import ChannelCredentials as GrpcioChannelCredentials
|
|
89
|
-
from grpc import ssl_channel_credentials as grpcio_ssl_channel_credentials
|
|
90
|
-
from grpc.aio import AioRpcError as GrpcioError
|
|
91
|
-
from grpc.aio import Channel as GrpcioChannel
|
|
92
|
-
from grpc.aio import insecure_channel as grpcio_insecure_channel
|
|
93
|
-
from grpc.aio import secure_channel as grpcio_secure_channel
|
|
94
|
-
|
|
95
|
-
def grpcio_create_channel(
|
|
96
|
-
host: str, port: int, ssl: bool
|
|
97
|
-
) -> AsyncContextManager[Any]:
|
|
98
|
-
"""Create a channel."""
|
|
99
|
-
if not ssl:
|
|
100
|
-
return grpcio_insecure_channel(f"{host}:{port}")
|
|
101
|
-
return grpcio_secure_channel(f"{host}:{port}", grpcio_ssl_channel_credentials())
|
|
102
|
-
|
|
103
|
-
except ImportError:
|
|
104
|
-
|
|
105
|
-
class GrpcioError(Exception): # type: ignore[no-redef]
|
|
106
|
-
"""A dummy class to avoid import errors.
|
|
107
|
-
|
|
108
|
-
This class will never be actually used, as it is only used for catching
|
|
109
|
-
exceptions from the grpc library. If the grpc library is not installed,
|
|
110
|
-
this class will never be instantiated.
|
|
111
|
-
"""
|
|
112
|
-
|
|
113
|
-
class GrpcioChannel: # type: ignore[no-redef]
|
|
114
|
-
"""A dummy class to avoid import errors.
|
|
115
|
-
|
|
116
|
-
This class will never be actually used, as it is only used for catching
|
|
117
|
-
exceptions from the grpc library. If the grpc library is not installed,
|
|
118
|
-
this class will never be instantiated.
|
|
119
|
-
"""
|
|
120
|
-
|
|
121
|
-
async def __aenter__(self) -> Self:
|
|
122
|
-
"""Enter a context manager."""
|
|
123
|
-
return self
|
|
124
|
-
|
|
125
|
-
async def __aexit__(
|
|
126
|
-
self,
|
|
127
|
-
_exc_type: type[BaseException] | None,
|
|
128
|
-
_exc_val: BaseException | None,
|
|
129
|
-
_exc_tb: Any | None,
|
|
130
|
-
) -> bool | None:
|
|
131
|
-
"""Exit a context manager."""
|
|
132
|
-
return None
|
|
133
|
-
|
|
134
|
-
def grpcio_create_channel(
|
|
135
|
-
host: str, port: int, ssl: bool # pylint: disable=unused-argument
|
|
136
|
-
) -> AsyncContextManager[Any]:
|
|
137
|
-
"""Create a channel."""
|
|
138
|
-
return GrpcioChannel()
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
# License: MIT
|
|
2
|
-
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
|
|
3
|
-
|
|
4
|
-
"""Handling of gRPC channels."""
|
|
5
|
-
|
|
6
|
-
from typing import Any, AsyncContextManager, TypeVar, cast
|
|
7
|
-
from urllib.parse import parse_qs, urlparse
|
|
8
|
-
|
|
9
|
-
from . import _grpchacks
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _to_bool(value: str) -> bool:
|
|
13
|
-
value = value.lower()
|
|
14
|
-
if value in ("true", "on", "1"):
|
|
15
|
-
return True
|
|
16
|
-
if value in ("false", "off", "0"):
|
|
17
|
-
return False
|
|
18
|
-
raise ValueError(f"Invalid boolean value '{value}'")
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
ChannelT = TypeVar("ChannelT", bound=AsyncContextManager[Any])
|
|
22
|
-
"""A `grpclib` or `grpcio` channel type."""
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def parse_grpc_uri(
|
|
26
|
-
uri: str, channel_type: type[ChannelT], /, *, default_port: int = 9090
|
|
27
|
-
) -> ChannelT:
|
|
28
|
-
"""Create a grpclib client channel from a URI.
|
|
29
|
-
|
|
30
|
-
The URI must have the following format:
|
|
31
|
-
|
|
32
|
-
```
|
|
33
|
-
grpc://hostname[:port][?ssl=false]
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
A few things to consider about URI components:
|
|
37
|
-
|
|
38
|
-
- If any other components are present in the URI, a [`ValueError`][] is raised.
|
|
39
|
-
- If the port is omitted, the `default_port` is used.
|
|
40
|
-
- If a query parameter is passed many times, the last value is used.
|
|
41
|
-
- The only supported query parameter is `ssl`, which must be a boolean value and
|
|
42
|
-
defaults to `false`.
|
|
43
|
-
- Boolean query parameters can be specified with the following values
|
|
44
|
-
(case-insensitive): `true`, `1`, `on`, `false`, `0`, `off`.
|
|
45
|
-
|
|
46
|
-
Args:
|
|
47
|
-
uri: The gRPC URI specifying the connection parameters.
|
|
48
|
-
channel_type: The type of channel to create.
|
|
49
|
-
default_port: The default port number to use if the URI does not specify one.
|
|
50
|
-
|
|
51
|
-
Returns:
|
|
52
|
-
A grpclib client channel object.
|
|
53
|
-
|
|
54
|
-
Raises:
|
|
55
|
-
ValueError: If the URI is invalid or contains unexpected components.
|
|
56
|
-
"""
|
|
57
|
-
parsed_uri = urlparse(uri)
|
|
58
|
-
if parsed_uri.scheme != "grpc":
|
|
59
|
-
raise ValueError(
|
|
60
|
-
f"Invalid scheme '{parsed_uri.scheme}' in the URI, expected 'grpc'", uri
|
|
61
|
-
)
|
|
62
|
-
if not parsed_uri.hostname:
|
|
63
|
-
raise ValueError(f"Host name is missing in URI '{uri}'", uri)
|
|
64
|
-
for attr in ("path", "fragment", "params", "username", "password"):
|
|
65
|
-
if getattr(parsed_uri, attr):
|
|
66
|
-
raise ValueError(
|
|
67
|
-
f"Unexpected {attr} '{getattr(parsed_uri, attr)}' in the URI '{uri}'",
|
|
68
|
-
uri,
|
|
69
|
-
)
|
|
70
|
-
|
|
71
|
-
options = {k: v[-1] for k, v in parse_qs(parsed_uri.query).items()}
|
|
72
|
-
ssl = _to_bool(options.pop("ssl", "false"))
|
|
73
|
-
if options:
|
|
74
|
-
raise ValueError(
|
|
75
|
-
f"Unexpected query parameters {options!r} in the URI '{uri}'",
|
|
76
|
-
uri,
|
|
77
|
-
)
|
|
78
|
-
|
|
79
|
-
host = parsed_uri.hostname
|
|
80
|
-
port = parsed_uri.port or default_port
|
|
81
|
-
match channel_type:
|
|
82
|
-
case _grpchacks.GrpcioChannel:
|
|
83
|
-
return cast(ChannelT, _grpchacks.grpcio_create_channel(host, port, ssl))
|
|
84
|
-
case _grpchacks.GrpclibChannel:
|
|
85
|
-
return cast(ChannelT, _grpchacks.grpclib_create_channel(host, port, ssl))
|
|
86
|
-
assert False, "Unexpected channel type: {channel_type}"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/__init__.py
RENAMED
|
File without changes
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/conftest.py
RENAMED
|
File without changes
|
{frequenz-client-base-0.5.0 → frequenz-client-base-0.6.1}/src/frequenz/client/base/conversion.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|