frequenz-client-base 0.3.0__tar.gz → 0.5.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.
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/PKG-INFO +3 -1
- frequenz-client-base-0.5.0/RELEASE_NOTES.md +16 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/pyproject.toml +30 -27
- frequenz-client-base-0.5.0/src/frequenz/client/base/_grpchacks.py +138 -0
- frequenz-client-base-0.5.0/src/frequenz/client/base/channel.py +86 -0
- frequenz-client-base-0.5.0/src/frequenz/client/base/client.py +312 -0
- frequenz-client-base-0.5.0/src/frequenz/client/base/exception.py +716 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/streaming.py +22 -21
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz_client_base.egg-info/PKG-INFO +3 -1
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz_client_base.egg-info/SOURCES.txt +4 -0
- frequenz-client-base-0.5.0/src/frequenz_client_base.egg-info/requires.txt +60 -0
- frequenz-client-base-0.3.0/RELEASE_NOTES.md +0 -10
- frequenz-client-base-0.3.0/src/frequenz_client_base.egg-info/requires.txt +0 -52
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/LICENSE +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/MANIFEST.in +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/README.md +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/setup.cfg +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/__init__.py +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/conftest.py +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/conversion.py +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/py.typed +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz/client/base/retry.py +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.0}/src/frequenz_client_base.egg-info/dependency_links.txt +0 -0
- {frequenz-client-base-0.3.0 → frequenz-client-base-0.5.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.
|
|
3
|
+
Version: 0.5.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,6 +19,8 @@ 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
|
|
22
24
|
Provides-Extra: dev-flake8
|
|
23
25
|
Provides-Extra: dev-formatting
|
|
24
26
|
Provides-Extra: dev-mkdocs
|
|
@@ -0,0 +1,16 @@
|
|
|
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.
|
|
@@ -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.
|
|
8
|
+
"frequenz-repo-config[lib] == 0.9.2",
|
|
9
9
|
]
|
|
10
10
|
build-backend = "setuptools.build_meta"
|
|
11
11
|
|
|
@@ -15,7 +15,6 @@ description = "Utilities for writing Frequenz API clients"
|
|
|
15
15
|
readme = "README.md"
|
|
16
16
|
license = { text = "MIT" }
|
|
17
17
|
keywords = ["frequenz", "python", "lib", "library", "client-base"]
|
|
18
|
-
# TODO(cookiecutter): Remove and add more classifiers if appropriate
|
|
19
18
|
classifiers = [
|
|
20
19
|
"Development Status :: 3 - Alpha",
|
|
21
20
|
"Intended Audience :: Developers",
|
|
@@ -26,11 +25,9 @@ classifiers = [
|
|
|
26
25
|
"Typing :: Typed",
|
|
27
26
|
]
|
|
28
27
|
requires-python = ">= 3.11, < 4"
|
|
29
|
-
# TODO(cookiecutter): Remove and add more dependencies if appropriate
|
|
30
28
|
dependencies = [
|
|
31
29
|
"frequenz-channels >= v1.0.0-rc1, < 2",
|
|
32
|
-
"
|
|
33
|
-
"protobuf >= 4.21.6, < 5",
|
|
30
|
+
"protobuf >= 4.21.6, < 6",
|
|
34
31
|
"typing-extensions >= 4.5.0, < 5",
|
|
35
32
|
]
|
|
36
33
|
dynamic = ["version"]
|
|
@@ -39,48 +36,52 @@ dynamic = ["version"]
|
|
|
39
36
|
name = "Frequenz Energy-as-a-Service GmbH"
|
|
40
37
|
email = "floss@frequenz.com"
|
|
41
38
|
|
|
42
|
-
# TODO(cookiecutter): Remove and add more optional dependencies if appropriate
|
|
43
39
|
[project.optional-dependencies]
|
|
40
|
+
grpcio = ["grpcio >= 1.54.2, < 2"]
|
|
41
|
+
grpclib = ["grpclib >= 0.4.0, < 0.5"]
|
|
44
42
|
dev-flake8 = [
|
|
45
|
-
"flake8 == 7.
|
|
43
|
+
"flake8 == 7.1.0",
|
|
46
44
|
"flake8-docstrings == 1.7.0",
|
|
47
|
-
"flake8-pyproject == 1.2.3",
|
|
48
|
-
"pydoclint == 0.
|
|
45
|
+
"flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
|
|
46
|
+
"pydoclint == 0.5.3",
|
|
49
47
|
"pydocstyle == 6.3.0",
|
|
48
|
+
"frequenz-client-base[grpclib,grpcio]",
|
|
50
49
|
]
|
|
51
|
-
dev-formatting = ["black == 24.2
|
|
50
|
+
dev-formatting = ["black == 24.4.2", "isort == 5.13.2"]
|
|
52
51
|
dev-mkdocs = [
|
|
53
|
-
"black == 24.2
|
|
54
|
-
"Markdown==3.
|
|
55
|
-
"mike == 2.
|
|
52
|
+
"black == 24.4.2",
|
|
53
|
+
"Markdown==3.6",
|
|
54
|
+
"mike == 2.1.2",
|
|
56
55
|
"mkdocs-gen-files == 0.5.0",
|
|
57
56
|
"mkdocs-literate-nav == 0.6.1",
|
|
58
57
|
"mkdocs-macros-plugin == 1.0.5",
|
|
59
|
-
"mkdocs-material == 9.5.
|
|
60
|
-
"mkdocstrings[python] == 0.
|
|
61
|
-
"frequenz-repo-config[lib] == 0.9.
|
|
58
|
+
"mkdocs-material == 9.5.27",
|
|
59
|
+
"mkdocstrings[python] == 0.25.1",
|
|
60
|
+
"frequenz-repo-config[lib] == 0.9.2",
|
|
61
|
+
"frequenz-client-base[grpclib,grpcio]",
|
|
62
62
|
]
|
|
63
63
|
dev-mypy = [
|
|
64
|
-
"mypy == 1.
|
|
65
|
-
"types-Markdown == 3.
|
|
66
|
-
"types-protobuf ==
|
|
64
|
+
"mypy == 1.10.1",
|
|
65
|
+
"types-Markdown == 3.6.0.20240316",
|
|
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 ==
|
|
71
|
+
dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.9.2"]
|
|
72
72
|
dev-pylint = [
|
|
73
|
-
"pylint == 3.
|
|
73
|
+
"pylint == 3.2.5",
|
|
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.9.
|
|
80
|
-
"pytest-mock == 3.
|
|
81
|
-
"pytest-asyncio == 0.23.
|
|
82
|
-
"async-solipsism == 0.
|
|
83
|
-
"hypothesis == 6.
|
|
78
|
+
"pytest == 8.2.2",
|
|
79
|
+
"frequenz-repo-config[extra-lint-examples] == 0.9.2",
|
|
80
|
+
"pytest-mock == 3.14.0",
|
|
81
|
+
"pytest-asyncio == 0.23.7",
|
|
82
|
+
"async-solipsism == 0.6",
|
|
83
|
+
"hypothesis == 6.104.2",
|
|
84
|
+
"frequenz-client-base[grpclib,grpcio]",
|
|
84
85
|
]
|
|
85
86
|
dev = [
|
|
86
87
|
"frequenz-client-base[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]",
|
|
@@ -141,6 +142,8 @@ disable = [
|
|
|
141
142
|
"line-too-long",
|
|
142
143
|
"unused-variable",
|
|
143
144
|
"unnecessary-lambda-assignment",
|
|
145
|
+
# Checked by mypy
|
|
146
|
+
"no-member",
|
|
144
147
|
]
|
|
145
148
|
|
|
146
149
|
[tool.pytest.ini_options]
|
|
@@ -0,0 +1,138 @@
|
|
|
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()
|
|
@@ -0,0 +1,86 @@
|
|
|
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}"
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
# License: MIT
|
|
2
|
+
# Copyright © 2024 Frequenz Energy-as-a-Service GmbH
|
|
3
|
+
|
|
4
|
+
"""Base class for API clients."""
|
|
5
|
+
|
|
6
|
+
import abc
|
|
7
|
+
import inspect
|
|
8
|
+
from collections.abc import Awaitable, Callable
|
|
9
|
+
from typing import Any, Generic, Self, TypeVar, overload
|
|
10
|
+
|
|
11
|
+
from . import _grpchacks
|
|
12
|
+
from .channel import ChannelT, parse_grpc_uri
|
|
13
|
+
from .exception import ApiClientError, ClientNotConnected
|
|
14
|
+
|
|
15
|
+
StubT = TypeVar("StubT")
|
|
16
|
+
"""The type of the gRPC stub."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BaseApiClient(abc.ABC, Generic[StubT, ChannelT]):
|
|
20
|
+
"""A base class for API clients.
|
|
21
|
+
|
|
22
|
+
This class provides a common interface for API clients that communicate with a API
|
|
23
|
+
server. It is designed to be subclassed by specific API clients that provide a more
|
|
24
|
+
specific interface.
|
|
25
|
+
|
|
26
|
+
Some extra tools are provided to make it easier to write API clients:
|
|
27
|
+
|
|
28
|
+
- [call_stub_method()][frequenz.client.base.client.call_stub_method] is a function
|
|
29
|
+
that calls a gRPC stub method and translates errors to API client errors.
|
|
30
|
+
- [GrpcStreamBroadcaster][frequenz.client.base.streaming.GrpcStreamBroadcaster] is
|
|
31
|
+
a class that helps sending messages from a gRPC stream to
|
|
32
|
+
a [Broadcast][frequenz.channels.Broadcast] channel.
|
|
33
|
+
|
|
34
|
+
Example:
|
|
35
|
+
This example illustrates how to create a simple API client that connects to a
|
|
36
|
+
gRPC server and calls a method on a stub.
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from collections.abc import AsyncIterable
|
|
40
|
+
import grpc
|
|
41
|
+
from frequenz.client.base.client import BaseApiClient, call_stub_method
|
|
42
|
+
from frequenz.client.base.streaming import GrpcStreamBroadcaster
|
|
43
|
+
from frequenz.channels import Receiver
|
|
44
|
+
|
|
45
|
+
# These classes are normally generated by protoc
|
|
46
|
+
class ExampleRequest:
|
|
47
|
+
int_value: int
|
|
48
|
+
str_value: str
|
|
49
|
+
|
|
50
|
+
class ExampleResponse:
|
|
51
|
+
float_value: float
|
|
52
|
+
|
|
53
|
+
class ExampleStub:
|
|
54
|
+
async def example_method(
|
|
55
|
+
self,
|
|
56
|
+
request: ExampleRequest # pylint: disable=unused-argument
|
|
57
|
+
) -> ExampleResponse:
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
def example_stream(self) -> AsyncIterable[ExampleResponse]:
|
|
61
|
+
...
|
|
62
|
+
# End of generated classes
|
|
63
|
+
|
|
64
|
+
class ExampleResponseWrapper:
|
|
65
|
+
def __init__(self, response: ExampleResponse):
|
|
66
|
+
self.transformed_value = f"{response.float_value:.2f}"
|
|
67
|
+
|
|
68
|
+
class MyApiClient(BaseApiClient[ExampleStub, grpc.Channel]):
|
|
69
|
+
def __init__(self, server_url: str, *, connect: bool = True):
|
|
70
|
+
super().__init__(
|
|
71
|
+
server_url, ExampleStub, grpc.Channel, connect=connect
|
|
72
|
+
)
|
|
73
|
+
self._broadcaster = GrpcStreamBroadcaster(
|
|
74
|
+
"stream",
|
|
75
|
+
lambda: self.stub.example_stream(ExampleRequest()),
|
|
76
|
+
ExampleResponseWrapper,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
async def example_method(
|
|
80
|
+
self, int_value: int, str_value: str
|
|
81
|
+
) -> ExampleResponseWrapper:
|
|
82
|
+
return await call_stub_method(
|
|
83
|
+
self,
|
|
84
|
+
lambda: self.stub.example_method(
|
|
85
|
+
ExampleRequest(int_value=int_value, str_value=str_value)
|
|
86
|
+
),
|
|
87
|
+
transform=ExampleResponseWrapper,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def example_stream(self) -> Receiver[ExampleResponseWrapper]:
|
|
91
|
+
return self._broadcaster.new_receiver()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def main():
|
|
95
|
+
client = MyApiClient("grpc://localhost")
|
|
96
|
+
response = await client.example_method(42, "hello")
|
|
97
|
+
print(response.transformed_value)
|
|
98
|
+
count = 0
|
|
99
|
+
async for response in client.example_stream():
|
|
100
|
+
print(response.transformed_value)
|
|
101
|
+
count += 1
|
|
102
|
+
if count >= 5:
|
|
103
|
+
break
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
!!! Note
|
|
107
|
+
* This example uses `grpcio` as the underlaying gRPC library, but `grpclib`
|
|
108
|
+
can be used as well.
|
|
109
|
+
* In this case a very simple `GrpcStreamBroadcaster` is used, asuming that
|
|
110
|
+
each call to `example_stream` will stream the same data. If the request
|
|
111
|
+
is more complex, you will probably need to have some kind of map from
|
|
112
|
+
a key based on the stream method request parameters to broadcaster
|
|
113
|
+
instances.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
server_url: str,
|
|
119
|
+
create_stub: Callable[[ChannelT], StubT],
|
|
120
|
+
channel_type: type[ChannelT],
|
|
121
|
+
*,
|
|
122
|
+
connect: bool = True,
|
|
123
|
+
) -> None:
|
|
124
|
+
"""Create an instance and connect to the server.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
server_url: The URL of the server to connect to.
|
|
128
|
+
create_stub: A function that creates a stub from a channel.
|
|
129
|
+
channel_type: The type of channel to use.
|
|
130
|
+
connect: Whether to connect to the server as soon as a client instance is
|
|
131
|
+
created. If `False`, the client will not connect to the server until
|
|
132
|
+
[connect()][frequenz.client.base.client.BaseApiClient.connect] is
|
|
133
|
+
called.
|
|
134
|
+
"""
|
|
135
|
+
self._server_url: str = server_url
|
|
136
|
+
self._create_stub: Callable[[ChannelT], StubT] = create_stub
|
|
137
|
+
self._channel_type: type[ChannelT] = channel_type
|
|
138
|
+
self._channel: ChannelT | None = None
|
|
139
|
+
self._stub: StubT | None = None
|
|
140
|
+
if connect:
|
|
141
|
+
self.connect(server_url)
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def server_url(self) -> str:
|
|
145
|
+
"""The URL of the server."""
|
|
146
|
+
return self._server_url
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def channel(self) -> ChannelT:
|
|
150
|
+
"""The underlying gRPC channel used to communicate with the server.
|
|
151
|
+
|
|
152
|
+
Warning:
|
|
153
|
+
This channel is provided as a last resort for advanced users. It is not
|
|
154
|
+
recommended to use this property directly unless you know what you are
|
|
155
|
+
doing and you don't care about being tied to a specific gRPC library.
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
ClientNotConnected: If the client is not connected to the server.
|
|
159
|
+
"""
|
|
160
|
+
if self._channel is None:
|
|
161
|
+
raise ClientNotConnected(server_url=self.server_url, operation="channel")
|
|
162
|
+
return self._channel
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def stub(self) -> StubT:
|
|
166
|
+
"""The underlying gRPC stub.
|
|
167
|
+
|
|
168
|
+
Warning:
|
|
169
|
+
This stub is provided as a last resort for advanced users. It is not
|
|
170
|
+
recommended to use this property directly unless you know what you are
|
|
171
|
+
doing and you don't care about being tied to a specific gRPC library.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
ClientNotConnected: If the client is not connected to the server.
|
|
175
|
+
"""
|
|
176
|
+
if self._stub is None:
|
|
177
|
+
raise ClientNotConnected(server_url=self.server_url, operation="stub")
|
|
178
|
+
return self._stub
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def is_connected(self) -> bool:
|
|
182
|
+
"""Whether the client is connected to the server."""
|
|
183
|
+
return self._channel is not None
|
|
184
|
+
|
|
185
|
+
def connect(self, server_url: str | None = None) -> None:
|
|
186
|
+
"""Connect to the server, possibly using a new URL.
|
|
187
|
+
|
|
188
|
+
If the client is already connected and the URL is the same as the previous URL,
|
|
189
|
+
this method does nothing. If you want to force a reconnection, you can call
|
|
190
|
+
[disconnect()][frequenz.client.base.client.BaseApiClient.disconnect] first.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
server_url: The URL of the server to connect to. If not provided, the
|
|
194
|
+
previously used URL is used.
|
|
195
|
+
"""
|
|
196
|
+
if server_url is not None and server_url != self._server_url: # URL changed
|
|
197
|
+
self._server_url = server_url
|
|
198
|
+
elif self.is_connected:
|
|
199
|
+
return
|
|
200
|
+
self._channel = parse_grpc_uri(self._server_url, self._channel_type)
|
|
201
|
+
self._stub = self._create_stub(self._channel)
|
|
202
|
+
|
|
203
|
+
async def disconnect(self) -> None:
|
|
204
|
+
"""Disconnect from the server.
|
|
205
|
+
|
|
206
|
+
If the client is not connected, this method does nothing.
|
|
207
|
+
"""
|
|
208
|
+
await self.__aexit__(None, None, None)
|
|
209
|
+
|
|
210
|
+
async def __aenter__(self) -> Self:
|
|
211
|
+
"""Enter a context manager."""
|
|
212
|
+
self.connect()
|
|
213
|
+
return self
|
|
214
|
+
|
|
215
|
+
async def __aexit__(
|
|
216
|
+
self,
|
|
217
|
+
_exc_type: type[BaseException] | None,
|
|
218
|
+
_exc_val: BaseException | None,
|
|
219
|
+
_exc_tb: Any | None,
|
|
220
|
+
) -> bool | None:
|
|
221
|
+
"""Exit a context manager."""
|
|
222
|
+
if self._channel is None:
|
|
223
|
+
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
|
+
result = await self._channel.__aexit__(_exc_type, _exc_val, _exc_tb)
|
|
233
|
+
self._channel = None
|
|
234
|
+
self._stub = None
|
|
235
|
+
return result
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
StubOutT = TypeVar("StubOutT")
|
|
239
|
+
"""The type of the response from a gRPC stub method."""
|
|
240
|
+
|
|
241
|
+
TransformOutT_co = TypeVar("TransformOutT_co", covariant=True)
|
|
242
|
+
"""The type of the transformed response from a gRPC stub method."""
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
@overload
|
|
246
|
+
async def call_stub_method(
|
|
247
|
+
client: BaseApiClient[StubT, ChannelT],
|
|
248
|
+
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
249
|
+
*,
|
|
250
|
+
method_name: str | None = None,
|
|
251
|
+
transform: Callable[[StubOutT], TransformOutT_co],
|
|
252
|
+
) -> TransformOutT_co: ...
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@overload
|
|
256
|
+
async def call_stub_method(
|
|
257
|
+
client: BaseApiClient[StubT, ChannelT],
|
|
258
|
+
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
259
|
+
*,
|
|
260
|
+
method_name: str | None = None,
|
|
261
|
+
transform: None = None,
|
|
262
|
+
) -> StubOutT: ...
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
async def call_stub_method(
|
|
266
|
+
client: BaseApiClient[StubT, ChannelT],
|
|
267
|
+
stub_method: Callable[[], Awaitable[StubOutT]],
|
|
268
|
+
*,
|
|
269
|
+
method_name: str | None = None,
|
|
270
|
+
transform: Callable[[StubOutT], TransformOutT_co] | None = None,
|
|
271
|
+
) -> StubOutT | TransformOutT_co:
|
|
272
|
+
"""Call a gRPC stub method and translate errors to API client errors.
|
|
273
|
+
|
|
274
|
+
This function is a convenience wrapper around calling a gRPC stub method. It
|
|
275
|
+
translates gRPC errors to API client errors and optionally transforms the response
|
|
276
|
+
using a provided function.
|
|
277
|
+
|
|
278
|
+
This function is designed to be used with API clients that subclass
|
|
279
|
+
[BaseApiClient][frequenz.client.base.client.BaseApiClient].
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
client: The API client to use.
|
|
283
|
+
stub_method: The gRPC stub method to call.
|
|
284
|
+
method_name: The name of the method being called. If not provided, the name of
|
|
285
|
+
the calling function is used.
|
|
286
|
+
transform: A function that transforms the response from the gRPC stub method.
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
The response from the gRPC stub method, possibly transformed by the `transform`
|
|
290
|
+
function if provided.
|
|
291
|
+
|
|
292
|
+
Raises:
|
|
293
|
+
ClientNotConnected: If the client is not connected to the server.
|
|
294
|
+
GrpcError: If a gRPC error occurs.
|
|
295
|
+
"""
|
|
296
|
+
if method_name is None:
|
|
297
|
+
# Get the name of the calling function
|
|
298
|
+
method_name = inspect.stack()[1][3]
|
|
299
|
+
|
|
300
|
+
if not client.is_connected:
|
|
301
|
+
raise ClientNotConnected(server_url=client.server_url, operation=method_name)
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
response = await stub_method()
|
|
305
|
+
except (_grpchacks.GrpclibError, _grpchacks.GrpcioError) as grpclib_error:
|
|
306
|
+
raise ApiClientError.from_grpc_error(
|
|
307
|
+
server_url=client.server_url,
|
|
308
|
+
operation=method_name,
|
|
309
|
+
grpc_error=grpclib_error,
|
|
310
|
+
) from grpclib_error
|
|
311
|
+
|
|
312
|
+
return response if transform is None else transform(response)
|