Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance code quality #6

Merged
merged 21 commits into from
May 31, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions trolldb/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"""

import asyncio
import sys
import time
from contextlib import contextmanager
from multiprocessing import Process
Expand All @@ -26,7 +27,7 @@
from pydantic import FilePath, ValidationError, validate_call

from trolldb.api.routes import api_router
from trolldb.config.config import AppConfig, Timeout, parse_config_yaml_file
from trolldb.config.config import AppConfig, Timeout, parse_config
from trolldb.database.mongodb import mongodb_context
from trolldb.errors.errors import ResponseError

Expand All @@ -46,6 +47,7 @@
"""These will appear in the auto-generated documentation and are passed to the ``FastAPI`` class as keyword args."""


@logger.catch(onerror=lambda _: sys.exit(1))
@validate_call
def run_server(config: Union[AppConfig, FilePath], **kwargs) -> None:
"""Runs the API server with all the routes and connection to the database.
Expand All @@ -68,10 +70,6 @@
take precedence over ``config``. Finally, :obj:`API_INFO`, which are hard-coded information for the API
server, will be concatenated and takes precedence over all.

Raises:
ValidationError:
If the function is not called with arguments of valid type.

Example:
.. code-block:: python

Expand All @@ -81,7 +79,7 @@
"""
logger.info("Attempt to run the API server ...")
if not isinstance(config, AppConfig):
config = parse_config_yaml_file(config)
config = parse_config(config)

Check warning on line 82 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L82

Added line #L82 was not covered by tests
pkhalaj marked this conversation as resolved.
Show resolved Hide resolved

# Concatenate the keyword arguments for the API server in the order of precedence (lower to higher).
app = FastAPI(**(config.api_server._asdict() | kwargs | API_INFO))
Expand All @@ -89,7 +87,7 @@
app.include_router(api_router)

@app.exception_handler(ResponseError)
async def auto_handler_response_errors(_, exc: ResponseError) -> PlainTextResponse:

Check warning on line 90 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L90

Added line #L90 was not covered by tests
"""Catches all the exceptions raised as a ResponseError, e.g. accessing non-existing databases/collections."""
status_code, message = exc.get_error_details()
info = dict(
Expand All @@ -99,13 +97,13 @@
logger.error(f"Response error caught by the API auto exception handler: {info}")
return PlainTextResponse(**info)

@app.exception_handler(ValidationError)
async def auto_handler_pydantic_validation_errors(_, exc: ValidationError) -> PlainTextResponse:

Check warning on line 101 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L100-L101

Added lines #L100 - L101 were not covered by tests
"""Catches all the exceptions raised as a Pydantic ValidationError."""
logger.error(f"Response error caught by the API auto exception handler: {exc}")
return PlainTextResponse(str(exc), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)

Check warning on line 104 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L103-L104

Added lines #L103 - L104 were not covered by tests

async def _serve() -> NoReturn:

Check warning on line 106 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L106

Added line #L106 was not covered by tests
"""An auxiliary coroutine to be used in the asynchronous execution of the FastAPI application."""
async with mongodb_context(config.database):
logger.info("Attempt to start the uvicorn server ...")
Expand Down Expand Up @@ -140,7 +138,7 @@
"""
logger.info("Attempt to run the API server process in a context manager ...")
if not isinstance(config, AppConfig):
config = parse_config_yaml_file(config)
config = parse_config(config)

Check warning on line 141 in trolldb/api/api.py

View check run for this annotation

Codecov / codecov/patch

trolldb/api/api.py#L141

Added line #L141 was not covered by tests
pkhalaj marked this conversation as resolved.
Show resolved Hide resolved

process = Process(target=run_server, args=(config,))
try:
Expand Down
Loading