fastgrpc2 0.2.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.
- fastgrpc2-0.2.0/LICENSE +21 -0
- fastgrpc2-0.2.0/PKG-INFO +110 -0
- fastgrpc2-0.2.0/README.md +80 -0
- fastgrpc2-0.2.0/fastgrpc2/__init__.py +39 -0
- fastgrpc2-0.2.0/fastgrpc2/app.py +110 -0
- fastgrpc2-0.2.0/fastgrpc2/client.py +177 -0
- fastgrpc2-0.2.0/fastgrpc2/codec.py +267 -0
- fastgrpc2-0.2.0/fastgrpc2/config.py +75 -0
- fastgrpc2-0.2.0/fastgrpc2/context.py +44 -0
- fastgrpc2-0.2.0/fastgrpc2/deadline.py +26 -0
- fastgrpc2-0.2.0/fastgrpc2/dependencies.py +31 -0
- fastgrpc2-0.2.0/fastgrpc2/errors.py +110 -0
- fastgrpc2-0.2.0/fastgrpc2/health.py +55 -0
- fastgrpc2-0.2.0/fastgrpc2/metadata.py +49 -0
- fastgrpc2-0.2.0/fastgrpc2/py.typed +0 -0
- fastgrpc2-0.2.0/fastgrpc2/security.py +81 -0
- fastgrpc2-0.2.0/fastgrpc2/service.py +212 -0
- fastgrpc2-0.2.0/fastgrpc2/testing.py +36 -0
- fastgrpc2-0.2.0/fastgrpc2.egg-info/PKG-INFO +110 -0
- fastgrpc2-0.2.0/fastgrpc2.egg-info/SOURCES.txt +23 -0
- fastgrpc2-0.2.0/fastgrpc2.egg-info/dependency_links.txt +1 -0
- fastgrpc2-0.2.0/fastgrpc2.egg-info/requires.txt +10 -0
- fastgrpc2-0.2.0/fastgrpc2.egg-info/top_level.txt +1 -0
- fastgrpc2-0.2.0/pyproject.toml +47 -0
- fastgrpc2-0.2.0/setup.cfg +4 -0
fastgrpc2-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruslan Kiradiev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
fastgrpc2-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastgrpc2
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: FastAPI-like developer experience for gRPC: pydantic-first, async, built on grpc.aio
|
|
5
|
+
Author: Ruslan Kiradiev
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: grpc,async,fastapi,pydantic,microservices,rpc
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
16
|
+
Classifier: Framework :: AsyncIO
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: pydantic>=2
|
|
21
|
+
Requires-Dist: grpcio>=1.60
|
|
22
|
+
Requires-Dist: protobuf>=4.21
|
|
23
|
+
Requires-Dist: typing-extensions>=4.0.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
27
|
+
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
28
|
+
Requires-Dist: mypy>=1.0.0; extra == "dev"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# fastgrpc2
|
|
32
|
+
|
|
33
|
+
FastAPI-подобная эргономика для gRPC. Pydantic на входе и выходе, вся механика
|
|
34
|
+
`grpc.aio` — внутри. Сестра [fastkafka2](../fastkafka2): тот же стиль `App` /
|
|
35
|
+
группа / декораторы / lifespan, но для gRPC.
|
|
36
|
+
|
|
37
|
+
Стек — чистый Python на `grpc.aio` (C-ядро gRPC + upb + pydantic-core). Это
|
|
38
|
+
тонкий эргономичный слой, не новый транспорт: потолок = `grpc.aio`, цена —
|
|
39
|
+
FastAPI-стиль, а не скорость компилируемых языков.
|
|
40
|
+
|
|
41
|
+
## Пример
|
|
42
|
+
|
|
43
|
+
Сервер:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from pydantic import BaseModel
|
|
47
|
+
from fastgrpc2 import GrpcApp, GrpcService, Context, Depends, GrpcError, StatusCode
|
|
48
|
+
|
|
49
|
+
class GetOrderRequest(BaseModel):
|
|
50
|
+
order_number: str
|
|
51
|
+
|
|
52
|
+
class OrderReply(BaseModel):
|
|
53
|
+
order_number: str
|
|
54
|
+
status: str
|
|
55
|
+
|
|
56
|
+
service = GrpcService("Orders")
|
|
57
|
+
|
|
58
|
+
@service.unary("GetOrder")
|
|
59
|
+
async def get_order(request: GetOrderRequest, ctx: Context) -> OrderReply:
|
|
60
|
+
if not request.order_number:
|
|
61
|
+
raise GrpcError(StatusCode.INVALID_ARGUMENT, "order_number required")
|
|
62
|
+
return OrderReply(order_number=request.order_number, status="paid")
|
|
63
|
+
|
|
64
|
+
app = GrpcApp("orders", address="0.0.0.0:50051")
|
|
65
|
+
app.add_service(service)
|
|
66
|
+
# await app.run()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Клиент:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from fastgrpc2 import GrpcClient, Channel
|
|
73
|
+
|
|
74
|
+
class OrderClient(GrpcClient):
|
|
75
|
+
service = "Orders"
|
|
76
|
+
get_order = GrpcClient.unary("GetOrder", GetOrderRequest, OrderReply)
|
|
77
|
+
|
|
78
|
+
async with Channel("127.0.0.1:50051", default_timeout=5.0) as ch:
|
|
79
|
+
client = OrderClient(ch)
|
|
80
|
+
reply = await client.get_order(GetOrderRequest(order_number="A-100"))
|
|
81
|
+
print(reply.status) # -> "paid"
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Статус (v0.2) — v1-скоуп закрыт, всё проверено прогоном
|
|
85
|
+
|
|
86
|
+
- **4 типа вызовов**: `@service.unary` / `unary_stream` / `stream_unary` / `stream_stream`.
|
|
87
|
+
- **codec pydantic↔protobuf**: динамические дескрипторы; `bool/int/float/str/bytes`,
|
|
88
|
+
вложенные `BaseModel`, `list[...]`, `Optional[...]` (с proto3-presence). Не
|
|
89
|
+
поддержанное (enum/dict/datetime/Union) — явный `TypeError`, не заглушка.
|
|
90
|
+
- **`export_proto()`** — .proto-контракт из моделей.
|
|
91
|
+
- **Context**: metadata, deadline (`time_remaining`), trailing-metadata, peer.
|
|
92
|
+
- **Metadata** multimap; **GrpcError + StatusCode** + rich-детали (`BadRequest`/
|
|
93
|
+
`ErrorInfo`, через `grpc-status-details-bin`).
|
|
94
|
+
- **Клиент**: `Channel` (переиспользуемый) + типизированный `GrpcClient`,
|
|
95
|
+
per-call `timeout`/`metadata`.
|
|
96
|
+
- **Безопасность**: `TLS` / `MTLS` / `Insecure` / `BearerToken`.
|
|
97
|
+
- **Интерсепторы** (pre-hook auth/логирование), **`Depends` + `dependency_overrides`**.
|
|
98
|
+
- **Lifespan**, **graceful `stop(grace)`**, **`run()`**.
|
|
99
|
+
- **`enable_health()`** (grpc.health.v1), **`TestClient`** (in-process).
|
|
100
|
+
- **Ручки**: `Compression`, `max_send_bytes`/`max_recv_bytes`, `RetryPolicy`,
|
|
101
|
+
`Keepalive`; **deadline-propagation** по цепочке.
|
|
102
|
+
|
|
103
|
+
Проверочные прогоны (из корня пакета): `smoke_test.py` (вызовы/presence/rich-errors),
|
|
104
|
+
`features_test.py` (TestClient/health/bearer/overrides), `tls_test.py` (mTLS),
|
|
105
|
+
`config_test.py` (compression/size/interceptor/deadline), `bench.py` (клей-налог
|
|
106
|
+
над голым grpc.aio — единицы %).
|
|
107
|
+
|
|
108
|
+
Later (не v1): write()/done_writing() для bidi-клиента, server reflection, OTel,
|
|
109
|
+
Connect/gRPC-Web, отмена-propagation, полный набор 10 google.rpc деталей с
|
|
110
|
+
google-namespace type_url.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# fastgrpc2
|
|
2
|
+
|
|
3
|
+
FastAPI-подобная эргономика для gRPC. Pydantic на входе и выходе, вся механика
|
|
4
|
+
`grpc.aio` — внутри. Сестра [fastkafka2](../fastkafka2): тот же стиль `App` /
|
|
5
|
+
группа / декораторы / lifespan, но для gRPC.
|
|
6
|
+
|
|
7
|
+
Стек — чистый Python на `grpc.aio` (C-ядро gRPC + upb + pydantic-core). Это
|
|
8
|
+
тонкий эргономичный слой, не новый транспорт: потолок = `grpc.aio`, цена —
|
|
9
|
+
FastAPI-стиль, а не скорость компилируемых языков.
|
|
10
|
+
|
|
11
|
+
## Пример
|
|
12
|
+
|
|
13
|
+
Сервер:
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from pydantic import BaseModel
|
|
17
|
+
from fastgrpc2 import GrpcApp, GrpcService, Context, Depends, GrpcError, StatusCode
|
|
18
|
+
|
|
19
|
+
class GetOrderRequest(BaseModel):
|
|
20
|
+
order_number: str
|
|
21
|
+
|
|
22
|
+
class OrderReply(BaseModel):
|
|
23
|
+
order_number: str
|
|
24
|
+
status: str
|
|
25
|
+
|
|
26
|
+
service = GrpcService("Orders")
|
|
27
|
+
|
|
28
|
+
@service.unary("GetOrder")
|
|
29
|
+
async def get_order(request: GetOrderRequest, ctx: Context) -> OrderReply:
|
|
30
|
+
if not request.order_number:
|
|
31
|
+
raise GrpcError(StatusCode.INVALID_ARGUMENT, "order_number required")
|
|
32
|
+
return OrderReply(order_number=request.order_number, status="paid")
|
|
33
|
+
|
|
34
|
+
app = GrpcApp("orders", address="0.0.0.0:50051")
|
|
35
|
+
app.add_service(service)
|
|
36
|
+
# await app.run()
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Клиент:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from fastgrpc2 import GrpcClient, Channel
|
|
43
|
+
|
|
44
|
+
class OrderClient(GrpcClient):
|
|
45
|
+
service = "Orders"
|
|
46
|
+
get_order = GrpcClient.unary("GetOrder", GetOrderRequest, OrderReply)
|
|
47
|
+
|
|
48
|
+
async with Channel("127.0.0.1:50051", default_timeout=5.0) as ch:
|
|
49
|
+
client = OrderClient(ch)
|
|
50
|
+
reply = await client.get_order(GetOrderRequest(order_number="A-100"))
|
|
51
|
+
print(reply.status) # -> "paid"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Статус (v0.2) — v1-скоуп закрыт, всё проверено прогоном
|
|
55
|
+
|
|
56
|
+
- **4 типа вызовов**: `@service.unary` / `unary_stream` / `stream_unary` / `stream_stream`.
|
|
57
|
+
- **codec pydantic↔protobuf**: динамические дескрипторы; `bool/int/float/str/bytes`,
|
|
58
|
+
вложенные `BaseModel`, `list[...]`, `Optional[...]` (с proto3-presence). Не
|
|
59
|
+
поддержанное (enum/dict/datetime/Union) — явный `TypeError`, не заглушка.
|
|
60
|
+
- **`export_proto()`** — .proto-контракт из моделей.
|
|
61
|
+
- **Context**: metadata, deadline (`time_remaining`), trailing-metadata, peer.
|
|
62
|
+
- **Metadata** multimap; **GrpcError + StatusCode** + rich-детали (`BadRequest`/
|
|
63
|
+
`ErrorInfo`, через `grpc-status-details-bin`).
|
|
64
|
+
- **Клиент**: `Channel` (переиспользуемый) + типизированный `GrpcClient`,
|
|
65
|
+
per-call `timeout`/`metadata`.
|
|
66
|
+
- **Безопасность**: `TLS` / `MTLS` / `Insecure` / `BearerToken`.
|
|
67
|
+
- **Интерсепторы** (pre-hook auth/логирование), **`Depends` + `dependency_overrides`**.
|
|
68
|
+
- **Lifespan**, **graceful `stop(grace)`**, **`run()`**.
|
|
69
|
+
- **`enable_health()`** (grpc.health.v1), **`TestClient`** (in-process).
|
|
70
|
+
- **Ручки**: `Compression`, `max_send_bytes`/`max_recv_bytes`, `RetryPolicy`,
|
|
71
|
+
`Keepalive`; **deadline-propagation** по цепочке.
|
|
72
|
+
|
|
73
|
+
Проверочные прогоны (из корня пакета): `smoke_test.py` (вызовы/presence/rich-errors),
|
|
74
|
+
`features_test.py` (TestClient/health/bearer/overrides), `tls_test.py` (mTLS),
|
|
75
|
+
`config_test.py` (compression/size/interceptor/deadline), `bench.py` (клей-налог
|
|
76
|
+
над голым grpc.aio — единицы %).
|
|
77
|
+
|
|
78
|
+
Later (не v1): write()/done_writing() для bidi-клиента, server reflection, OTel,
|
|
79
|
+
Connect/gRPC-Web, отмена-propagation, полный набор 10 google.rpc деталей с
|
|
80
|
+
google-namespace type_url.
|
|
@@ -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"
|
|
@@ -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"]
|
|
@@ -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"]
|