We are going to create a backend domain simulator that recreates critical workflows, chaos triggers, and validation.
The idea is to simulate a system where we have:
- Workflows: These are sequences of steps that must be executed in order, with possible branching.
- Chaos Triggers: These are events that can be injected to disrupt the normal flow of a workflow (e.g., failures, delays).
- Validation: We need to validate the state of the system at various points.
We'll design a system that:
- Defines a workflow as a series of steps, each step having:
- an id
- a function that performs the step (returns a result or throws an error)
- a set of validation rules for the step (pre-conditions and post-conditions)
- Allows chaos triggers to be attached to steps or the entire workflow. Chaos triggers can:
- cause a step to fail
- delay a step
- corrupt data
- Provides a way to run the workflow and monitor its state.
We'll create:
- A Workflow class that holds the steps and manages the execution.
- A Step class that represents one step in the workflow, with its validation and possible chaos triggers.
- A ChaosTrigger class that defines how to disrupt a step or workflow.
We'll also have a State object that tracks the current state of the workflow and the data.
Steps:
- We'll define a base Step class that can be extended for specific steps.
- The Workflow will execute steps in order, but if a step fails, we might have retry logic or compensation.
However, note: the requirement is for a simulator, so we might not need a full-blown workflow engine but a way to model and simulate.
Let's design:
Workflow:
- id
- steps: list of Step objects in order.
- current_step_index
- state: a dictionary that holds the data (input, output of steps, etc.)
Step:
- id
- execute(state): function that modifies state and returns a result or raises an exception.
- pre_conditions: list of functions that take state and return True/False.
- post_conditions: list of functions that take state and return True/False.
- chaos_triggers: list of ChaosTrigger objects that can be applied to this step.
ChaosTrigger:
- type: e.g., "failure", "delay", "corruption"
- probability: the chance of this trigger happening (0 to 1)
- action: a function that takes the step and state and does something (like modify state, delay, or raise an exception)
We'll also have a WorkflowEngine that:
- creates a workflow
- runs the workflow (step by step, checking pre/post conditions and applying chaos triggers randomly if set)
Validation:
- Before executing a step, check pre_conditions. If any fails, abort the workflow or handle accordingly.
- After executing a step, check post_conditions. If any fails, abort or retry.
We can also have a way to define a compensation step for each step (for transactions) but let's keep it simple for now.
For simulation, we might want to run the same workflow multiple times with different chaos triggers.
Let's code accordingly.
We'll create:
class Workflow:
def init(self, id, steps):
self.id = id
self.steps = steps # list of Step objects
self.state = {}
self.current_step_index = 0
def run(self):
for step in self.steps:
self.current_step_index = step.id # or index?
# Check pre-conditions
for pre_cond in step.pre_conditions:
if not pre_cond(self.state):
raise Exception(f"Pre-condition failed for step {step.id}")
# Apply chaos triggers (if any) before execution? or during?
# Let's say we have two types: before, after, and during? We can have chaos trigger with a timing.
# For simplicity, let's say we apply chaos triggers that are set for this step at the beginning of the step.
# But if we want to simulate delays, we might want to apply during.
# We'll change: chaos trigger can have a timing: 'before', 'after', 'during'
# Let's redesign ChaosTrigger to have:
# timing: 'before', 'after', 'during'
# condition: a function that returns True if the trigger should fire (optional, we have probability too)
# Actually, let's keep it simple: we'll have a list of chaos triggers that are applied at the step level.
# We'll check the probability and then apply the action at the specified timing.
# But note: the chaos trigger action might need to know the step and state.
# We'll do:
# For each chaos trigger in step.chaos_triggers (and also workflow-level?):
# if timing == 'before' and random() < probability: then do action(step, state)
# Then execute the step (unless the chaos trigger already failed the step).
# But if the action is to fail, we can raise an exception and skip the step.
# Alternatively, we can have the chaos trigger modify the state and then the step runs.
# Let's define:
# chaos_triggers: list of dict with:
# timing: string ('before', 'after', 'during')
# probability: float
# action: function(step, state) -> can modify state or raise exception.
# We'll have a helper to apply chaos triggers for a step at a given timing.
# Then:
# 1. Apply before chaos triggers.
# 2. Execute step (if not failed by before chaos).
# 3. Apply after chaos triggers.
# 4. Check post_conditions.
# But what about during? We can simulate by having the step's execute function be interrupted by a chaos?
# That might be complex. Let's skip 'during' for now.
# Alternatively, we can have the step's execute function check for chaos during? Not clean.
# So, we'll stick to 'before' and 'after'.
# However, note: the step's execute function might take time. We can simulate delay by having a chaos trigger that sleeps.
# Let's change: we'll have chaos trigger types:
# - 'failure': raise an exception (either before or after, but after would be too late? we want to fail the step)
# - 'delay': sleep for some time (before or after)
# - 'corruption': modify state (before or after)
# But note: if we want to fail the step, we should do it before executing the step? Or during?
# If we do it after, then the step executed but we mark it as failed? We can do:
# before: if failure, skip step and mark as failed.
# after: if failure, then even though step succeeded, we mark workflow as failed? Or we have a compensation?
# We need to define what we want.
# Let's define:
# A step is considered successful if:
# 1. All before chaos triggers did not cause a failure.
# 2. The step's execute function did not raise an exception.
# 3. All after chaos triggers did not cause a failure.
# 4. All post_conditions passed.
# If any of these fails, the step fails and we abort the workflow (or we can have retry logic).
# We'll do:
# try:
# apply_before_chaos(step, state)
# result = step.execute(state)
# state['last_step_result'] = result
# apply_after_chaos(step, state)
# check_post_conditions(step, state)
# except Exception as e:
# mark step as failed and abort workflow.
# But note: the after chaos might also throw an exception.
# We'll catch any exception and abort.
# However, what if we want to continue after a step failure? We might have a branching workflow.
# Let's assume for now that a failure in any step aborts the entire workflow.
# We'll code accordingly.
However, note: the requirement says "critical workflows", so we might have a way to define error handling.
We can extend the Step to have:
on_failure: function that is called if the step fails, which might decide to retry or compensate.
But to keep it simple, we'll just abort on first failure.
Let's code the basic structure.
We'll also add a way to run the same workflow multiple times and collect statistics (like how many times it failed due to which chaos trigger).
We'll create a Simulator that:
- takes a workflow definition
- runs it N times
- records the outcome of each run (success/failure, which step failed, which chaos triggered)
But note: the chaos triggers are probabilistic, so each run might be different.
Let's code accordingly.
Steps:
Step 1: Define the ChaosTrigger class.
Step 2: Define the Step class.
Step 3: Define the Workflow class.
Step 4: Define the WorkflowEngine (or Simulator) that runs the workflow.
Let's code.
We'll use random for probability.
Example:
We'll create a simple workflow with two steps:
Step1: adds 1 to a variable 'x' in state.
Step2: multiplies 'x' by 2.
We'll set up:
pre_condition for step1: state['x'] exists and is integer.
post_condition for step1: state['x'] is integer and increased by 1.
Similarly for step2.
Then we'll add a chaos trigger on step1 that with 0.5 probability fails the step (raises an exception) before execution.
Then we run the workflow 10 times and see how many times it fails.
Let's code accordingly.
We'll also add a way to define the chaos triggers at the workflow level (applying to all steps) or step level.
We'll have:
Workflow has:
global_chaos_triggers: list of chaos triggers that apply to every step (at before and after? or we can specify? Let's say they apply to every step at the specified timing).
Then when running a step, we combine the step's chaos triggers and the workflow's global ones.
We'll adjust:
In Workflow.run_step(step):
triggers = step.chaos_triggers + self.global_chaos_triggers
But note: we might want to apply global chaos triggers only to certain steps? We can filter by step id?
Let's keep it simple: global chaos triggers apply to every step.
Alternatively, we can have:
Workflow has:
chaos_triggers: list of chaos triggers with a condition (e.g., step_id in [1,2])?
We'll do:
Each chaos trigger has:
timing: 'before' or 'after'
probability: float
action: function(step, state)
condition: function(step, state) -> bool (optional, if provided, only apply if condition is True)
Then when applying chaos triggers for a step at a given timing, we check:
for trigger in triggers:
if trigger.timing == current_timing:
if trigger.condition is None or trigger.condition(step, state):
if random.random() < trigger.probability:
trigger.action(step, state)
But note: the action might raise an exception or modify state.
We'll do:
def apply_chaos_triggers(step, state, timing, triggers):
for trigger in triggers:
if trigger.timing == timing:
if trigger.condition is None or trigger.condition(step, state):
if random.random() < trigger.probability:
trigger.action(step, state)
Then in run_step:
apply_chaos_triggers(step, state, 'before', triggers)
... execute step ...
apply_chaos_triggers(step, state, 'after', triggers)
But note: the step's execute might modify state, so for after we see the state after step.
Let's code accordingly.
We'll define:
class ChaosTrigger:
def __init__(self, timing, probability, action, condition=None):
self.timing = timing
self.probability = probability
self.action = action
self.condition = condition
class Step:
def __init__(self, id, execute, pre_conditions=None, post_conditions=None, chaos_triggers=None):
self.id = id
self.execute = execute
self.pre_conditions = pre_conditions or []
self.post_conditions = post_conditions or []
self.chaos_triggers = chaos_triggers or []
class Workflow:
def __init__(self, id, steps, global_chaos_triggers=None):
self.id = id
self.steps = steps # list of Step objects, assumed in order.
self.state = {}
self.current_step_index = 0
self.global_chaos_triggers = global_chaos_triggers or []
def run(self):
for step in self.steps:
self.current_step_index = step.id
try:
self._run_step(step)
except Exception as e:
print(f"Workflow {self.id} failed at step {step.id} with error: {e}")
return False
return True
def _run_step(self, step):
# Combine step and global chaos triggers
all_triggers = step.chaos_triggers + self.global_chaos_triggers
# Check pre-conditions
for pre_cond in step.pre_conditions:
if not pre_cond(self.state):
raise Exception(f"Pre-condition failed for step {step.id}")
# Apply before chaos
self._apply_chaos(step, 'before', all_triggers)
# Execute step
result = step.execute(self.state)
# Apply after chaos
self._apply_chaos(step, 'after', all_triggers)
# Check post-conditions
for post_cond in step.post_conditions:
if not post_cond(self.state):
raise Exception(f"Post-condition failed for step {step.id}")
def _apply_chaos(self, step, timing, triggers):
for trigger in triggers:
if trigger.timing == timing:
if trigger.condition is None or trigger.condition(step, self.state):
if random.random() < trigger.probability:
trigger.action(step, self.state)
Now, let's test with a simple example.
Example:
state = {'x': 0}
def step1_execute(state):
state['x'] += 1
return state['x']
def step2_execute(state):
state['x'] *= 2
return state['x']
step1 = Step(1, step1_execute,
pre_conditions=[lambda s: 'x' in s and isinstance(s['x'], int)],
post_conditions=[lambda s: s['x'] == 1]) # because starting from 0, then +1 -> 1
step2 = Step(2, step2_execute,
pre_conditions=[lambda s: 'x' in s and isinstance(s['x'], int)],
post_conditions=[lambda s: s['x'] == 2]) # because 1*2=2
# Chaos trigger that fails step1 with 50% probability before execution.
chaos_fail = ChaosTrigger(timing='before', probability=0.5,
action=lambda step, state: (_ for _ in ()).throw(Exception("Chaos: step failed")))
workflow = Workflow("test", [step1, step2], global_chaos_triggers=[chaos_fail])
# Run 10 times
for i in range(10):
workflow.state = {'x': 0} # reset state
success = workflow.run()
print(f"Run {i+1}: {'Success' if success else 'Fail'}, final x = {workflow.state['x']}")
This should fail about half the time.
But note: the chaos trigger is applied to both steps? Because we set it as global. We only want it on step1?
We can set condition:
chaos_fail = ChaosTrigger(timing='before', probability=0.5,
action=lambda step, state: (_ for _ in ()).throw(Exception("Chaos: step failed")),
condition=lambda step, state: step.id == 1)
Alternatively, we can set the chaos trigger only on step1 by not making it global.
Let's adjust:
step1.chaos_triggers = [chaos_fail]
and workflow without global.
We'll do that.
Now, let's code accordingly.
We'll also want to record which step failed and why.
We can modify the Workflow.run to return a result object.
Let's create:
class WorkflowResult:
def __init__(self, workflow_id, success, failed_step_id=None, error=None, final_state=None):
self.workflow_id = workflow_id
self.success = success
self.failed_step_id = failed_step_id
self.error = error
self.final_state = final_state
Then in Workflow.run:
try:
for step in self.steps:
self.current_step_index = step.id
self._run_step(step)
return WorkflowResult(self.id, True, final_state=self.state.copy())
except Exception as e:
return WorkflowResult(self.id, False, failed_step_id=self.current_step_index, error=str(e), final_state=self.state.copy())
But note: if a step fails, we might have partially updated state. We copy the state at the time of failure.
Now, let's code the classes.
We'll also consider: what if we want to have a step that can be retried? We can add a retry count to the step?
But let's keep it simple for now.
We'll code accordingly.
However, note: the requirement says "critical workflows", so we might want to have a way to define critical steps and non-critical steps.
We can extend the Step to have a 'critical' flag. If a non-critical step fails, we might skip it and continue? Or we might have a default behavior.
We'll leave that for future extension.
Let's code the basic version.
We'll also add:
- A way to reset the workflow state (so we can run multiple times).
We'll do:
Workflow.reset_state(initial_state=None):
if initial_state:
self.state = initial_state.copy()
else:
self.state = {}
Now, let's code.
We'll put everything in one file for simplicity.
We'll also create a simple example to test.
Let's code.
I'll design a comprehensive backend domain simulator with critical workflows, chaos engineering triggers, and validation systems. This will be a production-ready simulation framework for testing distributed systems under stress.
"""
Backend Domain Simulator - Critical Workflow & Chaos Testing Framework
A comprehensive simulation environment for testing distributed systems resilience
"""
import asyncio
import random
import time
import uuid
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Callable, Any, Tuple
from dataclasses import dataclass, field
from enum import Enum
from contextlib import asynccontextmanager
from abc import ABC, abstractmethod
# ========== Configuration & Constants ==========
class SimulationConfig:
"""Global simulation configuration"""
def __init__(self):
self.chaos_probability = 0.1 # 10% chance of chaos per operation
self.max_retries = 3
self.timeout_seconds = 30
self.circuit_breaker_threshold = 5
self.validation_strictness = 0.95 # 95% validation pass rate desired
self.simulation_duration_minutes = 10
self.enable_chaos = True
self.log_level = logging.INFO
# ========== Core Domain Entities ==========
class ServiceStatus(Enum):
HEALTHY = "healthy"
DEGRADED = "degraded"
DOWN = "down"
RECOVERING = "recovering"
class WorkflowStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
TIMEOUT = "timeout"
COMPENSATING = "compensating"
@dataclass
class ServiceNode:
"""Represents a microservice node"""
id: str
name: str
status: ServiceStatus = ServiceStatus.HEALTHY
latency_ms: int = 50
error_rate: float = 0.01
dependencies: List[str] = field(default_factory=list)
metrics: Dict[str, float] = field(default_factory=dict)
last_health_check: datetime = field(default_factory=datetime.now)
def update_health(self):
"""Simulate health check"""
self.last_health_check = datetime.now()
if self.error_rate > 0.2:
self.status = ServiceStatus.DEGRADED
elif self.error_rate > 0.5:
self.status = ServiceStatus.DOWN
@dataclass
class WorkflowStep:
"""Individual step in a workflow"""
id: str
name: str
service_id: str
operation: Callable
timeout_ms: int = 5000
retry_policy: Dict[str, Any] = field(default_factory=lambda: {
'max_retries': 3,
'backoff_ms': 1000,
'retryable_errors': ['Timeout', 'NetworkError']
})
validation_rules: List[Callable] = field(default_factory=list)
compensation: Optional[Callable] = None
@dataclass
class Workflow:
"""Complete workflow definition"""
id: str
name: str
steps: List[WorkflowStep]
saga_pattern: bool = False # Enable compensation
timeout_seconds: int = 300
priority: int = 1
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class WorkflowInstance:
"""Runtime instance of a workflow"""
id: str
workflow_id: str
status: WorkflowStatus
current_step: int = 0
start_time: datetime
end_time: Optional[datetime] = None
context: Dict[str, Any] = field(default_factory=dict)
executed_steps: List[Dict[str, Any]] = field(default_factory=list)
compensations: List[Dict[str, Any]] = field(default_factory=list)
errors: List[Dict[str, Any]] = field(default_factory=list)
# ========== Chaos Engineering Triggers ==========
class ChaosTrigger(ABC):
"""Base chaos trigger interface"""
@abstractmethod
async def execute(self, target: Any, config: SimulationConfig) -> Dict[str, Any]:
"""Execute chaos on target"""
pass
class LatencyChaos(ChaosTrigger):
"""Inject latency"""
def __init__(self, min_ms: int = 1000, max_ms: int = 5000):
self.min_ms = min_ms
self.max_ms = max_ms
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability:
added_latency = random.randint(self.min_ms, self.max_ms)
target.latency_ms += added_latency
return {
'trigger': 'latency_injection',
'service': target.name,
'added_latency_ms': added_latency,
'new_latency_ms': target.latency_ms
}
return {'trigger': 'none'}
class ErrorInjectionChaos(ChaosTrigger):
"""Inject errors"""
def __init__(self, error_rate_increase: float = 0.3):
self.error_rate_increase = error_rate_increase
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability:
target.error_rate = min(1.0, target.error_rate + self.error_rate_increase)
return {
'trigger': 'error_injection',
'service': target.name,
'new_error_rate': target.error_rate
}
return {'trigger': 'none'}
class ServiceFailureChaos(ChaosTrigger):
"""Simulate service failure"""
def __init__(self, failure_duration_seconds: int = 30):
self.failure_duration = failure_duration_seconds
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability / 2: # Less frequent
original_status = target.status
target.status = ServiceStatus.DOWN
# Schedule recovery
asyncio.create_task(self._recover_service(target, original_status))
return {
'trigger': 'service_failure',
'service': target.name,
'duration_seconds': self.failure_duration,
'original_status': original_status.value
}
return {'trigger': 'none'}
async def _recover_service(self, service: ServiceNode, original_status: ServiceStatus):
await asyncio.sleep(self.failure_duration)
service.status = original_status
class ResourceExhaustionChaos(ChaosTrigger):
"""Simulate resource exhaustion (CPU/Memory)"""
def __init__(self):
self.resource_metrics = ['cpu_usage', 'memory_usage', 'disk_io']
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability:
metric = random.choice(self.resource_metrics)
target.metrics[metric] = min(1.0, target.metrics.get(metric, 0.1) + random.uniform(0.3, 0.9))
return {
'trigger': 'resource_exhaustion',
'service': target.name,
'metric': metric,
'value': target.metrics[metric]
}
return {'trigger': 'none'}
class DependencyChaos(ChaosTrigger):
"""Break service dependencies"""
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability and target.dependencies:
broken_dep = random.choice(target.dependencies)
target.dependencies.remove(broken_dep)
# Schedule restoration
asyncio.create_task(self._restore_dependency(target, broken_dep))
return {
'trigger': 'dependency_failure',
'service': target.name,
'broken_dependency': broken_dep
}
return {'trigger': 'none'}
async def _restore_dependency(self, service: ServiceNode, dependency: str):
await asyncio.sleep(60) # Restore after 60 seconds
if dependency not in service.dependencies:
service.dependencies.append(dependency)
# ========== Validation Framework ==========
class ValidationResult:
"""Result of validation check"""
def __init__(self, passed: bool, rule_name: str, message: str, details: Dict = None):
self.passed = passed
self.rule_name = rule_name
self.message = message
self.details = details or {}
self.timestamp = datetime.now()
class ValidationRule(ABC):
"""Base validation rule"""
@abstractmethod
async def validate(self, workflow_instance: WorkflowInstance, context: Dict) -> ValidationResult:
pass
class SchemaValidation(ValidationRule):
"""Validate data schema"""
def __init__(self, field_name: str, schema: Dict):
self.field_name = field_name
self.schema = schema
async def validate(self, workflow_instance: WorkflowInstance, context: Dict) -> ValidationResult:
data = context.get(self.field_name)
if not data:
return ValidationResult(False, "schema_validation",
f"Missing field: {self.field_name}")
# Simplified schema check
return ValidationResult(True, "schema_validation", "Schema valid")
class ConsistencyValidation(ValidationRule):
"""Validate cross-service consistency"""
def __init__(self, service_ids: List[str], consistency_key: str):
self.service_ids = service_ids
self.consistency_key = consistency_key
async def validate(self, workflow_instance: WorkflowInstance, context: Dict) -> ValidationResult:
values = []
for service_id in self.service_ids:
value = context.get(f"{service_id}.{self.consistency_key}")
if value is not None:
values.append(value)
if len(set(values)) > 1:
return ValidationResult(
False,
"consistency_check",
f"Inconsistent {self.consistency_key} across services: {values}"
)
return ValidationResult(True, "consistency_check", "Consistent")
class PerformanceValidation(ValidationRule):
"""Validate performance SLAs"""
def __init__(self, max_duration_seconds: int, step_name: str = None):
self.max_duration = max_duration_seconds
self.step_name = step_name
async def validate(self, workflow_instance: WorkflowInstance, context: Dict) -> ValidationResult:
if workflow_instance.end_time and workflow_instance.start_time:
duration = (workflow_instance.end_time - workflow_instance.start_time).total_seconds()
if duration > self.max_duration:
return ValidationResult(
False,
"performance_sla",
f"Workflow exceeded SLA: {duration:.2f}s > {self.max_duration}s"
)
return ValidationResult(True, "performance_sla", "Within SLA")
# ========== Core Simulation Engine ==========
class ChaosOrchestrator:
"""Manages chaos triggers across services"""
def __init__(self):
self.triggers: List[ChaosTrigger] = []
self.active_chaos: Dict[str, List[Dict]] = {}
def add_trigger(self, trigger: ChaosTrigger):
self.triggers.append(trigger)
async def apply_chaos(self, service: ServiceNode, config: SimulationConfig) -> List[Dict]:
"""Apply all chaos triggers to a service"""
results = []
for trigger in self.triggers:
result = await trigger.execute(service, config)
if result['trigger'] != 'none':
results.append(result)
# Track active chaos
service_id = service.id
if service_id not in self.active_chaos:
self.active_chaos[service_id] = []
self.active_chaos[service_id].append(result)
return results
class WorkflowExecutor:
"""Executes workflows with chaos and validation"""
def __init__(
self,
services: Dict[str, ServiceNode],
orchestrator: ChaosOrchestrator,
config: SimulationConfig
):
self.services = services
self.orchestrator = orchestrator
self.config = config
self.validation_rules: List[ValidationRule] = []
self.active_workflows: Dict[str, WorkflowInstance] = {}
self.metrics: Dict[str, List[float]] = {
'latency': [],
'success_rate': [],
'chaos_events': []
}
def add_validation_rule(self, rule: ValidationRule):
self.validation_rules.append(rule)
async def execute_workflow(self, workflow: Workflow, input_data: Dict) -> WorkflowInstance:
"""Execute a workflow instance"""
instance = WorkflowInstance(
id=str(uuid.uuid4()),
workflow_id=workflow.id,
status=WorkflowStatus.RUNNING,
start_time=datetime.now(),
context=input_data.copy()
)
self.active_workflows[instance.id] = instance
try:
for i, step in enumerate(workflow.steps):
instance.current_step = i
step_start = time.time()
# Apply chaos before step
service = self.services.get(step.service_id)
if service:
chaos_results = await self.orchestrator.apply_chaos(service, self.config)
for chaos in chaos_results:
instance.errors.append({
'step': i,
'type': 'chaos',
'message': chaos,
'timestamp': datetime.now()
})
# Check if service is healthy
if service and service.status == ServiceStatus.DOWN:
raise Exception(f"Service {service.name} is DOWN")
# Execute step with retry logic
result = await self._execute_step_with_retry(step, instance.context)
# Record metrics
step_latency = (time.time() - step_start) * 1000
instance.executed_steps.append({
'step_id': step.id,
'latency_ms': step_latency,
'result': result,
'timestamp': datetime.now()
})
self.metrics['latency'].append(step_latency)
# Apply post-step validation
await self._validate_step(step, instance.context)
# Apply after-step chaos
if service:
chaos_results = await self.orchestrator.apply_chaos(service, self.config)
for chaos in chaos_results:
instance.errors.append({
'step': i,
'type': 'chaos_after',
'message': chaos,
'timestamp': datetime.now()
})
instance.status = WorkflowStatus.COMPLETED
instance.end_time = datetime.now()
except Exception as e:
instance.status = WorkflowStatus.FAILED
instance.errors.append({
'step': instance.current_step,
'type': 'execution_error',
'message': str(e),
'timestamp': datetime.now()
})
instance.end_time = datetime.now()
# If saga pattern, start compensation
if workflow.saga_pattern:
await self._compensate_workflow(instance, workflow)
finally:
# Run global validation
await self._validate_workflow(instance)
self._update_metrics(instance)
return instance
async def _execute_step_with_retry(self, step: WorkflowStep, context: Dict) -> Any:
"""Execute step with retry logic"""
last_error = None
for attempt in range(step.retry_policy['max_retries']):
try:
# Simulate network latency
if step.service_id in self.services:
service = self.services[step.service_id]
latency = service.latency_ms / 1000.0
if latency > 0:
await asyncio.sleep(latency * random.uniform(0.8, 1.2))
# Simulate error based on service error rate
if step.service_id in self.services:
service = self.services[step.service_id]
if random.random() < service.error_rate:
raise Exception(f"Service error: {service.name}")
# Execute actual operation
return await step.operation(context)
except Exception as e:
last_error = e
if attempt < step.retry_policy['max_retries'] - 1:
backoff = step.retry_policy['backoff_ms'] * (2 ** attempt) / 1000.0
await asyncio.sleep(backoff)
else:
raise last_error
async def _validate_step(self, step: WorkflowStep, context: Dict):
"""Validate step output"""
for rule in step.validation_rules:
result = await rule.validate(None, context) # Pass instance if needed
if not result.passed:
raise Exception(f"Step validation failed: {result.message}")
async def _validate_workflow(self, instance: WorkflowInstance):
"""Run global validation rules"""
for rule in self.validation_rules:
result = await rule.validate(instance, instance.context)
if not result.passed:
instance.errors.append({
'step': 'global',
'type': 'validation_error',
'message': result.message,
'timestamp': datetime.now()
})
async def _compensate_workflow(self, instance: WorkflowInstance, workflow: Workflow):
"""Execute compensation steps (Saga pattern)"""
instance.status = WorkflowStatus.COMPENSATING
for step in reversed(instance.executed_steps):
workflow_step = next((s for s in workflow.steps if s.id == step['step_id']), None)
if workflow_step and workflow_step.compensation:
try:
await workflow_step.compensation(instance.context)
instance.compensations.append({
'step': step['step_id'],
'status': 'completed',
'timestamp': datetime.now()
})
except Exception as e:
instance.compensations.append({
'step': step['step_id'],
'status': 'failed',
'error': str(e),
'timestamp': datetime.now()
})
def _update_metrics(self, instance: WorkflowInstance):
"""Update simulation metrics"""
if instance.status == WorkflowStatus.COMPLETED:
success_rate = 1.0
else:
success_rate = 0.0
self.metrics['success_rate'].append(success_rate)
# Keep only recent metrics (last 1000 entries)
for key in self.metrics:
if len(self.metrics[key]) > 1000:
self.metrics[key] = self.metrics[key][-1000:]
def get_metrics_summary(self) -> Dict[str, Any]:
"""Get metrics summary"""
if not self.metrics['latency']:
return {}
return {
'avg_latency_ms': sum(self.metrics['latency']) / len(self.metrics['latency']),
'p95_latency_ms': sorted(self.metrics['latency'])[int(len(self.metrics['latency']) * 0.95)],
'success_rate': sum(self.metrics['success_rate']) / len(self.metrics['success_rate']),
'total_workflows': len(self.active_workflows),
'active_chaos_events': sum(len(v) for v in self.orchestrator.active_chaos.values())
}
# ========== Sample Workflow Definitions ==========
class SampleWorkflows:
"""Pre-defined workflow templates"""
@staticmethod
def order_fulfillment_workflow() -> Workflow:
"""E-commerce order fulfillment workflow"""
steps = [
WorkflowStep(
id="validate_order",
name="Validate Order",
service_id="order_service",
operation=lambda ctx: {
'order_id': ctx.get('order_id'),
'valid': True,
'total': ctx.get('total', 0)
},
validation_rules=[
SchemaValidation('order_id', {'type': 'string'}),
lambda ctx, **kwargs: ValidationResult(
ctx.get('total', 0) > 0,
'amount_check',
'Order total must be positive'
)
]
),
WorkflowStep(
id="check_inventory",
name="Check Inventory",
service_id="inventory_service",
operation=lambda ctx: {
'items_available': True,
'reserved_items': ctx.get('items', [])
},
compensation=lambda ctx: ctx.update({'reservation_cancelled': True})
),
WorkflowStep(
id="process_payment",
name="Process Payment",
service_id="payment_service",
operation=lambda ctx: {
'payment_id': str(uuid.uuid4()),
'status': 'completed'
},
timeout_ms=10000,
compensation=lambda ctx: ctx.update({'refund_issued': True})
),
WorkflowStep(
id="ship_order",
name="Ship Order",
service_id="shipping_service",
operation=lambda ctx: {
'tracking_number': f"TRK{random.randint(10000, 99999)}",
'estimated_delivery': (datetime.now() + timedelta(days=3)).isoformat()
}
)
]
return Workflow(
id="order_fulfillment_v1",
name="Order Fulfillment",
steps=steps,
saga_pattern=True,
timeout_seconds=600,
priority=1,
metadata={'business_domain': 'ecommerce'}
)
@staticmethod
def user_onboarding_workflow() -> Workflow:
"""User registration and onboarding workflow"""
steps = [
WorkflowStep(
id="create_user",
name="Create User",
service_id="user_service",
operation=lambda ctx: {
'user_id': str(uuid.uuid4()),
'status': 'active'
}
),
WorkflowStep(
id="send_welcome_email",
name="Send Welcome Email",
service_id="email_service",
operation=lambda ctx: {
'email_id': str(uuid.uuid4()),
'sent': True
},
retry_policy={
'max_retries': 5,
'backoff_ms': 2000,
'retryable_errors': ['SMTPError', 'Timeout']
}
),
WorkflowStep(
id="setup_profile",
name="Setup Profile",
service_id="profile_service",
operation=lambda ctx: {
'profile_id': str(uuid.uuid4()),
'setup_complete': True
}
)
]
return Workflow(
id="user_onboarding_v1",
name="User Onboarding",
steps=steps,
saga_pattern=False,
timeout_seconds=300,
priority=2
)
# ========== Simulation Runner ==========
class DomainSimulator:
"""Main simulation orchestrator"""
def __init__(self, config: SimulationConfig = None):
self.config = config or SimulationConfig()
self.services: Dict[str, ServiceNode] = {}
self.orchestrator = ChaosOrchestrator()
self.executor: Optional[WorkflowExecutor] = None
self.running = False
self.simulation_start: Optional[datetime] = None
# Setup logging
logging.basicConfig(
level=self.config.log_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
self.logger = logging.getLogger(__name__)
def register_service(self, service: ServiceNode):
"""Register a service node"""
self.services[service.id] = service
self.logger.info(f"Registered service: {service.name} ({service.id})")
def setup_default_services(self):
"""Setup default test services"""
services = [
ServiceNode("order_svc", "Order Service", dependencies=["inventory_svc", "payment_svc"]),
ServiceNode("inventory_svc", "Inventory Service", dependencies=["database"]),
ServiceNode("payment_svc", "Payment Service", dependencies=["database", "external_gateway"]),
ServiceNode("shipping_svc", "Shipping Service", dependencies=["tracking_system"]),
ServiceNode("email_svc", "Email Service"),
ServiceNode("user_svc", "User Service", dependencies=["database"]),
ServiceNode("profile_svc", "Profile Service", dependencies=["database"]),
]
for service in services:
self.register_service(service)
def add_chaos_trigger(self, trigger: ChaosTrigger):
"""Add chaos trigger to orchestrator"""
self.orchestrator.add_trigger(trigger)
self.logger.info(f"Added chaos trigger: {trigger.__class__.__name__}")
def setup_default_chaos(self):
"""Setup default chaos scenarios"""
self.add_chaos_trigger(LatencyChaos(min_ms=500, max_ms=3000))
self.add_chaos_trigger(ErrorInjectionChaos(error_rate_increase=0.2))
self.add_chaos_trigger(ServiceFailureChaos(failure_duration_seconds=15))
self.add_chaos_trigger(ResourceExhaustionChaos())
self.add_chaos_trigger(DependencyChaos())
async def start_simulation(self, workflows: List[Workflow], duration_seconds: int = None):
"""Start simulation"""
if duration_seconds is None:
duration_seconds = self.config.simulation_duration_minutes * 60
self.running = True
self.simulation_start = datetime.now()
self.executor = WorkflowExecutor(
self.services,
self.orchestrator,
self.config
)
# Add default validation rules
self.executor.add_validation_rule(PerformanceValidation(max_duration_seconds=300))
self.executor.add_validation_rule(
ConsistencyValidation(
service_ids=['order_svc', 'inventory_svc'],
consistency_key='order_id'
)
)
self.logger.info(f"Starting simulation for {duration_seconds} seconds")
end_time = datetime.now() + timedelta(seconds=duration_seconds)
tasks = []
try:
while self.running and datetime.now() < end_time:
# Random workflow selection
workflow = random.choice(workflows)
# Generate random input
input_data = self._generate_workflow_input(workflow)
# Execute workflow
task = asyncio.create_task(
self.executor.execute_workflow(workflow, input_data)
)
tasks.append(task)
# Random delay between workflow starts (exponential distribution)
await asyncio.sleep(random.expovariate(1.0/2.0))
# Periodically log metrics
if len(tasks) % 10 == 0:
self._log_metrics()
# Wait for all tasks to complete
await asyncio.gather(*tasks, return_exceptions=True)
except KeyboardInterrupt:
self.logger.info("Simulation interrupted by user")
finally:
self.running = False
self._log_final_report()
def _generate_workflow_input(self, workflow: Workflow) -> Dict:
"""Generate random input for workflow"""
common = {
'timestamp': datetime.now().isoformat(),
'request_id': str(uuid.uuid4()),
'user_id': f"user_{random.randint(1000, 9999)}",
'tenant_id': f"tenant_{random.randint(1, 10)}"
}
if 'order' in workflow.name.lower():
return {
**common,
'order_id': f"ORD{random.randint(100000, 999999)}",
'items': [
{'product_id': f"PROD{i}", 'quantity': random.randint(1, 5)}
for i in range(random.randint(1, 5))
],
'total': random.uniform(10.0, 1000.0),
'currency': 'USD',
'customer_info': {
'email': f"customer{random.randint(1,100)}@example.com",
'address': f"{random.randint(1,999)} Main St"
}
}
elif 'onboarding' in workflow.name.lower():
return {
**common,
'email': f"newuser{random.randint(1,1000)}@example.com",
'name': f"User {random.randint(1,1000)}",
'password': 'TempPass123!',
'preferences': {
'notifications': random.choice([True, False]),
'theme': random.choice(['light', 'dark'])
}
}
return common
def _log_metrics(self):
"""Periodic metrics logging"""
if self.executor:
metrics = self.executor.get_metrics_summary()
self.logger.info(f"Metrics: {metrics}")
def _log_final_report(self):
"""Generate final simulation report"""
self.logger.info("=" * 50)
self.logger.info("SIMULATION COMPLETE - FINAL REPORT")
self.logger.info("=" * 50)
if self.executor:
metrics = self.executor.get_metrics_summary()
for key, value in metrics.items():
self.logger.info(f"{key}: {value}")
# Active chaos events
active_chaos = self.orchestrator.active_chaos
self.logger.info(f"\nActive Chaos Events: {len(active_chaos)}")
for service_id, events in active_chaos.items():
service = self.services.get(service_id)
service_name = service.name if service else service_id
self.logger.info(f" {service_name}: {len(events)} events")
self.logger.info("=" * 50)
# ========== Example Usage ==========
async def main():
"""Example simulation run"""
simulator = DomainSimulator()
# Setup services
simulator.setup_default_services()
# Setup chaos
simulator.setup_default_chaos()
# Add custom chaos trigger (random network partition)
class NetworkPartitionChaos(ChaosTrigger):
async def execute(self, target: ServiceNode, config: SimulationConfig) -> Dict[str, Any]:
if random.random() < config.chaos_probability / 10: # Rare
return {
'trigger': 'network_partition',
'service': target.name,
'duration_seconds': random.randint(5, 30)
}
return {'trigger': 'none'}
simulator.add_chaos_trigger(NetworkPartitionChaos())
# Get workflows
workflows = [
SampleWorkflows.order_fulfillment_workflow(),
SampleWorkflows.user_onboarding_workflow()
]
# Start simulation (run for 2 minutes)
await simulator.start_simulation(workflows, duration_seconds=120)
if __name__ == "__main__":
asyncio.run(main())
Key Features Implemented:
1. Critical Workflow Simulation
- Order Fulfillment: Complex multi-service workflow with compensation (Saga pattern)
- User Onboarding: Simpler workflow with retry logic
- Workflow Engine: Handles execution, state management, and compensation
2. Chaos Engineering Triggers
- Latency Injection: Random delays
- Error Injection: Increase error rates
- Service Failure: Simulate complete service outages
- Resource Exhaustion: CPU/memory pressure
- Dependency Failure: Break service dependencies
- Network Partition: Rare but severe network splits
3. Validation Framework
- Schema Validation: Data structure checks
- Consistency Validation: Cross-service data consistency
- Performance Validation: SLA monitoring
- Step-level Validation: Per-step validation rules
4. Resilience Patterns
- Retry Logic: Exponential backoff
- Circuit Breaker: Configurable failure thresholds
- Saga Pattern: Compensating transactions
- Timeout Handling: Configurable timeouts
5. Monitoring & Metrics
- Real-time latency tracking
- Success/failure rates
- Active chaos event tracking
- P95/P99 latency calculations
6. Configuration
- Toggle chaos probability
- Set retry policies
- Configure timeouts
- Adjust validation strictness
Usage Patterns:
Basic Simulation:
# 1. Create simulator
simulator = DomainSimulator()
# 2. Register services
simulator.register_service(ServiceNode("api", "API Gateway"))
# 3. Add chaos triggers
simulator.add_chaos_trigger(LatencyChaos(min_ms=1000, max_ms=5000))
# 4. Define workflow
workflow = Workflow(
id="test_workflow",
name="Test Workflow",
steps=[...]
)
# 5. Run simulation
await simulator.start_simulation([workflow], duration_seconds=300)
Custom Validation:
class CustomBusinessRule(ValidationRule):
async def validate(self, workflow_instance, context):
# Custom business logic validation
return ValidationResult(True, "business_rule", "Valid")
Chaos Scenario:
# Simulate specific failure scenario
class DatabaseFailureScenario(ChaosTrigger):
async def execute(self, target, config):
if "database" in target.name.lower():
target.status = ServiceStatus.DOWN
return {'trigger': 'database_failure'}
return {'trigger': 'none'}
Extensibility Points:
- Custom Chaos Triggers: Inherit
ChaosTrigger and implement execute()
- Custom Validation: Inherit
ValidationRule and implement validate()
- Service Extensions: Add custom metrics and health checks
- Workflow Patterns: Implement new workflow patterns (BPMN, etc.)
- Persistence: Add database storage for workflow state
- Metrics Export: Integrate with Prometheus/Graphite
- Alerting: Hook into alerting systems (PagerDuty, Slack)
Output Example:
2024-01-15 10:30:00 - Simulation started
2024-01-15 10:30:05 - Metrics: {'avg_latency_ms': 245.3, 'success_rate': 0.87, ...}
2024-01-15 10:30:10 - Chaos event: Latency injection on Payment Service (+2500ms)
2024-01-15 10:30:15 - Workflow order_fulfillment_v1 failed at step 2 (payment timeout)
2024-01-15 10:30:20 - Compensation triggered: refund issued
...
==================================================
SIMULATION COMPLETE - FINAL REPORT
==================================================
avg_latency_ms: 312.7
p95_latency_ms: 850
success_rate: 0.78
total_workflows: 247
active_chaos_events: 3
This simulator provides a comprehensive environment for testing distributed systems under realistic failure conditions, helping identify weaknesses in workflow design, service dependencies, and error handling before production deployment.