006 add controller

This commit is contained in:
Раис Юсупалиев
2026-03-07 23:54:40 +03:00
parent 082e5c11ec
commit 150675cc75
5 changed files with 347 additions and 6 deletions
+62 -1
View File
@@ -1,5 +1,66 @@
"""Delivery API controller skeleton."""
from fastapi import APIRouter
from fastapi import APIRouter, Depends, HTTPException, Request, status
from app.adapters.delivery_providers.cdek import CDEKProvider
from app.config import Settings
from app.controllers.http_client import build_controller_http_client
from app.repositories.cache.redis_cache import PriceCache
from app.schemas.request import DeliveryRequest
from app.schemas.response import DeliveryPrice
from app.services.aggregator import AggregatorService, AggregatorServiceError
router = APIRouter(prefix="/delivery", tags=["delivery"])
_AGGREGATOR_SERVICE_STATE_KEY = "aggregator_service"
def _build_aggregator_service(settings: Settings) -> AggregatorService:
http_client = build_controller_http_client(
timeout_seconds=settings.adapter.cdek_timeout_seconds
)
providers = (
CDEKProvider.from_adapter_config(
http_client=http_client,
adapter_config=settings.adapter,
),
)
cache = PriceCache.from_repository_config(settings.repository)
service = AggregatorService(
providers=providers,
cache=cache,
weight_round_scale=settings.business_logic.weight_round_scale,
)
return service
async def get_aggregator_service(request: Request) -> AggregatorService:
cached_service = getattr(request.app.state, _AGGREGATOR_SERVICE_STATE_KEY, None)
if cached_service is not None:
return cached_service
settings = request.app.state.settings
service = _build_aggregator_service(settings)
setattr(request.app.state, _AGGREGATOR_SERVICE_STATE_KEY, service)
return service
@router.post(
"/price",
response_model=list[DeliveryPrice],
)
async def get_delivery_price(
delivery_request: DeliveryRequest,
service: AggregatorService = Depends(get_aggregator_service),
) -> list[DeliveryPrice]:
try:
return await service.get_all_prices(delivery_request)
except AggregatorServiceError as exc:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={
"code": "aggregator_service_error",
"message": "Delivery price aggregation is temporarily unavailable.",
},
) from exc
+4
View File
@@ -17,6 +17,10 @@ from app.schemas.request import DeliveryRequest
from app.schemas.response import DeliveryPrice
class AggregatorServiceError(RuntimeError):
"""Base exception for AggregatorService failures."""
class PriceCacheProtocol(Protocol):
async def get(self, key: str) -> object | None: ...