linkr 0.1.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.
Potentially problematic release.
This version of linkr might be problematic. Click here for more details.
- linkr/__init__.py +38 -0
- linkr/app.py +456 -0
- linkr/di.py +82 -0
- linkr/exceptions.py +25 -0
- linkr/middleware/__init__.py +2 -0
- linkr/middleware/base.py +57 -0
- linkr/middleware/gzip.py +41 -0
- linkr/models.py +91 -0
- linkr/py.typed +0 -0
- linkr/serializer.py +41 -0
- linkr/transports/__init__.py +85 -0
- linkr/transports/mock.py +87 -0
- linkr/transports/rmq.py +320 -0
- linkr-0.1.0.dist-info/METADATA +150 -0
- linkr-0.1.0.dist-info/RECORD +17 -0
- linkr-0.1.0.dist-info/WHEEL +4 -0
- linkr-0.1.0.dist-info/licenses/LICENSE +21 -0
linkr/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import importlib.metadata
|
|
2
|
+
|
|
3
|
+
from linkr.app import HandlerInfo, RpcApp, RpcCall
|
|
4
|
+
from linkr.di import Depends, DiContainer
|
|
5
|
+
from linkr.exceptions import RpcError
|
|
6
|
+
from linkr.middleware.base import AppMiddleware, BaseMiddleware, WireMiddleware
|
|
7
|
+
from linkr.middleware.gzip import GzipMiddleware
|
|
8
|
+
from linkr.models import RpcContext, RpcData, RpcHeaders, RpcRequest, RpcResponse
|
|
9
|
+
from linkr.serializer import JsonSerializer, Serializer
|
|
10
|
+
from linkr.transports import Transport
|
|
11
|
+
from linkr.transports.mock import MockTransport
|
|
12
|
+
from linkr.transports.rmq import RmqTransport
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Depends",
|
|
16
|
+
"DiContainer",
|
|
17
|
+
"RpcCall",
|
|
18
|
+
"HandlerInfo",
|
|
19
|
+
"RpcApp",
|
|
20
|
+
"RpcError",
|
|
21
|
+
"AppMiddleware",
|
|
22
|
+
"BaseMiddleware",
|
|
23
|
+
"WireMiddleware",
|
|
24
|
+
"GzipMiddleware",
|
|
25
|
+
"RpcRequest",
|
|
26
|
+
"RpcResponse",
|
|
27
|
+
"RpcContext",
|
|
28
|
+
"RpcData",
|
|
29
|
+
"RpcHeaders",
|
|
30
|
+
"JsonSerializer",
|
|
31
|
+
"Serializer",
|
|
32
|
+
"Transport",
|
|
33
|
+
"MockTransport",
|
|
34
|
+
"RmqTransport",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
__version__ = importlib.metadata.version("rmqaio")
|
linkr/app.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from functools import wraps
|
|
7
|
+
from typing import Any, get_args, get_origin, get_type_hints
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from pydantic import TypeAdapter as _TypeAdapter
|
|
11
|
+
from pydantic import ValidationError as _PydanticValidationError
|
|
12
|
+
|
|
13
|
+
from linkr.di import Depends, DiContainer
|
|
14
|
+
from linkr.exceptions import RpcError
|
|
15
|
+
from linkr.middleware.base import AppMiddleware, WireMiddleware
|
|
16
|
+
from linkr.models import HandlerInfo, RpcContext, RpcRequest, RpcResponse
|
|
17
|
+
from linkr.serializer import JsonSerializer, Serializer
|
|
18
|
+
from linkr.transports import Transport
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RpcCall:
|
|
22
|
+
"""
|
|
23
|
+
Builder for executing a prepared RPC request.
|
|
24
|
+
|
|
25
|
+
Returned by RpcApp.make(). Wraps a request and its origin app,
|
|
26
|
+
providing call() / __call__() convenience methods.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, app: RpcApp, request: RpcRequest) -> None:
|
|
30
|
+
self._app = app
|
|
31
|
+
self._request = request
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def app(self) -> RpcApp:
|
|
35
|
+
return self._app
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def request(self) -> RpcRequest:
|
|
39
|
+
return self._request
|
|
40
|
+
|
|
41
|
+
async def __call__(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
timeout: float | None = None,
|
|
45
|
+
ttl: float | None = None,
|
|
46
|
+
rttl: float | None = None,
|
|
47
|
+
**kwds: Any,
|
|
48
|
+
) -> Any:
|
|
49
|
+
return await self._app.call(self._request, timeout=timeout, ttl=ttl, rttl=rttl, **kwds)
|
|
50
|
+
|
|
51
|
+
async def call(
|
|
52
|
+
self,
|
|
53
|
+
*,
|
|
54
|
+
timeout: float | None = None,
|
|
55
|
+
ttl: float | None = None,
|
|
56
|
+
rttl: float | None = None,
|
|
57
|
+
**kwds: Any,
|
|
58
|
+
) -> Any:
|
|
59
|
+
return await self._app.call(self._request, timeout=timeout, ttl=ttl, rttl=rttl, **kwds)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class RpcApp:
|
|
63
|
+
"""
|
|
64
|
+
Main RPC application: register handlers, send requests, manage middleware.
|
|
65
|
+
|
|
66
|
+
Orchestrates serialization, encoding (compression/encryption), object-level
|
|
67
|
+
middleware and transport communication.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
transport: Transport,
|
|
73
|
+
*,
|
|
74
|
+
timeout: float | None = None,
|
|
75
|
+
ttl: float | None = None,
|
|
76
|
+
rttl: float | None = None,
|
|
77
|
+
serializer: Serializer | None = None,
|
|
78
|
+
) -> None:
|
|
79
|
+
self._transport = transport
|
|
80
|
+
self._timeout = timeout
|
|
81
|
+
self._ttl = ttl
|
|
82
|
+
self._rttl = rttl
|
|
83
|
+
self._closed = False
|
|
84
|
+
self._handlers: dict[str, HandlerInfo] = {}
|
|
85
|
+
self._app_mw: list[AppMiddleware] = []
|
|
86
|
+
self._wire_mw: list[WireMiddleware] = []
|
|
87
|
+
self._serializer = serializer or JsonSerializer()
|
|
88
|
+
self.dependencies = DiContainer()
|
|
89
|
+
|
|
90
|
+
def add_middleware(self, mw: AppMiddleware | WireMiddleware) -> None:
|
|
91
|
+
if isinstance(mw, WireMiddleware):
|
|
92
|
+
self._wire_mw.append(mw)
|
|
93
|
+
else:
|
|
94
|
+
self._app_mw.append(mw)
|
|
95
|
+
|
|
96
|
+
def method(
|
|
97
|
+
self,
|
|
98
|
+
name: str,
|
|
99
|
+
**options: Any,
|
|
100
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
101
|
+
"""Decorator that registers an RPC handler."""
|
|
102
|
+
|
|
103
|
+
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
104
|
+
@wraps(fn)
|
|
105
|
+
def wrapper(*args: Any, **kwds: Any) -> Any:
|
|
106
|
+
return fn(*args, **kwds)
|
|
107
|
+
|
|
108
|
+
dep_types: dict[str, type] = {}
|
|
109
|
+
hints = get_type_hints(fn, localns={"Depends": Depends})
|
|
110
|
+
for pname, ann in hints.items():
|
|
111
|
+
if pname == "return":
|
|
112
|
+
continue
|
|
113
|
+
if get_origin(ann) is Depends:
|
|
114
|
+
dep_types[pname] = get_args(ann)[0]
|
|
115
|
+
|
|
116
|
+
sig = str(inspect.signature(fn))
|
|
117
|
+
self._handlers[name] = HandlerInfo(
|
|
118
|
+
name=name,
|
|
119
|
+
fn=wrapper,
|
|
120
|
+
signature=sig,
|
|
121
|
+
options=options,
|
|
122
|
+
dep_types=dep_types,
|
|
123
|
+
)
|
|
124
|
+
return wrapper
|
|
125
|
+
|
|
126
|
+
return decorator
|
|
127
|
+
|
|
128
|
+
def get_handler(self, name: str) -> HandlerInfo | None:
|
|
129
|
+
return self._handlers.get(name)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def methods(self) -> dict[str, HandlerInfo]:
|
|
133
|
+
return dict(self._handlers)
|
|
134
|
+
|
|
135
|
+
def _routing_key(self, method: str) -> str:
|
|
136
|
+
if "/" not in method:
|
|
137
|
+
return "rpc.server"
|
|
138
|
+
group = method.rsplit("/", 1)[0]
|
|
139
|
+
return f"rpc.server.{group}"
|
|
140
|
+
|
|
141
|
+
def _resolve_deps(self, info: HandlerInfo) -> dict[str, Any]:
|
|
142
|
+
return {name: self.dependencies.resolve(dep_type) for name, dep_type in info.dep_types.items()}
|
|
143
|
+
|
|
144
|
+
def make(
|
|
145
|
+
self,
|
|
146
|
+
method: str,
|
|
147
|
+
*args: Any,
|
|
148
|
+
**kwds: Any,
|
|
149
|
+
) -> RpcCall:
|
|
150
|
+
request = RpcRequest(
|
|
151
|
+
id=uuid4(),
|
|
152
|
+
headers={"routing_key": self._routing_key(method)},
|
|
153
|
+
data={"method": method, "args": args, "kwds": kwds},
|
|
154
|
+
)
|
|
155
|
+
return RpcCall(self, request)
|
|
156
|
+
|
|
157
|
+
async def init(self) -> None:
|
|
158
|
+
await self._transport.init()
|
|
159
|
+
for amw in self._app_mw:
|
|
160
|
+
await amw.init(self)
|
|
161
|
+
for wmw in self._wire_mw:
|
|
162
|
+
await wmw.init(self)
|
|
163
|
+
|
|
164
|
+
async def close(self) -> None:
|
|
165
|
+
await self.stop_consume()
|
|
166
|
+
for amw in reversed(self._app_mw):
|
|
167
|
+
await amw.close()
|
|
168
|
+
for wmw in reversed(self._wire_mw):
|
|
169
|
+
await wmw.close()
|
|
170
|
+
await self._transport.close()
|
|
171
|
+
self._closed = True
|
|
172
|
+
|
|
173
|
+
async def consume(self) -> None:
|
|
174
|
+
if self._closed:
|
|
175
|
+
raise RuntimeError("RpcApp is closed")
|
|
176
|
+
await self._transport.consume(self._request_handler)
|
|
177
|
+
|
|
178
|
+
groups = set()
|
|
179
|
+
for full_name in self._handlers:
|
|
180
|
+
if "/" in full_name:
|
|
181
|
+
group = full_name.rsplit("/", 1)[0]
|
|
182
|
+
groups.add(group)
|
|
183
|
+
for group in groups:
|
|
184
|
+
await self._transport.consume(self._request_handler, queue=group)
|
|
185
|
+
|
|
186
|
+
async def stop_consume(self) -> None:
|
|
187
|
+
await self._transport.stop_consume()
|
|
188
|
+
|
|
189
|
+
async def call(
|
|
190
|
+
self,
|
|
191
|
+
request: RpcRequest,
|
|
192
|
+
*,
|
|
193
|
+
timeout: float | None = None,
|
|
194
|
+
ttl: float | None = None,
|
|
195
|
+
rttl: float | None = None,
|
|
196
|
+
**kwds: Any,
|
|
197
|
+
) -> Any:
|
|
198
|
+
if self._closed:
|
|
199
|
+
raise RuntimeError("RpcApp is closed")
|
|
200
|
+
|
|
201
|
+
timeout = timeout if timeout is not None else self._timeout
|
|
202
|
+
ttl = ttl if ttl is not None else self._ttl
|
|
203
|
+
rttl = rttl if rttl is not None else self._rttl
|
|
204
|
+
if ttl is None and timeout is not None:
|
|
205
|
+
ttl = timeout
|
|
206
|
+
if ttl is not None:
|
|
207
|
+
request.headers["ttl"] = ttl
|
|
208
|
+
if timeout is not None:
|
|
209
|
+
request.headers["timeout"] = timeout
|
|
210
|
+
if rttl is not None:
|
|
211
|
+
request.headers["rttl"] = rttl
|
|
212
|
+
|
|
213
|
+
ctx = RpcContext(app=self, direction="request", role="client", request=request)
|
|
214
|
+
ctx = await self._run_app_mw(ctx)
|
|
215
|
+
|
|
216
|
+
ctx.body = self._serializer.dumps_request(request)
|
|
217
|
+
|
|
218
|
+
ctx.state["call_kwds"] = kwds
|
|
219
|
+
ctx = await self._run_wire_mw(ctx)
|
|
220
|
+
|
|
221
|
+
response_bytes, response_wire = await self._transport.request(
|
|
222
|
+
ctx.body,
|
|
223
|
+
original=request,
|
|
224
|
+
wire_headers=dict(ctx.wire_headers) or None,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
ctx.direction = "response"
|
|
228
|
+
ctx.body = response_bytes
|
|
229
|
+
ctx.wire_headers = response_wire
|
|
230
|
+
ctx = await self._run_wire_mw(ctx)
|
|
231
|
+
|
|
232
|
+
response = self._serializer.loads_response(ctx.body)
|
|
233
|
+
|
|
234
|
+
ctx.direction = "response"
|
|
235
|
+
ctx.response = response
|
|
236
|
+
ctx = await self._run_app_mw(ctx)
|
|
237
|
+
|
|
238
|
+
if response.data and "error_code" in response.data:
|
|
239
|
+
raise RpcError(
|
|
240
|
+
error_code=response.data["error_code"],
|
|
241
|
+
error_message=response.data.get("error_message", ""),
|
|
242
|
+
error_details=response.data.get("error_details"),
|
|
243
|
+
)
|
|
244
|
+
if response.data is None:
|
|
245
|
+
return None
|
|
246
|
+
return response.data.get("result")
|
|
247
|
+
|
|
248
|
+
async def publish(
|
|
249
|
+
self,
|
|
250
|
+
request: RpcRequest,
|
|
251
|
+
*,
|
|
252
|
+
timeout: float | None = None,
|
|
253
|
+
ttl: float | None = None,
|
|
254
|
+
rttl: float | None = None,
|
|
255
|
+
**kwds: Any,
|
|
256
|
+
) -> None:
|
|
257
|
+
if self._closed:
|
|
258
|
+
raise RuntimeError("RpcApp is closed")
|
|
259
|
+
|
|
260
|
+
timeout = timeout if timeout is not None else self._timeout
|
|
261
|
+
ttl = ttl if ttl is not None else self._ttl
|
|
262
|
+
rttl = rttl if rttl is not None else self._rttl
|
|
263
|
+
if ttl is None and timeout is not None:
|
|
264
|
+
ttl = timeout
|
|
265
|
+
if ttl is not None:
|
|
266
|
+
request.headers["ttl"] = ttl
|
|
267
|
+
if timeout is not None:
|
|
268
|
+
request.headers["timeout"] = timeout
|
|
269
|
+
if rttl is not None:
|
|
270
|
+
request.headers["rttl"] = rttl
|
|
271
|
+
|
|
272
|
+
ctx = RpcContext(app=self, direction="request", role="client", request=request)
|
|
273
|
+
ctx = await self._run_app_mw(ctx)
|
|
274
|
+
|
|
275
|
+
ctx.body = self._serializer.dumps_request(request)
|
|
276
|
+
|
|
277
|
+
ctx.state["call_kwds"] = kwds
|
|
278
|
+
ctx = await self._run_wire_mw(ctx)
|
|
279
|
+
|
|
280
|
+
await self._transport.publish(ctx.body, original=request, wire_headers=dict(ctx.wire_headers) or None)
|
|
281
|
+
|
|
282
|
+
async def _request_handler(
|
|
283
|
+
self,
|
|
284
|
+
data: bytes,
|
|
285
|
+
original: RpcRequest,
|
|
286
|
+
wire_headers: dict[str, str] | None = None,
|
|
287
|
+
) -> tuple[bytes, RpcResponse | None, dict[str, str]] | None:
|
|
288
|
+
ctx = RpcContext(
|
|
289
|
+
app=self,
|
|
290
|
+
direction="request",
|
|
291
|
+
role="server",
|
|
292
|
+
request=original,
|
|
293
|
+
body=data,
|
|
294
|
+
wire_headers=wire_headers or {},
|
|
295
|
+
)
|
|
296
|
+
ctx = await self._run_wire_mw(ctx)
|
|
297
|
+
|
|
298
|
+
request = self._serializer.loads_request(ctx.body)
|
|
299
|
+
ctx.request = request
|
|
300
|
+
|
|
301
|
+
ctx = await self._run_app_mw(ctx)
|
|
302
|
+
|
|
303
|
+
if ctx.response is None:
|
|
304
|
+
ctx.response = await self._dispatch(request)
|
|
305
|
+
|
|
306
|
+
rttl = request.headers.get("rttl")
|
|
307
|
+
if rttl is not None and ctx.response is not None:
|
|
308
|
+
ctx.response.headers["rttl"] = rttl
|
|
309
|
+
|
|
310
|
+
if ctx.response is None:
|
|
311
|
+
return None
|
|
312
|
+
|
|
313
|
+
ctx.direction = "response"
|
|
314
|
+
ctx = await self._run_app_mw(ctx)
|
|
315
|
+
|
|
316
|
+
ctx.body = self._serializer.dumps_response(ctx.response) # type: ignore[arg-type]
|
|
317
|
+
ctx.wire_headers = {}
|
|
318
|
+
|
|
319
|
+
ctx = await self._run_wire_mw(ctx)
|
|
320
|
+
|
|
321
|
+
return (ctx.body, ctx.response, dict(ctx.wire_headers))
|
|
322
|
+
|
|
323
|
+
def _validate_args(
|
|
324
|
+
self, info: HandlerInfo, args: tuple[Any, ...], kwds: dict[str, Any], request: RpcRequest
|
|
325
|
+
) -> RpcResponse | None:
|
|
326
|
+
if not info.options.get("validate_types"):
|
|
327
|
+
return None
|
|
328
|
+
|
|
329
|
+
fn = inspect.unwrap(info.fn)
|
|
330
|
+
hints = get_type_hints(fn, localns={"Depends": Depends})
|
|
331
|
+
sig = inspect.signature(fn)
|
|
332
|
+
params = list(sig.parameters.values())
|
|
333
|
+
|
|
334
|
+
arg_map: dict[str, Any] = {}
|
|
335
|
+
for i, arg in enumerate(args):
|
|
336
|
+
if i < len(params):
|
|
337
|
+
arg_map[params[i].name] = arg
|
|
338
|
+
arg_map.update(kwds)
|
|
339
|
+
|
|
340
|
+
errors: list[str] = []
|
|
341
|
+
for pname, value in arg_map.items():
|
|
342
|
+
hint = hints.get(pname)
|
|
343
|
+
if hint is None:
|
|
344
|
+
continue
|
|
345
|
+
if pname == "return":
|
|
346
|
+
continue
|
|
347
|
+
if get_origin(hint) is Depends:
|
|
348
|
+
continue
|
|
349
|
+
if hint is Any:
|
|
350
|
+
continue
|
|
351
|
+
|
|
352
|
+
try:
|
|
353
|
+
_TypeAdapter(hint).validate_python(value)
|
|
354
|
+
except _PydanticValidationError as e:
|
|
355
|
+
errors.append(f"{pname}: {e.errors(include_input=False, include_url=False)}")
|
|
356
|
+
|
|
357
|
+
if errors:
|
|
358
|
+
return RpcResponse(
|
|
359
|
+
id=request.id,
|
|
360
|
+
data={
|
|
361
|
+
"error_code": "ValidationError",
|
|
362
|
+
"error_message": "; ".join(errors),
|
|
363
|
+
},
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
async def _dispatch(self, request: RpcRequest) -> RpcResponse:
|
|
369
|
+
data = request.data
|
|
370
|
+
if not isinstance(data, dict) or "method" not in data:
|
|
371
|
+
return RpcResponse(
|
|
372
|
+
id=request.id,
|
|
373
|
+
data={
|
|
374
|
+
"error_code": "BadRequest",
|
|
375
|
+
"error_message": "Missing 'method' in request data",
|
|
376
|
+
},
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
method = data["method"]
|
|
380
|
+
info = self._handlers.get(method)
|
|
381
|
+
if info is None:
|
|
382
|
+
return RpcResponse(
|
|
383
|
+
id=request.id,
|
|
384
|
+
data={
|
|
385
|
+
"error_code": "MethodNotFound",
|
|
386
|
+
"error_message": f"No handler registered for method: {method}",
|
|
387
|
+
},
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
error_response = self._validate_args(info, data.get("args", ()), data.get("kwds", {}), request)
|
|
391
|
+
if error_response is not None:
|
|
392
|
+
return error_response
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
deps = self._resolve_deps(info)
|
|
396
|
+
kwds = {**deps, **data.get("kwds", {})}
|
|
397
|
+
result = info.fn(*data.get("args", []), **kwds)
|
|
398
|
+
if asyncio.iscoroutine(result):
|
|
399
|
+
exec_timeout = request.headers.get("timeout")
|
|
400
|
+
if exec_timeout is not None:
|
|
401
|
+
result = await asyncio.wait_for(result, timeout=exec_timeout)
|
|
402
|
+
else:
|
|
403
|
+
result = await result
|
|
404
|
+
return RpcResponse(id=request.id, data={"result": result})
|
|
405
|
+
except TimeoutError:
|
|
406
|
+
return RpcResponse(
|
|
407
|
+
id=request.id,
|
|
408
|
+
data={
|
|
409
|
+
"error_code": "Timeout",
|
|
410
|
+
"error_message": "Handler execution timed out",
|
|
411
|
+
},
|
|
412
|
+
)
|
|
413
|
+
except Exception as exc:
|
|
414
|
+
return RpcResponse(
|
|
415
|
+
id=request.id,
|
|
416
|
+
data={
|
|
417
|
+
"error_code": "InternalError",
|
|
418
|
+
"error_message": str(exc),
|
|
419
|
+
"error_details": {"exc_type": type(exc).__name__},
|
|
420
|
+
},
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
async def _run_app_mw(self, ctx: RpcContext) -> RpcContext:
|
|
424
|
+
|
|
425
|
+
async def runner(idx: int, c: RpcContext) -> RpcContext:
|
|
426
|
+
if idx >= len(self._app_mw):
|
|
427
|
+
return c
|
|
428
|
+
mw = self._app_mw[idx]
|
|
429
|
+
|
|
430
|
+
async def call_next(inner_ctx: RpcContext) -> RpcContext:
|
|
431
|
+
return await runner(idx + 1, inner_ctx)
|
|
432
|
+
|
|
433
|
+
return await mw.dispatch(c, call_next)
|
|
434
|
+
|
|
435
|
+
return await runner(0, ctx)
|
|
436
|
+
|
|
437
|
+
async def _run_wire_mw(self, ctx: RpcContext) -> RpcContext:
|
|
438
|
+
|
|
439
|
+
async def runner(idx: int, c: RpcContext) -> RpcContext:
|
|
440
|
+
if idx >= len(self._wire_mw):
|
|
441
|
+
return c
|
|
442
|
+
mw = self._wire_mw[idx]
|
|
443
|
+
|
|
444
|
+
async def call_next(inner_ctx: RpcContext) -> RpcContext:
|
|
445
|
+
return await runner(idx + 1, inner_ctx)
|
|
446
|
+
|
|
447
|
+
return await mw.dispatch(c, call_next)
|
|
448
|
+
|
|
449
|
+
return await runner(0, ctx)
|
|
450
|
+
|
|
451
|
+
async def __aenter__(self) -> RpcApp:
|
|
452
|
+
await self.init()
|
|
453
|
+
return self
|
|
454
|
+
|
|
455
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
456
|
+
await self.close()
|
linkr/di.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any, Generic, TypeVar
|
|
5
|
+
|
|
6
|
+
T = TypeVar("T")
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Depends(Generic[T]):
|
|
10
|
+
"""Marker for dependency injection in handler parameters.
|
|
11
|
+
|
|
12
|
+
Usage::
|
|
13
|
+
|
|
14
|
+
def get_user(user_id: int, db: Depends[Database]) -> dict: ...
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DiContainer:
|
|
19
|
+
"""
|
|
20
|
+
Registry of dependency types.
|
|
21
|
+
|
|
22
|
+
Usage::
|
|
23
|
+
|
|
24
|
+
container = DiContainer()
|
|
25
|
+
container.add_singleton(Database, lambda: Database("postgres://..."))
|
|
26
|
+
container.add_transient(RequestContext, create_ctx)
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
self._singletons: dict[type, Any] = {}
|
|
31
|
+
self._singleton_factories: dict[type, Callable[[], Any]] = {}
|
|
32
|
+
self._transients: dict[type, Callable[[], Any]] = {}
|
|
33
|
+
|
|
34
|
+
def add_singleton(self, type_: type, factory: Callable[[], Any]) -> None:
|
|
35
|
+
"""Register a singleton dependency.
|
|
36
|
+
|
|
37
|
+
The factory is called once on first resolve and the result is
|
|
38
|
+
cached for all future resolutions.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
type_: The dependency type used in Depends[T].
|
|
42
|
+
factory: A zero-argument callable that produces the instance.
|
|
43
|
+
"""
|
|
44
|
+
self._singleton_factories[type_] = factory
|
|
45
|
+
|
|
46
|
+
def add_transient(self, type_: type, factory: Callable[[], Any]) -> None:
|
|
47
|
+
"""Register a transient dependency.
|
|
48
|
+
|
|
49
|
+
A new instance is created by calling the factory every time the
|
|
50
|
+
dependency is resolved.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
type_: The dependency type used in Depends[T].
|
|
54
|
+
factory: A zero-argument callable that produces the instance.
|
|
55
|
+
"""
|
|
56
|
+
self._transients[type_] = factory
|
|
57
|
+
|
|
58
|
+
def resolve(self, type_: type) -> Any:
|
|
59
|
+
"""Resolve a dependency by type.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
type_: The type to resolve.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
The resolved dependency instance.
|
|
66
|
+
|
|
67
|
+
Raises:
|
|
68
|
+
KeyError: If no dependency is registered for *type_*.
|
|
69
|
+
"""
|
|
70
|
+
if type_ in self._singletons:
|
|
71
|
+
return self._singletons[type_]
|
|
72
|
+
|
|
73
|
+
if type_ in self._singleton_factories:
|
|
74
|
+
instance = self._singleton_factories[type_]()
|
|
75
|
+
self._singletons[type_] = instance
|
|
76
|
+
del self._singleton_factories[type_]
|
|
77
|
+
return instance
|
|
78
|
+
|
|
79
|
+
factory = self._transients.get(type_)
|
|
80
|
+
if factory is None:
|
|
81
|
+
raise KeyError(f"No dependency registered for {type_}")
|
|
82
|
+
return factory()
|
linkr/exceptions.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RpcError(Exception):
|
|
7
|
+
"""
|
|
8
|
+
Structured RPC error returned by the server.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
error_code: Machine-readable error code (e.g. MethodNotFound).
|
|
12
|
+
error_message: Human-readable error description.
|
|
13
|
+
error_details: Optional structured error metadata.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
error_code: str = "InternalError",
|
|
19
|
+
error_message: str = "",
|
|
20
|
+
error_details: dict[str, Any] | None = None,
|
|
21
|
+
) -> None:
|
|
22
|
+
self.error_code = error_code
|
|
23
|
+
self.error_message = error_message
|
|
24
|
+
self.error_details = error_details
|
|
25
|
+
super().__init__(f"[{error_code}] {error_message}")
|
linkr/middleware/base.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
from linkr.models import RpcContext
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from linkr.app import RpcApp
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BaseMiddleware:
|
|
13
|
+
"""
|
|
14
|
+
Base class for RPC middleware.
|
|
15
|
+
|
|
16
|
+
Subclasses override dispatch() to intercept the request/response
|
|
17
|
+
flow. Optional lifecycle hooks: init() and close().
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
async def init(self, app: RpcApp) -> None:
|
|
21
|
+
"""
|
|
22
|
+
Initialize middleware when the app starts.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
app: The RpcApp instance.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
async def close(self) -> None:
|
|
29
|
+
"""Clean up middleware resources on app shutdown."""
|
|
30
|
+
|
|
31
|
+
async def dispatch(
|
|
32
|
+
self,
|
|
33
|
+
ctx: RpcContext,
|
|
34
|
+
call_next: Callable[..., Any],
|
|
35
|
+
) -> RpcContext:
|
|
36
|
+
"""
|
|
37
|
+
Intercept the request/response context.
|
|
38
|
+
|
|
39
|
+
Call call_next(ctx) to continue the chain, or return ctx early
|
|
40
|
+
to short-circuit.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
ctx: The current RpcContext.
|
|
44
|
+
call_next: Continuation that invokes the next middleware or handler.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
The (possibly mutated) RpcContext.
|
|
48
|
+
"""
|
|
49
|
+
return await call_next(ctx)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AppMiddleware(BaseMiddleware):
|
|
53
|
+
"""Base for middleware that works with deserialized request/response objects."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class WireMiddleware(BaseMiddleware):
|
|
57
|
+
"""Base for middleware that works with raw bytes in RpcContext.body."""
|
linkr/middleware/gzip.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import gzip
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from linkr.middleware.base import WireMiddleware
|
|
8
|
+
from linkr.models import RpcContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _merge_ce(headers: dict[str, str], name: str) -> None:
|
|
12
|
+
existing = headers.get("content_encoding", "")
|
|
13
|
+
headers["content_encoding"] = f"{existing},{name}" if existing else name
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GzipMiddleware(WireMiddleware):
|
|
17
|
+
"""Compress request/response body with gzip if body size >= min_size."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, min_size: int = 1024) -> None:
|
|
20
|
+
self._min_size = min_size
|
|
21
|
+
|
|
22
|
+
async def dispatch(self, ctx: RpcContext, call_next: Callable[..., Any]) -> RpcContext: # type: ignore[override]
|
|
23
|
+
if ctx.direction == "request" and ctx.role == "client":
|
|
24
|
+
if len(ctx.body) >= self._min_size:
|
|
25
|
+
ctx.body = gzip.compress(ctx.body)
|
|
26
|
+
_merge_ce(ctx.wire_headers, "gzip")
|
|
27
|
+
elif ctx.direction == "request" and ctx.role == "server":
|
|
28
|
+
if "gzip" in ctx.wire_headers.get("content_encoding", ""):
|
|
29
|
+
ctx.body = gzip.decompress(ctx.body)
|
|
30
|
+
|
|
31
|
+
ctx = await call_next(ctx)
|
|
32
|
+
|
|
33
|
+
if ctx.direction == "response" and ctx.role == "server":
|
|
34
|
+
if len(ctx.body) >= self._min_size:
|
|
35
|
+
ctx.body = gzip.compress(ctx.body)
|
|
36
|
+
_merge_ce(ctx.wire_headers, "gzip")
|
|
37
|
+
elif ctx.direction == "response" and ctx.role == "client":
|
|
38
|
+
if "gzip" in ctx.wire_headers.get("content_encoding", ""):
|
|
39
|
+
ctx.body = gzip.decompress(ctx.body)
|
|
40
|
+
|
|
41
|
+
return ctx
|