_app.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. import contextlib
  16. import json
  17. from typing import (
  18. Any,
  19. AsyncGenerator,
  20. Callable,
  21. Dict,
  22. Generic,
  23. List,
  24. Optional,
  25. Tuple,
  26. TypedDict,
  27. TypeVar,
  28. )
  29. import aiohttp
  30. import fastapi
  31. from fastapi.encoders import jsonable_encoder
  32. from fastapi.exceptions import RequestValidationError
  33. from fastapi.responses import JSONResponse
  34. from starlette.exceptions import HTTPException
  35. from typing_extensions import ParamSpec, TypeGuard
  36. from ....utils import logging
  37. from ...pipelines import BasePipeline
  38. from ..infra.config import AppConfig
  39. from ..infra.models import NoResultResponse
  40. from ..infra.utils import call_async, generate_log_id
  41. PipelineT = TypeVar("PipelineT", bound=BasePipeline)
  42. P = ParamSpec("P")
  43. R = TypeVar("R")
  44. class _Error(TypedDict):
  45. error: str
  46. def _is_error(obj: object) -> TypeGuard[_Error]:
  47. return (
  48. isinstance(obj, dict)
  49. and obj.keys() == {"error"}
  50. and isinstance(obj["error"], str)
  51. )
  52. # XXX: Since typing info (e.g., the pipeline class) cannot be easily obtained
  53. # without abstraction leaks, generic classes do not offer additional benefits
  54. # for type hinting. However, I would stick with the current design, as it does
  55. # not introduce runtime overhead at the moment and may prove useful in the
  56. # future.
  57. class PipelineWrapper(Generic[PipelineT]):
  58. def __init__(self, pipeline: PipelineT) -> None:
  59. super().__init__()
  60. self._pipeline = pipeline
  61. self._lock = asyncio.Lock()
  62. @property
  63. def pipeline(self) -> PipelineT:
  64. return self._pipeline
  65. async def infer(self, *args: Any, **kwargs: Any) -> List[Any]:
  66. def _infer() -> List[Any]:
  67. output: list = []
  68. with contextlib.closing(self._pipeline(*args, **kwargs)) as it:
  69. for item in it:
  70. if _is_error(item):
  71. raise fastapi.HTTPException(
  72. status_code=500, detail=item["error"]
  73. )
  74. output.append(item)
  75. return output
  76. return await self.call(_infer)
  77. async def call(self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:
  78. async with self._lock:
  79. return await call_async(func, *args, **kwargs)
  80. class AppContext(Generic[PipelineT]):
  81. def __init__(self, *, config: AppConfig) -> None:
  82. super().__init__()
  83. self._config = config
  84. self.extra: Dict[str, Any] = {}
  85. self._pipeline: Optional[PipelineWrapper[PipelineT]] = None
  86. self._aiohttp_session: Optional[aiohttp.ClientSession] = None
  87. @property
  88. def config(self) -> AppConfig:
  89. return self._config
  90. @property
  91. def pipeline(self) -> PipelineWrapper[PipelineT]:
  92. if not self._pipeline:
  93. raise AttributeError("`pipeline` has not been set.")
  94. return self._pipeline
  95. @pipeline.setter
  96. def pipeline(self, val: PipelineWrapper[PipelineT]) -> None:
  97. self._pipeline = val
  98. @property
  99. def aiohttp_session(self) -> aiohttp.ClientSession:
  100. if not self._aiohttp_session:
  101. raise AttributeError("`aiohttp_session` has not been set.")
  102. return self._aiohttp_session
  103. @aiohttp_session.setter
  104. def aiohttp_session(self, val: aiohttp.ClientSession) -> None:
  105. self._aiohttp_session = val
  106. def create_app(
  107. *, pipeline: PipelineT, app_config: AppConfig, app_aiohttp_session: bool = True
  108. ) -> Tuple[fastapi.FastAPI, AppContext[PipelineT]]:
  109. @contextlib.asynccontextmanager
  110. async def _app_lifespan(app: fastapi.FastAPI) -> AsyncGenerator[None, None]:
  111. ctx.pipeline = PipelineWrapper[PipelineT](pipeline)
  112. if app_aiohttp_session:
  113. async with aiohttp.ClientSession(
  114. cookie_jar=aiohttp.DummyCookieJar()
  115. ) as aiohttp_session:
  116. ctx.aiohttp_session = aiohttp_session
  117. yield
  118. else:
  119. yield
  120. # Should we control API versions?
  121. app = fastapi.FastAPI(lifespan=_app_lifespan)
  122. ctx = AppContext[PipelineT](config=app_config)
  123. app.state.context = ctx
  124. @app.get("/health", operation_id="checkHealth")
  125. async def _check_health() -> NoResultResponse:
  126. return NoResultResponse(
  127. logId=generate_log_id(), errorCode=0, errorMsg="Healthy"
  128. )
  129. @app.exception_handler(RequestValidationError)
  130. async def _validation_exception_handler(
  131. request: fastapi.Request, exc: RequestValidationError
  132. ) -> JSONResponse:
  133. json_compatible_data = jsonable_encoder(
  134. NoResultResponse(
  135. logId=generate_log_id(),
  136. errorCode=422,
  137. errorMsg=json.dumps(exc.errors()),
  138. )
  139. )
  140. return JSONResponse(content=json_compatible_data, status_code=422)
  141. @app.exception_handler(HTTPException)
  142. async def _http_exception_handler(
  143. request: fastapi.Request, exc: HTTPException
  144. ) -> JSONResponse:
  145. json_compatible_data = jsonable_encoder(
  146. NoResultResponse(
  147. logId=generate_log_id(), errorCode=exc.status_code, errorMsg=exc.detail
  148. )
  149. )
  150. return JSONResponse(content=json_compatible_data, status_code=exc.status_code)
  151. @app.exception_handler(Exception)
  152. async def _unexpected_exception_handler(
  153. request: fastapi.Request, exc: Exception
  154. ) -> JSONResponse:
  155. # XXX: The default server will duplicate the error message. Is it
  156. # necessary to log the exception info here?
  157. logging.exception("Unhandled exception")
  158. json_compatible_data = jsonable_encoder(
  159. NoResultResponse(
  160. logId=generate_log_id(),
  161. errorCode=500,
  162. errorMsg="Internal server error",
  163. )
  164. )
  165. return JSONResponse(content=json_compatible_data, status_code=500)
  166. return app, ctx
  167. # TODO: Precise type hints
  168. def primary_operation(
  169. app: fastapi.FastAPI, path: str, operation_id: str, **kwargs: Any
  170. ) -> Callable:
  171. return app.post(
  172. path,
  173. operation_id=operation_id,
  174. responses={422: {"model": NoResultResponse}, 500: {"model": NoResultResponse}},
  175. response_model_exclude_none=True,
  176. **kwargs,
  177. )