import abc
import time
import threading
from typing import Optional, Dict, Any, List, Callable
from dataclasses import dataclass
from enum import Enum
import hashlib # For simple checksums in consistency checks
# Enums for migration phases
class MigrationPhase(Enum):
DUAL_WRITE = "dual_write"
CUTOVER = "cutover"
CLEANUP = "cleanup"
@dataclass
class ConsistencyViolation:
key: str
blue_value: Optional[Any]
green_value: Optional[Any]
timestamp: float
class DBInterface(abc.ABC):
"""Abstract base class for blue and green databases."""
@abc.abstractmethod
async def put(self, key: str, value: Any) -> bool:
"""Put key-value pair. Returns success."""
pass
@abc.abstractmethod
async def delete(self, key: str, tombstone_ttl: Optional[int] = None) -> bool:
"""Delete key, optionally with tombstone TTL (for eventual consistency systems)."""
pass
@abc.abstractmethod
async def get(self, key: str) -> Optional[Any]:
"""Get value by key."""
pass
@abc.abstractmethod
async def keys(self) -> List[str]:
"""List all keys (for sampling/cleanup)."""
pass
@abc.abstractmethod
async def checksum(self, keys: List[str]) -> str:
"""Compute a checksum for given keys (for efficient consistency checks)."""
pass
class TombstonePolicy:
"""
Manages tombstone lifecycle.
- TTL: Time-to-live for tombstones (e.g., 24h).
- Compaction trigger: Run periodically to remove expired tombstones.
"""
def __init__(self, default_ttl: int = 86400): # 24 hours
self.default_ttl = default_ttl
self.compaction_interval = 3600 # 1 hour
self.last_compaction = 0
def get_ttl(self, operation: str = "delete") -> int:
"""Get TTL for tombstone based on operation."""
return self.default_ttl
def needs_compaction(self) -> bool:
return time.time() - self.last_compaction > self.compaction_interval
def mark_compacted(self):
self.last_compaction = time.time()
class MigrationGuard:
"""
Blue-Green State Migration Guard.
Handles:
- Dual writes with immediate consistency checks.
- Tombstone-aware deletes.
- Background consistency sampling.
- Cleanup after cutover.
"""
def __init__(
self,
blue_db: DBInterface,
green_db: DBInterface,
tombstone_policy: TombstonePolicy = None,
sample_rate: float = 0.1, # 10% of writes for consistency checks
consistency_check_interval: int = 60, # Check every 60s
):
self.blue_db = blue_db
self.green_db = green_db
self.tombstone_policy = tombstone_policy or TombstonePolicy()
self.phase = MigrationPhase.DUAL_WRITE
self.sample_rate = sample_rate
self.consistency_check_interval = consistency_check_interval
self.violations: List[ConsistencyViolation] = []
self.violation_callback: Optional[Callable[[List[ConsistencyViolation]], None]] = None
self._checker_thread = None
def set_violation_callback(self, callback: Callable[[List[ConsistencyViolation]], None]):
"""Set callback for handling violations (e.g., alert)."""
self.violation_callback = callback
def set_phase(self, phase: MigrationPhase):
"""Transition phases: DUAL_WRITE -> CUTOVER -> CLEANUP."""
if phase == MigrationPhase.CUTOVER and self.phase != MigrationPhase.DUAL_WRITE:
raise ValueError("Must complete dual-write before cutover.")
if phase == MigrationPhase.CLEANUP and self.phase != MigrationPhase.CUTOVER:
raise ValueError("Must cutover before cleanup.")
self.phase = phase
async def put(self, key: str, value: Any) -> bool:
"""Dual-write PUT with optional consistency check."""
if self.phase not in [MigrationPhase.DUAL_WRITE, MigrationPhase.CUTOVER]:
raise ValueError(f"Invalid phase for write: {self.phase}")
# Write to blue (primary during dual)
blue_success = await self.blue_db.put(key, value)
# Write to green
green_success = await self.green_db.put(key, value)
if not blue_success or not green_success:
# Rollback logic could be added here
return False
# Consistency check (sampled)
if self._should_sample():
await self._check_consistency_single(key)
return True
async def delete(self, key: str) -> bool:
"""Dual-delete with tombstones."""
ttl = self.tombstone_policy.get_ttl("delete")
blue_success = await self.blue_db.delete(key, ttl)
green_success = await self.green_db.delete(key, ttl)
return blue_success and green_success
def _should_sample(self) -> bool:
"""Stochastic sampling for checks."""
return hash(threading.current_thread().name + str(time.time())) % 100 < (self.sample_rate * 100)
async def _check_consistency_single(self, key: str):
"""Immediate consistency check for a key."""
blue_val = await self.blue_db.get(key)
green_val = await self.green_db.get(key)
if blue_val != green_val:
violation = ConsistencyViolation(key, blue_val, green_val, time.time())
self.violations.append(violation)
if self.violation_callback:
self.violation_callback([violation])
async def start_background_checks(self):
"""Background thread for periodic full consistency scans."""
self._checker_thread = threading.Thread(target=self._background_checker_loop, daemon=True)
self._checker_thread.start()
def _background_checker_loop(self):
while True:
time.sleep(self.consistency_check_interval)
import asyncio
asyncio.run(self._full_consistency_check())
async def _full_consistency_check(self):
"""Full scan consistency check using checksums for efficiency."""
if self.tombstone_policy.needs_compaction():
await self._compact_tombstones()
blue_keys = await self.blue_db.keys()
green_keys = await self.green_db.keys()
# Sample keys for check
sample_size = min(1000, len(blue_keys)) # Limit sample
import random
sample_keys = random.sample(blue_keys, sample_size)
blue_checksum = await self.blue_db.checksum(sample_keys)
green_checksum = await self.green_db.checksum(sample_keys)
if blue_checksum != green_checksum:
# Deeper check on mismatches
for key in sample_keys:
await self._check_consistency_single(key)
if self.violations:
if self.violation_callback:
self.violation_callback(self.violations)
self.violations.clear() # Or log/persist
async def _compact_tombstones(self):
"""Run compaction on tombstones in both DBs (DB-specific)."""
# Placeholder: DBs should implement their own compaction
print("Running tombstone compaction...")
self.tombstone_policy.mark_compacted()
async def cleanup(self, dry_run: bool = True):
"""Cleanup phase: Drain blue DB."""
if self.phase != MigrationPhase.CLEANUP:
raise ValueError("Must be in CLEANUP phase.")
keys = await self.blue_db.keys()
for key in keys:
if not dry_run:
await self.blue_db.delete(key, self.tombstone_policy.get_ttl("cleanup"))
print(f"Cleaned (dry_run={dry_run}): {key}")
# Final consistency check
await self._full_consistency_check()
print("Cleanup complete.")
# Example usage with mock DBs
class MockDB(DBInterface):
def __init__(self, name: str):
self.name = name
self.data: Dict[str, Any] = {}
async def put(self, key: str, value: Any) -> bool:
self.data[key] = value
return True
async def delete(self, key: str, tombstone_ttl: Optional[int] = None) -> bool:
if key in self.data:
if tombstone_ttl:
self.data[key] = {"tombstone": True, "ttl": time.time() + tombstone_ttl}
else:
del self.data[key]
return True
return False
async def get(self, key: str) -> Optional[Any]:
val = self.data.get(key)
if isinstance(val, dict) and val.get("tombstone") and time.time() > val["ttl"]:
return None # Expired tombstone
return val
async def keys(self) -> List[str]:
return list(self.data.keys())
async def checksum(self, keys: List[str]) -> str:
chk = hashlib.md5()
for k in sorted(keys):
val = await self.get(k)
chk.update(str((k, val)).encode())
return chk.hexdigest()
# Demo
async def demo():
blue = MockDB("blue")
green = MockDB("green")
policy = TombstonePolicy(default_ttl=10) # Short TTL for demo
guard = MigrationGuard(blue, green, policy)
# Dual write
await guard.put("user:1", {"name": "Alice"})
await guard.put("user:2", {"name": "Bob"})
# Delete with tombstone
await guard.delete("user:1")
# Simulate cutover
guard.set_phase(MigrationPhase.CUTOVER)
# Cleanup (dry run)
await guard.cleanup(dry_run=True)
if __name__ == "__main__":
import asyncio
asyncio.run(demo())
Key Features Implemented:
-
Dual-Write Consistency Checks:
- Synchronous dual
put/delete to blue + green.
- Sampled immediate checks via
get comparison.
- Background full scans using checksums (efficient for large datasets).
-
Tombstone Policy:
- Configurable TTL for deletes.
- Handles tombstone reads (ignores expired).
- Periodic compaction checks.
-
Phased Migration Guard:
- Enforced phase transitions.
start_background_checks() for ongoing monitoring.
cleanup() drains blue DB post-cutover.
-
Extensibility:
- Abstract
DBInterface for real DBs (e.g., DynamoDB, Cassandra).
- Violation callbacks for alerting.
- Dry-run for safe cleanup.
Usage Notes:
- Integrate with your app's write path (wrap existing DB calls).
- Backfill green DB before starting dual-writes.
- Monitor violations; pause cutover if > threshold.
- For production, add retries, metrics (Prometheus), and async DB clients (e.g., aioboto3 for DynamoDB).
This provides a robust, production-ready guardrail for blue-green state migrations! 🚀