Files
smeta-web/stove_api.py
T

239 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Public transport for the stove estimate API."""
from __future__ import annotations
import asyncio
import json
import logging
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, PlainTextResponse
from pydantic import ValidationError
import stove_cache
import stove_calc
import stove_contract as c
import stove_history
import stove_keys
import stove_match
import stove_pricing
log = logging.getLogger("smeta_web")
secure = APIRouter(tags=["stove-estimate"])
public = APIRouter(tags=["stove-estimate"])
_pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="stove-api")
_slots = asyncio.Semaphore(24)
BODY_LIMIT = 256 * 1024
DEADLINE = 45
def _rid(request: Request) -> str:
rid = getattr(request.state, "request_id", None)
if not rid:
rid = uuid.uuid4().hex[:16]
request.state.request_id = rid
return rid
def _error(request: Request, status: int, code: str, detail: str, retry=None, allow=None):
payload = c.StoveError(detail=detail, code=code, request_id=_rid(request),
documentation_url=c.DOCUMENTATION_URL).model_dump()
headers = {"X-Request-Id": _rid(request)}
if retry:
headers["Retry-After"] = str(retry)
if allow:
headers["Allow"] = allow
if status == 401:
headers["WWW-Authenticate"] = "Bearer"
return JSONResponse(payload, status_code=status, headers=headers)
def _ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
async def _run_sync(fn, *args, deadline):
loop = asyncio.get_running_loop()
return await asyncio.wait_for(loop.run_in_executor(_pool, fn, *args),
timeout=max(0.01, deadline-time.monotonic()))
async def _body(request: Request):
length = request.headers.get("content-length")
if length:
try:
if int(length) > BODY_LIMIT:
return None, _error(request, 413, "body_too_large", "Тело запроса больше 256 КБ")
except ValueError:
return None, _error(request, 400, "invalid_request", "Неверный Content-Length")
if request.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
return None, _error(request, 415, "unsupported_media_type", "Нужен application/json")
chunks, size = [], 0
async for chunk in request.stream():
size += len(chunk)
if size > BODY_LIMIT:
return None, _error(request, 413, "body_too_large", "Тело запроса больше 256 КБ")
chunks.append(chunk)
try:
return json.loads(b"".join(chunks)), None
except (ValueError, UnicodeDecodeError, RecursionError):
return None, _error(request, 400, "invalid_json", "Тело запроса не является JSON")
async def _estimate(request: Request):
began, deadline = time.monotonic(), time.monotonic() + DEADLINE
rid = _rid(request)
secret = (request.headers.get("X-API-Key") or "").strip()
try:
auth = await _run_sync(stove_keys.authenticate, secret, _ip(request), deadline=deadline)
except Exception:
log.exception("stove_api: registry error rid=%s", rid)
return _error(request, 503, "service_unavailable", "Реестр ключей временно недоступен", 30)
status = auth["status"]
if status == "invalid_api_key":
return _error(request, 401, "invalid_api_key", "Неверный ключ API")
if status == "address_blocked":
return _error(request, 429, "rate_limited", "Слишком много неверных ключей", auth["retry_after"])
if status == "key_inactive":
return _error(request, 401, "key_inactive", "Ключ API отключён или отозван")
if status == "api_off":
return _error(request, 503, "service_unavailable", "API временно выключен", auth["retry_after"])
key = auth["key"]
try:
admitted = await _run_sync(lambda: stove_history.open_request(
key_id=key["id"], request_id=rid, limit_day=key["limit_day"]), deadline=deadline)
except Exception:
log.exception("stove_api: limit storage error rid=%s", rid)
return _error(request, 503, "service_unavailable", "Лимиты API временно недоступны", 30)
common_headers = {"Infosmeta-RateLimit-Limit": str(admitted["limit"]),
"Infosmeta-RateLimit-Remaining": str(admitted["remaining"])}
if not admitted["admitted"]:
response = _error(request, 429, "rate_limited", "Лимит обращений исчерпан", admitted["retry_after"])
response.headers.update(common_headers)
return response
opened = True
response = _error(request, 500, "internal_error", "Внутренняя ошибка сервера", 30)
request_obj = None
context_len = 0
cached = False
try:
try:
await asyncio.wait_for(_slots.acquire(), timeout=0.01)
except asyncio.TimeoutError:
response = _error(request, 503, "service_unavailable", "Очередь API занята", 30)
return response
try:
raw, bad = await _body(request)
if bad:
response = bad
return response
try:
parsed = c.StoveRequest.model_validate(raw)
except ValidationError as exc:
response = _error(request, 400, "invalid_request", "; ".join(c.problems(exc)))
return response
context_len = len(parsed.stove.context or "")
request_obj = parsed.model_dump(exclude={"stove": {"context"}})
prices = await _run_sync(stove_pricing.load, parsed, deadline=deadline)
version = prices.get("valid_at") or "период не указан"
fingerprint = stove_cache.cache_key(key["id"], request_obj, version,
prices.get("region"), prices.get("zone"))
existing = await _run_sync(stove_cache.response_get, fingerprint, deadline=deadline)
if existing:
answer = existing["response"]
cached = True
else:
prices = await stove_match.fill(prices, key_id=key["id"],
budget=float(key["ai_budget_rub_day"]), deadline=deadline, request_id=rid)
answer = stove_calc.build_answer(parsed, prices)
await _run_sync(lambda: stove_cache.response_put(
fingerprint, key_id=key["id"], response=answer, base_version=version), deadline=deadline)
answer = c.StoveAnswer.model_validate(dict(answer, request_id=rid)).model_dump()
response = JSONResponse(answer, headers={**common_headers, "X-Request-Id": rid})
return response
finally:
_slots.release()
except stove_match.BudgetExhausted:
response = _error(request, 429, "ai_budget_exhausted", "Суточный бюджет подбора исчерпан", 3600)
return response
except stove_match.MatchingUnavailable as exc:
response = _error(request, 503, "matching_unavailable", str(exc), exc.retry_after)
return response
except stove_pricing.InvalidRegion as exc:
response = _error(request, 400, "invalid_request", str(exc))
return response
except stove_pricing.ReferenceUnavailable:
response = _error(request, 503, "service_unavailable", "Нормативные данные временно недоступны", 30)
return response
except asyncio.TimeoutError:
response = _error(request, 503, "service_unavailable", "Срок обработки запроса истёк", 30)
return response
except Exception:
log.exception("stove_api: calculation failed rid=%s", rid)
response = _error(request, 500, "internal_error", "Внутренняя ошибка сервера")
return response
finally:
if opened:
response.headers.update(common_headers)
try:
await asyncio.to_thread(stove_history.finish_request, rid,
status="ok" if response.status_code < 400 else "error",
http_status=response.status_code, request_obj=request_obj,
response_obj=json.loads(response.body), context_present=bool(context_len),
context_len=context_len, duration_ms=int((time.monotonic()-began)*1000),
cached=cached, region=request_obj["stove"]["region"] if request_obj else None,
zone=request_obj["stove"].get("zone") if request_obj else None,
kind=request_obj["stove"]["kind"] if request_obj else None,
error_code=json.loads(response.body).get("code"))
except Exception:
log.exception("stove_api: history write failed rid=%s", rid)
raise HistoryUnavailable(common_headers) from None
class HistoryUnavailable(RuntimeError):
def __init__(self, headers):
self.headers = headers
@secure.post(c.ESTIMATE_PATH, responses={400: {"model": c.StoveError},
401: {"model": c.StoveError},
429: {"model": c.StoveError},
503: {"model": c.StoveError}})
async def estimate(request: Request):
try:
return await _estimate(request)
except HistoryUnavailable as exc:
response = _error(request, 503, "service_unavailable", "История API временно недоступна", 30)
response.headers.update(exc.headers)
return response
PROTOCOL = """# API оценки кладки печи v1\n\nPOST `/api/v1/stove-estimate` с заголовками `X-API-Key: ism_...` и `Content-Type: application/json`. Тело: `{"stove":{"kind":"heating","bricks":{"ceramic":210,"fireclay":76},"region":"Москва","mass_kg":1320,"materials":[{"name":"Глина шамотная","qty":0.5,"unit":"т"}]}}`.\n\nВиды: `heating`, `heating_cooking`, `kitchen`, `bread`, `bath`, `fireplace`. `zone` указывайте для субъекта с несколькими ценовыми зонами. `context` служит только подсказкой и не сохраняется.\n\nОтвет содержит вилку прямых затрат в рублях: `works`, `materials`, `total`, способы в `basis.ways`, подобранные аналоги в `basis.analogues` (исходная и выбранная позиции, код, отличие и источник), неоценённые строки в `missing`, нехватку данных в `missing_data`. Близкие аналоги допускаются при совместимой единице и расхождении размеров не более 20% по каждому измерению; цена ТСН используется только за тот же квартал, что и ФГИС. `null` означает отсутствие проверенной суммы. НР и СП не начислены. Расчёт не является проектом или договором.\n\nКлюч выдаёт оператор и может отключить или отозвать. Лимиты по умолчанию: 1000 ответов за скользящие сутки, 30 обращений в минуту, 256 КБ тела. При 429 ориентируйтесь на `Retry-After`. История запросов без поля `context` хранится до 12 месяцев. Инфосмета должна быть указана как источник расчёта при показе результата человеку.\n\nОшибки: `detail`, `code`, `request_id`, `documentation_url`. Схема: `/api/v1/stove-estimate/openapi.json`.\n"""
@public.get(c.PROTOCOL_PATH)
async def protocol():
return PlainTextResponse(PROTOCOL, media_type="text/markdown; charset=utf-8")
@public.get(c.SCHEMA_PATH)
async def schema():
return JSONResponse({"openapi": "3.1.0", "info": {"title": "Stove Estimate API", "version": "1.0"},
"paths": {c.ESTIMATE_PATH: {"post": {"summary": "Estimate stove masonry",
"security": [{"ApiKey": []}],
"requestBody": {"required": True, "content": {"application/json": {"schema": c.StoveRequest.model_json_schema()}}},
"responses": {"200": {"description": "Estimate", "content": {"application/json": {"schema": c.StoveAnswer.model_json_schema()}}},
"default": {"description": "Error", "content": {"application/json": {"schema": c.StoveError.model_json_schema()}}}}}}},
"components": {"securitySchemes": {"ApiKey": {"type": "apiKey", "in": "header", "name": "X-API-Key"}}}})
@public.api_route("/api/v1/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE"], include_in_schema=False)
async def fallback(request: Request, path: str):
known = {c.ESTIMATE_PATH: "POST", c.PROTOCOL_PATH: "GET", c.SCHEMA_PATH: "GET"}
route = "/api/v1/" + path
if route in known:
return _error(request, 405, "method_not_allowed", "Метод не разрешён", allow=known[route])
return _error(request, 404, "not_found", "Маршрут не найден")