Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
dbbasic_state_machine.py · 16.1 KB · 422 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | DBBasic State Machine & Workflow Engine |
| 4 | Configuration-driven state transitions and business process automation |
| 5 | """ |
| 6 | |
| 7 | import yaml |
| 8 | import json |
| 9 | import logging |
| 10 | from typing import Dict, List, Any, Optional, Set |
| 11 | from datetime import datetime |
| 12 | from enum import Enum |
| 13 | from dataclasses import dataclass |
| 14 | import asyncio |
| 15 | |
| 16 | logger = logging.getLogger(__name__) |
| 17 | |
| 18 | class TransitionResult(Enum): |
| 19 | SUCCESS = "success" |
| 20 | BLOCKED = "blocked" |
| 21 | ERROR = "error" |
| 22 | PERMISSION_DENIED = "permission_denied" |
| 23 | |
| 24 | @dataclass |
| 25 | class StateTransition: |
| 26 | from_state: str |
| 27 | to_state: str |
| 28 | conditions: List[str] |
| 29 | actions: List[str] |
| 30 | permissions: List[str] |
| 31 | metadata: Dict[str, Any] |
| 32 | |
| 33 | @dataclass |
| 34 | class WorkflowEvent: |
| 35 | entity_id: str |
| 36 | entity_type: str |
| 37 | from_state: str |
| 38 | to_state: str |
| 39 | user_id: Optional[str] |
| 40 | metadata: Dict[str, Any] |
| 41 | timestamp: datetime |
| 42 | |
| 43 | class StateMachine: |
| 44 | """Configuration-driven state machine for business workflows""" |
| 45 | |
| 46 | def __init__(self, config: Dict[str, Any]): |
| 47 | self.config = config |
| 48 | self.states = config.get('states', {}) |
| 49 | self.initial_state = config.get('initial_state', 'pending') |
| 50 | self.final_states = set(config.get('final_states', [])) |
| 51 | self.transitions = self._build_transition_map() |
| 52 | self.global_conditions = config.get('global_conditions', {}) |
| 53 | |
| 54 | def _build_transition_map(self) -> Dict[str, List[StateTransition]]: |
| 55 | """Build transition map from configuration""" |
| 56 | transitions = {} |
| 57 | |
| 58 | for state_name, state_config in self.states.items(): |
| 59 | state_transitions = [] |
| 60 | |
| 61 | for target_state in state_config.get('transitions', []): |
| 62 | transition = StateTransition( |
| 63 | from_state=state_name, |
| 64 | to_state=target_state, |
| 65 | conditions=state_config.get('conditions', []), |
| 66 | actions=state_config.get('actions', []), |
| 67 | permissions=state_config.get('permissions', []), |
| 68 | metadata=state_config.get('metadata', {}) |
| 69 | ) |
| 70 | state_transitions.append(transition) |
| 71 | |
| 72 | transitions[state_name] = state_transitions |
| 73 | |
| 74 | return transitions |
| 75 | |
| 76 | def get_valid_transitions(self, current_state: str) -> List[str]: |
| 77 | """Get list of valid next states from current state""" |
| 78 | if current_state not in self.transitions: |
| 79 | return [] |
| 80 | return [t.to_state for t in self.transitions[current_state]] |
| 81 | |
| 82 | def can_transition(self, from_state: str, to_state: str, |
| 83 | context: Dict[str, Any] = None) -> bool: |
| 84 | """Check if transition is valid and conditions are met""" |
| 85 | if from_state not in self.transitions: |
| 86 | return False |
| 87 | |
| 88 | valid_transitions = [t for t in self.transitions[from_state] |
| 89 | if t.to_state == to_state] |
| 90 | if not valid_transitions: |
| 91 | return False |
| 92 | |
| 93 | transition = valid_transitions[0] |
| 94 | context = context or {} |
| 95 | |
| 96 | # Check conditions |
| 97 | for condition in transition.conditions: |
| 98 | if not self._evaluate_condition(condition, context): |
| 99 | return False |
| 100 | |
| 101 | return True |
| 102 | |
| 103 | def _evaluate_condition(self, condition: str, context: Dict[str, Any]) -> bool: |
| 104 | """Evaluate a condition string against context""" |
| 105 | # Simple condition evaluation - can be expanded with more complex logic |
| 106 | if condition.startswith('field_'): |
| 107 | field_name = condition[6:] # Remove 'field_' prefix |
| 108 | return context.get(field_name) is not None |
| 109 | |
| 110 | if condition.startswith('user_role_'): |
| 111 | required_role = condition[10:] # Remove 'user_role_' prefix |
| 112 | user_roles = context.get('user_roles', []) |
| 113 | return required_role in user_roles |
| 114 | |
| 115 | if condition.startswith('value_'): |
| 116 | # Format: value_field_name_operator_value (e.g., value_amount_gt_1000) |
| 117 | parts = condition.split('_') |
| 118 | if len(parts) >= 4: |
| 119 | field_name = parts[1] |
| 120 | operator = parts[2] |
| 121 | expected_value = '_'.join(parts[3:]) |
| 122 | |
| 123 | field_value = context.get(field_name) |
| 124 | if field_value is None: |
| 125 | return False |
| 126 | |
| 127 | if operator == 'eq': |
| 128 | return str(field_value) == expected_value |
| 129 | elif operator == 'gt': |
| 130 | return float(field_value) > float(expected_value) |
| 131 | elif operator == 'lt': |
| 132 | return float(field_value) < float(expected_value) |
| 133 | |
| 134 | return True # Default to allow if condition not recognized |
| 135 | |
| 136 | class WorkflowEngine: |
| 137 | """Manages multiple state machines and workflow execution""" |
| 138 | |
| 139 | def __init__(self): |
| 140 | self.state_machines: Dict[str, StateMachine] = {} |
| 141 | self.event_handlers = [] |
| 142 | self.workflow_history: List[WorkflowEvent] = [] |
| 143 | |
| 144 | def register_state_machine(self, name: str, config: Dict[str, Any]): |
| 145 | """Register a state machine from configuration""" |
| 146 | self.state_machines[name] = StateMachine(config) |
| 147 | logger.info(f"📋 Registered state machine: {name}") |
| 148 | |
| 149 | def load_from_config(self, config_path: str): |
| 150 | """Load workflow configurations from YAML file""" |
| 151 | with open(config_path, 'r') as f: |
| 152 | config = yaml.safe_load(f) |
| 153 | |
| 154 | for workflow_name, workflow_config in config.get('workflows', {}).items(): |
| 155 | self.register_state_machine(workflow_name, workflow_config) |
| 156 | |
| 157 | async def transition(self, entity_type: str, entity_id: str, |
| 158 | from_state: str, to_state: str, |
| 159 | context: Dict[str, Any] = None, |
| 160 | user_id: str = None) -> TransitionResult: |
| 161 | """Execute a state transition with all validations and actions""" |
| 162 | |
| 163 | if entity_type not in self.state_machines: |
| 164 | logger.error(f"No state machine found for entity type: {entity_type}") |
| 165 | return TransitionResult.ERROR |
| 166 | |
| 167 | state_machine = self.state_machines[entity_type] |
| 168 | context = context or {} |
| 169 | |
| 170 | # Validate transition |
| 171 | if not state_machine.can_transition(from_state, to_state, context): |
| 172 | logger.warning(f"Transition blocked: {entity_type}#{entity_id} {from_state} -> {to_state}") |
| 173 | return TransitionResult.BLOCKED |
| 174 | |
| 175 | # Get transition config |
| 176 | transition = None |
| 177 | for t in state_machine.transitions.get(from_state, []): |
| 178 | if t.to_state == to_state: |
| 179 | transition = t |
| 180 | break |
| 181 | |
| 182 | if not transition: |
| 183 | return TransitionResult.ERROR |
| 184 | |
| 185 | # Check permissions |
| 186 | if transition.permissions and user_id: |
| 187 | user_roles = context.get('user_roles', []) |
| 188 | if not any(role in transition.permissions for role in user_roles): |
| 189 | logger.warning(f"Permission denied: {user_id} cannot transition {entity_type}#{entity_id}") |
| 190 | return TransitionResult.PERMISSION_DENIED |
| 191 | |
| 192 | # Execute pre-transition actions |
| 193 | try: |
| 194 | await self._execute_actions(transition.actions, 'before', context) |
| 195 | |
| 196 | # Record the transition event |
| 197 | event = WorkflowEvent( |
| 198 | entity_id=entity_id, |
| 199 | entity_type=entity_type, |
| 200 | from_state=from_state, |
| 201 | to_state=to_state, |
| 202 | user_id=user_id, |
| 203 | metadata=context, |
| 204 | timestamp=datetime.now() |
| 205 | ) |
| 206 | self.workflow_history.append(event) |
| 207 | |
| 208 | # Execute post-transition actions |
| 209 | await self._execute_actions(transition.actions, 'after', context) |
| 210 | |
| 211 | # Notify event handlers |
| 212 | for handler in self.event_handlers: |
| 213 | await handler(event) |
| 214 | |
| 215 | logger.info(f"✅ Transition successful: {entity_type}#{entity_id} {from_state} -> {to_state}") |
| 216 | return TransitionResult.SUCCESS |
| 217 | |
| 218 | except Exception as e: |
| 219 | logger.error(f"Transition failed: {e}") |
| 220 | return TransitionResult.ERROR |
| 221 | |
| 222 | async def _execute_actions(self, actions: List[str], phase: str, |
| 223 | context: Dict[str, Any]): |
| 224 | """Execute workflow actions (hooks to AI Service Builder)""" |
| 225 | for action in actions: |
| 226 | if action.startswith(f'{phase}_'): |
| 227 | action_name = action[len(f'{phase}_'):] |
| 228 | await self._call_ai_service(action_name, context) |
| 229 | |
| 230 | async def _call_ai_service(self, action_name: str, context: Dict[str, Any]): |
| 231 | """Call AI Service Builder to execute business logic""" |
| 232 | try: |
| 233 | # This would integrate with the AI Service Builder |
| 234 | logger.info(f"🤖 Executing AI action: {action_name}") |
| 235 | # Placeholder for AI service integration |
| 236 | pass |
| 237 | except Exception as e: |
| 238 | logger.error(f"AI action failed: {action_name} - {e}") |
| 239 | |
| 240 | def get_workflow_history(self, entity_type: str = None, |
| 241 | entity_id: str = None) -> List[WorkflowEvent]: |
| 242 | """Get workflow history with optional filtering""" |
| 243 | history = self.workflow_history |
| 244 | |
| 245 | if entity_type: |
| 246 | history = [e for e in history if e.entity_type == entity_type] |
| 247 | if entity_id: |
| 248 | history = [e for e in history if e.entity_id == entity_id] |
| 249 | |
| 250 | return sorted(history, key=lambda x: x.timestamp, reverse=True) |
| 251 | |
| 252 | def get_entity_state_info(self, entity_type: str, current_state: str) -> Dict[str, Any]: |
| 253 | """Get information about current state and possible transitions""" |
| 254 | if entity_type not in self.state_machines: |
| 255 | return {} |
| 256 | |
| 257 | state_machine = self.state_machines[entity_type] |
| 258 | valid_transitions = state_machine.get_valid_transitions(current_state) |
| 259 | |
| 260 | state_config = state_machine.states.get(current_state, {}) |
| 261 | |
| 262 | return { |
| 263 | 'current_state': current_state, |
| 264 | 'valid_transitions': valid_transitions, |
| 265 | 'is_final_state': current_state in state_machine.final_states, |
| 266 | 'state_metadata': state_config.get('metadata', {}), |
| 267 | 'required_permissions': state_config.get('permissions', []), |
| 268 | 'actions': state_config.get('actions', []) |
| 269 | } |
| 270 | |
| 271 | # Global workflow engine instance |
| 272 | workflow_engine = WorkflowEngine() |
| 273 | |
| 274 | def get_workflow_engine() -> WorkflowEngine: |
| 275 | """Get global workflow engine instance""" |
| 276 | return workflow_engine |
| 277 | |
| 278 | # Example configuration for e-commerce order workflow |
| 279 | ECOMMERCE_WORKFLOW_CONFIG = { |
| 280 | 'workflows': { |
| 281 | 'orders': { |
| 282 | 'initial_state': 'pending', |
| 283 | 'final_states': ['delivered', 'cancelled', 'refunded'], |
| 284 | 'states': { |
| 285 | 'pending': { |
| 286 | 'transitions': ['confirmed', 'cancelled'], |
| 287 | 'permissions': ['customer', 'sales_rep', 'admin'], |
| 288 | 'actions': ['before_validate_order', 'after_send_confirmation'], |
| 289 | 'metadata': {'description': 'Order awaiting confirmation'} |
| 290 | }, |
| 291 | 'confirmed': { |
| 292 | 'transitions': ['processing', 'cancelled'], |
| 293 | 'permissions': ['sales_rep', 'admin'], |
| 294 | 'conditions': ['field_payment_authorized'], |
| 295 | 'actions': ['before_authorize_payment', 'after_reserve_inventory'], |
| 296 | 'metadata': {'description': 'Order confirmed and payment authorized'} |
| 297 | }, |
| 298 | 'processing': { |
| 299 | 'transitions': ['shipped', 'cancelled'], |
| 300 | 'permissions': ['fulfillment_team', 'admin'], |
| 301 | 'conditions': ['field_inventory_reserved'], |
| 302 | 'actions': ['before_pick_items', 'after_generate_shipping_label'], |
| 303 | 'metadata': {'description': 'Order being processed for shipment'} |
| 304 | }, |
| 305 | 'shipped': { |
| 306 | 'transitions': ['delivered'], |
| 307 | 'permissions': ['carrier_webhook', 'admin'], |
| 308 | 'actions': ['before_update_tracking', 'after_send_tracking_info'], |
| 309 | 'metadata': {'description': 'Order shipped to customer'} |
| 310 | }, |
| 311 | 'delivered': { |
| 312 | 'transitions': ['refunded'], |
| 313 | 'permissions': ['carrier_webhook', 'customer_confirmation', 'admin'], |
| 314 | 'actions': ['after_request_review', 'after_update_analytics'], |
| 315 | 'metadata': {'description': 'Order successfully delivered'} |
| 316 | }, |
| 317 | 'cancelled': { |
| 318 | 'transitions': [], |
| 319 | 'permissions': ['customer_if_early', 'admin'], |
| 320 | 'actions': ['after_process_refund', 'after_restore_inventory'], |
| 321 | 'metadata': {'description': 'Order cancelled'} |
| 322 | }, |
| 323 | 'refunded': { |
| 324 | 'transitions': [], |
| 325 | 'permissions': ['admin'], |
| 326 | 'actions': ['after_process_refund_payment'], |
| 327 | 'metadata': {'description': 'Order refunded'} |
| 328 | } |
| 329 | } |
| 330 | }, |
| 331 | 'leads': { |
| 332 | 'initial_state': 'new', |
| 333 | 'final_states': ['won', 'lost'], |
| 334 | 'states': { |
| 335 | 'new': { |
| 336 | 'transitions': ['contacted', 'lost'], |
| 337 | 'permissions': ['sales_rep', 'admin'], |
| 338 | 'actions': ['after_assign_lead_automatically'] |
| 339 | }, |
| 340 | 'contacted': { |
| 341 | 'transitions': ['qualified', 'lost'], |
| 342 | 'permissions': ['sales_rep', 'admin'], |
| 343 | 'actions': ['before_log_contact_attempt'] |
| 344 | }, |
| 345 | 'qualified': { |
| 346 | 'transitions': ['proposal', 'lost'], |
| 347 | 'permissions': ['sales_rep', 'admin'], |
| 348 | 'conditions': ['field_budget_confirmed', 'field_decision_maker_identified'] |
| 349 | }, |
| 350 | 'proposal': { |
| 351 | 'transitions': ['negotiation', 'lost'], |
| 352 | 'permissions': ['sales_rep', 'admin'], |
| 353 | 'actions': ['before_generate_proposal', 'after_schedule_follow_up'] |
| 354 | }, |
| 355 | 'negotiation': { |
| 356 | 'transitions': ['won', 'lost'], |
| 357 | 'permissions': ['sales_rep', 'admin'], |
| 358 | 'conditions': ['value_probability_gt_50'] |
| 359 | }, |
| 360 | 'won': { |
| 361 | 'transitions': [], |
| 362 | 'permissions': ['sales_rep', 'admin'], |
| 363 | 'actions': ['after_create_customer_record', 'after_update_sales_metrics'] |
| 364 | }, |
| 365 | 'lost': { |
| 366 | 'transitions': [], |
| 367 | 'permissions': ['sales_rep', 'admin'], |
| 368 | 'actions': ['after_analyze_loss_reason', 'after_update_pipeline_metrics'] |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | if __name__ == "__main__": |
| 376 | # Example usage |
| 377 | import tempfile |
| 378 | import os |
| 379 | |
| 380 | # Create a temporary config file |
| 381 | with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f: |
| 382 | yaml.dump(ECOMMERCE_WORKFLOW_CONFIG, f) |
| 383 | config_path = f.name |
| 384 | |
| 385 | try: |
| 386 | # Initialize workflow engine |
| 387 | engine = get_workflow_engine() |
| 388 | engine.load_from_config(config_path) |
| 389 | |
| 390 | # Example workflow execution |
| 391 | async def test_workflow(): |
| 392 | # Test order workflow |
| 393 | context = { |
| 394 | 'payment_authorized': True, |
| 395 | 'inventory_reserved': True, |
| 396 | 'user_roles': ['sales_rep'] |
| 397 | } |
| 398 | |
| 399 | # Transition from pending to confirmed |
| 400 | result = await engine.transition( |
| 401 | entity_type='orders', |
| 402 | entity_id='ORD-001', |
| 403 | from_state='pending', |
| 404 | to_state='confirmed', |
| 405 | context=context, |
| 406 | user_id='user123' |
| 407 | ) |
| 408 | |
| 409 | print(f"Transition result: {result}") |
| 410 | |
| 411 | # Get state info |
| 412 | info = engine.get_entity_state_info('orders', 'confirmed') |
| 413 | print(f"State info: {json.dumps(info, indent=2)}") |
| 414 | |
| 415 | # Get history |
| 416 | history = engine.get_workflow_history('orders', 'ORD-001') |
| 417 | print(f"Workflow history: {len(history)} events") |
| 418 | |
| 419 | asyncio.run(test_workflow()) |
| 420 | |
| 421 | finally: |
| 422 | os.unlink(config_path) |