Initial commit: Test GLM project
This commit is contained in:
@@ -0,0 +1,464 @@
|
||||
# Subtask: Inventory Reservation and Locking
|
||||
|
||||
**Parent Task**: Decomp/004
|
||||
**Subtask ID**: Decomp-004-03
|
||||
**Dependencies**: Decomp-004-01 (Database Schema)
|
||||
|
||||
## Description
|
||||
|
||||
Implement inventory reservation system with ACID guarantees to prevent overselling. Support optimistic locking, reservation expiration, and automatic release of stale reservations.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Reserve inventory during checkout
|
||||
- Prevent race conditions on concurrent orders
|
||||
- Support reservation expiration (timeout)
|
||||
- Release reservations on order cancellation
|
||||
- Commit reservations on payment success
|
||||
- Handle multiple inventory locations
|
||||
- Query available inventory accurately
|
||||
- Support backorders (optional)
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**Inventory reservation service**:
|
||||
```python
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import List, Dict, Optional, Tuple
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import asyncpg
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dataclass
|
||||
class ReservationResult:
|
||||
"""Result of inventory reservation."""
|
||||
success: bool
|
||||
reservation_id: Optional[int] = None
|
||||
failed_items: List[dict] = None
|
||||
reason: Optional[str] = None
|
||||
|
||||
@dataclass
|
||||
class InventoryStatus:
|
||||
"""Current inventory status for a product."""
|
||||
product_id: int
|
||||
quantity_on_hand: int
|
||||
quantity_reserved: int
|
||||
quantity_available: int
|
||||
locations: List[dict] = None
|
||||
|
||||
class InventoryReservationService:
|
||||
"""Service for managing inventory reservations."""
|
||||
|
||||
def __init__(self, db, reservation_timeout_minutes: int = 30):
|
||||
self.db = db
|
||||
self.reservation_timeout = timedelta(minutes=reservation_timeout_minutes)
|
||||
|
||||
async def get_inventory_status(self, product_id: int) -> InventoryStatus:
|
||||
"""Get current inventory status for a product."""
|
||||
async with self.db.acquire() as conn:
|
||||
# Get aggregated inventory
|
||||
row = await conn.fetchrow(
|
||||
"""SELECT
|
||||
product_id,
|
||||
COALESCE(SUM(quantity_on_hand), 0) as quantity_on_hand,
|
||||
COALESCE(SUM(quantity_reserved), 0) as quantity_reserved,
|
||||
COALESCE(SUM(quantity_available), 0) as quantity_available
|
||||
FROM inventory_items
|
||||
WHERE product_id = $1
|
||||
GROUP BY product_id""",
|
||||
product_id
|
||||
)
|
||||
|
||||
if not row:
|
||||
return InventoryStatus(
|
||||
product_id=product_id,
|
||||
quantity_on_hand=0,
|
||||
quantity_reserved=0,
|
||||
quantity_available=0
|
||||
)
|
||||
|
||||
# Get location details
|
||||
locations = await conn.fetch(
|
||||
"""SELECT il.*, l.name as location_name, l.location_type
|
||||
FROM inventory_items il
|
||||
JOIN inventory_locations l ON l.id = il.location_id
|
||||
WHERE il.product_id = $1""",
|
||||
product_id
|
||||
)
|
||||
|
||||
return InventoryStatus(
|
||||
product_id=product_id,
|
||||
quantity_on_hand=row["quantity_on_hand"],
|
||||
quantity_reserved=row["quantity_reserved"],
|
||||
quantity_available=row["quantity_available"],
|
||||
locations=[dict(l) for l in locations]
|
||||
)
|
||||
|
||||
async def reserve_inventory(
|
||||
self,
|
||||
order_id: int,
|
||||
items: List[dict], # [{product_id, quantity}]
|
||||
location_id: Optional[int] = None
|
||||
) -> ReservationResult:
|
||||
"""
|
||||
Reserve inventory for an order.
|
||||
|
||||
Uses SELECT FOR UPDATE SKIP LOCKED to handle concurrency.
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
try:
|
||||
async with conn.transaction():
|
||||
# Check and reserve each item
|
||||
reservation_ids = []
|
||||
failed_items = []
|
||||
|
||||
for item in items:
|
||||
product_id = item["product_id"]
|
||||
quantity = item["quantity"]
|
||||
|
||||
# Find available inventory with row-level lock
|
||||
if location_id:
|
||||
# Specific location
|
||||
location_ids = [location_id]
|
||||
else:
|
||||
# Any location with availability
|
||||
location_ids = await conn.fetch(
|
||||
"""SELECT location_id
|
||||
FROM inventory_items
|
||||
WHERE product_id = $1
|
||||
AND quantity_available >= $2
|
||||
ORDER BY quantity_available DESC
|
||||
FOR UPDATE""",
|
||||
product_id, quantity
|
||||
)
|
||||
|
||||
if not location_ids:
|
||||
failed_items.append({
|
||||
"product_id": product_id,
|
||||
"requested": quantity,
|
||||
"available": await self._get_available_quantity(conn, product_id)
|
||||
})
|
||||
continue
|
||||
|
||||
# Use the first available location
|
||||
loc_id = location_ids[0] if isinstance(location_ids[0], int) else location_ids[0]["location_id"]
|
||||
|
||||
# Create reservation
|
||||
reservation_id = await conn.fetchval(
|
||||
"""INSERT INTO inventory_reservations
|
||||
(order_id, product_id, quantity, location_id,
|
||||
status, expires_at)
|
||||
VALUES ($1, $2, $3, $4, 'pending', $5)
|
||||
RETURNING id""",
|
||||
order_id,
|
||||
product_id,
|
||||
quantity,
|
||||
loc_id,
|
||||
datetime.now(timezone.utc) + self.reservation_timeout
|
||||
)
|
||||
|
||||
# Update inventory reserved quantity
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_items
|
||||
SET quantity_reserved = quantity_reserved + $1
|
||||
WHERE product_id = $2 AND location_id = $3""",
|
||||
quantity, product_id, loc_id
|
||||
)
|
||||
|
||||
reservation_ids.append(reservation_id)
|
||||
|
||||
if failed_items:
|
||||
# Rollback will release any reservations made
|
||||
raise InsufficientInventoryError(
|
||||
f"Insufficient inventory for products: "
|
||||
f"{[f['product_id'] for f in failed_items]}"
|
||||
)
|
||||
|
||||
return ReservationResult(
|
||||
success=True,
|
||||
reservation_id=reservation_ids[0] if len(reservation_ids) == 1 else None
|
||||
)
|
||||
|
||||
except InsufficientInventoryError as e:
|
||||
return ReservationResult(
|
||||
success=False,
|
||||
failed_items=failed_items,
|
||||
reason=str(e)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error reserving inventory: {e}")
|
||||
return ReservationResult(
|
||||
success=False,
|
||||
reason=f"Database error: {str(e)}"
|
||||
)
|
||||
|
||||
async def _get_available_quantity(self, conn, product_id: int) -> int:
|
||||
"""Get available quantity for a product."""
|
||||
return await conn.fetchval(
|
||||
"""SELECT COALESCE(SUM(quantity_available), 0)
|
||||
FROM inventory_items
|
||||
WHERE product_id = $1""",
|
||||
product_id
|
||||
) or 0
|
||||
|
||||
async def commit_reservations(self, order_id: int) -> bool:
|
||||
"""
|
||||
Commit reservations (permanently deduct inventory).
|
||||
|
||||
Called after successful payment.
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
# Get all pending reservations for this order
|
||||
reservations = await conn.fetch(
|
||||
"""SELECT * FROM inventory_reservations
|
||||
WHERE order_id = $1 AND status = 'pending'
|
||||
FOR UPDATE""",
|
||||
order_id
|
||||
)
|
||||
|
||||
if not reservations:
|
||||
return True
|
||||
|
||||
# Commit each reservation
|
||||
for res in reservations:
|
||||
# Deduct from on-hand, reduce reserved
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_items
|
||||
SET quantity_on_hand = quantity_on_hand - $1,
|
||||
quantity_reserved = quantity_reserved - $1
|
||||
WHERE product_id = $2 AND location_id = $3""",
|
||||
res["quantity"], res["product_id"], res["location_id"]
|
||||
)
|
||||
|
||||
# Mark reservation as committed
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_reservations
|
||||
SET status = 'committed',
|
||||
committed_at = NOW()
|
||||
WHERE id = $1""",
|
||||
res["id"]
|
||||
)
|
||||
|
||||
logger.info(f"Committed {len(reservations)} inventory reservations for order {order_id}")
|
||||
return True
|
||||
|
||||
async def release_reservations(self, order_id: int) -> bool:
|
||||
"""
|
||||
Release reservations (return to available inventory).
|
||||
|
||||
Called on order cancellation or payment failure.
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
# Get all pending reservations for this order
|
||||
reservations = await conn.fetch(
|
||||
"""SELECT * FROM inventory_reservations
|
||||
WHERE order_id = $1 AND status = 'pending'
|
||||
FOR UPDATE""",
|
||||
order_id
|
||||
)
|
||||
|
||||
if not reservations:
|
||||
return True
|
||||
|
||||
# Release each reservation
|
||||
for res in reservations:
|
||||
# Reduce reserved quantity
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_items
|
||||
SET quantity_reserved = quantity_reserved - $1
|
||||
WHERE product_id = $2 AND location_id = $3""",
|
||||
res["quantity"], res["product_id"], res["location_id"]
|
||||
)
|
||||
|
||||
# Mark reservation as released
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_reservations
|
||||
SET status = 'released'
|
||||
WHERE id = $1""",
|
||||
res["id"]
|
||||
)
|
||||
|
||||
logger.info(f"Released {len(reservations)} inventory reservations for order {order_id}")
|
||||
return True
|
||||
|
||||
async def expire_reservations(self) -> int:
|
||||
"""
|
||||
Find and release expired reservations.
|
||||
|
||||
Should be run periodically (e.g., every 5 minutes).
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
# Find expired reservations
|
||||
expired = await conn.fetch(
|
||||
"""SELECT * FROM inventory_reservations
|
||||
WHERE status = 'pending'
|
||||
AND expires_at < NOW()
|
||||
FOR UPDATE"""
|
||||
)
|
||||
|
||||
if not expired:
|
||||
return 0
|
||||
|
||||
# Release each expired reservation
|
||||
for res in expired:
|
||||
# Reduce reserved quantity
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_items
|
||||
SET quantity_reserved = quantity_reserved - $1
|
||||
WHERE product_id = $2 AND location_id = $3""",
|
||||
res["quantity"], res["product_id"], res["location_id"]
|
||||
)
|
||||
|
||||
# Mark reservation as expired
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_reservations
|
||||
SET status = 'expired'
|
||||
WHERE id = $1""",
|
||||
res["id"]
|
||||
)
|
||||
|
||||
# Log order for potential follow-up
|
||||
logger.warning(
|
||||
f"Expired reservation {res['id']} for order {res['order_id']}, "
|
||||
f"product {res['product_id']}, quantity {res['quantity']}"
|
||||
)
|
||||
|
||||
return len(expired)
|
||||
|
||||
async def check_availability(
|
||||
self,
|
||||
items: List[dict]
|
||||
) -> Dict[int, bool]:
|
||||
"""
|
||||
Check if all items are available without reserving.
|
||||
|
||||
Returns {product_id: is_available}
|
||||
"""
|
||||
results = {}
|
||||
|
||||
async with self.db.acquire() as conn:
|
||||
for item in items:
|
||||
product_id = item["product_id"]
|
||||
quantity = item["quantity"]
|
||||
|
||||
available = await self._get_available_quantity(conn, product_id)
|
||||
results[product_id] = available >= quantity
|
||||
|
||||
return results
|
||||
|
||||
async def restock(
|
||||
self,
|
||||
product_id: int,
|
||||
quantity: int,
|
||||
location_id: int
|
||||
):
|
||||
"""Add inventory to a location."""
|
||||
async with self.db.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""INSERT INTO inventory_items (product_id, location_id, quantity_on_hand)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (product_id, location_id)
|
||||
DO UPDATE SET
|
||||
quantity_on_hand = inventory_items.quantity_on_hand + EXCLUDED.quantity_on_hand,
|
||||
last_restocked_at = NOW()""",
|
||||
product_id, location_id, quantity
|
||||
)
|
||||
|
||||
logger.info(f"Restocked {quantity} units of product {product_id} at location {location_id}")
|
||||
|
||||
async def adjust_inventory(
|
||||
self,
|
||||
product_id: int,
|
||||
location_id: int,
|
||||
quantity: int,
|
||||
reason: str = "manual_adjustment"
|
||||
):
|
||||
"""Manual inventory adjustment."""
|
||||
async with self.db.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""UPDATE inventory_items
|
||||
SET quantity_on_hand = quantity_on_hand + $1,
|
||||
updated_at = NOW()
|
||||
WHERE product_id = $2 AND location_id = $3""",
|
||||
quantity, product_id, location_id
|
||||
)
|
||||
|
||||
# Log adjustment
|
||||
await conn.execute(
|
||||
"""INSERT INTO inventory_adjustments
|
||||
(product_id, location_id, quantity, reason)
|
||||
VALUES ($1, $2, $3, $4)""",
|
||||
product_id, location_id, quantity, reason
|
||||
)
|
||||
|
||||
logger.info(f"Adjusted inventory for product {product_id} by {quantity}: {reason}")
|
||||
|
||||
|
||||
class InsufficientInventoryError(Exception):
|
||||
"""Raised when insufficient inventory is available."""
|
||||
pass
|
||||
```
|
||||
|
||||
**Background task for expiring reservations**:
|
||||
```python
|
||||
async def reservation_expiration_worker(inventory_service: InventoryReservationService):
|
||||
"""Background worker to expire stale reservations."""
|
||||
import asyncio
|
||||
|
||||
while True:
|
||||
try:
|
||||
expired = await inventory_service.expire_reservations()
|
||||
if expired > 0:
|
||||
logger.info(f"Expired {expired} stale inventory reservations")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in reservation expiration worker: {e}")
|
||||
|
||||
await asyncio.sleep(300) # Run every 5 minutes
|
||||
```
|
||||
|
||||
**Database extension for adjustments**:
|
||||
```sql
|
||||
-- Inventory adjustments audit table
|
||||
CREATE TABLE inventory_adjustments (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
product_id BIGINT NOT NULL REFERENCES products(id),
|
||||
location_id INTEGER REFERENCES inventory_locations(id),
|
||||
quantity INTEGER NOT NULL, -- Can be negative
|
||||
reason TEXT,
|
||||
adjusted_by VARCHAR(100),
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_adjustments_product ON inventory_adjustments(product_id);
|
||||
CREATE INDEX idx_adjustments_date ON inventory_adjustments(created_at DESC);
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Inventory can be reserved with SELECT FOR UPDATE
|
||||
- [ ] Concurrent orders don't cause overselling
|
||||
- [ ] Reservations expire after timeout
|
||||
- [ ] Committed reservations deduct from inventory
|
||||
- [ ] Released reservations return to available
|
||||
- [ ] Availability checks are accurate
|
||||
- [ ] Manual adjustments work correctly
|
||||
|
||||
## Notes
|
||||
|
||||
**Trade-offs**:
|
||||
- Per-order vs per-item reservations: Per-item for partial fulfillment
|
||||
- Immediate vs deferred commit: Deferred (on payment) for better UX
|
||||
|
||||
**Performance**:
|
||||
- Use connection pooling
|
||||
- Consider Redis for distributed locking if needed
|
||||
|
||||
**Alternatives considered**:
|
||||
- Pessimistic locking: Too much contention
|
||||
- Optimistic with version: Harder to implement correctly
|
||||
- Saga pattern: Overkill for single-database system
|
||||
Reference in New Issue
Block a user