|
1
|
|
|
import logging |
|
2
|
|
|
import typing |
|
3
|
|
|
|
|
4
|
|
|
from . import errors, protocol |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
__all__ = ( |
|
8
|
|
|
'exception_middleware', |
|
9
|
|
|
'extra_args_middleware', |
|
10
|
|
|
'logging_middleware', |
|
11
|
|
|
'DEFAULT_MIDDLEWARES', |
|
12
|
|
|
) |
|
13
|
|
|
|
|
14
|
|
|
logger = logging.getLogger(__name__) |
|
15
|
|
|
|
|
16
|
|
|
|
|
17
|
|
|
async def extra_args_middleware(request: protocol.JsonRpcRequest, handler: typing.Callable) -> protocol.JsonRpcResponse: |
|
18
|
|
|
request.extra_args['rpc_request'] = request |
|
19
|
|
|
return await handler(request) |
|
20
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
async def exception_middleware(request: protocol.JsonRpcRequest, handler: typing.Callable) -> protocol.JsonRpcResponse: |
|
23
|
|
|
try: |
|
24
|
|
|
response = await handler(request) |
|
25
|
|
|
except errors.JsonRpcError as e: |
|
26
|
|
|
logging.warning('Unprocessed errors.JsonRpcError', exc_info=True) |
|
27
|
|
|
response = protocol.JsonRpcResponse( |
|
28
|
|
|
msg_id=request.msg_id, |
|
29
|
|
|
jsonrpc=request.jsonrpc, |
|
30
|
|
|
error=e, |
|
31
|
|
|
) |
|
32
|
|
|
except Exception as e: |
|
33
|
|
|
logger.exception(e) |
|
34
|
|
|
response = protocol.JsonRpcResponse( |
|
35
|
|
|
msg_id=request.msg_id, |
|
36
|
|
|
jsonrpc=request.jsonrpc, |
|
37
|
|
|
error=errors.InternalError().with_traceback(), |
|
38
|
|
|
) |
|
39
|
|
|
|
|
40
|
|
|
return response |
|
41
|
|
|
|
|
42
|
|
|
|
|
43
|
|
|
async def logging_middleware(request: protocol.JsonRpcRequest, handler: typing.Callable) -> protocol.JsonRpcResponse: |
|
44
|
|
|
raw_request = request.to_dict() |
|
45
|
|
|
|
|
46
|
|
|
logger.info( |
|
47
|
|
|
'RpcRequest id="%s" method="%s" params="%s"', |
|
48
|
|
|
raw_request.get('id', ''), |
|
49
|
|
|
raw_request['method'], |
|
50
|
|
|
raw_request.get('params', ''), |
|
51
|
|
|
extra={'request': raw_request}, |
|
52
|
|
|
) |
|
53
|
|
|
|
|
54
|
|
|
response = await handler(request) |
|
55
|
|
|
|
|
56
|
|
|
raw_response = request.to_dict() |
|
57
|
|
|
|
|
58
|
|
|
logger.info( |
|
59
|
|
|
'RpcResponse id="%s" method="%s" params="%s" result="%s" error="%s"', |
|
60
|
|
|
raw_request.get('id', ''), |
|
61
|
|
|
raw_request['method'], |
|
62
|
|
|
raw_request.get('params', ''), |
|
63
|
|
|
raw_response.get('result', ''), |
|
64
|
|
|
raw_response.get('error', ''), |
|
65
|
|
|
extra={'request': raw_response, 'response': raw_response}, |
|
66
|
|
|
) |
|
67
|
|
|
|
|
68
|
|
|
return response |
|
69
|
|
|
|
|
70
|
|
|
|
|
71
|
|
|
DEFAULT_MIDDLEWARES = ( |
|
72
|
|
|
exception_middleware, |
|
73
|
|
|
extra_args_middleware, |
|
74
|
|
|
) |
|
75
|
|
|
|