|
| 1 | +# gRPC |
| 2 | + |
| 3 | +HawkAPI ships a **thin gRPC mount** that wires a `grpc.aio` server into the |
| 4 | +ASGI lifespan — so your gRPC service starts and stops with your HTTP server, |
| 5 | +shares the same process, and gets built-in observability for free. |
| 6 | + |
| 7 | +## Installation |
| 8 | + |
| 9 | +```bash |
| 10 | +pip install hawkapi[grpc] |
| 11 | +# or with uv: |
| 12 | +uv add "hawkapi[grpc]" |
| 13 | +``` |
| 14 | + |
| 15 | +## Quickstart |
| 16 | + |
| 17 | +### 1. Generate stubs |
| 18 | + |
| 19 | +```bash |
| 20 | +python -m grpc_tools.protoc \ |
| 21 | + -I proto \ |
| 22 | + --python_out=. \ |
| 23 | + --grpc_python_out=. \ |
| 24 | + proto/greeter.proto |
| 25 | +``` |
| 26 | + |
| 27 | +This produces `greeter_pb2.py` and `greeter_pb2_grpc.py`. |
| 28 | + |
| 29 | +### 2. Implement and mount the servicer |
| 30 | + |
| 31 | +```python |
| 32 | +import hawkapi |
| 33 | +from greeter_pb2_grpc import GreeterServicer, add_GreeterServicer_to_server |
| 34 | +from greeter_pb2 import HelloReply |
| 35 | + |
| 36 | +app = hawkapi.HawkAPI() |
| 37 | + |
| 38 | +class MyGreeter(GreeterServicer): |
| 39 | + async def SayHello(self, request, context): |
| 40 | + return HelloReply(message=f"Hello, {request.name}!") |
| 41 | + |
| 42 | +app.mount_grpc( |
| 43 | + MyGreeter(), |
| 44 | + add_to_server=add_GreeterServicer_to_server, |
| 45 | + port=50051, |
| 46 | +) |
| 47 | +``` |
| 48 | + |
| 49 | +That's it. When the ASGI server starts (e.g. `uvicorn`), the gRPC server |
| 50 | +starts on `:50051` automatically. |
| 51 | + |
| 52 | +## ASGI lifespan integration |
| 53 | + |
| 54 | +`mount_grpc` installs startup / shutdown hooks on the first call, so: |
| 55 | + |
| 56 | +- **startup** — `grpc.aio.server` is created, servicers are registered, port |
| 57 | + is bound, and `server.start()` is awaited. |
| 58 | +- **shutdown** — `server.stop(grace=5.0)` is awaited, draining in-flight RPCs. |
| 59 | + |
| 60 | +Use `autostart=False` if you need manual control: |
| 61 | + |
| 62 | +```python |
| 63 | +mount = app.mount_grpc( |
| 64 | + MyGreeter(), |
| 65 | + add_to_server=add_GreeterServicer_to_server, |
| 66 | + port=50051, |
| 67 | + autostart=False, |
| 68 | +) |
| 69 | + |
| 70 | +# Later: |
| 71 | +await mount.start() |
| 72 | +# ... |
| 73 | +await mount.stop(grace=10.0) |
| 74 | +``` |
| 75 | + |
| 76 | +## Accessing the HawkAPI app from a handler |
| 77 | + |
| 78 | +The built-in observability interceptor attaches two attributes to the |
| 79 | +`ServicerContext` before delegating to your handler: |
| 80 | + |
| 81 | +| Attribute | Value | |
| 82 | +|---|---| |
| 83 | +| `context.hawkapi_app` | The `HawkAPI` application instance | |
| 84 | +| `context.hawkapi_request_id` | `uuid.uuid4().hex` — 32-char hex string | |
| 85 | + |
| 86 | +```python |
| 87 | +class MyServicer(EchoServicer): |
| 88 | + async def Echo(self, request, context): |
| 89 | + app = context.hawkapi_app # HawkAPI instance |
| 90 | + rid = context.hawkapi_request_id # e.g. "a3f2..." |
| 91 | + return EchoReply(message=request.message) |
| 92 | +``` |
| 93 | + |
| 94 | +## TLS passthrough |
| 95 | + |
| 96 | +Pass a `grpc.ServerCredentials` object — HawkAPI calls |
| 97 | +`server.add_secure_port()` for you: |
| 98 | + |
| 99 | +```python |
| 100 | +import grpc |
| 101 | + |
| 102 | +credentials = grpc.ssl_server_credentials( |
| 103 | + [(open("server.key", "rb").read(), open("server.crt", "rb").read())] |
| 104 | +) |
| 105 | + |
| 106 | +app.mount_grpc( |
| 107 | + MyGreeter(), |
| 108 | + add_to_server=add_GreeterServicer_to_server, |
| 109 | + port=50051, |
| 110 | + ssl_credentials=credentials, |
| 111 | +) |
| 112 | +``` |
| 113 | + |
| 114 | +## Reflection |
| 115 | + |
| 116 | +Enable [gRPC server reflection](https://github.com/grpc/grpc/blob/master/doc/server-reflection.md) |
| 117 | +so tools like `grpcurl` can discover your services at runtime. |
| 118 | + |
| 119 | +Requires `pip install hawkapi[grpc]` (includes `grpcio-reflection`). |
| 120 | + |
| 121 | +```python |
| 122 | +from grpc_reflection.v1alpha import reflection |
| 123 | + |
| 124 | +app.mount_grpc( |
| 125 | + MyGreeter(), |
| 126 | + add_to_server=add_GreeterServicer_to_server, |
| 127 | + port=50051, |
| 128 | + reflection=True, |
| 129 | + reflection_service_names=[ |
| 130 | + "greeter.Greeter", # your service name |
| 131 | + reflection.SERVICE_NAME, # the reflection service itself |
| 132 | + ], |
| 133 | +) |
| 134 | +``` |
| 135 | + |
| 136 | +!!! note |
| 137 | + `reflection_service_names` is **required** when `reflection=True`. |
| 138 | + A `ConfigurationError` is raised with a clear message if it is omitted. |
| 139 | + |
| 140 | +## Observability |
| 141 | + |
| 142 | +### Structured logs |
| 143 | + |
| 144 | +The built-in interceptor emits two `INFO` log records per RPC to |
| 145 | +`logging.getLogger("hawkapi.grpc")`: |
| 146 | + |
| 147 | +```json |
| 148 | +{"event": "grpc.request", "method": "/greeter.Greeter/SayHello", "peer": "ipv6:[::1]:54321", "request_id": "a3f2..."} |
| 149 | +{"event": "grpc.response", "method": "/greeter.Greeter/SayHello", "code": "OK", "duration_ms": 1.234} |
| 150 | +``` |
| 151 | + |
| 152 | +### Prometheus metrics |
| 153 | + |
| 154 | +When `prometheus_client` is installed, two metrics are registered globally: |
| 155 | + |
| 156 | +| Metric | Type | Labels | |
| 157 | +|---|---|---| |
| 158 | +| `hawkapi_grpc_requests_total` | Counter | `method`, `code` | |
| 159 | +| `hawkapi_grpc_request_duration_seconds` | Histogram | `method` | |
| 160 | + |
| 161 | +Metrics are created once (idempotent) — safe to import in tests multiple times. |
| 162 | + |
| 163 | +### Disabling observability |
| 164 | + |
| 165 | +```python |
| 166 | +app.mount_grpc( |
| 167 | + MyGreeter(), |
| 168 | + add_to_server=add_GreeterServicer_to_server, |
| 169 | + observability=False, # skip the built-in interceptor entirely |
| 170 | +) |
| 171 | +``` |
| 172 | + |
| 173 | +## Multiple services on one port |
| 174 | + |
| 175 | +Call `mount_grpc` twice with the **same port** — servicers are merged onto one |
| 176 | +`grpc.aio.Server`: |
| 177 | + |
| 178 | +```python |
| 179 | +mount_a = app.mount_grpc(GreeterServicer(), add_to_server=add_GreeterServicer_to_server, port=50051) |
| 180 | +mount_b = app.mount_grpc(EchoServicer(), add_to_server=add_EchoServicer_to_server, port=50051) |
| 181 | +assert mount_a is mount_b # same server |
| 182 | +``` |
| 183 | + |
| 184 | +## Custom interceptors |
| 185 | + |
| 186 | +Pass additional `grpc.aio.ServerInterceptor` instances via `interceptors=`. |
| 187 | +The built-in observability interceptor always runs **first**: |
| 188 | + |
| 189 | +```python |
| 190 | +from my_auth import AuthInterceptor |
| 191 | + |
| 192 | +app.mount_grpc( |
| 193 | + MyGreeter(), |
| 194 | + add_to_server=add_GreeterServicer_to_server, |
| 195 | + interceptors=[AuthInterceptor()], |
| 196 | +) |
| 197 | +``` |
| 198 | + |
| 199 | +## Full signature reference |
| 200 | + |
| 201 | +```python |
| 202 | +app.mount_grpc( |
| 203 | + servicer, # your servicer object |
| 204 | + add_to_server=add_Foo_to_server, # generated registration function |
| 205 | + port=50051, # TCP port (default 50051) |
| 206 | + host="[::]", # bind address (default all interfaces) |
| 207 | + interceptors=(), # extra ServerInterceptor instances |
| 208 | + observability=True, # built-in interceptor (default on) |
| 209 | + reflection=False, # gRPC server reflection |
| 210 | + reflection_service_names=None, # required when reflection=True |
| 211 | + ssl_credentials=None, # grpc.ServerCredentials for TLS |
| 212 | + autostart=True, # start on ASGI lifespan (default on) |
| 213 | + max_workers=None, # reserved, currently unused |
| 214 | + options=(), # grpc channel options |
| 215 | +) |
| 216 | +``` |
| 217 | + |
| 218 | +Returns a `GrpcMount` with: |
| 219 | + |
| 220 | +- `.server` — the underlying `grpc.aio.Server` (available after start) |
| 221 | +- `.port` — bound port |
| 222 | +- `.start()` — async, idempotent |
| 223 | +- `.stop(grace=5.0)` — async, safe no-op if not started |
| 224 | + |
| 225 | +## Roadmap |
| 226 | + |
| 227 | +- Bi-directional streaming support (infrastructure is in place; tests cover unary + server-streaming) |
| 228 | +- Per-mount Prometheus registry (currently uses the default global registry) |
| 229 | +- Health checking protocol (`grpc.health.v1`) |
0 commit comments