init
This commit is contained in:
30 files changed
+1757
No files matched your search
@@ -0,0 +1,178 @@
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Annotated, cast
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException, Request, Response, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
||||
from redis.asyncio import Redis
|
||||
from starlette.middleware.base import RequestResponseEndpoint
|
||||
|
||||
from warehouse_allocation.application import AllocationService
|
||||
from warehouse_allocation.config import Settings, get_settings
|
||||
from warehouse_allocation.domain.exceptions import (
|
||||
CandidateLimitExceededError,
|
||||
InventoryUnavailableError,
|
||||
NoFeasibleWarehouseError,
|
||||
)
|
||||
from warehouse_allocation.domain.models import (
|
||||
AllocationRequest,
|
||||
AllocationResponse,
|
||||
ErrorDetail,
|
||||
ErrorResponse,
|
||||
HealthResponse,
|
||||
InventoryUpsertRequest,
|
||||
)
|
||||
from warehouse_allocation.infrastructure.inventory import (
|
||||
InMemoryInventoryRepository,
|
||||
InventoryRepository,
|
||||
RedisInventoryRepository,
|
||||
)
|
||||
from warehouse_allocation.metrics import ALLOCATION_DURATION, ALLOCATION_REQUESTS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _inventory_from_settings(settings: Settings) -> InventoryRepository:
|
||||
if settings.inventory_backend == "redis":
|
||||
client = Redis.from_url(
|
||||
settings.redis_url,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=settings.redis_socket_timeout_seconds,
|
||||
socket_timeout=settings.redis_socket_timeout_seconds,
|
||||
health_check_interval=15,
|
||||
)
|
||||
return RedisInventoryRepository(client)
|
||||
return InMemoryInventoryRepository()
|
||||
|
||||
|
||||
def create_app(
|
||||
settings: Settings | None = None,
|
||||
inventory: InventoryRepository | None = None,
|
||||
) -> FastAPI:
|
||||
active_settings = settings or get_settings()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
repository = inventory or _inventory_from_settings(active_settings)
|
||||
app.state.inventory = repository
|
||||
app.state.allocation_service = AllocationService(repository, active_settings)
|
||||
yield
|
||||
await repository.close()
|
||||
|
||||
app = FastAPI(
|
||||
title="Warehouse Allocation Service",
|
||||
version="1.0.0",
|
||||
description="Inventory-aware, traffic-sensitive warehouse routing with atomic reservation.",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.state.settings = active_settings
|
||||
|
||||
def get_inventory(request: Request) -> InventoryRepository:
|
||||
return cast(InventoryRepository, request.app.state.inventory)
|
||||
|
||||
def get_service(request: Request) -> AllocationService:
|
||||
return cast(AllocationService, request.app.state.allocation_service)
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_timing(request: Request, call_next: RequestResponseEndpoint) -> Response:
|
||||
started = time.perf_counter()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Process-Time-Ms"] = f"{(time.perf_counter() - started) * 1000:.2f}"
|
||||
return response
|
||||
|
||||
@app.exception_handler(NoFeasibleWarehouseError)
|
||||
async def no_feasible_handler(request: Request, exc: NoFeasibleWarehouseError) -> JSONResponse:
|
||||
del request
|
||||
ALLOCATION_REQUESTS.labels(result="no_feasible_warehouse").inc()
|
||||
body = ErrorResponse(error=ErrorDetail(code="NO_FEASIBLE_WAREHOUSE", message=str(exc)))
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT, content=body.model_dump(by_alias=True)
|
||||
)
|
||||
|
||||
@app.exception_handler(InventoryUnavailableError)
|
||||
async def inventory_unavailable_handler(
|
||||
request: Request, exc: InventoryUnavailableError
|
||||
) -> JSONResponse:
|
||||
logger.warning("inventory dependency unavailable", exc_info=exc)
|
||||
body = ErrorResponse(
|
||||
error=ErrorDetail(
|
||||
code="INVENTORY_UNAVAILABLE", message="inventory is temporarily unavailable"
|
||||
)
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
content=body.model_dump(by_alias=True),
|
||||
headers={"Retry-After": "1"},
|
||||
)
|
||||
|
||||
@app.exception_handler(CandidateLimitExceededError)
|
||||
async def candidate_limit_handler(
|
||||
request: Request, exc: CandidateLimitExceededError
|
||||
) -> JSONResponse:
|
||||
del request
|
||||
body = ErrorResponse(error=ErrorDetail(code="CANDIDATE_LIMIT_EXCEEDED", message=str(exc)))
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, content=body.model_dump(by_alias=True)
|
||||
)
|
||||
|
||||
@app.post(
|
||||
"/v1/allocations",
|
||||
response_model=AllocationResponse,
|
||||
responses={
|
||||
400: {"model": ErrorResponse},
|
||||
409: {"model": ErrorResponse},
|
||||
503: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
async def allocate(
|
||||
payload: AllocationRequest,
|
||||
service: Annotated[AllocationService, Depends(get_service)],
|
||||
) -> AllocationResponse:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
result = await service.allocate(payload)
|
||||
ALLOCATION_REQUESTS.labels(result="success").inc()
|
||||
return result
|
||||
finally:
|
||||
ALLOCATION_DURATION.observe(time.perf_counter() - started)
|
||||
|
||||
@app.put("/v1/inventory", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def upsert_inventory(
|
||||
payload: InventoryUpsertRequest,
|
||||
repository: Annotated[InventoryRepository, Depends(get_inventory)],
|
||||
x_admin_token: Annotated[str | None, Header()] = None,
|
||||
) -> Response:
|
||||
expected = active_settings.inventory_admin_token
|
||||
if expected is not None and x_admin_token != expected:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid admin token"
|
||||
)
|
||||
await repository.set_levels(
|
||||
payload.warehouse_id, {level.sku: level.quantity for level in payload.levels}
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
@app.get("/health/live", response_model=HealthResponse)
|
||||
async def liveness() -> HealthResponse:
|
||||
return HealthResponse(status="ok", service=active_settings.app_name)
|
||||
|
||||
@app.get("/health/ready", response_model=HealthResponse)
|
||||
async def readiness(
|
||||
repository: Annotated[InventoryRepository, Depends(get_inventory)],
|
||||
) -> HealthResponse:
|
||||
ready = await repository.ping()
|
||||
if not ready:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="not ready")
|
||||
return HealthResponse(status="ok", service=active_settings.app_name, inventory="ok")
|
||||
|
||||
@app.get("/metrics", include_in_schema=False)
|
||||
async def metrics() -> Response:
|
||||
return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
Reference in new issue
Block a user