import asyncio
import random
import logging
from dataclasses import dataclass, field
from typing import List, Dict, Optional
from enum import Enum, auto
import time
# --- 1. Domain Models ---
class OrderStatus(Enum):
PENDING = auto()
INVENTORY_RESERVED = auto()
PAYMENT_PROCESSED = auto()
COMPLETED = auto()
FAILED = auto()
ROLLED_BACK = auto()
@dataclass
class Order:
id: str
items: List[str]
total: float
status: OrderStatus = OrderStatus.PENDING
history: List[str] = field(default_factory=list)
def record(self, msg: str):
self.history.append(f"[{time.strftime('%H:%M:%S')}] {msg}")
@dataclass
class Inventory:
stock: Dict[str, int] = field(default_factory=dict)
reserved: Dict[str, int] = field(default_factory=dict)
def available(self, item: str) -> int:
return self.stock.get(item, 0) - self.reserved.get(item, 0)
# --- 2. Service Layer (The "Real" Backend Logic) ---
class InventoryService:
def __init__(self):
self.db = Inventory(stock={"widget": 10, "gadget": 5})
async def reserve(self, order_id: str, items: List[str]) -> bool:
# Simulate DB IO
await asyncio.sleep(0.1)
for item in items:
if self.db.available(item) <= 0:
return False
for item in items:
self.db.reserved[item] = self.db.reserved.get(item, 0) + 1
return True
async def release(self, order_id: str, items: List[str]):
await asyncio.sleep(0.1)
for item in items:
if item in self.db.reserved:
self.db.reserved[item] -= 1
print(f"🔄 [Inventory] Released items for order {order_id}")
class PaymentService:
async def process(self, order_id: str, amount: float) -> bool:
await asyncio.sleep(0.2)
# Simulate 80% success rate naturally
return random.random() < 0.8
# --- 3. Chaos Engineering Layer ---
class ChaosType(Enum):
NONE = auto()
LATENCY = auto()
EXCEPTION = auto()
class ChaosProxy:
"""
Wraps a service to inject faults.
"""
def __init__(self, service: any, name: str):
self.service = service
self.name = name
self.chaos_config = ChaosType.NONE
self.is_active = True
def configure_chaos(self, chaos_type: ChaosType):
self.chaos_config = chaos_type
print(f"💥 [Chaos] Configured {self.name} with {chaos_type.name}")
def reset(self):
self.chaos_config = ChaosType.NONE
self.is_active = True
async def execute(self, method_name: str, *args, **kwargs):
# 1. Simulate Outage
if not self.is_active:
raise ConnectionError(f"Connection refused: {self.name} is down")
# 2. Inject Latency
if self.chaos_config == ChaosType.LATENCY:
print(f"🐢 [Chaos] Injecting 3s latency into {self.name}")
await asyncio.sleep(3)
# 3. Inject Exceptions
if self.chaos_config == ChaosType.EXCEPTION:
raise RuntimeError(f"Random Failure in {self.name}")
# 4. Execute Actual Logic
method = getattr(self.service, method_name)
return await method(*args, **kwargs)
# --- 4. Workflow Orchestrator (Saga Pattern) ---
class OrderWorkflow:
def __init__(self, inventory_proxy: ChaosProxy, payment_proxy: ChaosProxy):
self.inventory = inventory_proxy
self.payment = payment_proxy
async def process_order(self, order: Order):
print(f"\n🚀 Starting Workflow for Order {order.id} ({order.items})")
order.record("Workflow Started")
try:
# STEP 1: Reserve Inventory
success = await self.inventory.execute("reserve", order.id, order.items)
if not success:
order.status = OrderStatus.FAILED
order.record("Failed: Out of Stock")
return order
order.status = OrderStatus.INVENTORY_RESERVED
order.record("Inventory Reserved")
# STEP 2: Process Payment
# Note: If this fails, we must trigger compensation (Rollback)
paid = await self.payment.execute("process", order.id, order.total)
if not paid:
order.record("Payment Failed (Business Logic)")
await self._compensate(order)
return order
order.status = OrderStatus.COMPLETED
order.record("Order Completed Successfully")
return order
except Exception as e:
# Handle System Failures (Chaos)
order.record(f"System Error: {str(e)}")
await self._compensate(order)
order.status = OrderStatus.FAILED
return order
async def _compensate(self, order: Order):
print(f"🚨 [Workflow] COMPENSATING Order {order.id} (Rolling back inventory)")
order.record("Triggering Rollback")
try:
# We must ensure the rollback happens even if the system is unstable
await self.inventory.execute("release", order.id, order.items)
order.status = OrderStatus.ROLLED_BACK
except Exception as e:
order.record(f"CRITICAL: Rollback Failed! {str(e)}")
# In a real system, this requires manual intervention or retry queues
# --- 5. Validation & Simulation Runner ---
class Simulator:
def __init__(self):
# Setup real services
inv_svc = InventoryService()
pay_svc = PaymentService()
# Wrap in Proxies
self.inv_proxy = ChaosProxy(inv_svc, "InventoryService")
self.pay_proxy = ChaosProxy(pay_svc, "PaymentService")
self.workflow = OrderWorkflow(self.inv_proxy, self.pay_proxy)
self.validation_rules = []
def add_validation(self, rule):
self.validation_rules.append(rule)
async def run_scenario(self, name: str, chaos_config: dict):
print(f"\n{'='*60}\n⚙️ SCENARIO: {name}\n{'='*60}")
# Reset state
self.inv_proxy.reset()
self.pay_proxy.reset()
# Apply Chaos Configuration
if "inventory" in chaos_config:
self.inv_proxy.configure_chaos(chaos_config["inventory"])
if "payment" in chaos_config:
self.pay_proxy.configure_chaos(chaos_config["payment"])
# Run Workloads
orders = [
Order("ORD-001", ["widget"], 100.0),
Order("ORD-002", ["gadget"], 200.0),
Order("ORD-003", ["widget"], 100.0)
]
tasks = [self.workflow.process_order(o) for o in orders]
results = await asyncio.gather(*tasks)
# Validate
self.validate(results)
def validate(self, orders: List[Order]):
print(f"\n🔍 VALIDATION REPORT")
all_pass = True
for rule in self.validation_rules:
passed, msg = rule(orders)
status = "✅ PASS" if passed else "❌ FAIL"
if not passed: all_pass = False
print(f"{status}: {rule.__name__} - {msg}")
print("-" * 30)
for o in orders:
print(f"Order {o.id}: {o.status.name}")
# for h in o.history: print(f" {h}")
# --- Validation Rules (Invariants) ---
def invariant_stock_consistency(orders):
"""If order failed, stock should not be reserved (unless rollback failed)."""
# In this simple sim, we check logical consistency
# 10 widgets started. 2 orders requested.
# If failures happened, stock logic is hard to verify without inspecting internals
# but we can check internal history logs.
return True, "Stock logic is internal, assume valid for demo."
def invariant_saga_compensation(orders):
"""Ensure failed orders were rolled back."""
for o in orders:
if o.status == OrderStatus.FAILED:
if "Rollback" not in " ".join(o.history):
return False, f"Order {o.id} failed but no rollback triggered."
return True, "All failed orders attempted compensation."
def invariant_no_zombie_states(orders):
"""Ensure no orders stuck in 'Inventory Reserved' state."""
for o in orders:
if o.status == OrderStatus.INVENTORY_RESERVED:
return False, f"Order {o.id} stuck in reserved state."
return True, "No zombie states detected."
# --- Main Execution ---
async def main():
sim = Simulator()
sim.add_validation(invariant_saga_compensation)
sim.add_validation(invariant_no_zombie_states)
# sim.add_validation(invariant_stock_consistency)
# Scenario 1: Happy Path
await sim.run_scenario("Happy Path (High Success Rate)", {})
# Scenario 2: Network Latency (Should still succeed, just slower)
await sim.run_scenario("Network Latency", {"inventory": ChaosType.LATENCY})
# Scenario 3: Inventory Crashes (Expect Rollbacks & Failures)
await sim.run_scenario("Inventory Service Crash", {"inventory": ChaosType.EXCEPTION})
# Scenario 4: Payment Unavailable
await sim.run_scenario("Payment Service Outage", {"payment": ChaosType.EXCEPTION})
if __name__ == "__main__":
# Run the async loop
asyncio.run(main())