2020-04-15 14:04:30 +02:00
|
|
|
import logging
|
2020-07-07 12:28:41 +02:00
|
|
|
import time
|
2020-04-15 14:04:30 +02:00
|
|
|
|
|
|
|
from fastapi import APIRouter
|
2020-10-15 18:41:36 +02:00
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
from rest_api.application import PIPELINE
|
|
|
|
from rest_api.config import LOG_LEVEL, CONCURRENT_REQUEST_PER_WORKER
|
|
|
|
from rest_api.schema import QueryRequest, QueryResponse
|
2020-06-22 12:07:12 +02:00
|
|
|
from rest_api.controller.utils import RequestLimiter
|
2020-04-15 14:04:30 +02:00
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
|
2021-04-07 17:53:32 +02:00
|
|
|
logging.getLogger("haystack").setLevel(LOG_LEVEL)
|
|
|
|
logger = logging.getLogger("haystack")
|
2020-11-04 09:54:02 +01:00
|
|
|
|
2021-04-07 17:53:32 +02:00
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
router = APIRouter()
|
2021-06-29 07:44:25 +02:00
|
|
|
concurrency_limiter = RequestLimiter(CONCURRENT_REQUEST_PER_WORKER)
|
2021-04-07 17:53:32 +02:00
|
|
|
|
|
|
|
|
2021-09-27 16:40:25 +02:00
|
|
|
@router.get("/initialized")
|
|
|
|
def initialized():
|
|
|
|
"""
|
|
|
|
This endpoint can be used during startup to understand if the
|
|
|
|
server is ready to take any requests, or is still loading.
|
|
|
|
|
|
|
|
The recommended approach is to call this endpoint with a short timeout,
|
|
|
|
like 500ms, and in case of no reply, consider the server busy.
|
|
|
|
"""
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
@router.post("/query", response_model=QueryResponse)
|
|
|
|
def query(request: QueryRequest):
|
2021-04-07 17:53:32 +02:00
|
|
|
with concurrency_limiter.run():
|
|
|
|
result = _process_request(PIPELINE, request)
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2021-10-04 11:21:00 +02:00
|
|
|
def _process_request(pipeline, request) -> QueryResponse:
|
2021-04-07 17:53:32 +02:00
|
|
|
start_time = time.time()
|
|
|
|
|
2021-09-10 11:41:16 +02:00
|
|
|
params = request.params or {}
|
2021-09-10 14:47:34 +02:00
|
|
|
params["filters"] = params.get("filters") or {}
|
2021-04-07 17:53:32 +02:00
|
|
|
filters = {}
|
2021-09-10 11:41:16 +02:00
|
|
|
if "filters" in params: # put filter values into a list and remove filters with null value
|
|
|
|
for key, values in params["filters"].items():
|
2021-04-07 17:53:32 +02:00
|
|
|
if values is None:
|
|
|
|
continue
|
|
|
|
if not isinstance(values, list):
|
|
|
|
values = [values]
|
|
|
|
filters[key] = values
|
2021-09-10 11:41:16 +02:00
|
|
|
params["filters"] = filters
|
|
|
|
result = pipeline.run(query=request.query, params=params)
|
2020-10-16 13:25:31 +02:00
|
|
|
end_time = time.time()
|
2021-09-10 11:41:16 +02:00
|
|
|
logger.info({"request": request.dict(), "response": result, "time": f"{(end_time - start_time):.2f}"})
|
2021-04-07 17:53:32 +02:00
|
|
|
|
|
|
|
return result
|