-
Notifications
You must be signed in to change notification settings - Fork 28
/
__init__.py
1348 lines (1099 loc) · 43.2 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import contextvars # noqa
import inspect
import logging
import typing
from collections import ChainMap
from collections.abc import Coroutine
from contextlib import AsyncExitStack, AbstractAsyncContextManager, asynccontextmanager, contextmanager
from types import FunctionType
from typing import List, Union, Any, Callable, Type, Optional, Dict, Sequence, Awaitable
from pydantic import DictError # noqa
from pydantic import StrictStr, ValidationError
from pydantic import BaseModel, BaseConfig
from pydantic.fields import ModelField, Field, Undefined
from pydantic.main import ModelMetaclass # noqa
from fastapi.dependencies.models import Dependant
from fastapi.encoders import jsonable_encoder
from fastapi.params import Depends
from fastapi import FastAPI, Body
from fastapi.dependencies.utils import solve_dependencies, get_dependant, get_flat_dependant, \
get_parameterless_sub_dependant
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.routing import APIRoute, APIRouter, serialize_response
from starlette.background import BackgroundTasks
from starlette.concurrency import run_in_threadpool
from starlette.requests import Request
from starlette.responses import Response, JSONResponse
from starlette.routing import Match, request_response, compile_path
import fastapi.params
import aiojobs
logger = logging.getLogger(__name__)
try:
from functools import cached_property
except ImportError:
class cached_property: # noqa
def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
def __get__(self, obj, cls):
if obj is None:
return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
try:
import sentry_sdk
from sentry_sdk.utils import transaction_from_function as sentry_transaction_from_function
except ImportError:
sentry_sdk = None
sentry_transaction_from_function = None
class Params(fastapi.params.Body):
def __init__(
self,
default: Any,
*,
media_type: str = 'application/json',
title: str = None,
description: str = None,
gt: float = None,
ge: float = None,
lt: float = None,
le: float = None,
min_length: int = None,
max_length: int = None,
regex: str = None,
example: Any = Undefined,
examples: Optional[Dict[str, Any]] = None,
**extra: Any,
):
super().__init__(
default,
embed=False,
media_type=media_type,
alias='params',
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
regex=regex,
example=example,
examples=examples,
**extra,
)
components = {}
def component_name(name: str, module: str = None):
"""OpenAPI components must be unique by name"""
def decorator(obj):
obj.__name__ = name
obj.__qualname__ = name
if module is not None:
obj.__module__ = module # see: pydantic.schema.get_long_model_name
key = (obj.__name__, obj.__module__)
if key in components:
if components[key].schema() != obj.schema():
raise RuntimeError(
f"Different models with the same name detected: {obj!r} != {components[key]}"
)
return components[key]
components[key] = obj
return obj
return decorator
def is_scope_child(owner: type, child: type):
return (
(
owner.__dict__.get(child.__name__) is child or
owner.__dict__.get(child.__name__) is Optional[child]
) and
child.__qualname__ == owner.__qualname__ + '.' + child.__name__ and
child.__module__ == owner.__module__
)
def rename_if_scope_child_component(owner: type, child, postfix: str):
if is_scope_child(owner, child):
child = component_name(f'{owner.__name__}.{postfix}', owner.__module__)(child)
return child
class BaseError(Exception):
CODE = None
MESSAGE = None
ErrorModel = None
DataModel = None
data_required = False
errors_required = False
error_model = None
data_model = None
resp_model = None
_component_name = None
def __init__(self, data=None):
if data is None:
data = {}
raw_data = data
data = self.validate_data(raw_data)
Exception.__init__(self, self.CODE, self.MESSAGE)
self.data = data
self.raw_data = raw_data
@classmethod
def validate_data(cls, data):
data_model = cls.get_data_model()
if data_model:
data = data_model.validate(data)
return data
def __str__(self):
s = f"[{self.CODE}] {self.MESSAGE}"
if self.data:
s += f": {self.data!r}"
return s
def get_resp_data(self):
return self.raw_data
@classmethod
def get_description(cls):
s = cls.get_default_description()
if cls.__doc__:
s += "\n\n" + cls.__doc__
return s
@classmethod
def get_default_description(cls):
return f"[{cls.CODE}] {cls.MESSAGE}"
def get_resp(self) -> dict:
error = {
'code': self.CODE,
'message': self.MESSAGE,
}
resp_data = self.get_resp_data()
if resp_data:
error['data'] = resp_data
resp = {
'jsonrpc': '2.0',
'error': error,
'id': None,
}
return jsonable_encoder(resp)
@classmethod
def get_error_model(cls):
if cls.__dict__.get('error_model') is not None:
return cls.error_model
cls.error_model = cls.build_error_model()
return cls.error_model
@classmethod
def build_error_model(cls):
if cls.ErrorModel is not None:
return rename_if_scope_child_component(cls, cls.ErrorModel, 'Error')
return None
@classmethod
def get_data_model(cls):
if cls.__dict__.get('data_model') is not None:
return cls.data_model
cls.data_model = cls.build_data_model()
return cls.data_model
@classmethod
def build_data_model(cls):
if cls.DataModel is not None:
return rename_if_scope_child_component(cls, cls.DataModel, 'Data')
error_model = cls.get_error_model()
if error_model is None:
return None
errors_annotation = List[error_model]
if not cls.errors_required:
errors_annotation = Optional[errors_annotation]
ns = {
'__annotations__': {
'errors': errors_annotation,
}
}
_ErrorData = ModelMetaclass.__new__(ModelMetaclass, '_ErrorData', (BaseModel,), ns)
_ErrorData = component_name(f'_ErrorData[{error_model.__name__}]', error_model.__module__)(_ErrorData)
return _ErrorData
@classmethod
def get_resp_model(cls):
if cls.__dict__.get('resp_model') is not None:
return cls.resp_model
cls.resp_model = cls.build_resp_model()
return cls.resp_model
@classmethod
def build_resp_model(cls):
ns = {
'code': Field(cls.CODE, const=True, example=cls.CODE),
'message': Field(cls.MESSAGE, const=True, example=cls.MESSAGE),
'__annotations__': {
'code': int,
'message': str,
}
}
data_model = cls.get_data_model()
if data_model is not None:
if not cls.data_required:
data_model = Optional[data_model]
# noinspection PyTypeChecker
ns['__annotations__']['data'] = data_model
name = cls._component_name or cls.__name__
_JsonRpcErrorModel = ModelMetaclass.__new__(ModelMetaclass, '_JsonRpcErrorModel', (BaseModel,), ns)
_JsonRpcErrorModel = component_name(name, cls.__module__)(_JsonRpcErrorModel)
@component_name(f'_ErrorResponse[{name}]', cls.__module__)
class _ErrorResponseModel(BaseModel):
jsonrpc: StrictStr = Field('2.0', const=True, example='2.0')
id: Union[StrictStr, int] = Field(None, example=0)
error: _JsonRpcErrorModel
class Config:
extra = 'forbid'
return _ErrorResponseModel
@component_name('_Error')
class ErrorModel(BaseModel):
loc: List[str]
msg: str
type: str
ctx: Optional[Dict[str, Any]]
class ParseError(BaseError):
"""Invalid JSON was received by the server"""
CODE = -32700
MESSAGE = "Parse error"
class InvalidRequest(BaseError):
"""The JSON sent is not a valid Request object"""
CODE = -32600
MESSAGE = "Invalid Request"
error_model = ErrorModel
class MethodNotFound(BaseError):
"""The method does not exist / is not available"""
CODE = -32601
MESSAGE = "Method not found"
class InvalidParams(BaseError):
"""Invalid method parameter(s)"""
CODE = -32602
MESSAGE = "Invalid params"
error_model = ErrorModel
class InternalError(BaseError):
"""Internal JSON-RPC error"""
CODE = -32603
MESSAGE = "Internal error"
class NoContent(Exception):
pass
async def call_sync_async(call, *args, **kwargs):
is_coroutine = asyncio.iscoroutinefunction(call)
if is_coroutine:
return await call(*args, **kwargs)
else:
return await run_in_threadpool(call, *args, **kwargs)
def errors_responses(errors: Sequence[Type[BaseError]] = None):
responses = {'default': {}}
if errors:
# Swagger UI 5.0 and above allow use only int status_codes and in _valid range_
# generate fake status codes for each error
for fake_status_code, error_cls in enumerate(errors, start=210):
responses[fake_status_code] = {
'model': error_cls.get_resp_model(),
'description': error_cls.get_description(),
}
return responses
@component_name(f'_Request')
class JsonRpcRequest(BaseModel):
jsonrpc: StrictStr = Field('2.0', const=True, example='2.0')
id: Union[StrictStr, int] = Field(None, example=0)
method: StrictStr
params: dict = Field(default_factory=dict)
class Config:
extra = 'forbid'
@component_name(f'_Response')
class JsonRpcResponse(BaseModel):
jsonrpc: StrictStr = Field('2.0', const=True, example='2.0')
id: Union[StrictStr, int] = Field(None, example=0)
result: dict
class Config:
extra = 'forbid'
def invalid_request_from_validation_error(exc: ValidationError) -> InvalidRequest:
return InvalidRequest(data={'errors': exc.errors()})
def invalid_params_from_validation_error(exc: ValidationError) -> InvalidParams:
errors = []
for err in exc.errors():
if err['loc'][:1] == ('body', ):
err['loc'] = err['loc'][1:]
else:
assert err['loc']
err['loc'] = (f"<{err['loc'][0]}>", ) + err['loc'][1:]
errors.append(err)
return InvalidParams(data={'errors': errors})
def fix_query_dependencies(dependant: Dependant):
dependant.body_params.extend(dependant.query_params)
dependant.query_params = []
for field in dependant.body_params:
if not isinstance(field.field_info, Params):
field.field_info.embed = True
for sub_dependant in dependant.dependencies:
fix_query_dependencies(sub_dependant)
def clone_dependant(dependant: Dependant) -> Dependant:
new_dependant = Dependant()
new_dependant.path_params = dependant.path_params
new_dependant.query_params = dependant.query_params
new_dependant.header_params = dependant.header_params
new_dependant.cookie_params = dependant.cookie_params
new_dependant.body_params = dependant.body_params
new_dependant.dependencies = dependant.dependencies
new_dependant.security_requirements = dependant.security_requirements
new_dependant.request_param_name = dependant.request_param_name
new_dependant.websocket_param_name = dependant.websocket_param_name
new_dependant.response_param_name = dependant.response_param_name
new_dependant.background_tasks_param_name = dependant.background_tasks_param_name
new_dependant.security_scopes = dependant.security_scopes
new_dependant.security_scopes_param_name = dependant.security_scopes_param_name
new_dependant.name = dependant.name
new_dependant.call = dependant.call
new_dependant.use_cache = dependant.use_cache
new_dependant.path = dependant.path
new_dependant.cache_key = dependant.cache_key
return new_dependant
def insert_dependencies(target: Dependant, dependencies: Sequence[Depends] = None):
assert target.path
if not dependencies:
return
for depends in dependencies[::-1]:
target.dependencies.insert(
0,
get_parameterless_sub_dependant(depends=depends, path=target.path),
)
def make_request_model(name, module, body_params: List[ModelField]):
whole_params_list = [p for p in body_params if isinstance(p.field_info, Params)]
if len(whole_params_list):
if len(whole_params_list) > 1:
raise RuntimeError(
f"Only one 'Params' allowed: "
f"params={whole_params_list}"
)
body_params_list = [p for p in body_params if not isinstance(p.field_info, Params)]
if body_params_list:
raise RuntimeError(
f"No other params allowed when 'Params' used: "
f"params={whole_params_list}, other={body_params_list}"
)
if whole_params_list:
assert whole_params_list[0].alias == 'params'
params_field = whole_params_list[0]
else:
_JsonRpcRequestParams = ModelMetaclass.__new__(ModelMetaclass, '_JsonRpcRequestParams', (BaseModel,), {})
for f in body_params:
example = f.field_info.example # noqa
if example is not Undefined:
f.field_info.extra['example'] = jsonable_encoder(example)
examples = f.field_info.extra.get('examples')
if examples is not None:
f.field_info.extra['examples'] = jsonable_encoder(examples)
_JsonRpcRequestParams.__fields__[f.name] = f
_JsonRpcRequestParams = component_name(f'_Params[{name}]', module)(_JsonRpcRequestParams)
params_field = ModelField(
name='params',
type_=_JsonRpcRequestParams,
class_validators={},
default=None,
required=True,
model_config=BaseConfig,
field_info=Field(...),
)
class _Request(BaseModel):
jsonrpc: StrictStr = Field('2.0', const=True, example='2.0')
id: Union[StrictStr, int] = Field(None, example=0)
method: StrictStr = Field(name, const=True, example=name)
class Config:
extra = 'forbid'
_Request.__fields__[params_field.name] = params_field
_Request = component_name(f'_Request[{name}]', module)(_Request)
return _Request
class JsonRpcContext:
def __init__(
self,
entrypoint: 'Entrypoint',
raw_request: Any,
http_request: Request,
background_tasks: BackgroundTasks,
http_response: Response,
json_rpc_request_class: Type[JsonRpcRequest] = JsonRpcRequest,
method_route: typing.Optional['MethodRoute'] = None,
):
self.entrypoint: Entrypoint = entrypoint
self.raw_request: Any = raw_request
self.http_request: Request = http_request
self.background_tasks: BackgroundTasks = background_tasks
self.http_response: Response = http_response
self.request_class: Type[JsonRpcRequest] = json_rpc_request_class
self.method_route: typing.Optional[MethodRoute] = method_route
self._raw_response: Optional[dict] = None
self.exception: Optional[Exception] = None
self.is_unhandled_exception: bool = False
self.exit_stack: Optional[AsyncExitStack] = None
self.jsonrpc_context_token: Optional[contextvars.Token] = None
def on_raw_response(
self,
raw_response: Union[dict, Exception],
):
exception = None
is_unhandled_exception = False
if isinstance(raw_response, Exception):
exception = raw_response
if isinstance(exception, BaseError):
raw_response = exception.get_resp()
elif isinstance(exception, HTTPException):
raw_response = None
else:
raw_response = InternalError().get_resp()
is_unhandled_exception = True
if raw_response is not None:
raw_response.pop('id', None)
if isinstance(self.raw_request, dict) and 'id' in self.raw_request:
raw_response['id'] = self.raw_request.get('id')
elif 'error' in raw_response:
raw_response['id'] = None
self._raw_response = raw_response
self.exception = exception
self.is_unhandled_exception = is_unhandled_exception
@property
def raw_response(self) -> dict:
return self._raw_response
@raw_response.setter
def raw_response(self, value: dict):
self.on_raw_response(value)
@cached_property
def request(self) -> JsonRpcRequest:
try:
return self.request_class.validate(self.raw_request)
except DictError:
raise InvalidRequest(data={'errors': [{
'loc': (),
'type': 'type_error.dict',
'msg': "value is not a valid dict",
}]})
except ValidationError as exc:
raise invalid_request_from_validation_error(exc)
async def __aenter__(self):
assert self.exit_stack is None
self.exit_stack = await AsyncExitStack().__aenter__()
if sentry_sdk is not None:
self.exit_stack.enter_context(self._fix_sentry_scope())
await self.exit_stack.enter_async_context(self._handle_exception(reraise=False))
self.jsonrpc_context_token = _jsonrpc_context.set(self)
return self
async def __aexit__(self, *exc_details):
assert self.jsonrpc_context_token is not None
_jsonrpc_context.reset(self.jsonrpc_context_token)
return await self.exit_stack.__aexit__(*exc_details)
@asynccontextmanager
async def _handle_exception(self, reraise=True):
try:
yield
except Exception as exception:
if exception is not self.exception:
try:
resp = await self.entrypoint.handle_exception(exception)
except Exception as exc:
self.on_raw_response(exc)
else:
self.on_raw_response(resp)
if self.exception is not None and (reraise or isinstance(self.exception, HTTPException)):
raise self.exception
if self.exception is not None and self.is_unhandled_exception:
logger.exception(str(self.exception), exc_info=self.exception)
def _make_sentry_event_processor(self):
def event_processor(event, _):
if self.method_route is not None:
event['transaction'] = sentry_transaction_from_function(self.method_route.func)
return event
return event_processor
@contextmanager
def _fix_sentry_scope(self):
hub = sentry_sdk.Hub.current
with sentry_sdk.Hub(hub) as hub:
with hub.configure_scope() as scope:
scope.clear_breadcrumbs()
scope.add_event_processor(self._make_sentry_event_processor())
yield
async def enter_middlewares(self, middlewares: Sequence['JsonRpcMiddleware']):
for mw in middlewares:
cm = mw(self)
if not isinstance(cm, AbstractAsyncContextManager):
raise RuntimeError("JsonRpcMiddleware(context) must return AsyncContextManager")
await self.exit_stack.enter_async_context(cm)
await self.exit_stack.enter_async_context(self._handle_exception())
JsonRpcMiddleware = Callable[[JsonRpcContext], AbstractAsyncContextManager]
_jsonrpc_context = contextvars.ContextVar('_fastapi_jsonrpc__jsonrpc_context')
def get_jsonrpc_context() -> JsonRpcContext:
return _jsonrpc_context.get()
def get_jsonrpc_request_id() -> Optional[Union[str, int]]:
return get_jsonrpc_context().raw_request.get('id')
def get_jsonrpc_method() -> Optional[str]:
return get_jsonrpc_context().raw_request.get('method')
class MethodRoute(APIRoute):
def __init__(
self,
entrypoint: 'Entrypoint',
path: str,
func: Union[FunctionType, Coroutine],
*,
result_model: Type[Any] = None,
name: str = None,
errors: List[Type[BaseError]] = None,
dependencies: Sequence[Depends] = None,
response_class: Type[Response] = JSONResponse,
request_class: Type[JsonRpcRequest] = JsonRpcRequest,
middlewares: Sequence[JsonRpcMiddleware] = None,
**kwargs,
):
name = name or func.__name__
result_model = result_model or func.__annotations__.get('return')
_, path_format, _ = compile_path(path)
func_dependant = get_dependant(path=path_format, call=func)
insert_dependencies(func_dependant, dependencies)
insert_dependencies(func_dependant, entrypoint.common_dependencies)
fix_query_dependencies(func_dependant)
flat_dependant = get_flat_dependant(func_dependant, skip_repeats=True)
_Request = make_request_model(name, func.__module__, flat_dependant.body_params)
@component_name(f'_Response[{name}]', func.__module__)
class _Response(BaseModel):
jsonrpc: StrictStr = Field('2.0', const=True, example='2.0')
id: Union[StrictStr, int] = Field(None, example=0)
result: result_model
class Config:
extra = 'forbid'
# Only needed to generate OpenAPI
async def endpoint(__request__: _Request):
del __request__
endpoint.__name__ = func.__name__
endpoint.__doc__ = func.__doc__
responses = errors_responses(errors)
super().__init__(
path,
endpoint,
methods=['POST'],
name=name,
response_class=response_class,
response_model=_Response,
responses=responses,
**kwargs,
)
# Add dependencies and other parameters from func_dependant for correct OpenAPI generation
self.dependant.path_params = func_dependant.path_params
self.dependant.header_params = func_dependant.header_params
self.dependant.cookie_params = func_dependant.cookie_params
self.dependant.dependencies = func_dependant.dependencies
self.dependant.security_requirements = func_dependant.security_requirements
self.func = func
self.func_dependant = func_dependant
self.entrypoint = entrypoint
self.middlewares = middlewares or []
self.app = request_response(self.handle_http_request)
self.request_class = request_class
self.errors = errors or []
def __hash__(self):
return hash(self.path)
def __eq__(self, other):
return (
isinstance(other, MethodRoute)
and self.path == other.path
and self.func == other.func
)
async def parse_body(self, http_request) -> Any:
try:
req = await http_request.json()
except ValueError:
raise ParseError()
return req
async def handle_http_request(self, http_request: Request):
background_tasks = BackgroundTasks()
sub_response = Response()
del sub_response.headers["content-length"]
sub_response.status_code = None # type: ignore
try:
body = await self.parse_body(http_request)
except Exception as exc:
resp = await self.entrypoint.handle_exception_to_resp(exc)
response = self.response_class(content=resp, background=background_tasks)
else:
try:
resp = await self.handle_body(http_request, background_tasks, sub_response, body)
except NoContent:
# no content for successful notifications
response = Response(media_type='application/json', background=background_tasks)
else:
response = self.response_class(content=resp, background=background_tasks)
response.headers.raw.extend(sub_response.headers.raw)
if sub_response.status_code:
response.status_code = sub_response.status_code
return response
async def handle_body(
self,
http_request: Request,
background_tasks: BackgroundTasks,
sub_response: Response,
body: Any,
) -> dict:
# Shared dependencies for all requests in one json-rpc batch request
shared_dependencies_error = None
try:
dependency_cache = await self.entrypoint.solve_shared_dependencies(
http_request,
background_tasks,
sub_response,
)
except BaseError as error:
shared_dependencies_error = error
dependency_cache = None
resp = await self.handle_req_to_resp(
http_request, background_tasks, sub_response, body,
dependency_cache=dependency_cache,
shared_dependencies_error=shared_dependencies_error,
)
# No response for successful notifications
has_content = 'error' in resp or 'id' in resp
if not has_content:
raise NoContent
return resp
async def handle_req_to_resp(
self,
http_request: Request,
background_tasks: BackgroundTasks,
sub_response: Response,
req: Any,
dependency_cache: dict = None,
shared_dependencies_error: BaseError = None
) -> dict:
async with JsonRpcContext(
entrypoint=self.entrypoint,
method_route=self,
raw_request=req,
http_request=http_request,
background_tasks=background_tasks,
http_response=sub_response,
json_rpc_request_class=self.request_class,
) as ctx:
await ctx.enter_middlewares(self.entrypoint.middlewares)
if ctx.request.method != self.name:
raise MethodNotFound
resp = await self.handle_req(
http_request, background_tasks, sub_response, ctx,
dependency_cache=dependency_cache,
shared_dependencies_error=shared_dependencies_error,
)
ctx.on_raw_response(resp)
return ctx.raw_response
async def handle_req(
self,
http_request: Request,
background_tasks: BackgroundTasks,
sub_response: Response,
ctx: JsonRpcContext,
dependency_cache: dict = None,
shared_dependencies_error: BaseError = None
):
await ctx.enter_middlewares(self.middlewares)
if shared_dependencies_error:
raise shared_dependencies_error
# dependency_cache - there are shared dependencies, we pass them to each method, since
# they are common to all methods in the batch.
# But if the methods have their own dependencies, they are resolved separately.
dependency_cache = dependency_cache.copy()
values, errors, background_tasks, _, _ = await solve_dependencies(
request=http_request,
dependant=self.func_dependant,
body=ctx.request.params,
background_tasks=background_tasks,
response=sub_response,
dependency_overrides_provider=self.dependency_overrides_provider,
dependency_cache=dependency_cache,
)
if errors:
raise invalid_params_from_validation_error(RequestValidationError(errors))
result = await call_sync_async(self.func, **values)
response = {
'jsonrpc': '2.0',
'result': result,
}
# noinspection PyTypeChecker
resp = await serialize_response(
field=self.secure_cloned_response_field,
response_content=response,
include=self.response_model_include,
exclude=self.response_model_exclude,
by_alias=self.response_model_by_alias,
exclude_unset=self.response_model_exclude_unset,
)
return resp
class RequestShadow(Request):
def __init__(self, request: Request):
super().__init__(scope=ChainMap({}, request.scope))
self.request = request
async def stream(self):
async for body in self.request.stream():
yield body
async def body(self):
return await self.request.body()
async def json(self):
return await self.request.json()
async def form(self):
return await self.request.form()
async def close(self):
raise NotImplementedError
async def is_disconnected(self):
return await self.request.is_disconnected()
class EntrypointRoute(APIRoute):
def __init__(
self,
entrypoint: 'Entrypoint',
path: str,
*,
name: str = None,
errors: List[Type[BaseError]] = None,
common_dependencies: Sequence[Depends] = None,
response_class: Type[Response] = JSONResponse,
request_class: Type[JsonRpcRequest] = JsonRpcRequest,
**kwargs,
):
name = name or 'entrypoint'
_, path_format, _ = compile_path(path)
_Request = request_class
common_dependant = Dependant(path=path_format)
if common_dependencies:
insert_dependencies(common_dependant, common_dependencies)
fix_query_dependencies(common_dependant)
common_dependant = get_flat_dependant(common_dependant, skip_repeats=True)
if common_dependant.body_params:
_Request = make_request_model(name, entrypoint.callee_module, common_dependant.body_params)
# This is only necessary for generating OpenAPI
def endpoint(__request__: _Request):
del __request__
responses = errors_responses(errors)
super().__init__(
path,
endpoint,
methods=['POST'],
name=name,
response_class=response_class,
response_model=JsonRpcResponse,
responses=responses,
**kwargs,
)
flat_dependant = get_flat_dependant(self.dependant, skip_repeats=True)
if len(flat_dependant.body_params) > 1:
body_params = [p for p in flat_dependant.body_params if p.type_ is not _Request]
raise RuntimeError(
f"Entrypoint shared dependencies can't use 'Body' parameters: "
f"params={body_params}"
)
if flat_dependant.query_params:
raise RuntimeError(
f"Entrypoint shared dependencies can't use 'Query' parameters: "
f"params={flat_dependant.query_params}"
)
self.shared_dependant = clone_dependant(self.dependant)
# No shared 'Body' params, because each JSON-RPC request in batch has own body
self.shared_dependant.body_params = []
# Add dependencies and other parameters from common_dependant for correct OpenAPI generation
self.dependant.path_params.extend(common_dependant.path_params)
self.dependant.header_params.extend(common_dependant.header_params)
self.dependant.cookie_params.extend(common_dependant.cookie_params)
self.dependant.dependencies.extend(common_dependant.dependencies)
self.dependant.security_requirements.extend(common_dependant.security_requirements)
self.app = request_response(self.handle_http_request)
self.entrypoint = entrypoint
self.common_dependencies = common_dependencies
self.request_class = request_class
self.errors = errors or []
def __hash__(self):
return hash(self.path)
def __eq__(self, other):
return (
isinstance(other, EntrypointRoute)
and self.path == other.path
)
async def solve_shared_dependencies(
self,
http_request: Request,