/
server.py
164 lines (134 loc) · 4.96 KB
/
server.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
# coding=utf-8
# Copyright 2021-present, the Recognai S.L. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This module configures the global fastapi application
"""
import logging
import os
from pathlib import Path
from brotli_asgi import BrotliMiddleware
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from pydantic import ConfigError
from rubrix import __version__ as rubrix_version
from rubrix.server.commons.es_wrapper import create_es_wrapper
from rubrix.server.commons.static_rewrite import RewriteStaticFiles
from rubrix.server.datasets.dao import DatasetsDAO
from rubrix.server.security import auth
from rubrix.server.tasks.commons.dao.dao import DatasetRecordsDAO
from ..logging import LoguruLoggerHandler
from .commons.errors import APIErrorHandler
from .commons.settings import settings
from .commons.settings import settings as api_settings
from .routes import api_router
def configure_middleware(app: FastAPI):
"""Configures fastapi middleware"""
app.add_middleware(
CORSMiddleware,
allow_origins=api_settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(BrotliMiddleware, minimum_size=512, quality=7)
def configure_api_exceptions(api: FastAPI):
"""Configures fastapi exception handlers"""
api.exception_handler(Exception)(APIErrorHandler.common_exception_handler)
api.exception_handler(RequestValidationError)(
APIErrorHandler.common_exception_handler
)
def configure_api_router(app: FastAPI):
"""Configures and set the api router to app"""
app.include_router(api_router, prefix="/api")
def configure_app_statics(app: FastAPI):
"""Configure static folder for app"""
parent_path = Path(__file__).parent.absolute()
app.mount(
"/",
RewriteStaticFiles(
directory=os.path.join(
parent_path,
"static",
),
html=True,
check_dir=False,
),
name="static",
)
def configure_app_storage(app: FastAPI):
@app.on_event("startup")
async def configure_elasticsearch():
import opensearchpy
try:
es_wrapper = create_es_wrapper()
dataset_records: DatasetRecordsDAO = DatasetRecordsDAO(es_wrapper)
datasets: DatasetsDAO = DatasetsDAO.get_instance(
es_wrapper, records_dao=dataset_records
)
datasets.init()
dataset_records.init()
except opensearchpy.exceptions.ConnectionError as error:
raise ConfigError(
f"Your Elasticsearch endpoint at {settings.obfuscated_elasticsearch()} "
"is not available or not responding.\n"
"Please make sure your Elasticsearch instance is launched and correctly running and\n"
"you have the necessary access permissions. "
"Once you have verified this, restart the Rubrix server.\n"
) from error
def configure_app_security(app: FastAPI):
if hasattr(auth, "router"):
app.include_router(auth.router)
def configure_app_logging(app: FastAPI):
"""Configure app logging using"""
intercept_handler = LoguruLoggerHandler()
if not intercept_handler.is_available:
return
def _inner_logging_config():
logging.basicConfig(handlers=[intercept_handler], level=logging.WARNING)
for name in logging.root.manager.loggerDict:
logger = logging.getLogger(name)
logger.handlers = []
for name in [
"uvicorn",
"uvicorn.lifespan",
"uvicorn.error",
"uvicorn.access",
"fastapi",
]:
logger = logging.getLogger(name)
logger.propagate = False
logger.handlers = [intercept_handler]
_inner_logging_config()
app.on_event("startup")(_inner_logging_config)
app = FastAPI(
title="Rubrix",
description="Rubrix API",
# Disable default openapi configuration
openapi_url="/api/docs/spec.json",
docs_url="/api/docs" if api_settings.docs_enabled else None,
redoc_url=None,
version=str(rubrix_version),
)
for app_configure in [
configure_app_logging,
configure_middleware,
configure_api_exceptions,
configure_app_security,
configure_api_router,
configure_app_statics,
configure_app_storage,
]:
app_configure(app)