Files
ict-warehouse-allocation/src/warehouse_allocation/infrastructure/inventory.py
T
2026-07-23 06:40:30 +03:30

144 lines
4.7 KiB
Python

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()