File size: 1,515 Bytes
fbcc709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""Deterministic teaching simulator for dual-write delivery strategies."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Result:
    order_saved: bool
    event_recorded: bool
    event_delivered: bool
    duplicate_events: int
    lost_events: int
    recovery: str
    explanation: str

def simulate(strategy: str, crash_at: str = "none", retry: bool = True) -> Result:
    """Simulate a DB write + publish at one crash boundary."""
    if strategy not in {"dual_write", "transactional_outbox"}: raise ValueError("strategy must be dual_write or transactional_outbox")
    if crash_at not in {"none", "after_db", "after_publish"}: raise ValueError("unsupported crash boundary")
    outbox = strategy == "transactional_outbox"
    if crash_at == "after_db":
        if outbox: return Result(True, True, False, 0, 0, "relay retry" if retry else "pending outbox", "Order and event intent committed atomically; a later relay can deliver the pending event.")
        return Result(True, False, False, 0, 1, "no recovery", "Order committed before a crash; separate publish never ran, so its event is lost.")
    if crash_at == "after_publish" and outbox:
        return Result(True, True, True, 1 if retry else 0, 0, "idempotency key suppresses duplicate" if retry else "none", "Crash after broker acknowledgement can cause redelivery; consumers need idempotency to suppress duplicates.")
    return Result(True, outbox, True, 0, 0, "none", "Order and event delivery completed in this simulated run.")