import threading
import queue
import time
import json
import uuid
import random
from typing import Dict, Any
from dataclasses import dataclass
@dataclass
class Message:
type: str
tx_id: str
payload: Dict[str, Any] = None
class LogStore:
def __init__(self, node_id: str, filename: str = None):
self.node_id = node_id
self.filename = filename or f"{node_id}_log.json"
self.log: Dict[str, str] = self._load()
def _load(self) -> Dict[str, str]:
try:
with open(self.filename, 'r') as f:
return json.load(f)
except FileNotFoundError:
return {}
def _save(self):
with open(self.filename, 'w') as f:
json.dump(self.log, f)
def write(self, tx_id: str, action: str):
self.log[tx_id] = action
self._save()
def read(self, tx_id: str) -> str:
return self.log.get(tx_id)
class Participant:
def __init__(self, part_id: str, msg_queues: Dict[str, queue.Queue]):
self.part_id = part_id
self.msg_queues = msg_queues # {target: queue}
self.log = LogStore(part_id)
self.local_state: Dict[str, bool] = {} # tx_id → prepared
self.thread = threading.Thread(target=self._run, daemon=True)
self.thread.start()
def _run(self):
while True:
msg = self.msg_queues[self.part_id].get()
self._handle(msg)
def execute_local_op(self, tx_id: str, action: str) -> bool:
# Simulate local tx work (e.g., DB update)
time.sleep(random.uniform(0.1, 0.5)) # Work
success = random.random() > 0.1 # 90% success
self.local_state[tx_id] = success
return success
def _handle(self, msg: Message):
tx_id = msg.tx_id
if msg.type == 'PREPARE':
prepared = self.execute_local_op(tx_id, 'write')
vote = 'VOTE_YES' if prepared else 'VOTE_NO'
self.log.write(tx_id, vote)
resp_queue = self.msg_queues['coord']
resp_queue.put(Message(vote, tx_id))
elif msg.type == 'COMMIT':
self.log.write(tx_id, 'COMMITTED')
self.msg_queues['coord'].put(Message('ACK', tx_id))
print(f"[{self.part_id}] COMMITTED {tx_id}")
elif msg.type == 'ABORT':
self.log.write(tx_id, 'ABORTED')
self.msg_queues['coord'].put(Message('ACK', tx_id))
print(f"[{self.part_id}] ABORTED {tx_id}")
class Coordinator:
def __init__(self, part_ids: list[str], msg_queues: Dict[str, queue.Queue]):
self.part_ids = part_ids
self.msg_queues = msg_queues
self.log = LogStore('coord')
self.votes: Dict[str, Dict[str, str]] = {} # tx_id → {part: vote}
def start_tx(self, tx_id: str) -> str:
print(f"[Coord] Starting TX {tx_id}")
# Phase 1: Prepare
for part_id in self.part_ids:
self.msg_queues[part_id].put(Message('PREPARE', tx_id))
# Wait for votes with timeout
timeout = 30
start = time.time()
yes_count = 0
while time.time() - start < timeout and yes_count < len(self.part_ids):
for part_id in self.part_ids:
try:
msg = self.msg_queues['coord'].get_nowait()
if msg.tx_id == tx_id:
self.votes.setdefault(tx_id, {})[msg.type.split('_')[1]] = part_id # Simplified
if msg.type == 'VOTE_YES':
yes_count += 1
except queue.Empty:
pass
time.sleep(0.1)
# Decision
decision = 'COMMIT' if yes_count == len(self.part_ids) else 'ABORT'
self.log.write(tx_id, decision)
print(f"[Coord] Decision for {tx_id}: {decision}")
# Phase 2: Commit/Abort
for part_id in self.part_ids:
self.msg_queues[part_id].put(Message(decision, tx_id))
return decision
# Simulation Runner
def simulate(num_parts: int = 3, fail_mode: str = None):
part_ids = [f'part_{i}' for i in range(num_parts)]
msg_queues = {node: queue.Queue() for node in ['coord'] + part_ids}
# Wire queues: coord ↔ parts bidirectional
for part_id in part_ids:
msg_queues['coord'] = msg_queues['coord'] # Shared coord recv
msg_queues[part_id] = msg_queues[part_id]
participants = {pid: Participant(pid, msg_queues) for pid in part_ids}
coord = Coordinator(part_ids, msg_queues)
tx_id = str(uuid.uuid4())[:8]
# Optional failure: e.g., crash coord after prepare
if fail_mode == 'coord_crash_after_prepare':
# Simulate by not sending phase 2, but recovery would query logs
outcome = coord.start_tx(tx_id)
print(f"[Sim] TX {tx_id} outcome: {outcome}")
time.sleep(2) # Let ACKs drain
if __name__ == "__main__":
simulate(num_parts=3)