fastgrpc2 0.2.0__py3-none-any.whl
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.
- fastgrpc2/__init__.py +39 -0
- fastgrpc2/app.py +110 -0
- fastgrpc2/client.py +177 -0
- fastgrpc2/codec.py +267 -0
- fastgrpc2/config.py +75 -0
- fastgrpc2/context.py +44 -0
- fastgrpc2/deadline.py +26 -0
- fastgrpc2/dependencies.py +31 -0
- fastgrpc2/errors.py +110 -0
- fastgrpc2/health.py +55 -0
- fastgrpc2/metadata.py +49 -0
- fastgrpc2/py.typed +0 -0
- fastgrpc2/security.py +81 -0
- fastgrpc2/service.py +212 -0
- fastgrpc2/testing.py +36 -0
- fastgrpc2-0.2.0.dist-info/METADATA +110 -0
- fastgrpc2-0.2.0.dist-info/RECORD +20 -0
- fastgrpc2-0.2.0.dist-info/WHEEL +5 -0
- fastgrpc2-0.2.0.dist-info/licenses/LICENSE +21 -0
- fastgrpc2-0.2.0.dist-info/top_level.txt +1 -0
fastgrpc2/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""fastgrpc2 — FastAPI-подобная эргономика для gRPC.
|
|
2
|
+
|
|
3
|
+
Pydantic на входе и выходе, вся механика grpc.aio — внутри. Юзер пишет
|
|
4
|
+
голые pydantic-модели и async-функции и не трогает grpc/_pb2/ServicerContext.
|
|
5
|
+
"""
|
|
6
|
+
from .app import GrpcApp
|
|
7
|
+
from .service import GrpcService
|
|
8
|
+
from .context import Context
|
|
9
|
+
from .dependencies import Depends
|
|
10
|
+
from .client import Channel, GrpcClient
|
|
11
|
+
from .config import Compression, Keepalive, RetryPolicy
|
|
12
|
+
from .errors import BadRequest, ErrorInfo, FieldViolation, GrpcError, StatusCode, register_detail
|
|
13
|
+
from .metadata import Metadata
|
|
14
|
+
from .security import BearerToken, Insecure, MTLS, TLS
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"GrpcApp",
|
|
18
|
+
"GrpcService",
|
|
19
|
+
"Context",
|
|
20
|
+
"Depends",
|
|
21
|
+
"Channel",
|
|
22
|
+
"GrpcClient",
|
|
23
|
+
"GrpcError",
|
|
24
|
+
"StatusCode",
|
|
25
|
+
"Metadata",
|
|
26
|
+
"TLS",
|
|
27
|
+
"MTLS",
|
|
28
|
+
"Insecure",
|
|
29
|
+
"BearerToken",
|
|
30
|
+
"ErrorInfo",
|
|
31
|
+
"BadRequest",
|
|
32
|
+
"FieldViolation",
|
|
33
|
+
"register_detail",
|
|
34
|
+
"Compression",
|
|
35
|
+
"RetryPolicy",
|
|
36
|
+
"Keepalive",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
__version__ = "0.2.0"
|
fastgrpc2/app.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""GrpcApp — приложение/сервер (аналог KafkaApp в fastkafka2, FastAPI в REST).
|
|
2
|
+
|
|
3
|
+
Сервисы, grpc.aio.server, lifespan, graceful-stop, health, интерсепторы.
|
|
4
|
+
TLS/mTLS — tls=TLS(...)/MTLS(...); по умолчанию insecure (dev).
|
|
5
|
+
Ручки: max_send_bytes/max_recv_bytes, compression, keepalive.
|
|
6
|
+
add_interceptor(fn) — pre-hook (auth/logging) перед каждым хендлером.
|
|
7
|
+
dependency_overrides — подмена Depends (тесты). export_proto() — .proto-контракт.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Awaitable, Callable
|
|
12
|
+
|
|
13
|
+
import grpc
|
|
14
|
+
import grpc.aio
|
|
15
|
+
|
|
16
|
+
from . import codec, config, security
|
|
17
|
+
from .context import Context
|
|
18
|
+
from .health import HealthService
|
|
19
|
+
from .service import GrpcService
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GrpcApp:
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
title: str = "",
|
|
26
|
+
description: str = "",
|
|
27
|
+
*,
|
|
28
|
+
address: str = "0.0.0.0:50051",
|
|
29
|
+
tls=None,
|
|
30
|
+
compression=None,
|
|
31
|
+
max_send_bytes: int | None = None,
|
|
32
|
+
max_recv_bytes: int | None = None,
|
|
33
|
+
keepalive=None,
|
|
34
|
+
lifespan: Callable[["GrpcApp"], object] | None = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
self.title = title
|
|
37
|
+
self.description = description
|
|
38
|
+
self.address = address
|
|
39
|
+
self.tls = tls
|
|
40
|
+
self.compression = compression
|
|
41
|
+
self.max_send_bytes = max_send_bytes
|
|
42
|
+
self.max_recv_bytes = max_recv_bytes
|
|
43
|
+
self.keepalive = keepalive
|
|
44
|
+
self.dependency_overrides: dict = {}
|
|
45
|
+
self.bound_port: int | None = None
|
|
46
|
+
self._interceptors: list[Callable[[Context], Awaitable[None]]] = []
|
|
47
|
+
self._lifespan_func = lifespan
|
|
48
|
+
self._lifespan_cm = None
|
|
49
|
+
self._services: list[GrpcService] = []
|
|
50
|
+
self._health: HealthService | None = None
|
|
51
|
+
self._server: grpc.aio.Server | None = None
|
|
52
|
+
|
|
53
|
+
def add_service(self, service: GrpcService) -> None:
|
|
54
|
+
self._services.append(service)
|
|
55
|
+
|
|
56
|
+
include_service = add_service # alias под доктрину include_*
|
|
57
|
+
|
|
58
|
+
def add_interceptor(self, interceptor: Callable[[Context], Awaitable[None]]) -> None:
|
|
59
|
+
"""Pre-hook перед каждым хендлером (любого типа): auth/логирование.
|
|
60
|
+
Бросает GrpcError -> отказ. Порядок = порядок добавления."""
|
|
61
|
+
self._interceptors.append(interceptor)
|
|
62
|
+
|
|
63
|
+
def enable_health(self) -> HealthService:
|
|
64
|
+
"""grpc.health.v1.Health (k8s/LB-пробы). overall=SERVING после старта."""
|
|
65
|
+
self._health = HealthService()
|
|
66
|
+
return self._health
|
|
67
|
+
|
|
68
|
+
def export_proto(self) -> str:
|
|
69
|
+
return codec.render_proto(self._services)
|
|
70
|
+
|
|
71
|
+
async def start(self) -> None:
|
|
72
|
+
if self._lifespan_func is not None:
|
|
73
|
+
self._lifespan_cm = self._lifespan_func(self)
|
|
74
|
+
await self._lifespan_cm.__aenter__()
|
|
75
|
+
|
|
76
|
+
options = config.channel_options(self.max_send_bytes, self.max_recv_bytes, None, self.keepalive) or None
|
|
77
|
+
self._server = grpc.aio.server(options=options, compression=self.compression)
|
|
78
|
+
|
|
79
|
+
interceptors = tuple(self._interceptors)
|
|
80
|
+
for svc in self._services:
|
|
81
|
+
self._server.add_generic_rpc_handlers([svc._generic_handler(self.dependency_overrides, interceptors)])
|
|
82
|
+
if self._health is not None:
|
|
83
|
+
self._server.add_generic_rpc_handlers([self._health._generic_handler()])
|
|
84
|
+
|
|
85
|
+
if security.is_secure(self.tls):
|
|
86
|
+
self.bound_port = self._server.add_secure_port(self.address, security.server_credentials(self.tls))
|
|
87
|
+
else:
|
|
88
|
+
self.bound_port = self._server.add_insecure_port(self.address)
|
|
89
|
+
|
|
90
|
+
await self._server.start()
|
|
91
|
+
if self._health is not None:
|
|
92
|
+
self._health.set_serving("")
|
|
93
|
+
|
|
94
|
+
async def stop(self, grace: float | None = None) -> None:
|
|
95
|
+
if self._server is not None:
|
|
96
|
+
await self._server.stop(grace)
|
|
97
|
+
self._server = None
|
|
98
|
+
if self._lifespan_cm is not None:
|
|
99
|
+
await self._lifespan_cm.__aexit__(None, None, None)
|
|
100
|
+
self._lifespan_cm = None
|
|
101
|
+
|
|
102
|
+
async def run(self) -> None:
|
|
103
|
+
await self.start()
|
|
104
|
+
try:
|
|
105
|
+
await self._server.wait_for_termination()
|
|
106
|
+
finally:
|
|
107
|
+
await self.stop()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
__all__ = ["GrpcApp"]
|
fastgrpc2/client.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Клиент: Channel (переиспользуемое соединение) + типизированный GrpcClient.
|
|
2
|
+
|
|
3
|
+
Все 4 типа вызова как дескрипторы-методы:
|
|
4
|
+
get_order = GrpcClient.unary("GetOrder", Req, Resp) await -> Resp
|
|
5
|
+
watch = GrpcClient.unary_stream("Watch", Req, Ev) async for ev in ...
|
|
6
|
+
upload = GrpcClient.stream_unary("Upload", Sample, Sum) await(aiter) -> Sum
|
|
7
|
+
chat = GrpcClient.stream_stream("Chat", In, Out) async for out in ...(aiter)
|
|
8
|
+
|
|
9
|
+
Канал держим один и шарим между вызовами. v0.1: insecure. TLS/mTLS, .call()
|
|
10
|
+
с доступом к metadata/трейлерам, write()/done_writing() для bidi — later.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import grpc
|
|
15
|
+
import grpc.aio
|
|
16
|
+
|
|
17
|
+
from . import codec, config, security
|
|
18
|
+
from .deadline import get_budget
|
|
19
|
+
from .errors import TRAILER_KEY, GrpcError, unpack_details
|
|
20
|
+
from .metadata import Metadata
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _to_grpc_error(e: grpc.aio.AioRpcError) -> GrpcError:
|
|
24
|
+
details: list = []
|
|
25
|
+
try:
|
|
26
|
+
for k, v in e.trailing_metadata() or ():
|
|
27
|
+
if k == TRAILER_KEY:
|
|
28
|
+
details = unpack_details(v if isinstance(v, (bytes, bytearray)) else bytes(v))
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
return GrpcError(e.code(), e.details(), details)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Channel:
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
target: str,
|
|
38
|
+
*,
|
|
39
|
+
default_timeout: float | None = None,
|
|
40
|
+
tls=None,
|
|
41
|
+
auth=None,
|
|
42
|
+
compression=None,
|
|
43
|
+
max_send_bytes: int | None = None,
|
|
44
|
+
max_recv_bytes: int | None = None,
|
|
45
|
+
retry=None,
|
|
46
|
+
keepalive=None,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.target = target
|
|
49
|
+
self.default_timeout = default_timeout
|
|
50
|
+
self.auth = auth
|
|
51
|
+
options = config.channel_options(max_send_bytes, max_recv_bytes, retry, keepalive) or None
|
|
52
|
+
if security.is_secure(tls):
|
|
53
|
+
self._channel = grpc.aio.secure_channel(
|
|
54
|
+
target, security.channel_credentials(tls), options=options, compression=compression
|
|
55
|
+
)
|
|
56
|
+
else:
|
|
57
|
+
self._channel = grpc.aio.insecure_channel(target, options=options, compression=compression)
|
|
58
|
+
|
|
59
|
+
async def close(self, grace: float | None = None) -> None:
|
|
60
|
+
await self._channel.close(grace)
|
|
61
|
+
|
|
62
|
+
async def __aenter__(self) -> "Channel":
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
async def __aexit__(self, *exc) -> None:
|
|
66
|
+
await self.close()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def _aiter_wrap(call):
|
|
70
|
+
try:
|
|
71
|
+
async for item in call:
|
|
72
|
+
yield item
|
|
73
|
+
except grpc.aio.AioRpcError as e:
|
|
74
|
+
raise _to_grpc_error(e) from e
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _Method:
|
|
78
|
+
"""Дескриптор метода клиента; kind = unary|unary_stream|stream_unary|stream_stream."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, kind: str, rpc_name: str, request_model: type, response_model: type) -> None:
|
|
81
|
+
self.kind = kind
|
|
82
|
+
self.rpc_name = rpc_name
|
|
83
|
+
self.request_model = request_model
|
|
84
|
+
self.response_model = response_model
|
|
85
|
+
|
|
86
|
+
def __set_name__(self, owner, name: str) -> None:
|
|
87
|
+
self.attr = name
|
|
88
|
+
|
|
89
|
+
def __get__(self, instance, owner):
|
|
90
|
+
if instance is None:
|
|
91
|
+
return self
|
|
92
|
+
return _Bound(instance, self)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _Bound:
|
|
96
|
+
def __init__(self, client: "GrpcClient", method: _Method) -> None:
|
|
97
|
+
self._client = client
|
|
98
|
+
self._m = method
|
|
99
|
+
|
|
100
|
+
def _make_callable(self):
|
|
101
|
+
ch = self._client._channel._channel
|
|
102
|
+
path = f"/{self._client.full_service_name}/{self._m.rpc_name}"
|
|
103
|
+
ser = codec.serializer(self._m.request_model)
|
|
104
|
+
de = codec.deserializer(self._m.response_model)
|
|
105
|
+
factory = {
|
|
106
|
+
"unary": ch.unary_unary,
|
|
107
|
+
"unary_stream": ch.unary_stream,
|
|
108
|
+
"stream_unary": ch.stream_unary,
|
|
109
|
+
"stream_stream": ch.stream_stream,
|
|
110
|
+
}[self._m.kind]
|
|
111
|
+
return factory(path, request_serializer=ser, response_deserializer=de)
|
|
112
|
+
|
|
113
|
+
def __call__(self, request, *, timeout: float | None = None, metadata=None):
|
|
114
|
+
callable_ = self._make_callable()
|
|
115
|
+
ch = self._client._channel
|
|
116
|
+
pairs: list = []
|
|
117
|
+
if ch.auth is not None:
|
|
118
|
+
pairs.extend(ch.auth.metadata())
|
|
119
|
+
if isinstance(metadata, Metadata):
|
|
120
|
+
pairs.extend(metadata.to_grpc())
|
|
121
|
+
elif metadata:
|
|
122
|
+
pairs.extend(metadata)
|
|
123
|
+
md = pairs or None
|
|
124
|
+
to = timeout
|
|
125
|
+
if to is None:
|
|
126
|
+
to = get_budget() # наследуем дедлайн-бюджет цепочки, если он есть
|
|
127
|
+
if to is None:
|
|
128
|
+
to = ch.default_timeout
|
|
129
|
+
if self._m.kind in ("unary_stream", "stream_stream"):
|
|
130
|
+
# стрим на выходе -> возвращаем async-итератор (его НЕ await-им, его итерируем)
|
|
131
|
+
return _aiter_wrap(callable_(request, timeout=to, metadata=md))
|
|
132
|
+
# одиночный ответ -> возвращаем корутину под await
|
|
133
|
+
return self._await(callable_, request, to, md)
|
|
134
|
+
|
|
135
|
+
async def _await(self, callable_, request, to, md):
|
|
136
|
+
try:
|
|
137
|
+
return await callable_(request, timeout=to, metadata=md)
|
|
138
|
+
except grpc.aio.AioRpcError as e:
|
|
139
|
+
raise _to_grpc_error(e) from e
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class GrpcClient:
|
|
143
|
+
"""Базовый типизированный клиент. Наследник задаёт service и методы:
|
|
144
|
+
|
|
145
|
+
class OrderClient(GrpcClient):
|
|
146
|
+
service = "Orders"
|
|
147
|
+
get_order = GrpcClient.unary("GetOrder", GetOrderRequest, OrderReply)
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
package: str = "fastgrpc2"
|
|
151
|
+
service: str = ""
|
|
152
|
+
|
|
153
|
+
def __init__(self, channel: Channel) -> None:
|
|
154
|
+
self._channel = channel
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def full_service_name(self) -> str:
|
|
158
|
+
return f"{self.package}.{self.service}"
|
|
159
|
+
|
|
160
|
+
@staticmethod
|
|
161
|
+
def unary(rpc_name: str, request_model: type, response_model: type) -> _Method:
|
|
162
|
+
return _Method("unary", rpc_name, request_model, response_model)
|
|
163
|
+
|
|
164
|
+
@staticmethod
|
|
165
|
+
def unary_stream(rpc_name: str, request_model: type, response_model: type) -> _Method:
|
|
166
|
+
return _Method("unary_stream", rpc_name, request_model, response_model)
|
|
167
|
+
|
|
168
|
+
@staticmethod
|
|
169
|
+
def stream_unary(rpc_name: str, request_model: type, response_model: type) -> _Method:
|
|
170
|
+
return _Method("stream_unary", rpc_name, request_model, response_model)
|
|
171
|
+
|
|
172
|
+
@staticmethod
|
|
173
|
+
def stream_stream(rpc_name: str, request_model: type, response_model: type) -> _Method:
|
|
174
|
+
return _Method("stream_stream", rpc_name, request_model, response_model)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
__all__ = ["Channel", "GrpcClient"]
|
fastgrpc2/codec.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Codec — pydantic <-> protobuf, динамические дескрипторы.
|
|
2
|
+
|
|
3
|
+
Сигнатура хендлера = контракт. По pydantic-модели на лету строим protobuf-
|
|
4
|
+
дескриптор (FileDescriptorProto -> DescriptorPool -> message class) и держим
|
|
5
|
+
его в кэше. На проводе — настоящий protobuf (интероп с любым gRPC-клиентом),
|
|
6
|
+
а юзер видит только pydantic-модель.
|
|
7
|
+
|
|
8
|
+
v0.1 поддерживает: bool/int/float/str/bytes, вложенные BaseModel, list[...],
|
|
9
|
+
Optional[...] (разворачивается в singular). Остальное (enum, dict/map, Union-
|
|
10
|
+
oneof, datetime, рекурсия) бросает явный TypeError — это later, не заглушка.
|
|
11
|
+
|
|
12
|
+
model_construct() при декоде осознанно пропускает ре-валидацию: данные пришли
|
|
13
|
+
из типобезопасного protobuf, форма уже гарантирована проводом.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import types as _types
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any, Union, get_args, get_origin
|
|
20
|
+
|
|
21
|
+
from google.protobuf import descriptor_pb2, descriptor_pool, message_factory
|
|
22
|
+
from pydantic import BaseModel
|
|
23
|
+
|
|
24
|
+
_PACKAGE = "fastgrpc2"
|
|
25
|
+
_POOL = descriptor_pool.DescriptorPool()
|
|
26
|
+
|
|
27
|
+
_FD = descriptor_pb2.FieldDescriptorProto
|
|
28
|
+
_SCALAR: dict[type, int] = {
|
|
29
|
+
bool: _FD.TYPE_BOOL, # bool раньше int — он его подтип
|
|
30
|
+
int: _FD.TYPE_INT64,
|
|
31
|
+
float: _FD.TYPE_DOUBLE,
|
|
32
|
+
str: _FD.TYPE_STRING,
|
|
33
|
+
bytes: _FD.TYPE_BYTES,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class _Field:
|
|
39
|
+
repeated: bool
|
|
40
|
+
is_message: bool
|
|
41
|
+
scalar_type: int | None = None
|
|
42
|
+
model: type | None = None
|
|
43
|
+
optional: bool = False # proto3 presence для скаляра (Optional[...] -> None различимо)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class _Registered:
|
|
48
|
+
message_class: type
|
|
49
|
+
full_name: str
|
|
50
|
+
file_name: str
|
|
51
|
+
fields: dict[str, _Field]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
_CACHE: dict[type, _Registered] = {}
|
|
55
|
+
_IN_PROGRESS: set[type] = set()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _field_of(annotation: Any) -> _Field:
|
|
59
|
+
origin = get_origin(annotation)
|
|
60
|
+
if origin in (Union, _types.UnionType):
|
|
61
|
+
non_none = [a for a in get_args(annotation) if a is not type(None)]
|
|
62
|
+
if len(non_none) == 1:
|
|
63
|
+
inner = _field_of(non_none[0]) # Optional[X] -> singular X
|
|
64
|
+
if not inner.repeated and not inner.is_message:
|
|
65
|
+
inner.optional = True # presence для скаляра через proto3 optional
|
|
66
|
+
return inner
|
|
67
|
+
raise TypeError(f"fastgrpc2 v0.1: Union/oneof пока не поддержан: {annotation!r}")
|
|
68
|
+
if origin is list:
|
|
69
|
+
(inner,) = get_args(annotation)
|
|
70
|
+
f = _field_of(inner)
|
|
71
|
+
if f.repeated:
|
|
72
|
+
raise TypeError("fastgrpc2 v0.1: вложенные списки не поддержаны")
|
|
73
|
+
return _Field(repeated=True, is_message=f.is_message, scalar_type=f.scalar_type, model=f.model)
|
|
74
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
75
|
+
return _Field(repeated=False, is_message=True, model=annotation)
|
|
76
|
+
if annotation in _SCALAR:
|
|
77
|
+
return _Field(repeated=False, is_message=False, scalar_type=_SCALAR[annotation])
|
|
78
|
+
raise TypeError(
|
|
79
|
+
f"fastgrpc2 v0.1: тип поля не поддержан: {annotation!r}. "
|
|
80
|
+
"Поддержано: bool/int/float/str/bytes, BaseModel, list[...], Optional[...]."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def register_model(model: type) -> _Registered:
|
|
85
|
+
"""Строит (и кэширует) protobuf message class для pydantic-модели."""
|
|
86
|
+
cached = _CACHE.get(model)
|
|
87
|
+
if cached is not None:
|
|
88
|
+
return cached
|
|
89
|
+
if model in _IN_PROGRESS:
|
|
90
|
+
raise TypeError(f"fastgrpc2 v0.1: рекурсивные модели не поддержаны: {model.__name__}")
|
|
91
|
+
|
|
92
|
+
_IN_PROGRESS.add(model)
|
|
93
|
+
try:
|
|
94
|
+
fields: dict[str, _Field] = {}
|
|
95
|
+
deps: list[str] = []
|
|
96
|
+
for fname, finfo in model.model_fields.items():
|
|
97
|
+
f = _field_of(finfo.annotation)
|
|
98
|
+
fields[fname] = f
|
|
99
|
+
if f.is_message:
|
|
100
|
+
child = register_model(f.model) # вложенные регистрируем первыми
|
|
101
|
+
if child.file_name not in deps:
|
|
102
|
+
deps.append(child.file_name)
|
|
103
|
+
|
|
104
|
+
name = model.__name__
|
|
105
|
+
file_name = f"{_PACKAGE}/{name}.proto"
|
|
106
|
+
full_name = f"{_PACKAGE}.{name}"
|
|
107
|
+
|
|
108
|
+
fdp = descriptor_pb2.FileDescriptorProto()
|
|
109
|
+
fdp.name = file_name
|
|
110
|
+
fdp.package = _PACKAGE
|
|
111
|
+
fdp.syntax = "proto3"
|
|
112
|
+
for d in deps:
|
|
113
|
+
fdp.dependency.append(d)
|
|
114
|
+
|
|
115
|
+
msg = fdp.message_type.add()
|
|
116
|
+
msg.name = name
|
|
117
|
+
for number, (fname, f) in enumerate(fields.items(), start=1):
|
|
118
|
+
pf = msg.field.add()
|
|
119
|
+
pf.name = fname
|
|
120
|
+
pf.number = number
|
|
121
|
+
pf.label = _FD.LABEL_REPEATED if f.repeated else _FD.LABEL_OPTIONAL
|
|
122
|
+
if f.is_message:
|
|
123
|
+
pf.type = _FD.TYPE_MESSAGE
|
|
124
|
+
pf.type_name = f".{_PACKAGE}.{f.model.__name__}"
|
|
125
|
+
else:
|
|
126
|
+
pf.type = f.scalar_type
|
|
127
|
+
if f.optional:
|
|
128
|
+
# синтетический oneof -> presence для proto3-скаляра (HasField работает)
|
|
129
|
+
oneof = msg.oneof_decl.add()
|
|
130
|
+
oneof.name = f"_{fname}"
|
|
131
|
+
pf.oneof_index = len(msg.oneof_decl) - 1
|
|
132
|
+
pf.proto3_optional = True
|
|
133
|
+
|
|
134
|
+
_POOL.Add(fdp)
|
|
135
|
+
descriptor = _POOL.FindMessageTypeByName(full_name)
|
|
136
|
+
message_class = _build_class(descriptor)
|
|
137
|
+
reg = _Registered(message_class, full_name, file_name, fields)
|
|
138
|
+
_CACHE[model] = reg
|
|
139
|
+
return reg
|
|
140
|
+
finally:
|
|
141
|
+
_IN_PROGRESS.discard(model)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _build_class(descriptor) -> type:
|
|
145
|
+
# protobuf >= 4.22
|
|
146
|
+
get_cls = getattr(message_factory, "GetMessageClass", None)
|
|
147
|
+
if get_cls is not None:
|
|
148
|
+
return get_cls(descriptor)
|
|
149
|
+
return message_factory.MessageFactory(_POOL).GetPrototype(descriptor) # legacy fallback
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def encode(instance: BaseModel, reg: _Registered | None = None):
|
|
153
|
+
if reg is None:
|
|
154
|
+
reg = register_model(type(instance))
|
|
155
|
+
msg = reg.message_class()
|
|
156
|
+
for fname, f in reg.fields.items():
|
|
157
|
+
value = getattr(instance, fname)
|
|
158
|
+
if value is None:
|
|
159
|
+
continue
|
|
160
|
+
if f.repeated:
|
|
161
|
+
target = getattr(msg, fname)
|
|
162
|
+
if f.is_message:
|
|
163
|
+
child = register_model(f.model)
|
|
164
|
+
for item in value:
|
|
165
|
+
target.add().CopyFrom(encode(item, child))
|
|
166
|
+
else:
|
|
167
|
+
target.extend(value)
|
|
168
|
+
elif f.is_message:
|
|
169
|
+
getattr(msg, fname).CopyFrom(encode(value, register_model(f.model)))
|
|
170
|
+
else:
|
|
171
|
+
setattr(msg, fname, value)
|
|
172
|
+
return msg
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def decode(msg, model: type) -> BaseModel:
|
|
176
|
+
reg = register_model(model)
|
|
177
|
+
data: dict[str, Any] = {}
|
|
178
|
+
for fname, f in reg.fields.items():
|
|
179
|
+
if f.repeated:
|
|
180
|
+
raw = getattr(msg, fname)
|
|
181
|
+
data[fname] = [decode(x, f.model) for x in raw] if f.is_message else list(raw)
|
|
182
|
+
elif f.is_message:
|
|
183
|
+
data[fname] = decode(getattr(msg, fname), f.model) if msg.HasField(fname) else None
|
|
184
|
+
elif f.optional:
|
|
185
|
+
data[fname] = getattr(msg, fname) if msg.HasField(fname) else None
|
|
186
|
+
else:
|
|
187
|
+
data[fname] = getattr(msg, fname)
|
|
188
|
+
return model.model_construct(**data)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def serializer(model: type):
|
|
192
|
+
"""obj -> bytes (request_serializer на клиенте / response_serializer на сервере)."""
|
|
193
|
+
reg = register_model(model)
|
|
194
|
+
|
|
195
|
+
def _ser(instance: BaseModel) -> bytes:
|
|
196
|
+
return encode(instance, reg).SerializeToString()
|
|
197
|
+
|
|
198
|
+
return _ser
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def deserializer(model: type):
|
|
202
|
+
"""bytes -> obj (request_deserializer на сервере / response_deserializer на клиенте)."""
|
|
203
|
+
reg = register_model(model)
|
|
204
|
+
|
|
205
|
+
def _de(data: bytes) -> BaseModel:
|
|
206
|
+
msg = reg.message_class()
|
|
207
|
+
msg.ParseFromString(data)
|
|
208
|
+
return decode(msg, model)
|
|
209
|
+
|
|
210
|
+
return _de
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
_PROTO_NAME = {
|
|
214
|
+
_FD.TYPE_BOOL: "bool",
|
|
215
|
+
_FD.TYPE_INT64: "int64",
|
|
216
|
+
_FD.TYPE_DOUBLE: "double",
|
|
217
|
+
_FD.TYPE_STRING: "string",
|
|
218
|
+
_FD.TYPE_BYTES: "bytes",
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _render_message(model: type) -> str:
|
|
223
|
+
reg = register_model(model)
|
|
224
|
+
lines = [f"message {model.__name__} {{"]
|
|
225
|
+
for number, (fname, f) in enumerate(reg.fields.items(), start=1):
|
|
226
|
+
prefix = "repeated " if f.repeated else ("optional " if f.optional else "")
|
|
227
|
+
tname = f.model.__name__ if f.is_message else _PROTO_NAME[f.scalar_type]
|
|
228
|
+
lines.append(f" {prefix}{tname} {fname} = {number};")
|
|
229
|
+
lines.append("}")
|
|
230
|
+
return "\n".join(lines)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def render_proto(services) -> str:
|
|
234
|
+
"""Собирает .proto-текст из pydantic-моделей сервисов (доктрина: сигнатура = контракт)."""
|
|
235
|
+
models: list[type] = []
|
|
236
|
+
seen: set[type] = set()
|
|
237
|
+
|
|
238
|
+
def add(model: type) -> None:
|
|
239
|
+
reg = register_model(model)
|
|
240
|
+
for f in reg.fields.values():
|
|
241
|
+
if f.is_message:
|
|
242
|
+
add(f.model)
|
|
243
|
+
if model not in seen:
|
|
244
|
+
seen.add(model)
|
|
245
|
+
models.append(model)
|
|
246
|
+
|
|
247
|
+
for svc in services:
|
|
248
|
+
for spec in svc._methods.values():
|
|
249
|
+
add(spec.request_model)
|
|
250
|
+
add(spec.response_model)
|
|
251
|
+
|
|
252
|
+
parts = ['syntax = "proto3";', "", f"package {_PACKAGE};", ""]
|
|
253
|
+
for model in models:
|
|
254
|
+
parts.append(_render_message(model))
|
|
255
|
+
parts.append("")
|
|
256
|
+
for svc in services:
|
|
257
|
+
parts.append(f"service {svc.name} {{")
|
|
258
|
+
for spec in svc._methods.values():
|
|
259
|
+
req = ("stream " if spec.input_stream else "") + spec.request_model.__name__
|
|
260
|
+
resp = ("stream " if spec.output_stream else "") + spec.response_model.__name__
|
|
261
|
+
parts.append(f" rpc {spec.rpc_name}({req}) returns ({resp});")
|
|
262
|
+
parts.append("}")
|
|
263
|
+
parts.append("")
|
|
264
|
+
return "\n".join(parts).rstrip() + "\n"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
__all__ = ["register_model", "encode", "decode", "serializer", "deserializer", "render_proto"]
|
fastgrpc2/config.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Типизированные ручки канала/сервера: сжатие, лимиты размера, ретраи, keepalive.
|
|
2
|
+
|
|
3
|
+
Скрывают сырые grpc.* опции-кортежи и service_config JSON за нормальными типами.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
import grpc
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Compression:
|
|
14
|
+
NoCompression = grpc.Compression.NoCompression
|
|
15
|
+
Gzip = grpc.Compression.Gzip
|
|
16
|
+
Deflate = grpc.Compression.Deflate
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class RetryPolicy:
|
|
21
|
+
"""Сериализуется в grpc service_config (юзер не пишет JSON руками)."""
|
|
22
|
+
max_attempts: int = 3
|
|
23
|
+
initial_backoff: str = "0.1s"
|
|
24
|
+
max_backoff: str = "1s"
|
|
25
|
+
backoff_multiplier: float = 2.0
|
|
26
|
+
retryable_status_codes: tuple[str, ...] = ("UNAVAILABLE",)
|
|
27
|
+
|
|
28
|
+
def _service_config_json(self) -> str:
|
|
29
|
+
return json.dumps(
|
|
30
|
+
{
|
|
31
|
+
"methodConfig": [
|
|
32
|
+
{
|
|
33
|
+
"name": [{}], # все методы
|
|
34
|
+
"retryPolicy": {
|
|
35
|
+
"maxAttempts": self.max_attempts,
|
|
36
|
+
"initialBackoff": self.initial_backoff,
|
|
37
|
+
"maxBackoff": self.max_backoff,
|
|
38
|
+
"backoffMultiplier": self.backoff_multiplier,
|
|
39
|
+
"retryableStatusCodes": list(self.retryable_status_codes),
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Keepalive:
|
|
49
|
+
time_ms: int = 60000
|
|
50
|
+
timeout_ms: int = 20000
|
|
51
|
+
permit_without_calls: bool = False
|
|
52
|
+
|
|
53
|
+
def _options(self) -> list[tuple[str, int]]:
|
|
54
|
+
return [
|
|
55
|
+
("grpc.keepalive_time_ms", self.time_ms),
|
|
56
|
+
("grpc.keepalive_timeout_ms", self.timeout_ms),
|
|
57
|
+
("grpc.keepalive_permit_without_calls", 1 if self.permit_without_calls else 0),
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def channel_options(max_send_bytes, max_recv_bytes, retry, keepalive) -> list[tuple]:
|
|
62
|
+
options: list[tuple] = []
|
|
63
|
+
if max_send_bytes is not None:
|
|
64
|
+
options.append(("grpc.max_send_message_length", max_send_bytes))
|
|
65
|
+
if max_recv_bytes is not None:
|
|
66
|
+
options.append(("grpc.max_receive_message_length", max_recv_bytes))
|
|
67
|
+
if keepalive is not None:
|
|
68
|
+
options.extend(keepalive._options())
|
|
69
|
+
if retry is not None:
|
|
70
|
+
options.append(("grpc.enable_retries", 1))
|
|
71
|
+
options.append(("grpc.service_config", retry._service_config_json()))
|
|
72
|
+
return options
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
__all__ = ["Compression", "RetryPolicy", "Keepalive", "channel_options"]
|