This commit is contained in:
Meghdad committed 2026-07-23 06:40:30 +03:30
1 parent 26d41cd03f
commit db57e0e4a2
30 files changed
+1757

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
"""Warehouse allocation microservice."""
__version__ = "1.0.0"
+178
View File
@@ -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()
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
from warehouse_allocation.config import Settings
from warehouse_allocation.domain.exceptions import (
CandidateLimitExceededError,
NoFeasibleWarehouseError,
)
from warehouse_allocation.domain.models import AllocationRequest, AllocationResponse
from warehouse_allocation.domain.optimizer import rank_warehouses
from warehouse_allocation.infrastructure.inventory import InventoryRepository
class AllocationService:
def __init__(self, inventory: InventoryRepository, settings: Settings) -> None:
self._inventory = inventory
self._settings = settings
async def allocate(self, request: AllocationRequest) -> AllocationResponse:
warehouse_ids = [item.warehouse_id for item in request.transportation_costs]
if len(warehouse_ids) > self._settings.max_candidate_warehouses:
limit = self._settings.max_candidate_warehouses
raise CandidateLimitExceededError(f"at most {limit} candidate warehouses are allowed")
required = {item.sku: item.quantity for item in request.items}
feasible = await self._inventory.feasible_warehouses(warehouse_ids, required)
ranked = rank_warehouses(request, feasible)
if not ranked:
raise NoFeasibleWarehouseError("no warehouse can fulfill the complete order")
selected = ranked[0]
reserved = False
if request.reserve_inventory:
# A concurrent order can consume the first choice after the read. Try the remaining
# ranked candidates; each reservation itself is atomic in the repository.
for candidate in ranked:
if await self._inventory.reserve(candidate.warehouse_id, required):
selected = candidate
reserved = True
break
if not reserved:
raise NoFeasibleWarehouseError(
"inventory changed before reservation; no candidate can fulfill the order"
)
return AllocationResponse(
request_id=request.request_id,
warehouse_id=selected.warehouse_id,
estimated_delivery_time=round(selected.delivery_minutes),
total_cost=round(selected.total_cost, 2),
route_optimization_score=round(selected.score, 2),
inventory_reserved=reserved,
score_breakdown=selected.breakdown,
)
+23
View File
@@ -0,0 +1,23 @@
from functools import lru_cache
from typing import Literal
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="WA_", env_file=".env", extra="ignore")
app_name: str = "warehouse-allocation"
environment: str = "development"
log_level: str = "INFO"
inventory_backend: Literal["memory", "redis"] = "memory"
redis_url: str = "redis://localhost:6379/0"
redis_socket_timeout_seconds: float = Field(default=0.08, gt=0, le=1)
max_candidate_warehouses: int = Field(default=33, ge=1, le=500)
inventory_admin_token: str | None = None
@lru_cache
def get_settings() -> Settings:
return Settings()
@@ -0,0 +1 @@
"""Domain models and allocation logic."""
@@ -0,0 +1,14 @@
class AllocationError(Exception):
"""Base class for expected allocation failures."""
class NoFeasibleWarehouseError(AllocationError):
"""No candidate can fulfill every item in the order."""
class InventoryUnavailableError(AllocationError):
"""Inventory storage could not be reached within its latency budget."""
class CandidateLimitExceededError(AllocationError):
"""The request would exceed the configured latency guardrail."""
+137
View File
@@ -0,0 +1,137 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
Sku = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)]
WarehouseId = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)]
def to_camel(value: str) -> str:
head, *tail = value.split("_")
return head + "".join(word.capitalize() for word in tail)
class ApiModel(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel,
populate_by_name=True,
extra="forbid",
str_strip_whitespace=True,
)
class CustomerLocation(ApiModel):
latitude: float = Field(ge=-90, le=90)
longitude: float = Field(ge=-180, le=180)
class OrderItem(ApiModel):
sku: Sku
quantity: int = Field(gt=0, le=100_000)
class TransportationCost(ApiModel):
warehouse_id: WarehouseId
fixed_cost: float = Field(ge=0)
distance_km: float = Field(ge=0)
cost_per_km: float = Field(default=0, ge=0)
base_delivery_minutes: float = Field(gt=0, le=43_200)
surcharge: float = Field(default=0, ge=0)
class LogisticsConstraint(ApiModel):
warehouse_id: WarehouseId
traffic_multiplier: float = Field(default=1, ge=0.1, le=10)
fleet_priority: float = Field(
default=1,
ge=0.1,
le=5,
description="Values above one represent preferred/faster fleet capacity.",
)
handling_minutes: float = Field(default=0, ge=0, le=1_440)
available: bool = True
class OptimizationWeights(ApiModel):
cost: float = Field(default=0.7, ge=0, le=1)
delivery_time: float = Field(default=0.3, ge=0, le=1)
@model_validator(mode="after")
def weights_must_sum_to_one(self) -> OptimizationWeights:
if abs((self.cost + self.delivery_time) - 1) > 1e-6:
raise ValueError("cost and deliveryTime weights must sum to 1")
return self
class AllocationRequest(ApiModel):
request_id: Annotated[str, StringConstraints(min_length=1, max_length=128)]
customer_location: CustomerLocation
items: list[OrderItem] = Field(min_length=1, max_length=100)
transportation_costs: list[TransportationCost] = Field(min_length=1, max_length=500)
logistics_constraints: list[LogisticsConstraint] = Field(default_factory=list, max_length=500)
weights: OptimizationWeights = Field(default_factory=OptimizationWeights)
promised_delivery_minutes: float | None = Field(default=None, gt=0, le=43_200)
reserve_inventory: bool = False
@model_validator(mode="after")
def identifiers_must_be_unique(self) -> AllocationRequest:
skus = [item.sku for item in self.items]
if len(skus) != len(set(skus)):
raise ValueError("items must contain unique SKUs")
warehouse_ids = [cost.warehouse_id for cost in self.transportation_costs]
if len(warehouse_ids) != len(set(warehouse_ids)):
raise ValueError("transportationCosts must contain unique warehouse IDs")
constraint_ids = [constraint.warehouse_id for constraint in self.logistics_constraints]
if len(constraint_ids) != len(set(constraint_ids)):
raise ValueError("logisticsConstraints must contain unique warehouse IDs")
unknown = set(constraint_ids) - set(warehouse_ids)
if unknown:
raise ValueError(f"constraints reference unknown warehouses: {sorted(unknown)}")
return self
class ScoreBreakdown(ApiModel):
transport_cost: float
normalized_cost: float
normalized_delivery_time: float
sla_penalty: float
feasible_warehouse_count: int
class AllocationResponse(ApiModel):
request_id: str
warehouse_id: str
estimated_delivery_time: int
total_cost: float
route_optimization_score: float
inventory_reserved: bool
score_breakdown: ScoreBreakdown
calculated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class InventoryLevel(ApiModel):
sku: Sku
quantity: int = Field(ge=0, le=2_147_483_647)
class InventoryUpsertRequest(ApiModel):
warehouse_id: WarehouseId
levels: list[InventoryLevel] = Field(min_length=1, max_length=10_000)
class HealthResponse(ApiModel):
status: str
service: str
inventory: str | None = None
class ErrorDetail(ApiModel):
code: str
message: str
class ErrorResponse(ApiModel):
error: ErrorDetail
@@ -0,0 +1,106 @@
from __future__ import annotations
from dataclasses import dataclass
from warehouse_allocation.domain.models import (
AllocationRequest,
LogisticsConstraint,
ScoreBreakdown,
TransportationCost,
)
@dataclass(frozen=True, slots=True)
class RankedWarehouse:
warehouse_id: str
delivery_minutes: float
total_cost: float
objective: float
score: float
breakdown: ScoreBreakdown
def _min_max(value: float, values: list[float]) -> float:
low, high = min(values), max(values)
if high == low:
return 0.0
return (value - low) / (high - low)
def _effective_values(
cost: TransportationCost, constraint: LogisticsConstraint
) -> tuple[float, float]:
raw_cost = cost.fixed_cost + (cost.distance_km * cost.cost_per_km) + cost.surcharge
# Congestion consumes fuel/driver time, while preferred fleet capacity lowers that overhead.
congestion_cost_factor = 1 + max(0.0, constraint.traffic_multiplier - 1) * 0.15
total_cost = raw_cost * congestion_cost_factor / constraint.fleet_priority
delivery_minutes = (
cost.base_delivery_minutes * constraint.traffic_multiplier + constraint.handling_minutes
) / constraint.fleet_priority
return total_cost, delivery_minutes
def rank_warehouses(request: AllocationRequest, feasible_ids: set[str]) -> list[RankedWarehouse]:
constraints = {item.warehouse_id: item for item in request.logistics_constraints}
candidates: list[tuple[str, float, float]] = []
for cost in request.transportation_costs:
constraint = constraints.get(cost.warehouse_id) or LogisticsConstraint(
warehouse_id=cost.warehouse_id
)
if cost.warehouse_id not in feasible_ids or not constraint.available:
continue
total_cost, delivery_minutes = _effective_values(cost, constraint)
candidates.append((cost.warehouse_id, total_cost, delivery_minutes))
if not candidates:
return []
costs = [candidate[1] for candidate in candidates]
delivery_times = [candidate[2] for candidate in candidates]
ranked: list[RankedWarehouse] = []
for warehouse_id, total_cost, delivery_minutes in candidates:
normalized_cost = _min_max(total_cost, costs)
normalized_time = _min_max(delivery_minutes, delivery_times)
sla_penalty = 0.0
if (
request.promised_delivery_minutes
and delivery_minutes > request.promised_delivery_minutes
):
overrun_ratio = (
delivery_minutes - request.promised_delivery_minutes
) / request.promised_delivery_minutes
sla_penalty = min(0.25, overrun_ratio * 0.25)
objective = min(
1.0,
request.weights.cost * normalized_cost
+ request.weights.delivery_time * normalized_time
+ sla_penalty,
)
ranked.append(
RankedWarehouse(
warehouse_id=warehouse_id,
delivery_minutes=delivery_minutes,
total_cost=total_cost,
objective=objective,
score=(1 - objective) * 100,
breakdown=ScoreBreakdown(
transport_cost=round(total_cost, 2),
normalized_cost=round(normalized_cost, 6),
normalized_delivery_time=round(normalized_time, 6),
sla_penalty=round(sla_penalty, 6),
feasible_warehouse_count=len(candidates),
),
)
)
return sorted(
ranked,
key=lambda candidate: (
candidate.objective,
candidate.total_cost,
candidate.delivery_minutes,
candidate.warehouse_id,
),
)
@@ -0,0 +1 @@
"""Infrastructure adapters."""
@@ -0,0 +1,143 @@
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Mapping, Sequence
from typing import Any, Protocol, cast
from redis.asyncio import Redis
from redis.exceptions import RedisError
from warehouse_allocation.domain.exceptions import InventoryUnavailableError
class InventoryRepository(Protocol):
async def feasible_warehouses(
self, warehouse_ids: Sequence[str], required: Mapping[str, int]
) -> set[str]: ...
async def reserve(self, warehouse_id: str, required: Mapping[str, int]) -> bool: ...
async def set_levels(self, warehouse_id: str, levels: Mapping[str, int]) -> None: ...
async def ping(self) -> bool: ...
async def close(self) -> None: ...
class InMemoryInventoryRepository:
"""Development/test adapter; every mutation is protected by one process-local lock."""
def __init__(self) -> None:
self._stock: dict[str, dict[str, int]] = {}
self._lock = asyncio.Lock()
async def feasible_warehouses(
self, warehouse_ids: Sequence[str], required: Mapping[str, int]
) -> set[str]:
async with self._lock:
return {
warehouse_id
for warehouse_id in warehouse_ids
if all(
self._stock.get(warehouse_id, {}).get(sku, 0) >= quantity
for sku, quantity in required.items()
)
}
async def reserve(self, warehouse_id: str, required: Mapping[str, int]) -> bool:
async with self._lock:
warehouse = self._stock.get(warehouse_id, {})
if not all(warehouse.get(sku, 0) >= quantity for sku, quantity in required.items()):
return False
for sku, quantity in required.items():
warehouse[sku] -= quantity
return True
async def set_levels(self, warehouse_id: str, levels: Mapping[str, int]) -> None:
async with self._lock:
warehouse = self._stock.setdefault(warehouse_id, {})
warehouse.update(levels)
async def ping(self) -> bool:
return True
async def close(self) -> None:
return None
_RESERVE_LUA = """
local key = KEYS[1]
for i = 1, #ARGV, 2 do
local available = tonumber(redis.call('HGET', key, ARGV[i]) or '0')
local requested = tonumber(ARGV[i + 1])
if available < requested then
return 0
end
end
for i = 1, #ARGV, 2 do
redis.call('HINCRBY', key, ARGV[i], -tonumber(ARGV[i + 1]))
end
return 1
"""
class RedisInventoryRepository:
"""Fast stock projections in Redis, with all-SKU atomic reservations via Lua."""
def __init__(self, client: Redis) -> None:
self._client = client
@staticmethod
def _key(warehouse_id: str) -> str:
return f"inventory:{warehouse_id}"
async def feasible_warehouses(
self, warehouse_ids: Sequence[str], required: Mapping[str, int]
) -> set[str]:
try:
async with self._client.pipeline(transaction=False) as pipeline:
for warehouse_id in warehouse_ids:
pipeline.hmget(self._key(warehouse_id), list(required))
rows = await pipeline.execute()
except RedisError as exc:
raise InventoryUnavailableError("inventory store unavailable") from exc
feasible: set[str] = set()
for warehouse_id, row in zip(warehouse_ids, rows, strict=True):
available = [int(value or 0) for value in row]
if all(
stock >= requested
for stock, requested in zip(available, required.values(), strict=True)
):
feasible.add(warehouse_id)
return feasible
async def reserve(self, warehouse_id: str, required: Mapping[str, int]) -> bool:
arguments: list[str] = []
for sku, quantity in required.items():
arguments.extend((sku, str(quantity)))
try:
result = await cast(
Awaitable[Any],
self._client.eval(_RESERVE_LUA, 1, self._key(warehouse_id), *arguments),
)
except RedisError as exc:
raise InventoryUnavailableError("inventory store unavailable") from exc
return bool(result)
async def set_levels(self, warehouse_id: str, levels: Mapping[str, int]) -> None:
try:
await cast(
Awaitable[int], self._client.hset(self._key(warehouse_id), mapping=dict(levels))
)
except RedisError as exc:
raise InventoryUnavailableError("inventory store unavailable") from exc
async def ping(self) -> bool:
try:
return bool(await self._client.ping())
except RedisError:
return False
async def close(self) -> None:
await self._client.aclose()
+12
View File
@@ -0,0 +1,12 @@
from prometheus_client import Counter, Histogram
ALLOCATION_REQUESTS = Counter(
"warehouse_allocation_requests_total",
"Allocation attempts grouped by result.",
("result",),
)
ALLOCATION_DURATION = Histogram(
"warehouse_allocation_duration_seconds",
"End-to-end allocation request duration.",
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.2, 0.5, 1),
)