init
This commit is contained in:
30 files changed
+1757
No files matched your search
@@ -0,0 +1,12 @@
|
|||||||
|
.git
|
||||||
|
.github
|
||||||
|
.idea
|
||||||
|
.venv
|
||||||
|
__pycache__
|
||||||
|
.pytest_cache
|
||||||
|
.mypy_cache
|
||||||
|
.ruff_cache
|
||||||
|
.coverage
|
||||||
|
htmlcov
|
||||||
|
tests
|
||||||
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
WA_ENVIRONMENT=development
|
||||||
|
WA_INVENTORY_BACKEND=redis
|
||||||
|
WA_REDIS_URL=redis://localhost:6379/0
|
||||||
|
WA_REDIS_SOCKET_TIMEOUT_SECONDS=0.08
|
||||||
|
WA_MAX_CANDIDATE_WAREHOUSES=33
|
||||||
|
WA_INVENTORY_ADMIN_TOKEN=change-me
|
||||||
|
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quality-and-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.12"
|
||||||
|
cache: pip
|
||||||
|
- run: pip install -e '.[dev]'
|
||||||
|
- name: Ruff
|
||||||
|
run: ruff check . && ruff format --check .
|
||||||
|
- name: Mypy
|
||||||
|
run: mypy src
|
||||||
|
- name: Unit and integration tests
|
||||||
|
run: pytest --cov-report=xml
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: coverage
|
||||||
|
path: coverage.xml
|
||||||
|
|
||||||
|
container:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: quality-and-tests
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: false
|
||||||
|
tags: warehouse-allocation:${{ github.sha }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
name: SonarQube
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
scan:
|
||||||
|
if: ${{ vars.SONAR_HOST_URL != '' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.12"
|
||||||
|
- run: pip install -e '.[dev]' && pytest --cov-report=xml
|
||||||
|
- uses: SonarSource/sonarqube-scan-action@v5
|
||||||
|
with:
|
||||||
|
args: -Dsonar.qualitygate.wait=true
|
||||||
|
env:
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
|
SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}
|
||||||
+12
@@ -1,3 +1,15 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.venv/
|
.venv/
|
||||||
venv/
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.pytest_cache/
|
||||||
|
.mypy_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
|
htmlcov/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg-info/
|
||||||
|
.env
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
# syntax=docker/dockerfile:1.7
|
||||||
|
FROM python:3.12-slim AS builder
|
||||||
|
|
||||||
|
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||||
|
PIP_NO_CACHE_DIR=1
|
||||||
|
WORKDIR /build
|
||||||
|
COPY pyproject.toml README.md ./
|
||||||
|
COPY src ./src
|
||||||
|
RUN pip wheel --wheel-dir /wheels .
|
||||||
|
|
||||||
|
FROM python:3.12-slim AS runtime
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||||
|
WA_INVENTORY_BACKEND=redis
|
||||||
|
|
||||||
|
RUN groupadd --system --gid 10001 app && useradd --system --uid 10001 --gid app app
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=builder /wheels /wheels
|
||||||
|
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
CMD ["uvicorn", "warehouse_allocation.api:app", "--host", "0.0.0.0", "--port", "8080", "--no-access-log"]
|
||||||
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
.PHONY: install lint test run compose-up benchmark
|
||||||
|
|
||||||
|
install:
|
||||||
|
python -m pip install -e '.[dev]'
|
||||||
|
|
||||||
|
lint:
|
||||||
|
ruff check .
|
||||||
|
ruff format --check .
|
||||||
|
mypy src
|
||||||
|
|
||||||
|
test:
|
||||||
|
pytest
|
||||||
|
|
||||||
|
run:
|
||||||
|
uvicorn warehouse_allocation.api:app --reload --port 8080
|
||||||
|
|
||||||
|
compose-up:
|
||||||
|
docker compose up --build
|
||||||
|
|
||||||
|
benchmark:
|
||||||
|
python scripts/benchmark.py --url http://localhost:8080 --requests 1000 --concurrency 25
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
# سرویس هوشمند تخصیص انبار
|
||||||
|
|
||||||
|
یک مایکروسرویس stateless و کمتأخیر برای انتخاب انباری که **تمام SKUهای سفارش** را موجود دارد و با توجه به هزینه حمل، فاصله، ترافیک، ظرفیت ناوگان و SLA بهترین نتیجه را میدهد. سرویس برای ۳۳ هاب طراحی شده، اما سقف کاندیدا قابل تنظیم است.
|
||||||
|
|
||||||
|
## اجرای سریع با Docker Compose
|
||||||
|
|
||||||
|
پیشنیاز: Docker و Docker Compose.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
پس از healthy شدن سرویس، مستندات تعاملی در `http://localhost:8080/docs` و متریکها در `http://localhost:8080/metrics` در دسترساند.
|
||||||
|
|
||||||
|
ابتدا موجودی projection را ثبت کنید:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X PUT http://localhost:8080/v1/inventory \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'X-Admin-Token: local-development-token' \
|
||||||
|
-d '{
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"levels": [{"sku": "SKU-RED-42", "quantity": 20}]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
سپس تخصیص را درخواست کنید:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8080/v1/allocations \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{
|
||||||
|
"requestId": "order-1001",
|
||||||
|
"customerLocation": {"latitude": 35.7219, "longitude": 51.3347},
|
||||||
|
"items": [{"sku": "SKU-RED-42", "quantity": 2}],
|
||||||
|
"transportationCosts": [{
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"fixedCost": 100000,
|
||||||
|
"distanceKm": 12,
|
||||||
|
"costPerKm": 3500,
|
||||||
|
"baseDeliveryMinutes": 60,
|
||||||
|
"surcharge": 0
|
||||||
|
}],
|
||||||
|
"logisticsConstraints": [{
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"trafficMultiplier": 1.2,
|
||||||
|
"fleetPriority": 1.1,
|
||||||
|
"handlingMinutes": 10,
|
||||||
|
"available": true
|
||||||
|
}],
|
||||||
|
"weights": {"cost": 0.7, "deliveryTime": 0.3},
|
||||||
|
"promisedDeliveryMinutes": 90,
|
||||||
|
"reserveInventory": true
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
نمونه خروجی:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requestId": "order-1001",
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"estimatedDeliveryTime": 75,
|
||||||
|
"totalCost": 132963.64,
|
||||||
|
"routeOptimizationScore": 100.0,
|
||||||
|
"inventoryReserved": true,
|
||||||
|
"scoreBreakdown": {
|
||||||
|
"transportCost": 132963.64,
|
||||||
|
"normalizedCost": 0.0,
|
||||||
|
"normalizedDeliveryTime": 0.0,
|
||||||
|
"slaPenalty": 0.0,
|
||||||
|
"feasibleWarehouseCount": 1
|
||||||
|
},
|
||||||
|
"calculatedAt": "2026-07-23T03:30:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> `customerLocation` در قرارداد ثبت میشود تا سرویس بالادستی مسیریابی بتواند ماتریس هزینه مقصد را تولید و trace کند. این سرویس از مقادیر محاسبهشده `distanceKm`، هزینه و زمان استفاده میکند و محاسبه مسیر جادهای را تکرار نمیکند.
|
||||||
|
|
||||||
|
## اجرای توسعه و تست
|
||||||
|
|
||||||
|
Python 3.11 یا بالاتر لازم است.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install -e '.[dev]'
|
||||||
|
make lint
|
||||||
|
make test
|
||||||
|
```
|
||||||
|
|
||||||
|
حالت توسعه بهصورت پیشفرض از حافظه محلی استفاده میکند:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make run
|
||||||
|
```
|
||||||
|
|
||||||
|
برای اتصال مستقیم به Redis، `.env.example` را به `.env` کپی و متغیرها را تنظیم کنید. backend حافظهای فقط برای توسعه و تست مناسب است و با scale-out سازگار نیست.
|
||||||
|
|
||||||
|
## منطق انتخاب و علت الگوریتم
|
||||||
|
|
||||||
|
این مسئله در ورودی حاضر shortest-path نیست: هزینه و زمان مسیر هر انبار تا مقصد قبلاً بهصورت ماتریس داده شده و تعداد انبارها حداکثر چند ده مورد است. بنابراین Dijkstra هزینه اضافی دارد و بدون گراف جادهای ارزش ایجاد نمیکند. الگوریتم ژنتیک نیز برای انتخاب یک عضو از ۳۳ کاندیدا هم کندتر و هم غیرقطعی است.
|
||||||
|
|
||||||
|
راهکار استفادهشده یک **فیلتر محدودیت + امتیازدهی قطعی چندمعیاره** با پیچیدگی `O(W × S)` است؛ `W` تعداد انبار و `S` تعداد SKU سفارش است:
|
||||||
|
|
||||||
|
1. با یک Redis pipeline موجودی همه SKUها در همه انبارهای کاندیدا خوانده میشود.
|
||||||
|
2. انبار فاقد هر یک از اقلام یا انبار غیرفعال حذف میشود؛ سفارش بین انبارها split نمیشود.
|
||||||
|
3. هزینه مؤثر و ETA محاسبه میشوند:
|
||||||
|
|
||||||
|
```text
|
||||||
|
rawCost = fixedCost + distanceKm × costPerKm + surcharge
|
||||||
|
totalCost = rawCost × (1 + max(traffic-1, 0) × 0.15) / fleetPriority
|
||||||
|
ETA = (baseDeliveryMinutes × traffic + handlingMinutes) / fleetPriority
|
||||||
|
```
|
||||||
|
|
||||||
|
4. هزینه و ETA بین کاندیداهای feasible با min-max به بازه صفر تا یک تبدیل میشوند.
|
||||||
|
5. تابع هدف برابر `costWeight × normalizedCost + timeWeight × normalizedETA + slaPenalty` است. امتیاز مسیر `100 × (1 - objective)` و در بازه ۰ تا ۱۰۰ است.
|
||||||
|
6. در تساوی، هزینه، زمان و شناسه انبار بهترتیب tie-break میکنند؛ در نتیجه پاسخ deterministic است.
|
||||||
|
|
||||||
|
وزن پیشفرض هزینه ۷۰٪ و زمان ۳۰٪ است، ولی هر سفارش میتواند وزن دیگری با مجموع دقیقاً یک ارسال کند. عبور از زمان تعهدشده تا ۲۵٪ جریمه به تابع هدف اضافه میکند. برای تحلیل ترافیکی پیشرفتهتر، سرویس پیشبینی بیرونی میتواند `trafficMultiplier` زمانی/مکانی را بدون تغییر این هسته تزریق کند.
|
||||||
|
|
||||||
|
## معماری و مقیاسپذیری
|
||||||
|
|
||||||
|
```text
|
||||||
|
Client / Order Service
|
||||||
|
│ HTTP
|
||||||
|
▼
|
||||||
|
FastAPI stateless pods ─── Prometheus /health /metrics
|
||||||
|
│ pipeline reads + atomic Lua reservation
|
||||||
|
▼
|
||||||
|
Redis inventory projection
|
||||||
|
▲
|
||||||
|
│ CDC / inventory events (production recommendation)
|
||||||
|
Transactional inventory source of truth
|
||||||
|
```
|
||||||
|
|
||||||
|
- لایه domain هیچ وابستگی به FastAPI یا Redis ندارد و مستقل تست میشود.
|
||||||
|
- API state محلی ماندگار ندارد؛ podها پشت Service و HPA مستقل scale میشوند.
|
||||||
|
- Redis projection برای جستوجوی سریع موجودی انتخاب شده است. دیتابیس تراکنشی سفارش/انبار همچنان source of truth باقی میماند.
|
||||||
|
- timeout اتصال Redis برابر ۸۰ms است تا بودجه پاسخ ۲۰۰ms با failure سریع حفظ شود.
|
||||||
|
- یک Lua script بررسی و کسر همه SKUهای یک انبار را اتمیک انجام میدهد. اگر موجودی انتخاب اول در race تغییر کند، سرویس انبارهای بعدی را به ترتیب امتیاز امتحان میکند.
|
||||||
|
- در production، idempotency سفارش باید در orchestrator یا با رکورد reservation دارای `requestId` و TTL اعمال شود. `requestId` فعلاً برای trace/correlation است؛ ارسال دوباره درخواست رزروی عمداً یک رزرو جدید محسوب میشود.
|
||||||
|
|
||||||
|
### مدیریت consistency
|
||||||
|
|
||||||
|
مدل پیشنهادی **transactional source of truth + Redis read model** است:
|
||||||
|
|
||||||
|
- تغییرات موجودی با Outbox/CDC به Redis منتشر میشوند؛ eventها دارای version ترتیبیاند و consumer فقط نسخه جدیدتر را اعمال میکند.
|
||||||
|
- رزرو محلی Redis اتمیک است و oversell همزمان در همین سرویس را حذف میکند.
|
||||||
|
- سرویس سفارش رزرو را در source of truth نهایی میکند. failure بین دو سیستم با Saga و عملیات compensation (آزادسازی reservation) مدیریت میشود.
|
||||||
|
- reconciliation دورهای اختلاف projection و دیتابیس اصلی را اصلاح میکند.
|
||||||
|
- برای نیاز سختگیرانه به consistency، Lua را میتوان با stored procedure/transaction دیتابیس اصلی جایگزین کرد؛ latency و throughput کمتر خواهد شد.
|
||||||
|
|
||||||
|
## Latency و بار
|
||||||
|
|
||||||
|
پس از اجرای Compose:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make benchmark
|
||||||
|
```
|
||||||
|
|
||||||
|
اسکریپت پس از warm-up اتصالها، ۱۰۰۰ درخواست با concurrency برابر ۲۵ و ۳۳ انبار میفرستد و اگر failure رخ دهد یا p95 به ۲۰۰ms برسد با exit code غیرصفر پایان مییابد. اجرای محلی مرجع روی یک process با backend حافظهای، throughput برابر `500.7 req/s` و p95 برابر `124.6ms` ثبت کرد. عدد نهایی به سختافزار و Redis وابسته است؛ برای production، معیار SLO باید از histogram متریک `warehouse_allocation_duration_seconds` و تست در محیط مشابه production استخراج شود. بار بالاتر به کمک HPA بین replicaهای stateless پخش میشود.
|
||||||
|
|
||||||
|
## API و عملیات
|
||||||
|
|
||||||
|
| Endpoint | کاربرد |
|
||||||
|
|---|---|
|
||||||
|
| `POST /v1/allocations` | انتخاب انبار و رزرو اختیاری |
|
||||||
|
| `PUT /v1/inventory` | بهروزرسانی projection موجودی؛ قابل محافظت با `X-Admin-Token` |
|
||||||
|
| `GET /health/live` | liveness probe بدون وابستگی خارجی |
|
||||||
|
| `GET /health/ready` | readiness همراه با ping موجودی |
|
||||||
|
| `GET /metrics` | متریک Prometheus |
|
||||||
|
| `GET /docs` | OpenAPI/Swagger UI |
|
||||||
|
|
||||||
|
خطای نبود انبار مناسب با HTTP 409 و خرابی Redis با HTTP 503 و `Retry-After` برگردانده میشود. ورودیهای ناشناخته رد میشوند تا typo باعث تصمیم لجستیکی اشتباه نشود.
|
||||||
|
|
||||||
|
## CI/CD و استقرار
|
||||||
|
|
||||||
|
GitHub Actions این مراحل را اجرا میکند:
|
||||||
|
|
||||||
|
1. نصب وابستگیها از `pyproject.toml`؛
|
||||||
|
2. Ruff lint/format، mypy strict؛
|
||||||
|
3. unit و integration test با حداقل coverage برابر ۸۵٪؛
|
||||||
|
4. تولید `coverage.xml` و artifact؛
|
||||||
|
5. build ایمیج Docker؛
|
||||||
|
6. اجرای اختیاری SonarQube با `SONAR_TOKEN` و `SONAR_HOST_URL`.
|
||||||
|
|
||||||
|
فایل `deploy/kubernetes.yaml` شامل Deployment غیر-root و read-only، probes، resource limits، Service و HPA از ۲ تا ۲۰ replica است. قبل از اعمال، آدرس image و Secret را برای محیط مقصد تنظیم کنید.
|
||||||
|
|
||||||
|
## محدودیتها و مسیر توسعه
|
||||||
|
|
||||||
|
- split shipment عمداً پیاده نشده چون هزینه بستهبندی/ارسال چندگانه مدل متفاوتی لازم دارد. نسخه بعدی میتواند مسئله را به min-cost flow تبدیل کند.
|
||||||
|
- هزینه و زمان مسیر از ورودی قابل اعتماد دریافت میشود. در سامانه واقعی، یک adapter با cache کوتاهعمر باید آن را از route engine مانند OSRM/GraphHopper تولید کند.
|
||||||
|
- endpoint موجودی نمونه ingestion است؛ در production بهتر است private باشد و projection از event stream ساخته شود.
|
||||||
|
- پیشبینی ترافیک ML خارج از critical path اجرا میشود و مقدار نسخهدار آن وارد درخواست میگردد تا تصمیم قابل بازتولید بماند.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
services:
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
WA_ENVIRONMENT: local-compose
|
||||||
|
WA_INVENTORY_BACKEND: redis
|
||||||
|
WA_REDIS_URL: redis://redis:6379/0
|
||||||
|
WA_INVENTORY_ADMIN_TOKEN: local-development-token
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
depends_on:
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- python
|
||||||
|
- -c
|
||||||
|
- "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=1)"
|
||||||
|
interval: 5s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 10
|
||||||
|
start_period: 5s
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7.4-alpine
|
||||||
|
command: ["redis-server", "--appendonly", "yes", "--maxmemory-policy", "noeviction"]
|
||||||
|
volumes:
|
||||||
|
- redis-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 10
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
redis-data:
|
||||||
|
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: warehouse-allocation
|
||||||
|
data:
|
||||||
|
WA_ENVIRONMENT: production
|
||||||
|
WA_INVENTORY_BACKEND: redis
|
||||||
|
WA_REDIS_URL: redis://redis.inventory.svc.cluster.local:6379/0
|
||||||
|
WA_MAX_CANDIDATE_WAREHOUSES: "33"
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: warehouse-allocation
|
||||||
|
spec:
|
||||||
|
replicas: 2
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: warehouse-allocation
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: warehouse-allocation
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: api
|
||||||
|
image: registry.example.com/warehouse-allocation:1.0.0
|
||||||
|
ports:
|
||||||
|
- containerPort: 8080
|
||||||
|
envFrom:
|
||||||
|
- configMapRef:
|
||||||
|
name: warehouse-allocation
|
||||||
|
- secretRef:
|
||||||
|
name: warehouse-allocation-secrets
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health/ready
|
||||||
|
port: 8080
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health/live
|
||||||
|
port: 8080
|
||||||
|
periodSeconds: 10
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: "1"
|
||||||
|
memory: 512Mi
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
runAsNonRoot: true
|
||||||
|
capabilities:
|
||||||
|
drop: ["ALL"]
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: warehouse-allocation
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
app: warehouse-allocation
|
||||||
|
ports:
|
||||||
|
- port: 80
|
||||||
|
targetPort: 8080
|
||||||
|
---
|
||||||
|
apiVersion: autoscaling/v2
|
||||||
|
kind: HorizontalPodAutoscaler
|
||||||
|
metadata:
|
||||||
|
name: warehouse-allocation
|
||||||
|
spec:
|
||||||
|
scaleTargetRef:
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
name: warehouse-allocation
|
||||||
|
minReplicas: 2
|
||||||
|
maxReplicas: 20
|
||||||
|
behavior:
|
||||||
|
scaleDown:
|
||||||
|
stabilizationWindowSeconds: 300
|
||||||
|
metrics:
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: cpu
|
||||||
|
target:
|
||||||
|
type: Utilization
|
||||||
|
averageUtilization: 65
|
||||||
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["hatchling>=1.27"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "warehouse-allocation"
|
||||||
|
version = "1.0.0"
|
||||||
|
description = "Low-latency warehouse routing and inventory allocation microservice"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115,<1",
|
||||||
|
"prometheus-client>=0.21,<1",
|
||||||
|
"pydantic-settings>=2.7,<3",
|
||||||
|
"redis[hiredis]>=5.2,<7",
|
||||||
|
"uvicorn[standard]>=0.34,<1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"httpx>=0.28,<1",
|
||||||
|
"mypy>=1.14,<2",
|
||||||
|
"pytest>=8.3,<9",
|
||||||
|
"pytest-asyncio>=0.25,<2",
|
||||||
|
"pytest-cov>=6,<8",
|
||||||
|
"ruff>=0.9,<1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["src/warehouse_allocation"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
addopts = "-q --strict-markers --cov=warehouse_allocation --cov-report=term-missing --cov-fail-under=85"
|
||||||
|
asyncio_mode = "auto"
|
||||||
|
testpaths = ["tests"]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
branch = true
|
||||||
|
source = ["warehouse_allocation"]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py311"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.11"
|
||||||
|
strict = true
|
||||||
|
plugins = ["pydantic.mypy"]
|
||||||
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import statistics
|
||||||
|
import time
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
PAYLOAD = {
|
||||||
|
"requestId": "benchmark",
|
||||||
|
"customerLocation": {"latitude": 35.72, "longitude": 51.33},
|
||||||
|
"items": [{"sku": "BENCHMARK-SKU", "quantity": 1}],
|
||||||
|
"transportationCosts": [
|
||||||
|
{
|
||||||
|
"warehouseId": f"w{i}",
|
||||||
|
"fixedCost": 100 + i,
|
||||||
|
"distanceKm": 10 + i,
|
||||||
|
"costPerKm": 2,
|
||||||
|
"baseDeliveryMinutes": 45 + i,
|
||||||
|
}
|
||||||
|
for i in range(1, 34)
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def run(url: str, count: int, concurrency: int) -> None:
|
||||||
|
limits = httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency)
|
||||||
|
timeout = httpx.Timeout(2)
|
||||||
|
durations: list[float] = []
|
||||||
|
failures = 0
|
||||||
|
semaphore = asyncio.Semaphore(concurrency)
|
||||||
|
async with httpx.AsyncClient(base_url=url, limits=limits, timeout=timeout) as client:
|
||||||
|
levels = [{"sku": "BENCHMARK-SKU", "quantity": count}]
|
||||||
|
for i in range(1, 34):
|
||||||
|
await client.put(
|
||||||
|
"/v1/inventory",
|
||||||
|
headers={"X-Admin-Token": "local-development-token"},
|
||||||
|
json={"warehouseId": f"w{i}", "levels": levels},
|
||||||
|
)
|
||||||
|
|
||||||
|
async def send(index: int, prefix: str) -> tuple[float, int]:
|
||||||
|
payload = PAYLOAD | {"requestId": f"{prefix}-{index}"}
|
||||||
|
request_started = time.perf_counter()
|
||||||
|
response = await client.post("/v1/allocations", json=payload)
|
||||||
|
return (time.perf_counter() - request_started) * 1000, response.status_code
|
||||||
|
|
||||||
|
# Establish the whole keep-alive pool before measuring steady-state API latency.
|
||||||
|
warmup = await asyncio.gather(*(send(index, "warmup") for index in range(concurrency)))
|
||||||
|
if any(status != 200 for _, status in warmup):
|
||||||
|
raise SystemExit("warm-up request failed")
|
||||||
|
|
||||||
|
async def one(index: int) -> None:
|
||||||
|
nonlocal failures
|
||||||
|
async with semaphore:
|
||||||
|
duration, response_status = await send(index, "benchmark")
|
||||||
|
durations.append(duration)
|
||||||
|
failures += int(response_status != 200)
|
||||||
|
|
||||||
|
started = time.perf_counter()
|
||||||
|
await asyncio.gather(*(one(index) for index in range(count)))
|
||||||
|
elapsed = time.perf_counter() - started
|
||||||
|
|
||||||
|
ordered = sorted(durations)
|
||||||
|
p95 = ordered[max(0, round(len(ordered) * 0.95) - 1)]
|
||||||
|
print(
|
||||||
|
f"requests={count} failures={failures} throughput={count / elapsed:.1f} req/s "
|
||||||
|
f"mean={statistics.mean(durations):.1f}ms p95={p95:.1f}ms"
|
||||||
|
)
|
||||||
|
if failures or p95 >= 200:
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--url", default="http://localhost:8080")
|
||||||
|
parser.add_argument("--requests", type=int, default=1_000)
|
||||||
|
parser.add_argument("--concurrency", type=int, default=25)
|
||||||
|
args = parser.parse_args()
|
||||||
|
asyncio.run(run(args.url, args.requests, args.concurrency))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
sonar.projectKey=warehouse-allocation
|
||||||
|
sonar.projectName=Warehouse Allocation
|
||||||
|
sonar.sources=src
|
||||||
|
sonar.tests=tests
|
||||||
|
sonar.python.coverage.reportPaths=coverage.xml
|
||||||
|
sonar.python.version=3.11,3.12,3.13
|
||||||
|
sonar.coverage.exclusions=tests/**
|
||||||
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Warehouse allocation microservice."""
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
@@ -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()
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
@@ -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."""
|
||||||
@@ -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()
|
||||||
@@ -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),
|
||||||
|
)
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from warehouse_allocation.api import create_app
|
||||||
|
from warehouse_allocation.config import Settings
|
||||||
|
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def inventory() -> InMemoryInventoryRepository:
|
||||||
|
return InMemoryInventoryRepository()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def client(
|
||||||
|
inventory: InMemoryInventoryRepository,
|
||||||
|
) -> AsyncIterator[httpx.AsyncClient]:
|
||||||
|
app = create_app(Settings(inventory_backend="memory"), inventory)
|
||||||
|
async with app.router.lifespan_context(app):
|
||||||
|
transport = httpx.ASGITransport(app=app)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://test") as test_client:
|
||||||
|
yield test_client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def allocation_payload() -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"requestId": "order-1001",
|
||||||
|
"customerLocation": {"latitude": 35.7219, "longitude": 51.3347},
|
||||||
|
"items": [{"sku": "SKU-RED-42", "quantity": 2}],
|
||||||
|
"transportationCosts": [
|
||||||
|
{
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"fixedCost": 100,
|
||||||
|
"distanceKm": 12,
|
||||||
|
"costPerKm": 2,
|
||||||
|
"baseDeliveryMinutes": 60,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"warehouseId": "karaj",
|
||||||
|
"fixedCost": 90,
|
||||||
|
"distanceKm": 50,
|
||||||
|
"costPerKm": 2,
|
||||||
|
"baseDeliveryMinutes": 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"logisticsConstraints": [
|
||||||
|
{
|
||||||
|
"warehouseId": "tehran-west",
|
||||||
|
"trafficMultiplier": 1.2,
|
||||||
|
"fleetPriority": 1.1,
|
||||||
|
"handlingMinutes": 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"warehouseId": "karaj",
|
||||||
|
"trafficMultiplier": 1,
|
||||||
|
"fleetPriority": 1,
|
||||||
|
"handlingMinutes": 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import httpx
|
||||||
|
|
||||||
|
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||||
|
|
||||||
|
|
||||||
|
async def seed(repository: InMemoryInventoryRepository) -> None:
|
||||||
|
await repository.set_levels("tehran-west", {"SKU-RED-42": 10})
|
||||||
|
await repository.set_levels("karaj", {"SKU-RED-42": 10})
|
||||||
|
|
||||||
|
|
||||||
|
async def test_allocation_contract_and_selection(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
inventory: InMemoryInventoryRepository,
|
||||||
|
allocation_payload: dict[str, object],
|
||||||
|
) -> None:
|
||||||
|
await seed(inventory)
|
||||||
|
|
||||||
|
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||||
|
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
assert response.headers["x-process-time-ms"]
|
||||||
|
body = response.json()
|
||||||
|
assert body["requestId"] == "order-1001"
|
||||||
|
assert body["warehouseId"] == "tehran-west"
|
||||||
|
assert body["estimatedDeliveryTime"] == 75
|
||||||
|
assert body["totalCost"] == 116.11
|
||||||
|
assert 0 <= body["routeOptimizationScore"] <= 100
|
||||||
|
assert body["scoreBreakdown"]["feasibleWarehouseCount"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_reservation_decrements_inventory(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
inventory: InMemoryInventoryRepository,
|
||||||
|
allocation_payload: dict[str, object],
|
||||||
|
) -> None:
|
||||||
|
await inventory.set_levels("tehran-west", {"SKU-RED-42": 2})
|
||||||
|
await inventory.set_levels("karaj", {"SKU-RED-42": 0})
|
||||||
|
allocation_payload["reserveInventory"] = True
|
||||||
|
|
||||||
|
first = await client.post("/v1/allocations", json=allocation_payload)
|
||||||
|
second = await client.post("/v1/allocations", json=allocation_payload)
|
||||||
|
|
||||||
|
assert first.status_code == 200, first.text
|
||||||
|
assert first.json()["inventoryReserved"] is True
|
||||||
|
assert second.status_code == 409
|
||||||
|
assert second.json()["error"]["code"] == "NO_FEASIBLE_WAREHOUSE"
|
||||||
|
|
||||||
|
|
||||||
|
async def test_no_single_warehouse_can_split_fulfillment(
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
inventory: InMemoryInventoryRepository,
|
||||||
|
allocation_payload: dict[str, object],
|
||||||
|
) -> None:
|
||||||
|
await inventory.set_levels("tehran-west", {"SKU-RED-42": 1})
|
||||||
|
await inventory.set_levels("karaj", {"SKU-RED-42": 1})
|
||||||
|
|
||||||
|
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||||
|
|
||||||
|
assert response.status_code == 409
|
||||||
|
|
||||||
|
|
||||||
|
async def test_inventory_upsert_and_health_endpoints(client: httpx.AsyncClient) -> None:
|
||||||
|
upsert = await client.put(
|
||||||
|
"/v1/inventory",
|
||||||
|
json={"warehouseId": "w1", "levels": [{"sku": "A", "quantity": 5}]},
|
||||||
|
)
|
||||||
|
live = await client.get("/health/live")
|
||||||
|
ready = await client.get("/health/ready")
|
||||||
|
metrics = await client.get("/metrics")
|
||||||
|
|
||||||
|
assert upsert.status_code == 204, upsert.text
|
||||||
|
assert live.json()["status"] == "ok"
|
||||||
|
assert ready.json()["inventory"] == "ok"
|
||||||
|
assert "warehouse_allocation_requests_total" in metrics.text
|
||||||
|
|
||||||
|
|
||||||
|
async def test_validation_error_is_structured(
|
||||||
|
client: httpx.AsyncClient, allocation_payload: dict[str, object]
|
||||||
|
) -> None:
|
||||||
|
allocation_payload["customerLocation"] = {"latitude": 200, "longitude": 51}
|
||||||
|
|
||||||
|
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||||
|
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"]
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from warehouse_allocation.application import AllocationService
|
||||||
|
from warehouse_allocation.config import Settings
|
||||||
|
from warehouse_allocation.domain.exceptions import CandidateLimitExceededError
|
||||||
|
from warehouse_allocation.domain.models import AllocationRequest
|
||||||
|
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||||
|
|
||||||
|
|
||||||
|
def allocation_request(*, reserve: bool = False) -> AllocationRequest:
|
||||||
|
return AllocationRequest.model_validate(
|
||||||
|
{
|
||||||
|
"requestId": "fallback-test",
|
||||||
|
"customerLocation": {"latitude": 35, "longitude": 51},
|
||||||
|
"items": [{"sku": "A", "quantity": 2}],
|
||||||
|
"transportationCosts": [
|
||||||
|
{
|
||||||
|
"warehouseId": "w1",
|
||||||
|
"fixedCost": 10,
|
||||||
|
"distanceKm": 1,
|
||||||
|
"baseDeliveryMinutes": 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"warehouseId": "w2",
|
||||||
|
"fixedCost": 20,
|
||||||
|
"distanceKm": 2,
|
||||||
|
"baseDeliveryMinutes": 20,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"reserveInventory": reserve,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_quote_does_not_mutate_inventory() -> None:
|
||||||
|
inventory = InMemoryInventoryRepository()
|
||||||
|
await inventory.set_levels("w1", {"A": 2})
|
||||||
|
service = AllocationService(inventory, Settings())
|
||||||
|
|
||||||
|
response = await service.allocate(allocation_request())
|
||||||
|
|
||||||
|
assert response.warehouse_id == "w1"
|
||||||
|
assert response.inventory_reserved is False
|
||||||
|
assert await inventory.feasible_warehouses(["w1"], {"A": 2}) == {"w1"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_reservation_falls_back_after_concurrent_stock_change() -> None:
|
||||||
|
inventory = InMemoryInventoryRepository()
|
||||||
|
await inventory.set_levels("w1", {"A": 1})
|
||||||
|
await inventory.set_levels("w2", {"A": 2})
|
||||||
|
service = AllocationService(inventory, Settings())
|
||||||
|
|
||||||
|
# Simulate an optimistic feasibility read that becomes stale before the atomic reservation.
|
||||||
|
original_feasible = inventory.feasible_warehouses
|
||||||
|
|
||||||
|
async def stale_feasible(*args: object, **kwargs: object) -> set[str]:
|
||||||
|
del args, kwargs
|
||||||
|
return {"w1", "w2"}
|
||||||
|
|
||||||
|
inventory.feasible_warehouses = stale_feasible # type: ignore[method-assign]
|
||||||
|
response = await service.allocate(allocation_request(reserve=True))
|
||||||
|
inventory.feasible_warehouses = original_feasible # type: ignore[method-assign]
|
||||||
|
|
||||||
|
assert response.warehouse_id == "w2"
|
||||||
|
assert response.inventory_reserved is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_candidate_limit_is_enforced() -> None:
|
||||||
|
service = AllocationService(InMemoryInventoryRepository(), Settings(max_candidate_warehouses=1))
|
||||||
|
|
||||||
|
with pytest.raises(CandidateLimitExceededError, match="at most 1"):
|
||||||
|
await service.allocate(allocation_request())
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import asyncio
|
||||||
|
|
||||||
|
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||||
|
|
||||||
|
|
||||||
|
async def test_feasibility_requires_every_sku() -> None:
|
||||||
|
repository = InMemoryInventoryRepository()
|
||||||
|
await repository.set_levels("w1", {"A": 3, "B": 1})
|
||||||
|
await repository.set_levels("w2", {"A": 4, "B": 5})
|
||||||
|
|
||||||
|
feasible = await repository.feasible_warehouses(["w1", "w2", "w3"], {"A": 2, "B": 2})
|
||||||
|
|
||||||
|
assert feasible == {"w2"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_concurrent_reservations_do_not_oversell() -> None:
|
||||||
|
repository = InMemoryInventoryRepository()
|
||||||
|
await repository.set_levels("w1", {"A": 5})
|
||||||
|
|
||||||
|
results = await asyncio.gather(
|
||||||
|
repository.reserve("w1", {"A": 4}),
|
||||||
|
repository.reserve("w1", {"A": 4}),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert sorted(results) == [False, True]
|
||||||
|
assert await repository.feasible_warehouses(["w1"], {"A": 2}) == set()
|
||||||
|
assert await repository.ping() is True
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import pytest
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from warehouse_allocation.domain.models import AllocationRequest
|
||||||
|
from warehouse_allocation.domain.optimizer import rank_warehouses
|
||||||
|
|
||||||
|
|
||||||
|
def request_from(**overrides: object) -> AllocationRequest:
|
||||||
|
payload: dict[str, object] = {
|
||||||
|
"requestId": "optimizer-test",
|
||||||
|
"customerLocation": {"latitude": 35.7, "longitude": 51.4},
|
||||||
|
"items": [{"sku": "A", "quantity": 1}],
|
||||||
|
"transportationCosts": [
|
||||||
|
{
|
||||||
|
"warehouseId": "cheap",
|
||||||
|
"fixedCost": 100,
|
||||||
|
"distanceKm": 0,
|
||||||
|
"baseDeliveryMinutes": 120,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"warehouseId": "fast",
|
||||||
|
"fixedCost": 150,
|
||||||
|
"distanceKm": 0,
|
||||||
|
"baseDeliveryMinutes": 60,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return AllocationRequest.model_validate(payload)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_weight_selects_cheaper_warehouse() -> None:
|
||||||
|
ranked = rank_warehouses(request_from(), {"cheap", "fast"})
|
||||||
|
|
||||||
|
assert ranked[0].warehouse_id == "cheap"
|
||||||
|
assert ranked[0].score == pytest.approx(70)
|
||||||
|
assert ranked[0].breakdown.feasible_warehouse_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_delivery_weight_selects_faster_warehouse() -> None:
|
||||||
|
request = request_from(weights={"cost": 0.2, "deliveryTime": 0.8})
|
||||||
|
|
||||||
|
ranked = rank_warehouses(request, {"cheap", "fast"})
|
||||||
|
|
||||||
|
assert ranked[0].warehouse_id == "fast"
|
||||||
|
|
||||||
|
|
||||||
|
def test_traffic_and_fleet_change_effective_time_and_cost() -> None:
|
||||||
|
request = request_from(
|
||||||
|
logisticsConstraints=[
|
||||||
|
{
|
||||||
|
"warehouseId": "cheap",
|
||||||
|
"trafficMultiplier": 2,
|
||||||
|
"fleetPriority": 0.5,
|
||||||
|
"handlingMinutes": 20,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
ranked = rank_warehouses(request, {"cheap", "fast"})
|
||||||
|
|
||||||
|
assert ranked[0].warehouse_id == "fast"
|
||||||
|
cheap = next(candidate for candidate in ranked if candidate.warehouse_id == "cheap")
|
||||||
|
assert cheap.delivery_minutes == pytest.approx(520)
|
||||||
|
assert cheap.total_cost == pytest.approx(230)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sla_overrun_adds_bounded_penalty() -> None:
|
||||||
|
ranked = rank_warehouses(
|
||||||
|
request_from(promisedDeliveryMinutes=30),
|
||||||
|
{"cheap", "fast"},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert all(candidate.breakdown.sla_penalty == 0.25 for candidate in ranked)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unavailable_and_infeasible_candidates_are_removed() -> None:
|
||||||
|
request = request_from(logisticsConstraints=[{"warehouseId": "cheap", "available": False}])
|
||||||
|
|
||||||
|
assert rank_warehouses(request, {"cheap"}) == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"override",
|
||||||
|
[
|
||||||
|
{"weights": {"cost": 0.4, "deliveryTime": 0.4}},
|
||||||
|
{"items": [{"sku": "A", "quantity": 1}, {"sku": "A", "quantity": 2}]},
|
||||||
|
{
|
||||||
|
"transportationCosts": [
|
||||||
|
{
|
||||||
|
"warehouseId": "duplicate",
|
||||||
|
"fixedCost": 1,
|
||||||
|
"distanceKm": 1,
|
||||||
|
"baseDeliveryMinutes": 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"warehouseId": "duplicate",
|
||||||
|
"fixedCost": 2,
|
||||||
|
"distanceKm": 1,
|
||||||
|
"baseDeliveryMinutes": 1,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_requests_are_rejected(override: dict[str, object]) -> None:
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
request_from(**override)
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import pytest
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
|
||||||
|
from warehouse_allocation.domain.exceptions import InventoryUnavailableError
|
||||||
|
from warehouse_allocation.infrastructure.inventory import RedisInventoryRepository
|
||||||
|
|
||||||
|
|
||||||
|
class FakePipeline:
|
||||||
|
def __init__(self, rows: dict[str, dict[str, int]], fails: bool = False) -> None:
|
||||||
|
self.rows = rows
|
||||||
|
self.fails = fails
|
||||||
|
self.queries: list[tuple[str, list[str]]] = []
|
||||||
|
|
||||||
|
async def __aenter__(self) -> "FakePipeline":
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *args: object) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def hmget(self, key: str, fields: list[str]) -> None:
|
||||||
|
self.queries.append((key, fields))
|
||||||
|
|
||||||
|
async def execute(self) -> list[list[int | None]]:
|
||||||
|
if self.fails:
|
||||||
|
raise RedisError("down")
|
||||||
|
return [
|
||||||
|
[self.rows.get(key, {}).get(field) for field in fields] for key, fields in self.queries
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRedis:
|
||||||
|
def __init__(self, *, fails: bool = False) -> None:
|
||||||
|
self.rows: dict[str, dict[str, int]] = {
|
||||||
|
"inventory:w1": {"A": 3, "B": 2},
|
||||||
|
"inventory:w2": {"A": 1, "B": 5},
|
||||||
|
}
|
||||||
|
self.fails = fails
|
||||||
|
self.closed = False
|
||||||
|
self.eval_result = 1
|
||||||
|
|
||||||
|
def pipeline(self, transaction: bool = False) -> FakePipeline:
|
||||||
|
assert transaction is False
|
||||||
|
return FakePipeline(self.rows, self.fails)
|
||||||
|
|
||||||
|
async def eval(self, *args: object) -> int:
|
||||||
|
if self.fails:
|
||||||
|
raise RedisError("down")
|
||||||
|
assert args[1] == 1
|
||||||
|
return self.eval_result
|
||||||
|
|
||||||
|
async def hset(self, key: str, mapping: dict[str, int]) -> int:
|
||||||
|
if self.fails:
|
||||||
|
raise RedisError("down")
|
||||||
|
self.rows.setdefault(key, {}).update(mapping)
|
||||||
|
return len(mapping)
|
||||||
|
|
||||||
|
async def ping(self) -> bool:
|
||||||
|
if self.fails:
|
||||||
|
raise RedisError("down")
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def aclose(self) -> None:
|
||||||
|
self.closed = True
|
||||||
|
|
||||||
|
|
||||||
|
def repository(client: FakeRedis) -> RedisInventoryRepository:
|
||||||
|
return RedisInventoryRepository(client) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_pipeline_feasibility_and_missing_values() -> None:
|
||||||
|
result = await repository(FakeRedis()).feasible_warehouses(
|
||||||
|
["w1", "w2", "missing"], {"A": 2, "B": 2}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result == {"w1"}
|
||||||
|
|
||||||
|
|
||||||
|
async def test_reserve_set_ping_and_close() -> None:
|
||||||
|
client = FakeRedis()
|
||||||
|
adapter = repository(client)
|
||||||
|
|
||||||
|
assert await adapter.reserve("w1", {"A": 2, "B": 1}) is True
|
||||||
|
client.eval_result = 0
|
||||||
|
assert await adapter.reserve("w1", {"A": 99}) is False
|
||||||
|
await adapter.set_levels("w3", {"A": 7})
|
||||||
|
assert client.rows["inventory:w3"] == {"A": 7}
|
||||||
|
assert await adapter.ping() is True
|
||||||
|
await adapter.close()
|
||||||
|
assert client.closed is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("operation", ["feasible", "reserve", "set_levels"])
|
||||||
|
async def test_redis_errors_become_domain_errors(operation: str) -> None:
|
||||||
|
adapter = repository(FakeRedis(fails=True))
|
||||||
|
|
||||||
|
with pytest.raises(InventoryUnavailableError):
|
||||||
|
if operation == "feasible":
|
||||||
|
await adapter.feasible_warehouses(["w1"], {"A": 1})
|
||||||
|
elif operation == "reserve":
|
||||||
|
await adapter.reserve("w1", {"A": 1})
|
||||||
|
else:
|
||||||
|
await adapter.set_levels("w1", {"A": 1})
|
||||||
|
|
||||||
|
|
||||||
|
async def test_failed_ping_reports_not_ready() -> None:
|
||||||
|
assert await repository(FakeRedis(fails=True)).ping() is False
|
||||||
Reference in new issue
Block a user