22 KiB
22 KiB
Subtask: Data Replication Engine
Parent Task: Decomp/005 Subtask ID: Decomp-005-04 Dependencies: Decomp-005-01 (Storage Architecture), Decomp-005-02 (File Upload API)
Description
Implement asynchronous replication engine for data durability. Support configurable replication factor, conflict resolution, node failure handling, and replication status tracking.
Requirements
- Replicate objects to N nodes
- Asynchronous replication for performance
- Replication status tracking
- Handle node failures gracefully
- Re-replicate when nodes come back online
- Anti-entropy for consistency verification
- Prioritize critical data replication
Technical Specifications
Replication engine:
from typing import List, Dict, Any, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from enum import Enum
import asyncio
import logging
logger = logging.getLogger(__name__)
class ReplicationStatus(Enum):
"""Replication status."""
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class ReplicationTask:
"""A replication task for an object."""
object_id: int
source_node: str
target_nodes: Set[str]
priority: int = 5 # 1=highest, 10=lowest
retry_count: int = 0
max_retries: int = 3
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
@dataclass
class ReplicationResult:
"""Result of replication attempt."""
object_id: int
success: bool
completed_nodes: List[str]
failed_nodes: List[str]
error: str = None
class ReplicationEngine:
"""Engine for managing data replication across storage nodes."""
def __init__(
self,
db,
storage_adapter,
replication_factor: int = 3,
max_concurrent: int = 10
):
self.db = db
self.storage = storage_adapter
self.replication_factor = replication_factor
self.max_concurrent = max_concurrent
# Task queues
self.pending_queue: asyncio.Queue[ReplicationTask] = asyncio.Queue()
self.in_progress: Dict[int, ReplicationTask] = {}
self.worker_tasks: List[asyncio.Task] = []
# Statistics
self.stats = {
"replicated": 0,
"failed": 0,
"bytes_replicated": 0,
"start_time": datetime.now(timezone.utc)
}
async def start(self):
"""Start replication workers."""
for i in range(self.max_concurrent):
task = asyncio.create_task(self._worker(f"worker-{i}"))
self.worker_tasks.append(task)
logger.info(f"Started {self.max_concurrent} replication workers")
async def stop(self):
"""Stop replication workers."""
for task in self.worker_tasks:
task.cancel()
await asyncio.gather(*self.worker_tasks, return_exceptions=True)
self.worker_tasks.clear()
logger.info("Stopped replication workers")
async def replicate_object(
self,
object_id: int,
source_node: str,
target_nodes: List[str],
priority: int = 5
) -> str:
"""
Queue object for replication.
Returns:
replication_id for tracking
"""
task = ReplicationTask(
object_id=object_id,
source_node=source_node,
target_nodes=set(target_nodes),
priority=priority
)
# Record in database
async with self.db.acquire() as conn:
for target_node in target_nodes:
await conn.execute(
"""INSERT INTO replication_status
(object_id, source_node, target_node, status, started_at)
VALUES ($1, $2, $3, 'pending', NOW())""",
object_id, source_node, target_node
)
await self.pending_queue.put(task)
logger.info(f"Queued replication for object {object_id} to {len(target_nodes)} nodes")
return f"replication-{object_id}-{datetime.now().timestamp()}"
async def get_replication_status(
self,
object_id: int
) -> Dict[str, Any]:
"""Get replication status for an object."""
async with self.db.acquire() as conn:
rows = await conn.fetch(
"""SELECT rs.*
FROM replication_status rs
WHERE rs.object_id = $1
ORDER BY rs.target_node""",
object_id
)
completed = sum(1 for r in rows if r["status"] == "completed")
failed = sum(1 for r in rows if r["status"] == "failed")
pending = sum(1 for r in rows if r["status"] in ("pending", "in_progress"))
return {
"object_id": object_id,
"total": len(rows),
"completed": completed,
"failed": failed,
"pending": pending,
"is_fully_replicated": completed >= self.replication_factor - 1,
"details": [
{
"target_node": r["target_node"],
"status": r["status"],
"started_at": r["started_at"].isoformat() if r["started_at"] else None,
"completed_at": r["completed_at"].isoformat() if r["completed_at"] else None,
"error": r["error_message"]
}
for r in rows
]
}
async def _worker(self, worker_name: str):
"""Worker that processes replication tasks."""
logger.info(f"Replication worker {worker_name} started")
while True:
try:
task = await asyncio.wait_for(
self.pending_queue.get(),
timeout=1.0
)
result = await self._execute_replication(task)
if result.success:
self.stats["replicated"] += 1
else:
self.stats["failed"] += 1
except asyncio.TimeoutError:
continue
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Worker {worker_name} error: {e}")
await asyncio.sleep(1)
async def _execute_replication(
self,
task: ReplicationTask
) -> ReplicationResult:
"""Execute replication for a task."""
self.in_progress[task.object_id] = task
try:
# Get object details
async with self.db.acquire() as conn:
obj = await conn.fetchrow(
"""SELECT o.*, b.name as bucket_name
FROM objects o
JOIN buckets b ON b.id = o.bucket_id
WHERE o.id = $1""",
task.object_id
)
if not obj:
return ReplicationResult(
object_id=task.object_id,
success=False,
completed_nodes=[],
failed_nodes=list(task.target_nodes),
error="Object not found"
)
# Read from source node
source_path = f"{obj['bucket_name']}/{obj['object_key']}"
source_data = await self.storage.read_file(
node_id=task.source_node,
file_path=source_path
)
self.stats["bytes_replicated"] += len(source_data)
# Replicate to each target node
completed = []
failed = []
for target_node in task.target_nodes:
try:
# Write to target node
await self.storage.write_file(
node_id=target_node,
bucket_name=obj["bucket_name"],
object_key=obj["object_key"],
data=source_data
)
# Update status
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE replication_status
SET status = 'completed', completed_at = NOW()
WHERE object_id = $1 AND target_node = $2""",
task.object_id, target_node
)
completed.append(target_node)
logger.debug(f"Replicated object {task.object_id} to {target_node}")
except Exception as e:
failed.append(target_node)
logger.error(f"Failed to replicate to {target_node}: {e}")
# Update failure status
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE replication_status
SET status = 'failed',
error_message = $1,
completed_at = NOW()
WHERE object_id = $2 AND target_node = $3""",
str(e), task.object_id, target_node
)
success = len(completed) >= len(task.target_nodes) - 1 # Allow 1 failure
return ReplicationResult(
object_id=task.object_id,
success=success,
completed_nodes=completed,
failed_nodes=failed,
error=f"Failed to replicate to {len(failed)} nodes" if failed else None
)
finally:
self.in_progress.pop(task.object_id, None)
async def check_replication_health(self) -> Dict[str, Any]:
"""Check health of replication across all objects."""
async with self.db.acquire() as conn:
# Find under-replicated objects
under_replicated = await conn.fetch(
"""SELECT o.id, o.bucket_id, o.object_key,
COUNT(rs.id) FILTER (WHERE rs.status = 'completed') as replicas
FROM objects o
LEFT JOIN replication_status rs ON rs.object_id = o.id
GROUP BY o.id
HAVING COUNT(rs.id) FILTER (WHERE rs.status = 'completed') < $1
LIMIT 100""",
self.replication_factor - 1
)
# Get node health
nodes = await conn.fetch(
"""SELECT node_id, status,
COUNT(rs.id) FILTER (WHERE rs.status = 'in_progress') as active_replications
FROM storage_nodes sn
LEFT JOIN replication_status rs ON rs.target_node = sn.node_id AND rs.status = 'in_progress'
GROUP BY sn.node_id, sn.status"""
)
return {
"under_replicated_objects": len(under_replicated),
"replication_factor": self.replication_factor,
"worker_stats": self.stats,
"nodes": [
{
"node_id": n["node_id"],
"status": n["status"],
"active_replications": n["active_replications"]
}
for n in nodes
]
}
async def re_replicate_objects(self, limit: int = 100) -> int:
"""
Find and re-replicate under-replicated objects.
Should be run periodically.
"""
async with self.db.acquire() as conn:
# Find objects that need re-replication
objects = await conn.fetch(
"""SELECT o.id, o.storage_nodes
FROM objects o
WHERE o.created_at > NOW() - INTERVAL '7 days'
LIMIT $1""",
limit
)
re_replicated = 0
for obj in objects:
object_id = obj["id"]
current_nodes = set(json.loads(obj.get("storage_nodes", "[]")))
# Check if all nodes are still available
available_nodes = await conn.fetch(
"""SELECT node_id FROM storage_nodes
WHERE status = 'active'"""
)
available_set = {n["node_id"] for n in available_nodes}
missing_nodes = available_set - current_nodes
if missing_nodes:
# Get a healthy source node
source_node = next((n for n in current_nodes if n in available_set), None)
if source_node:
# Queue re-replication
new_nodes = list(missing_nodes)[:self.replication_factor - len(current_nodes)]
if new_nodes:
await self.replicate_object(
object_id=object_id,
source_node=source_node,
target_nodes=new_nodes,
priority=3 # Higher priority for re-replication
)
re_replicated += 1
if re_replicated > 0:
logger.info(f"Re-replicated {re_replicated} objects")
return re_replicated
async def anti_entropy_scan(
self,
bucket_id: int = None,
sample_size: int = 1000
) -> Dict[str, Any]:
"""
Perform anti-entropy scan to verify replication consistency.
Compares checksums across replicas.
"""
async with self.db.acquire() as conn:
# Sample objects
query = "SELECT o.* FROM objects o"
params = []
if bucket_id:
query += " WHERE o.bucket_id = $1"
params.append(bucket_id)
query += f" ORDER BY RANDOM() LIMIT ${len(params) + 1}"
params.append(sample_size)
objects = await conn.fetch(query, *params)
inconsistencies = []
for obj in objects:
storage_nodes = json.loads(obj.get("storage_nodes", "[]"))
if len(storage_nodes) < 2:
continue # Skip single-replica objects
# Check checksums on each replica
checksums = {}
for node_id in storage_nodes:
try:
file_info = await self.storage.get_file_info(
node_id=node_id,
file_path=f"{obj.get('bucket_name')}/{obj['object_key']}"
)
checksums[node_id] = file_info.get("checksum")
except Exception as e:
logger.warning(f"Could not read {obj['id']} from {node_id}: {e}")
# Check if all checksums match
unique_checksums = set(checksums.values())
if len(unique_checksums) > 1:
inconsistencies.append({
"object_id": obj["id"],
"object_key": obj["object_key"],
"checksums": checksums
})
# Trigger re-replication from primary
primary_node = storage_nodes[0]
await self.replicate_object(
object_id=obj["id"],
source_node=primary_node,
target_nodes=storage_nodes[1:],
priority=2 # High priority
)
return {
"sample_size": len(objects),
"inconsistencies_found": len(inconsistencies),
"inconsistencies": inconsistencies[:10] # Return first 10
}
async def handle_node_failure(self, failed_node: str):
"""
Handle a node failure by marking its replicas for re-replication.
Called when a node goes offline.
"""
logger.warning(f"Handling node failure: {failed_node}")
async with self.db.acquire() as conn:
# Find all objects on this node
objects = await conn.fetch(
"""SELECT DISTINCT o.id, o.storage_nodes
FROM objects o
WHERE o.storage_nodes @> $1::jsonb
LIMIT 10000""",
json.dumps([failed_node])
)
re_replicated = 0
for obj in objects:
object_id = obj["id"]
current_nodes = set(json.loads(obj["storage_nodes"]))
# Remove failed node
current_nodes.discard(failed_node)
if len(current_nodes) < self.replication_factor:
# Get available nodes
available = await conn.fetch(
"""SELECT node_id FROM storage_nodes
WHERE status = 'active'
AND node_id != $1
LIMIT 10""",
failed_node
)
available_nodes = [a["node_id"] for a in available]
# Select new replicas
needed = self.replication_factor - len(current_nodes)
new_nodes = available_nodes[:needed]
if new_nodes and current_nodes:
# Queue re-replication
await self.replicate_object(
object_id=object_id,
source_node=list(current_nodes)[0],
target_nodes=new_nodes,
priority=1 # Highest priority
)
re_replicated += 1
logger.info(f"Queued {re_replicated} objects for re-replication after node {failed_node} failure")
return re_replicated
Node health monitor:
class NodeHealthMonitor:
"""Monitor storage node health and trigger re-replication."""
def __init__(
self,
db,
replication_engine: ReplicationEngine,
heartbeat_timeout: int = 60
):
self.db = db
self.replication = replication_engine
self.heartbeat_timeout = heartbeat_timeout
self.task: Optional[asyncio.Task] = None
async def start(self):
"""Start health monitoring."""
self.task = asyncio.create_task(self._monitor_loop())
logger.info("Node health monitor started")
async def stop(self):
"""Stop health monitoring."""
if self.task:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass
logger.info("Node health monitor stopped")
async def _monitor_loop(self):
"""Monitor node health continuously."""
while True:
try:
await self._check_node_health()
await asyncio.sleep(30) # Check every 30 seconds
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Health monitor error: {e}")
await asyncio.sleep(30)
async def _check_node_health(self):
"""Check health of all storage nodes."""
async with self.db.acquire() as conn:
# Find nodes with stale heartbeats
failed_nodes = await conn.fetch(
"""SELECT node_id, status
FROM storage_nodes
WHERE last_heartbeat < NOW() - INTERVAL '1 second' * $1
AND status = 'active'""",
self.heartbeat_timeout
)
# Find nodes that are back online
recovered_nodes = await conn.fetch(
"""SELECT node_id, status
FROM storage_nodes
WHERE last_heartbeat >= NOW() - INTERVAL '1 second' * $1
AND status IN ('offline', 'maintenance')""",
self.heartbeat_timeout
)
# Handle failures
for node in failed_nodes:
logger.warning(f"Node {node['node_id']} appears to be down")
await conn.execute(
"UPDATE storage_nodes SET status = 'offline' WHERE node_id = $1",
node["node_id"]
)
await self.replication.handle_node_failure(node["node_id"])
# Handle recoveries
for node in recovered_nodes:
logger.info(f"Node {node['node_id']} is back online")
await conn.execute(
"UPDATE storage_nodes SET status = 'active' WHERE node_id = $1",
node["node_id"]
)
Replication metrics API:
from fastapi import APIRouter
router = APIRouter(prefix="/v1/replication", tags=["replication"])
@router.get("/health")
async def replication_health():
"""Get replication health status."""
replication = get_replication_engine()
return await replication.check_replication_health()
@router.get("/objects/{object_id}/status")
async def object_replication_status(object_id: int):
"""Get replication status for an object."""
replication = get_replication_engine()
return await replication.get_replication_status(object_id)
@router.post("/re-replicate")
async def trigger_re_replication(limit: int = 100):
"""Trigger re-replication of under-replicated objects."""
replication = get_replication_engine()
count = await replication.re_replicate_objects(limit)
return {"re_replicated": count}
@router.post("/anti-entropy")
async def run_anti_entropy_scan(
bucket_id: Optional[int] = None,
sample_size: int = 1000
):
"""Run anti-entropy scan to verify data consistency."""
replication = get_replication_engine()
return await replication.anti_entropy_scan(bucket_id, sample_size)
Acceptance Criteria
- Objects are replicated to N nodes
- Replication status is tracked
- Failed nodes trigger re-replication
- Anti-entropy scan detects inconsistencies
- Node failures are handled gracefully
- Workers process replication queue
- Health monitoring works correctly
Notes
Trade-offs:
- Synchronous vs asynchronous replication: Async for upload performance
- Strong vs eventual consistency: Eventual with verification
Performance:
- Use connection pooling for storage nodes
- Prioritize critical data replication
Alternatives considered:
- Raft consensus: Overkill for this use case
- Chain replication: Slower recovery time