Build a cross-region primary election rehearsal: quorum simulation, failure injection,…
- User
Build a cross-region primary election rehearsal: quorum simulation, failure injection, and rollback.
Assistant
Build a cross-region primary election rehearsal: quorum simulation, failure injection, and rollback.
This is a complex distributed systems simulation - a cross-region primary election rehearsal. Let me think about what this needs:
Key components to visualize:
Design approach:
Let me create a single HTML file with all this functionality:
Visual Layout:
Interactions:
Animations:
Let me build this with a clean, professional design - maybe a dark theme with cyan/teal accents for a "control room" feel.
This is a distributed systems simulation featuring:
The simulation uses a Raft-inspired election mechanism with configurable quorum requirements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cross-Region Election Rehearsal</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Space+Grotesk:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0e14;
--bg-elevated: #12171f;
--bg-card: #1a2029;
--fg: #e6edf3;
--muted: #7d8590;
--accent: #00d9ff;
--accent-dim: #00d9ff33;
--success: #3fb950;
--warning: #d29922;
--danger: #f85149;
--border: #30363d;
}
* { box-sizing: border-box; }
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
}
.mono { font-family: 'JetBrains Mono', monospace; }
.grid-bg {
background-image:
linear-gradient(rgba(0, 217, 255, 0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 217, 255, 0.03) 1px, transparent 1px);
background-size: 40px 40px;
}
.glow-accent {
box-shadow: 0 0 20px var(--accent-dim), inset 0 1px 0 rgba(255,255,255,0.1);
}
.node-ring {
animation: pulse-ring 2s ease-out infinite;
}
@keyframes pulse-ring {
0% { transform: scale(1); opacity: 0.8; }
100% { transform: scale(1.5); opacity: 0; }
}
@keyframes vote-travel {
0% { offset-distance: 0%; opacity: 1; }
100% { offset-distance: 100%; opacity: 0.6; }
}
@keyframes float-in {
0% { opacity: 0; transform: translateY(20px); }
100% { opacity: 1; transform: translateY(0); }
}
.animate-float-in {
animation: float-in 0.5s ease-out forwards;
}
.status-led {
width: 8px;
height: 8px;
border-radius: 50%;
animation: led-blink 1.5s ease-in-out infinite;
}
@keyframes led-blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.partition-line {
stroke-dasharray: 8 4;
animation: dash-move 0.5s linear infinite;
}
@keyframes dash-move {
to { stroke-dashoffset: -12; }
}
.checkpoint-dot {
transition: all 0.2s ease;
}
.checkpoint-dot:hover {
transform: scale(1.3);
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
.btn {
transition: all 0.15s ease;
}
.btn:hover:not(:disabled) {
transform: translateY(-1px);
}
.btn:active:not(:disabled) {
transform: translateY(0);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.log-entry {
animation: float-in 0.3s ease-out;
}
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
</style>
</head>
<body class="grid-bg">
<div class="min-h-screen p-4 lg:p-6">
<!-- Header -->
<header class="mb-6 animate-float-in">
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
<div>
<h1 class="text-2xl lg:text-3xl font-bold tracking-tight" style="color: var(--fg);">
Cross-Region Election Rehearsal
</h1>
<p class="text-sm mt-1" style="color: var(--muted);">
Distributed consensus simulation with failure injection and rollback capability
</p>
</div>
<div class="flex items-center gap-3">
<div class="flex items-center gap-2 px-3 py-1.5 rounded-lg" style="background: var(--bg-card); border: 1px solid var(--border);">
<span class="status-led" style="background: var(--success);"></span>
<span class="mono text-xs" id="system-status">SYSTEM NOMINAL</span>
</div>
<div class="mono text-xs px-3 py-1.5 rounded-lg" style="background: var(--bg-card); border: 1px solid var(--border);">
Term: <span id="current-term">1</span>
</div>
</div>
</div>
</header>
<div class="grid grid-cols-1 xl:grid-cols-4 gap-4 lg:gap-6">
<!-- Main Visualization -->
<div class="xl:col-span-3 space-y-4">
<!-- Cluster Visualization -->
<div class="rounded-xl p-4 lg:p-6" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<div class="flex items-center justify-between mb-4">
<h2 class="font-semibold">Cluster Topology</h2>
<div class="flex items-center gap-4 text-xs" style="color: var(--muted);">
<span class="flex items-center gap-1.5">
<span class="w-3 h-3 rounded-full" style="background: var(--success);"></span> Leader
</span>
<span class="flex items-center gap-1.5">
<span class="w-3 h-3 rounded-full" style="background: var(--accent);"></span> Follower
</span>
<span class="flex items-center gap-1.5">
<span class="w-3 h-3 rounded-full" style="background: var(--warning);"></span> Candidate
</span>
<span class="flex items-center gap-1.5">
<span class="w-3 h-3 rounded-full" style="background: var(--danger);"></span> Failed
</span>
</div>
</div>
<svg id="cluster-svg" viewBox="0 0 900 500" class="w-full h-auto" style="min-height: 300px;">
<!-- Definitions -->
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="3" result="coloredBlur"/>
<feMerge>
<feMergeNode in="coloredBlur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
<linearGradient id="link-gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color: #00d9ff; stop-opacity: 0.3"/>
<stop offset="50%" style="stop-color: #00d9ff; stop-opacity: 0.6"/>
<stop offset="100%" style="stop-color: #00d9ff; stop-opacity: 0.3"/>
</linearGradient>
</defs>
<!-- Dynamic content rendered by JS -->
</svg>
</div>
<!-- Quorum Progress -->
<div class="rounded-xl p-4 lg:p-6" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<div class="flex items-center justify-between mb-4">
<h2 class="font-semibold">Quorum Status</h2>
<span class="mono text-sm" id="quorum-count" style="color: var(--accent);">0 / 5 votes</span>
</div>
<div class="h-3 rounded-full overflow-hidden" style="background: var(--bg-card);">
<div id="quorum-bar" class="h-full rounded-full transition-all duration-500"
style="background: linear-gradient(90deg, var(--accent), #00ffaa); width: 0%;"></div>
</div>
<div class="flex justify-between mt-2 text-xs" style="color: var(--muted);">
<span>0</span>
<span>Majority: <span id="majority-threshold">5</span></span>
<span id="total-nodes">9</span>
</div>
</div>
<!-- Event Log -->
<div class="rounded-xl p-4 lg:p-6" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<div class="flex items-center justify-between mb-4">
<h2 class="font-semibold">Event Log</h2>
<button onclick="clearLog()" class="btn text-xs px-3 py-1 rounded-lg"
style="background: var(--bg-card); border: 1px solid var(--border); color: var(--muted);">
Clear
</button>
</div>
<div id="event-log" class="h-40 overflow-y-auto space-y-1 mono text-xs" style="color: var(--muted);">
<div class="log-entry py-1">[BOOT] System initialized</div>
</div>
</div>
</div>
<!-- Control Panel -->
<div class="space-y-4">
<!-- Election Control -->
<div class="rounded-xl p-4" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
Election Control
</h3>
<div class="space-y-3">
<button onclick="startElection()" id="btn-election"
class="btn w-full py-2.5 rounded-lg font-medium text-sm glow-accent"
style="background: var(--accent); color: var(--bg);">
Trigger Election
</button>
<button onclick="resetCluster()"
class="btn w-full py-2.5 rounded-lg font-medium text-sm"
style="background: var(--bg-card); border: 1px solid var(--border); color: var(--fg);">
Reset Cluster
</button>
</div>
</div>
<!-- Failure Injection -->
<div class="rounded-xl p-4" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<svg class="w-4 h-4" style="color: var(--danger);" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
</svg>
Failure Injection
</h3>
<div class="space-y-3">
<button onclick="killRandomNode()"
class="btn w-full py-2 rounded-lg text-sm text-left px-3"
style="background: rgba(248, 81, 73, 0.1); border: 1px solid rgba(248, 81, 73, 0.3); color: var(--danger);">
Kill Random Node
</button>
<button onclick="killLeader()"
class="btn w-full py-2 rounded-lg text-sm text-left px-3"
style="background: rgba(248, 81, 73, 0.1); border: 1px solid rgba(248, 81, 73, 0.3); color: var(--danger);">
Kill Leader
</button>
<button onclick="partitionRegion()"
class="btn w-full py-2 rounded-lg text-sm text-left px-3"
style="background: rgba(210, 153, 34, 0.1); border: 1px solid rgba(210, 153, 34, 0.3); color: var(--warning);">
Network Partition
</button>
<button onclick="injectLatency()"
class="btn w-full py-2 rounded-lg text-sm text-left px-3"
style="background: rgba(210, 153, 34, 0.1); border: 1px solid rgba(210, 153, 34, 0.3); color: var(--warning);">
Inject Latency Spike
</button>
<button onclick="healAll()"
class="btn w-full py-2 rounded-lg text-sm text-left px-3"
style="background: rgba(63, 185, 80, 0.1); border: 1px solid rgba(63, 185, 80, 0.3); color: var(--success);">
Heal All Failures
</button>
</div>
</div>
<!-- Rollback Timeline -->
<div class="rounded-xl p-4" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<h3 class="font-semibold mb-4 flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
Rollback Timeline
</h3>
<button onclick="createCheckpoint()"
class="btn w-full py-2 rounded-lg text-sm mb-4"
style="background: var(--accent); color: var(--bg);">
Create Checkpoint
</button>
<div id="checkpoint-list" class="space-y-2 max-h-48 overflow-y-auto">
<div class="text-xs text-center py-4" style="color: var(--muted);">No checkpoints yet</div>
</div>
</div>
<!-- Node Selection -->
<div class="rounded-xl p-4" style="background: var(--bg-elevated); border: 1px solid var(--border);">
<h3 class="font-semibold mb-4">Node Actions</h3>
<p class="text-xs mb-3" style="color: var(--muted);">Click a node in the visualization to select it</p>
<div id="selected-node-info" class="text-sm" style="color: var(--muted);">
No node selected
</div>
<div id="node-actions" class="hidden space-y-2 mt-3">
<button onclick="toggleSelectedNode()" id="btn-toggle-node"
class="btn w-full py-2 rounded-lg text-sm"
style="background: var(--bg-card); border: 1px solid var(--border);">
Toggle Node State
</button>
</div>
</div>
</div>
</div>
</div>
<script>
// Configuration
const REGIONS = [
{ id: 'us-east', name: 'US-East', x: 200, y: 120, color: '#00d9ff' },
{ id: 'us-west', name: 'US-West', x: 700, y: 120, color: '#00ffaa' },
{ id: 'eu-west', name: 'EU-West', x: 200, y: 380, color: '#ff6b9d' },
{ id: 'ap-south', name: 'AP-South', x: 700, y: 380, color: '#ffd93d' }
];
const NODES_PER_REGION = [2, 3, 2, 2]; // 9 total nodes
const ELECTION_TIMEOUT_MIN = 1500;
const ELECTION_TIMEOUT_MAX = 3000;
// State
let nodes = [];
let currentLeader = null;
let currentTerm = 1;
let votes = {};
let electionInProgress = false;
let checkpoints = [];
let selectedNode = null;
let partitions = [];
let latencyInjected = false;
// Initialize cluster
function initCluster() {
nodes = [];
let nodeId = 0;
REGIONS.forEach((region, regionIdx) => {
const count = NODES_PER_REGION[regionIdx];
for (let i = 0; i < count; i++) {
const angle = (i / count) * Math.PI * 2 - Math.PI / 2;
const radius = 50;
nodes.push({
id: nodeId,
region: region.id,
regionName: region.name,
x: region.x + Math.cos(angle) * radius,
y: region.y + Math.sin(angle) * radius,
state: 'follower',
term: 1,
alive: true,
votedFor: null,
latency: 0
});
nodeId++;
}
});
// Elect initial leader (first node)
nodes[0].state = 'leader';
currentLeader = nodes[0];
updateMajorityThreshold();
renderCluster();
updateQuorumDisplay();
logEvent('INIT', 'Cluster initialized with 9 nodes across 4 regions');
logEvent('LEADER', `Node N0 (${nodes[0].regionName}) is initial leader`);
}
function updateMajorityThreshold() {
const aliveNodes = nodes.filter(n => n.alive).length;
const majority = Math.floor(aliveNodes / 2) + 1;
document.getElementById('majority-threshold').textContent = majority;
document.getElementById('total-nodes').textContent = aliveNodes;
}
// Render cluster visualization
function renderCluster() {
const svg = document.getElementById('cluster-svg');
svg.innerHTML = `
<defs>
<filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="3" result="coloredBlur"/>
<feMerge>
<feMergeNode in="coloredBlur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
`;
// Draw inter-region connections
const connections = [
[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]
];
connections.forEach(([a, b]) => {
const regionA = REGIONS[a];
const regionB = REGIONS[b];
const isPartitioned = partitions.some(p =>
(p.includes(regionA.id) && !p.includes(regionB.id)) ||
(!p.includes(regionA.id) && p.includes(regionB.id))
);
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', regionA.x);
line.setAttribute('y1', regionA.y);
line.setAttribute('x2', regionB.x);
line.setAttribute('y2', regionB.y);
line.setAttribute('stroke', isPartitioned ? '#f85149' : '#30363d');
line.setAttribute('stroke-width', isPartitioned ? '2' : '1');
line.setAttribute('stroke-dasharray', isPartitioned ? '8 4' : '0');
if (isPartitioned) {
line.classList.add('partition-line');
}
line.setAttribute('opacity', isPartitioned ? '0.8' : '0.4');
svg.appendChild(line);
});
// Draw regions
REGIONS.forEach(region => {
// Region circle
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', region.x);
circle.setAttribute('cy', region.y);
circle.setAttribute('r', '80');
circle.setAttribute('fill', 'none');
circle.setAttribute('stroke', region.color);
circle.setAttribute('stroke-width', '1');
circle.setAttribute('stroke-dasharray', '4 4');
circle.setAttribute('opacity', '0.3');
svg.appendChild(circle);
// Region label
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', region.x);
text.setAttribute('y', region.y - 95);
text.setAttribute('text-anchor', 'middle');
text.setAttribute('fill', region.color);
text.setAttribute('font-size', '12');
text.setAttribute('font-family', 'JetBrains Mono');
text.textContent = region.name;
svg.appendChild(text);
});
// Draw nodes
nodes.forEach(node => {
const group = document.createElementNS('http://www.w3.org/2000/svg', 'g');
group.style.cursor = 'pointer';
group.onclick = () => selectNode(node);
const color = getNodeColor(node);
// Leader ring
if (node.state === 'leader' && node.alive) {
const ring = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
ring.setAttribute('cx', node.x);
ring.setAttribute('cy', node.y);
ring.setAttribute('r', '28');
ring.setAttribute('fill', 'none');
ring.setAttribute('stroke', '#3fb950');
ring.setAttribute('stroke-width', '2');
ring.classList.add('node-ring');
svg.appendChild(ring);
}
// Node circle
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', node.x);
circle.setAttribute('cy', node.y);
circle.setAttribute('r', '20');
circle.setAttribute('fill', node.alive ? color : '#2d333b');
circle.setAttribute('stroke', node.alive ? color : '#f85149');
circle.setAttribute('stroke-width', selectedNode?.id === node.id ? '3' : '2');
if (node.alive && (node.state === 'leader' || node.state === 'candidate')) {
circle.setAttribute('filter', 'url(#glow)');
}
group.appendChild(circle);
// Node ID
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', node.x);
text.setAttribute('y', node.y + 4);
text.setAttribute('text-anchor', 'middle');
text.setAttribute('fill', node.alive ? '#0a0e14' : '#7d8590');
text.setAttribute('font-size', '11');
text.setAttribute('font-weight', '600');
text.setAttribute('font-family', 'JetBrains Mono');
text.textContent = `N${node.id}`;
group.appendChild(text);
// Latency indicator
if (node.latency > 0 && node.alive) {
const latencyText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
latencyText.setAttribute('x', node.x);
latencyText.setAttribute('y', node.y + 35);
latencyText.setAttribute('text-anchor', 'middle');
latencyText.setAttribute('fill', '#d29922');
latencyText.setAttribute('font-size', '9');
latencyText.setAttribute('font-family', 'JetBrains Mono');
latencyText.textContent = `+${node.latency}ms`;
group.appendChild(latencyText);
}
svg.appendChild(group);
});
updateSystemStatus();
}
function getNodeColor(node) {
if (!node.alive) return '#2d333b';
switch (node.state) {
case 'leader': return '#3fb950';
case 'candidate': return '#d29922';
case 'follower': return '#00d9ff';
default: return '#7d8590';
}
}
// Election logic
function startElection() {
if (electionInProgress) return;
const aliveNodes = nodes.filter(n => n.alive);
if (aliveNodes.length === 0) {
logEvent('ERROR', 'No alive nodes to participate in election');
return;
}
electionInProgress = true;
currentTerm++;
document.getElementById('current-term').textContent = currentTerm;
// Find a candidate (prefer triggering from a specific region)
const candidateNode = aliveNodes[Math.floor(Math.random() * aliveNodes.length)];
// Step down current leader
if (currentLeader && currentLeader.alive) {
currentLeader.state = 'follower';
}
candidateNode.state = 'candidate';
candidateNode.term = currentTerm;
votes = { [candidateNode.id]: 1 };
logEvent('ELECTION', `Node N${candidateNode.id} (${candidateNode.regionName}) starts election for term ${currentTerm}`);
updateQuorumDisplay();
renderCluster();
// Simulate vote gathering
simulateVoteGathering(candidateNode);
}
function simulateVoteGathering(candidate) {
const aliveNodes = nodes.filter(n => n.alive && n.id !== candidate.id);
const majority = Math.floor(nodes.filter(n => n.alive).length / 2) + 1;
let votesReceived = 1; // Candidate votes for itself
aliveNodes.forEach((node, index) => {
const baseDelay = 200 + index * 150;
const latencyDelay = node.latency + (latencyInjected ? Math.random() * 500 : 0);
const partitionDelay = isPartitioned(candidate.region, node.region) ? 999999 : 0;
setTimeout(() => {
if (!electionInProgress || !candidate.alive) return;
// Simulate vote decision (higher chance if in same region or no leader)
const sameRegion = candidate.region === node.region;
const voteProbability = sameRegion ? 0.95 : 0.7;
const willVote = Math.random() < voteProbability && partitionDelay === 0;
if (willVote) {
votesReceived++;
votes[node.id] = 1;
animateVote(node, candidate);
logEvent('VOTE', `Node N${node.id} (${node.regionName}) voted for N${candidate.id}`);
updateQuorumDisplay();
// Check if quorum reached
if (votesReceived >= majority && candidate.state === 'candidate') {
candidate.state = 'leader';
currentLeader = candidate;
electionInProgress = false;
// Update all followers
nodes.forEach(n => {
if (n.id !== candidate.id && n.alive) {
n.state = 'follower';
}
});
logEvent('LEADER', `Node N${candidate.id} (${candidate.regionName}) elected as leader (term ${currentTerm})`);
updateQuorumDisplay();
renderCluster();
}
} else {
if (partitionDelay > 0) {
logEvent('PARTITION', `Node N${node.id} (${node.regionName}) unreachable due to partition`);
} else {
logEvent('VOTE', `Node N${node.id} (${node.regionName}) rejected vote`);
}
}
}, baseDelay + latencyDelay + partitionDelay);
});
// Election timeout
setTimeout(() => {
if (electionInProgress && candidate.state === 'candidate') {
electionInProgress = false;
candidate.state = 'follower';
logEvent('TIMEOUT', `Election for term ${currentTerm} failed - no quorum reached`);
renderCluster();
}
}, ELECTION_TIMEOUT_MAX + 1000);
}
function animateVote(fromNode, toNode) {
const svg = document.getElementById('cluster-svg');
const vote = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
vote.setAttribute('cx', fromNode.x);
vote.setAttribute('cy', fromNode.y);
vote.setAttribute('r', '4');
vote.setAttribute('fill', '#00d9ff');
const duration = 500;
const startTime = performance.now();
function animate(time) {
const elapsed = time - startTime;
const progress = Math.min(elapsed / duration, 1);
const x = fromNode.x + (toNode.x - fromNode.x) * progress;
const y = fromNode.y + (toNode.y - fromNode.y) * progress;
vote.setAttribute('cx', x);
vote.setAttribute('cy', y);
vote.setAttribute('opacity', 1 - progress * 0.5);
if (progress < 1) {
requestAnimationFrame(animate);
} else {
vote.remove();
}
}
svg.appendChild(vote);
requestAnimationFrame(animate);
}
function isPartitioned(regionA, regionB) {
return partitions.some(p =>
(p.includes(regionA) && !p.includes(regionB)) ||
(!p.includes(regionA) && p.includes(regionB))
);
}
// Failure injection
function killRandomNode() {
const aliveNodes = nodes.filter(n => n.alive);
if (aliveNodes.length <= 1) {
logEvent('ERROR', 'Cannot kill last alive node');
return;
}
const target = aliveNodes[Math.floor(Math.random() * aliveNodes.length)];
killNode(target);
}
function killLeader() {
if (!currentLeader || !currentLeader.alive) {
logEvent('ERROR', 'No alive leader to kill');
return;
}
killNode(currentLeader);
// Trigger automatic election after brief delay
setTimeout(() => {
if (!nodes.some(n => n.state === 'leader' && n.alive)) {
logEvent('AUTO', 'Triggering automatic election after leader failure');
startElection();
}
}, 1000);
}
function killNode(node) {
node.alive = false;
node.state = 'dead';
if (node.id === currentLeader?.id) {
currentLeader = null;
}
logEvent('FAILURE', `Node N${node.id} (${node.regionName}) killed`);
updateMajorityThreshold();
renderCluster();
}
function partitionRegion() {
if (partitions.length >= 2) {
logEvent('ERROR', 'Maximum partitions reached');
return;
}
const regionIdx = Math.floor(Math.random() * REGIONS.length);
const region = REGIONS[regionIdx];
partitions.push([region.id]);
logEvent('PARTITION', `Network partition: ${region.name} isolated`);
renderCluster();
}
function injectLatency() {
const targetNodes = nodes.filter(n => n.alive);
const count = Math.ceil(targetNodes.length / 3);
for (let i = 0; i < count; i++) {
const target = targetNodes[Math.floor(Math.random() * targetNodes.length)];
target.latency = Math.floor(100 + Math.random() * 400);
logEvent('LATENCY', `Node N${target.id} (${target.regionName}) latency: +${target.latency}ms`);
}
latencyInjected = true;
renderCluster();
}
function healAll() {
nodes.forEach(node => {
node.alive = true;
node.latency = 0;
if (node.state === 'dead') {
node.state = 'follower';
}
});
partitions = [];
latencyInjected = false;
logEvent('HEAL', 'All failures healed');
updateMajorityThreshold();
renderCluster();
}
// Checkpointing and rollback
function createCheckpoint() {
const checkpoint = {
id: checkpoints.length,
timestamp: new Date().toLocaleTimeString(),
nodes: JSON.parse(JSON.stringify(nodes)),
currentLeader: currentLeader ? currentLeader.id : null,
currentTerm: currentTerm,
partitions: [...partitions]
};
checkpoints.push(checkpoint);
logEvent('CHECKPOINT', `Checkpoint #${checkpoint.id} created`);
renderCheckpoints();
}
function rollback(checkpointId) {
const checkpoint = checkpoints.find(c => c.id === checkpointId);
if (!checkpoint) return;
nodes = JSON.parse(JSON.stringify(checkpoint.nodes));
currentLeader = checkpoint.currentLeader !== null ?
nodes.find(n => n.id === checkpoint.currentLeader) : null;
currentTerm = checkpoint.currentTerm;
partitions = [...checkpoint.partitions];
electionInProgress = false;
votes = {};
document.getElementById('current-term').textContent = currentTerm;
logEvent('ROLLBACK', `Rolled back to checkpoint #${checkpointId}`);
updateMajorityThreshold();
updateQuorumDisplay();
renderCluster();
}
function renderCheckpoints() {
const container = document.getElementById('checkpoint-list');
if (checkpoints.length === 0) {
container.innerHTML = '<div class="text-xs text-center py-4" style="color: var(--muted);">No checkpoints yet</div>';
return;
}
container.innerHTML = checkpoints.map(cp => `
<button onclick="rollback(${cp.id})"
class="btn w-full p-2 rounded-lg text-left group"
style="background: var(--bg-card); border: 1px solid var(--border);">
<div class="flex items-center justify-between">
<span class="mono text-xs font-semibold" style="color: var(--accent);">CP #${cp.id}</span>
<span class="mono text-xs" style="color: var(--muted);">${cp.timestamp}</span>
</div>
<div class="text-xs mt-1" style="color: var(--muted);">
Term ${cp.currentTerm} · Leader: ${cp.currentLeader !== null ? 'N' + cp.currentLeader : 'None'}
</div>
</button>
`).join('');
}
// Node selection
function selectNode(node) {
selectedNode = node;
document.getElementById('selected-node-info').innerHTML = `
<div class="space-y-2">
<div class="flex items-center justify-between">
<span class="font-semibold" style="color: var(--fg);">Node N${node.id}</span>
<span class="text-xs px-2 py-0.5 rounded" style="background: ${getNodeColor(node)}22; color: ${getNodeColor(node)};">
${node.state.toUpperCase()}
</span>
</div>
<div class="text-xs space-y-1" style="color: var(--muted);">
<div>Region: ${node.regionName}</div>
<div>Term: ${node.term}</div>
<div>Status: ${node.alive ? 'Alive' : 'Dead'}</div>
${node.latency > 0 ? `<div>Latency: +${node.latency}ms</div>` : ''}
</div>
</div>
`;
document.getElementById('node-actions').classList.remove('hidden');
document.getElementById('btn-toggle-node').textContent = node.alive ? 'Kill Node' : 'Revive Node';
document.getElementById('btn-toggle-node').style.borderColor = node.alive ?
'rgba(248, 81, 73, 0.5)' : 'rgba(63, 185, 80, 0.5)';
renderCluster();
}
function toggleSelectedNode() {
if (!selectedNode) return;
if (selectedNode.alive) {
killNode(selectedNode);
if (selectedNode.id === currentLeader?.id) {
setTimeout(() => {
if (!nodes.some(n => n.state === 'leader' && n.alive)) {
startElection();
}
}, 1000);
}
} else {
selectedNode.alive = true;
selectedNode.state = 'follower';
logEvent('HEAL', `Node N${selectedNode.id} (${selectedNode.regionName}) revived`);
updateMajorityThreshold();
}
renderCluster();
selectNode(selectedNode);
}
// Utility functions
function updateQuorumDisplay() {
const voteCount = Object.keys(votes).length;
const majority = Math.floor(nodes.filter(n => n.alive).length / 2) + 1;
const percentage = Math.min((voteCount / majority) * 100, 100);
document.getElementById('quorum-count').textContent = `${voteCount} / ${majority} votes`;
document.getElementById('quorum-bar').style.width = `${percentage}%`;
if (voteCount >= majority) {
document.getElementById('quorum-bar').style.background =
'linear-gradient(90deg, #3fb950, #00ffaa)';
} else {
document.getElementById('quorum-bar').style.background =
'linear-gradient(90deg, #00d9ff, #00ffaa)';
}
}
function updateSystemStatus() {
const statusEl = document.getElementById('system-status');
const ledEl = statusEl.previousElementSibling;
const aliveCount = nodes.filter(n => n.alive).length;
const hasLeader = nodes.some(n => n.state === 'leader' && n.alive);
const hasPartition = partitions.length > 0;
if (aliveCount < 5) {
statusEl.textContent = 'DEGRADED';
statusEl.style.color = '#f85149';
ledEl.style.background = '#f85149';
} else if (!hasLeader || hasPartition) {
statusEl.textContent = 'WARNING';
statusEl.style.color = '#d29922';
ledEl.style.background = '#d29922';
} else {
statusEl.textContent = 'SYSTEM NOMINAL';
statusEl.style.color = '#3fb950';
ledEl.style.background = '#3fb950';
}
}
function logEvent(type, message) {
const log = document.getElementById('event-log');
const timestamp = new Date().toLocaleTimeString();
const colors = {
'INIT': '#7d8590',
'BOOT': '#7d8590',
'ELECTION': '#00d9ff',
'VOTE': '#00ffaa',
'LEADER': '#3fb950',
'FAILURE': '#f85149',
'PARTITION': '#d29922',
'LATENCY': '#d29922',
'HEAL': '#3fb950',
'CHECKPOINT': '#a371f7',
'ROLLBACK': '#a371f7',
'TIMEOUT': '#f85149',
'ERROR': '#f85149',
'AUTO': '#d29922'
};
const entry = document.createElement('div');
entry.className = 'log-entry py-1';
entry.innerHTML = `<span style="color: #7d8590;">[${timestamp}]</span> <span style="color: ${colors[type] || '#7d8590'};">[${type}]</span> ${message}`;
log.appendChild(entry);
log.scrollTop = log.scrollHeight;
}
function clearLog() {
const log = document.getElementById('event-log');
log.innerHTML = '<div class="log-entry py-1">[BOOT] Log cleared</div>';
}
function resetCluster() {
checkpoints = [];
partitions = [];
latencyInjected = false;
votes = {};
electionInProgress = false;
currentTerm = 1;
document.getElementById('current-term').textContent = currentTerm;
document.getElementById('checkpoint-list').innerHTML =
'<div class="text-xs text-center py-4" style="color: var(--muted);">No checkpoints yet</div>';
initCluster();
logEvent('RESET', 'Cluster reset to initial state');
}
// Initialize
initCluster();
// Auto-create initial checkpoint
setTimeout(() => createCheckpoint(), 500);
</script>
</body>
</html>