import uuid
import random
import time
from enum import Enum, auto
from dataclasses import dataclass
# --- Enums and Data Structures ---
class TransactionState(Enum):
INIT = auto()
PREPARED = auto()
COMMITTED = auto()
ABORTED = auto()
class Vote(Enum):
YES = auto()
NO = auto()
@dataclass
class TransactionLog:
xid: str
state: TransactionState
# --- Participant (Resource Manager) ---
class Participant:
def __init__(self, name, failure_rate=0.1):
self.name = name
self.failure_rate = failure_rate
self.data_store = {}
self.locks = {} # Tracks locks per transaction ID
def execute_local(self, xid, key, value):
"""Simulates execution of the transaction logic (acquiring locks)."""
print(f" [{self.name}] Executing local transaction for {xid}...")
# Simulate random execution failure (e.g., deadlock, constraint error)
if random.random() < self.failure_rate:
print(f" [{self.name}] ❌ Local execution failed (Simulated Error).")
return False
# Simulate acquiring a lock
self.locks[xid] = True
# Store tentative value (in undo/redo log usually)
self.data_store[f"tmp_{xid}"] = value
print(f" [{self.name}] ✅ Local execution successful. Lock acquired.")
return True
def prepare(self, xid):
"""
Phase 1: Vote Yes/No.
In a real DB, this ensures data is flushed to disk but not visible.
"""
print(f" [{self.name}] Received PREPARE request for {xid}.")
if xid in self.locks:
# In a real system, we flush logs to disk here.
print(f" [{self.name}] Voting YES.")
return Vote.YES
else:
print(f" [{self.name}] Voting NO (Lock missing).")
return Vote.NO
def commit(self, xid):
"""Phase 2: Make changes permanent."""
if f"tmp_{xid}" in self.data_store:
# Move from temp to perm
val = self.data_store.pop(f"tmp_{xid}")
# In real scenario, we'd apply the change to the actual key
print(f" [{self.name}] COMMITTING transaction {xid}. Releasing lock.")
self.locks.pop(xid, None)
return True
return False
def rollback(self, xid):
"""Phase 2: Undo changes."""
print(f" [{self.name}] ROLLING BACK transaction {xid}. Releasing lock.")
self.data_store.pop(f"tmp_{xid}", None)
self.locks.pop(xid, None)
# --- Coordinator (Transaction Manager) ---
class Coordinator:
def __init__(self, participants):
self.participants = participants
self.transaction_logs = {} # WAL (Write Ahead Log)
def begin_transaction(self, operations):
"""
operations: list of dicts [{'participant': p1, 'key': 'a', 'val': 1}, ...]
"""
xid = str(uuid.uuid4())[:8]
print(f"\n=== Starting Transaction {xid} ===")
# Log Start
self.transaction_logs[xid] = TransactionLog(xid, TransactionState.INIT)
# 1. Execute Local Logic (Run the SQL/Logic on participants)
# Note: In XA, this happens before prepare.
all_executed = True
for op in operations:
p = op['participant']
success = p.execute_local(xid, op['key'], op['val'])
if not success:
all_executed = False
break
if not all_executed:
self._handle_abort(xid, "Execution Failure")
return
# 2. PHASE 1: PREPARE (Voting)
print(f"\n[Coordinator] Phase 1: Sending PREPARE to participants...")
votes = []
for op in operations:
p = op['participant']
vote = p.prepare(xid)
votes.append(vote)
# 3. DECISION
if all(v == Vote.YES for v in votes):
self._handle_commit(xid)
else:
self._handle_abort(xid, "Participant voted NO")
def _handle_commit(self, xid):
print(f"\n[Coordinator] Phase 2: Decision is COMMIT. Propagating...")
# Log decision first (Atomic Commitment)
self.transaction_logs[xid].state = TransactionState.COMMITTED
for p in self.participants:
p.commit(xid)
print(f"=== Transaction {xid} FINISHED (SUCCESS) ===\n")
def _handle_abort(self, xid, reason):
print(f"\n[Coordinator] Phase 2: Decision is ABORT. Reason: {reason}")
self.transaction_logs[xid].state = TransactionState.ABORTED
for p in self.participants:
p.rollback(xid)
print(f"=== Transaction {xid} FINISHED (ABORTED) ===\n")
# --- Simulation Runner ---
def run_simulation():
# Setup 3 Participants (Databases)
db1 = Participant("DB-1", failure_rate=0.0) # Always reliable
db2 = Participant("DB-2", failure_rate=0.0) # Always reliable
db3 = Participant("DB-3", failure_rate=0.5) # 50% chance of failure during execution
coordinator = Coordinator([db1, db2, db3])
# Transaction 1: Transfer money involving all 3 DBs
ops = [
{'participant': db1, 'key': 'acc_a', 'val': -100},
{'participant': db2, 'key': 'acc_b', 'val': +50},
{'participant': db3, 'key': 'acc_c', 'val': +50}
]
try:
coordinator.begin_transaction(ops)
except Exception as e:
print(f"System Error: {e}")
# Run a second time to see different results
print("\n--- Running Second Transaction ---")
coordinator.begin_transaction(ops)
if __name__ == "__main__":
run_simulation()