-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaft-Protocol-Simulation.html
More file actions
828 lines (703 loc) · 33.6 KB
/
Raft-Protocol-Simulation.html
File metadata and controls
828 lines (703 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Raft Protocol Visualization</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
</head>
<body class="bg-gray-900 text-gray-100 flex flex-col items-center justify-center min-h-screen p-4">
<div class="w-full max-w-7xl mx-auto flex flex-col lg:flex-row gap-4">
<!-- Main Visualization Area -->
<div class="lg:w-2/3 w-full bg-gray-800 rounded-2xl shadow-2xl p-4 relative raft-vis-height" id="visualization-area">
<!-- Nodes and messages will be dynamically added here -->
</div>
<!-- Control and Information Panel -->
<div class="lg:w-1/3 w-full flex flex-col gap-4 lg:h-[600px]">
<div class="bg-gray-800 rounded-2xl shadow-2xl p-6">
<h1 class="text-2xl font-bold text-white mb-4">Raft Visualization</h1>
<div class="grid grid-cols-2 gap-2">
<button id="play-btn" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-lg transition">Play</button>
<button id="pause-btn" class="w-full bg-red-600 hover:bg-red-700 text-white font-semibold py-2 px-4 rounded-lg transition">Pause</button>
<button id="step-btn" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-semibold py-2 px-4 rounded-lg transition">Step</button>
<button id="reset-btn" class="w-full bg-gray-600 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition">Reset</button>
</div>
<div class="mt-4">
<button id="client-request-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-semibold py-2 px-4 rounded-lg transition">Client Request</button>
</div>
<div class="mt-4">
<label for="speed-slider" class="block mb-2 text-sm font-medium text-gray-300">Simulation Speed</label>
<input id="speed-slider" type="range" min="1" max="10" value="5" class="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer">
</div>
<div class="mt-4 text-center text-sm text-gray-400">
Click a node to toggle its status (Up/Down).
</div>
</div>
<div class="bg-gray-800 rounded-2xl shadow-2xl p-4 flex flex-col flex-grow overflow-hidden">
<h2 class="text-lg font-semibold text-white mb-2 shrink-0">Event Log</h2>
<div id="event-log" class="text-sm text-gray-400 space-y-1 h-full overflow-y-auto pr-2">
<!-- Log messages will appear here -->
</div>
</div>
</div>
</div>
<!-- Step Explanation -->
<div id="explanation-container" class="w-full max-w-7xl mx-auto mt-4 bg-gray-800 rounded-2xl shadow-2xl p-4 flex flex-col transition-all duration-300 ease-in-out explanation-height">
<div id="explanation-header" class="flex justify-between items-center cursor-pointer shrink-0">
<h2 class="text-lg font-semibold text-white">Step Explanation</h2>
<svg id="explanation-toggle-icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-6 h-6 text-white transition-transform duration-300">
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
</svg>
</div>
<div id="explanation-box" class="text-gray-300 prose prose-invert prose-sm overflow-y-auto pr-2 mt-2">
<p id="explanation-placeholder">Click "Play" to start the simulation or "Step" to walk through it event by event.</p>
</div>
</div>
<!-- Node Details Section -->
<div id="nodes-details-container" class="w-full max-w-7xl mx-auto mt-4 bg-gray-800 rounded-2xl shadow-2xl p-4 transition-opacity duration-300">
<h2 class="text-lg font-semibold text-white mb-3">Node States</h2>
<div id="nodes-details" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
<!-- Node details will be rendered here -->
</div>
</div>
<script>
// --- CONFIGURATION ---
const NUM_NODES = 5;
const ELECTION_TIMEOUT_MIN = 2500;
const ELECTION_TIMEOUT_MAX = 4000;
const HEARTBEAT_INTERVAL = 500;
const MESSAGE_SPEED_FACTOR = 0.002; // Controls animation speed
// --- GEMINI API CALLER ---
async function callGemini(prompt) {
const apiKey = ""; // Canvas will provide this
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`;
const payload = {
contents: [{ parts: [{ text: prompt }] }],
};
// Exponential backoff for retries
let response;
let delay = 1000;
for (let i = 0; i < 5; i++) {
try {
response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
const result = await response.json();
const text = result.candidates?.[0]?.content?.parts?.[0]?.text;
if (text) {
return text;
} else {
throw new Error("Invalid response structure from Gemini API");
}
} else if (response.status === 429) { // Throttling
console.warn(`Gemini API request throttled. Retrying in ${delay}ms...`);
await new Promise(res => setTimeout(res, delay));
delay *= 2;
} else {
throw new Error(`Gemini API request failed with status ${response.status}`);
}
} catch (error) {
console.error("Error calling Gemini API:", error);
if (i === 4) return "Sorry, I couldn't get a detailed explanation at this time.";
await new Promise(res => setTimeout(res, delay));
delay *= 2;
}
}
return "Sorry, I couldn't get a detailed explanation after several retries.";
}
// --- RAFT NODE LOGIC ---
class RaftNode {
constructor(id, cluster) {
this.id = id;
this.cluster = cluster;
// Persistent state
this.term = 0;
this.votedFor = null;
this.log = [{ term: 0, value: null }]; // Dummy entry at index 0
// Volatile state
this.state = 'follower';
this.commitIndex = 0;
this.lastApplied = 0;
// Leader-specific state
this.nextIndex = {};
this.matchIndex = {};
// Volatile state
this.votesReceived = 0;
this.isDown = false;
this.electionTimeoutEnd = 0;
this.resetElectionTimeout();
}
reset() {
this.term = 0;
this.votedFor = null;
this.log = [{ term: 0, value: null }];
this.state = 'follower';
this.commitIndex = 0;
this.lastApplied = 0;
this.votesReceived = 0;
this.isDown = false;
this.resetElectionTimeout();
}
resetElectionTimeout() {
if (this.electionTimeout) clearTimeout(this.electionTimeout);
const timeoutDuration = ELECTION_TIMEOUT_MIN + Math.random() * (ELECTION_TIMEOUT_MAX - ELECTION_TIMEOUT_MIN);
this.electionTimeoutEnd = Date.now() + (timeoutDuration / this.cluster.speed);
// Only set a real timer if the simulation is running
if (!this.cluster.isPaused) {
this.electionTimeout = setTimeout(() => {
if (!this.isDown) this.startElection();
}, timeoutDuration / this.cluster.speed);
}
}
startElection() {
if (this.isDown) return;
this.term++;
this.state = 'candidate';
this.votedFor = this.id;
this.votesReceived = 1;
this.cluster.leaderId = null;
this.cluster.logEvent(`Node ${this.id} starting election for term ${this.term}.`);
this.cluster.renderer.updateExplanation(`
<p><strong>Node ${this.id} became a candidate.</strong></p>
<ul>
<li>Its election timer expired, so it's starting a new election.</li>
<li>It incremented its term to <strong>${this.term}</strong>.</li>
<li>It voted for itself and is now requesting votes from other nodes.</li>
</ul>
`);
this.resetElectionTimeout();
this.cluster.renderer.render();
this.cluster.nodes.forEach(node => {
if (node.id !== this.id && !node.isDown) {
this.cluster.renderer.renderMessage(this.id, node.id, 'vote-request', () => {
node.handleVoteRequest({
term: this.term,
candidateId: this.id,
lastLogIndex: this.log.length - 1,
lastLogTerm: this.log[this.log.length - 1].term
});
});
}
});
}
handleVoteRequest(request) {
if (this.isDown) return;
let grantVote = false;
if (request.term > this.term) {
this.becomeFollower(request.term);
}
const myLastLogTerm = this.log[this.log.length - 1].term;
const myLastLogIndex = this.log.length - 1;
const candidateLogIsUpToDate = request.lastLogTerm > myLastLogTerm || (request.lastLogTerm === myLastLogTerm && request.lastLogIndex >= myLastLogIndex);
if (request.term === this.term && (this.votedFor === null || this.votedFor === request.candidateId) && candidateLogIsUpToDate) {
grantVote = true;
this.votedFor = request.candidateId;
this.resetElectionTimeout();
}
this.cluster.logEvent(`Node ${this.id} responding to vote request from ${request.candidateId} in term ${request.term}. Vote granted: ${grantVote}.`);
this.cluster.renderer.renderMessage(this.id, request.candidateId, 'vote-response', () => {
this.cluster.nodes[request.candidateId].handleVoteResponse({
term: this.term,
voterId: this.id,
voteGranted: grantVote
});
});
}
handleVoteResponse(response) {
if (this.isDown || this.state !== 'candidate' || response.term < this.term) {
return;
}
if (response.term > this.term) {
this.becomeFollower(response.term);
return;
}
if (response.voteGranted) {
this.votesReceived++;
this.cluster.logEvent(`Node ${this.id} received a vote. Total votes: ${this.votesReceived}.`);
if (this.votesReceived > Math.floor(this.cluster.nodes.length / 2)) {
this.becomeLeader();
}
}
}
becomeLeader() {
if (this.state !== 'candidate' || this.isDown) return;
this.state = 'leader';
this.cluster.leaderId = this.id;
this.cluster.logEvent(`Node ${this.id} is now the leader for term ${this.term}!`);
this.cluster.renderer.updateExplanation(`
<p><strong>Node ${this.id} became the leader!</strong></p>
<ul>
<li>It received votes from a majority of nodes (${this.votesReceived} votes).</li>
<li>It will now send periodic heartbeats to all followers to assert its authority and prevent new elections.</li>
</ul>
`);
this.cluster.nodes.forEach(node => {
this.nextIndex[node.id] = this.log.length;
this.matchIndex[node.id] = 0;
});
this.sendHeartbeats();
this.cluster.renderer.render();
}
sendHeartbeats() {
if (this.state !== 'leader' || this.isDown) return;
this.cluster.nodes.forEach(node => {
if (node.id !== this.id && !node.isDown) {
this.sendAppendEntries(node.id);
}
});
if (!this.cluster.isPaused) {
this.heartbeatTimeout = setTimeout(() => this.sendHeartbeats(), HEARTBEAT_INTERVAL / this.cluster.speed);
}
}
sendAppendEntries(followerId) {
if (this.state !== 'leader' || this.isDown) return;
const prevLogIndex = this.nextIndex[followerId] - 1;
const prevLogTerm = this.log[prevLogIndex].term;
const entries = this.log.slice(this.nextIndex[followerId]);
this.cluster.renderer.renderMessage(this.id, followerId, 'append-request', () => {
this.cluster.nodes[followerId].handleAppendEntries({
term: this.term,
leaderId: this.id,
prevLogIndex,
prevLogTerm,
entries,
leaderCommit: this.commitIndex
});
});
}
handleAppendEntries(request) {
if (this.isDown) return;
let success = false;
if (request.term > this.term) {
this.becomeFollower(request.term);
}
if (request.term === this.term) {
this.state = 'follower';
this.cluster.leaderId = request.leaderId;
this.resetElectionTimeout();
const logIsConsistent = this.log.length > request.prevLogIndex && this.log[request.prevLogIndex].term === request.prevLogTerm;
if (logIsConsistent) {
success = true;
// Delete conflicting entries and append new ones
this.log.splice(request.prevLogIndex + 1);
this.log.push(...request.entries);
if (request.leaderCommit > this.commitIndex) {
this.commitIndex = Math.min(request.leaderCommit, this.log.length - 1);
}
}
}
this.cluster.renderer.renderMessage(this.id, request.leaderId, 'append-response', () => {
this.cluster.nodes[request.leaderId].handleAppendEntriesResponse({
followerId: this.id,
term: this.term,
success: success,
lastLogIndex: this.log.length - 1
});
});
}
handleAppendEntriesResponse(response) {
if (this.state !== 'leader' || this.isDown || response.term < this.term) {
return;
}
if (response.term > this.term) {
this.becomeFollower(response.term);
return;
}
if (response.success) {
this.nextIndex[response.followerId] = response.lastLogIndex + 1;
this.matchIndex[response.followerId] = response.lastLogIndex;
this.updateCommitIndex();
} else {
// Decrement nextIndex and retry
this.nextIndex[response.followerId] = Math.max(1, this.nextIndex[response.followerId] - 1);
}
}
updateCommitIndex() {
if (this.state !== 'leader') return;
for (let N = this.log.length - 1; N > this.commitIndex; N--) {
if (this.log[N].term === this.term) {
let matchCount = 1;
this.cluster.nodes.forEach(node => {
if (node.id !== this.id && this.matchIndex[node.id] >= N) {
matchCount++;
}
});
if (matchCount > Math.floor(this.cluster.nodes.length / 2)) {
this.commitIndex = N;
this.cluster.logEvent(`Leader ${this.id} updated commit index to ${this.commitIndex}.`);
this.cluster.renderer.updateExplanation(`
<p><strong>Leader ${this.id} committed index ${this.commitIndex}.</strong></p>
<ul>
<li>A majority of nodes have replicated the log up to this index.</li>
<li>The command can now be considered safely stored.</li>
<li>The new commit index will be sent to followers on the next heartbeat.</li>
</ul>
`);
break;
}
}
}
}
becomeFollower(newTerm) {
this.state = 'follower';
this.term = newTerm;
this.votedFor = null;
this.cluster.leaderId = null;
this.resetElectionTimeout();
this.cluster.logEvent(`Node ${this.id} became a follower in term ${newTerm}.`);
}
toggleStatus() {
this.isDown = !this.isDown;
if (this.isDown) {
if (this.electionTimeout) clearTimeout(this.electionTimeout);
if (this.heartbeatTimeout) clearTimeout(this.heartbeatTimeout);
this.state = 'down';
this.cluster.logEvent(`Node ${this.id} is now DOWN.`);
if(this.id === this.cluster.leaderId) {
this.cluster.leaderId = null;
}
} else {
this.state = 'follower';
this.resetElectionTimeout();
this.cluster.logEvent(`Node ${this.id} is now UP.`);
}
this.cluster.renderer.render();
}
}
// --- CLUSTER MANAGEMENT ---
class RaftCluster {
constructor(numNodes, renderer) {
this.numNodes = numNodes;
this.renderer = renderer;
this.nodes = [];
this.leaderId = null;
this.isPaused = true;
this.speed = 5;
this.clientRequestCounter = 0;
for (let i = 0; i < numNodes; i++) {
this.nodes.push(new RaftNode(i, this));
}
this.mainLoopInterval = null;
}
reset() {
this.pause();
this.nodes = [];
this.leaderId = null;
this.clientRequestCounter = 0;
this.isPaused = true;
for (let i = 0; i < this.numNodes; i++) {
this.nodes.push(new RaftNode(i, this));
}
this.renderer.logArea.innerHTML = '';
this.renderer.explanationBox.innerHTML = '<p id="explanation-placeholder">Click "Play" to start the simulation or "Step" to walk through it event by event.</p>';
this.logEvent("Simulation reset to initial state.");
this.renderer.initialize();
}
play() {
if (!this.isPaused) return;
this.isPaused = false;
this.logEvent("Simulation started.");
// Restart election timers and heartbeats for all nodes
this.nodes.forEach(node => {
if (!node.isDown) {
if (node.state === 'leader') {
node.sendHeartbeats();
} else {
node.resetElectionTimeout();
}
}
});
this.renderer.render();
}
pause() {
if (this.isPaused) return;
this.isPaused = true;
// Stop all timers
this.nodes.forEach(node => {
if (node.electionTimeout) clearTimeout(node.electionTimeout);
if (node.heartbeatTimeout) clearTimeout(node.heartbeatTimeout);
});
this.logEvent("Simulation paused.");
}
step() {
// Stop the simulation without logging "paused"
this.isPaused = true;
this.nodes.forEach(node => {
if (node.electionTimeout) clearTimeout(node.electionTimeout);
if (node.heartbeatTimeout) clearTimeout(node.heartbeatTimeout);
});
this.renderer.addStepSeparator();
if (this.leaderId !== null && this.nodes[this.leaderId] && !this.nodes[this.leaderId].isDown) {
// If there's a leader, a "step" means the leader sends heartbeats.
const leader = this.nodes[this.leaderId];
this.renderer.updateExplanation(`
<p><strong>Leader ${leader.id} is sending heartbeats.</strong></p>
<ul>
<li>These are AppendEntries RPCs sent to all followers to assert authority.</li>
<li>Heartbeats reset follower election timers, preventing new elections.</li>
<li>They also serve to replicate any new log entries to the followers.</li>
</ul>
`);
leader.sendHeartbeats();
} else {
// No leader. A "step" means the first election timeout fires.
let earliestNode = null;
let earliestTime = Infinity;
this.nodes.forEach(node => {
if (!node.isDown && (node.state === 'follower' || node.state === 'candidate')) {
if (node.electionTimeoutEnd < earliestTime) {
earliestTime = node.electionTimeoutEnd;
earliestNode = node;
}
}
});
if (earliestNode) {
this.logEvent(`Stepping: Node ${earliestNode.id}'s timer is next to expire.`);
earliestNode.startElection();
} else {
this.logEvent("Stepping: No active nodes to start an election.");
}
}
this.renderer.render();
}
setSpeed(speed) {
this.speed = speed;
if (!this.isPaused) {
this.pause();
this.play();
}
}
clientRequest() {
if (this.leaderId === null || this.nodes[this.leaderId].isDown) {
this.logEvent("Client request failed: No leader available.");
return;
}
this.clientRequestCounter++;
const leader = this.nodes[this.leaderId];
const newValue = `CMD ${this.clientRequestCounter}`;
leader.log.push({ term: leader.term, value: newValue });
this.logEvent(`Client request '${newValue}' sent to leader ${leader.id}.`);
this.renderer.updateExplanation(`
<p><strong>Client sent a request to Leader ${leader.id}.</strong></p>
<ul>
<li>The leader adds the new command '${newValue}' to its own log.</li>
<li>This new entry will be replicated to followers via the next AppendEntries (heartbeat) RPCs.</li>
</ul>
`);
// Replicate immediately
leader.sendHeartbeats();
this.renderer.render();
}
logEvent(message) {
this.renderer.logEvent(message);
}
}
// --- RENDERING ---
class Renderer {
constructor(cluster, visArea, logArea, detailsArea, explanationBox) {
this.cluster = cluster;
this.visArea = visArea;
this.logArea = logArea;
this.detailsArea = detailsArea;
this.explanationBox = explanationBox;
this.nodePositions = [];
}
initialize() {
this.visArea.innerHTML = '';
this.detailsArea.innerHTML = '';
this.nodePositions = [];
const width = this.visArea.offsetWidth;
const height = this.visArea.offsetHeight;
const centerX = width / 2;
const centerY = height / 2;
const radius = Math.min(width, height) / 2 * 0.75;
for (let i = 0; i < this.cluster.nodes.length; i++) {
const node = this.cluster.nodes[i];
const angle = (i / this.cluster.nodes.length) * 2 * Math.PI - (Math.PI / 2);
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
this.nodePositions[i] = { x, y };
const nodeEl = document.createElement('div');
nodeEl.className = 'node absolute flex flex-col items-center justify-center w-16 h-16 rounded-full border-4 font-semibold text-white shadow-lg';
nodeEl.style.left = `${x - 32}px`;
nodeEl.style.top = `${y - 32}px`;
nodeEl.innerHTML = `<span>ID: ${i}</span><span>T: 0</span>`;
nodeEl.addEventListener('click', (e) => {
e.stopPropagation();
node.toggleStatus();
});
this.visArea.appendChild(nodeEl);
const detailCard = document.createElement('div');
detailCard.className = 'bg-gray-700 p-3 rounded-lg text-sm';
this.detailsArea.appendChild(detailCard);
}
this.render();
}
render() {
this.cluster.nodes.forEach((node, i) => {
const nodeEl = this.visArea.children[i];
nodeEl.className = `node absolute flex flex-col items-center justify-center w-16 h-16 rounded-full border-4 font-semibold text-white shadow-lg ${node.state}`;
nodeEl.children[0].textContent = `ID: ${node.id}`;
nodeEl.children[1].textContent = `T: ${node.term}`;
// Update details card
const detailCard = this.detailsArea.children[i];
const logHTML = [...node.log].reverse().map((entry, revIdx) => {
const idx = node.log.length - 1 - revIdx;
return `<div class="log-entry ${idx > 0 && idx <= node.commitIndex ? 'committed' : ''} p-1.5 my-1 rounded-md bg-gray-600 text-gray-200">
<span class="font-mono text-gray-400 mr-2">${idx}:</span> <span class="font-semibold">T${entry.term}:</span> ${entry.value || 'nil'}
</div>`
}).join('');
detailCard.innerHTML = `
<div class="font-bold mb-2 text-lg flex justify-between items-center text-white">
<span>Node ${node.id}</span>
<span class="px-2 py-1 rounded-full text-xs font-semibold uppercase ${node.state}">${node.state}</span>
</div>
<div class="space-y-1 text-gray-300">
<div><strong>Term:</strong> <span class="font-mono float-right">${node.term}</span></div>
<div><strong>Voted For:</strong> <span class="font-mono float-right">${node.votedFor === null ? 'null' : node.votedFor}</span></div>
<div><strong>Commit Index:</strong> <span class="font-mono float-right">${node.commitIndex}</span></div>
</div>
<div class="font-semibold mt-3 mb-1 text-white">Log:</div>
<div class="max-h-32 overflow-y-auto bg-gray-800 p-2 rounded-md">${logHTML}</div>
`;
});
}
renderMessage(fromId, toId, type, onComplete) {
const fromPos = this.nodePositions[fromId];
const toPos = this.nodePositions[toId];
const messageEl = document.createElement('div');
messageEl.className = `message ${type}`;
messageEl.textContent = type.split('-')[0].charAt(0).toUpperCase(); // V, A
this.visArea.appendChild(messageEl);
const duration = Math.hypot(toPos.x - fromPos.x, toPos.y - fromPos.y) * MESSAGE_SPEED_FACTOR * this.cluster.speed;
messageEl.style.left = `${fromPos.x - 10}px`;
messageEl.style.top = `${fromPos.y - 10}px`;
messageEl.style.transitionDuration = `${duration}s`;
requestAnimationFrame(() => {
messageEl.style.transform = `translate(${toPos.x - fromPos.x}px, ${toPos.y - fromPos.y}px)`;
messageEl.style.opacity = '1';
});
setTimeout(() => {
messageEl.style.opacity = '0';
setTimeout(() => {
if(this.visArea.contains(messageEl)) {
this.visArea.removeChild(messageEl);
}
}, 500);
onComplete();
}, duration * 1000);
}
logEvent(message) {
if (this.logArea.children.length > 100) {
this.logArea.removeChild(this.logArea.firstChild);
}
const logEntry = document.createElement('div');
logEntry.textContent = message;
this.logArea.appendChild(logEntry);
this.logArea.scrollTop = this.logArea.scrollHeight;
}
updateExplanation(html) {
const placeholder = document.getElementById('explanation-placeholder');
if (placeholder) {
placeholder.remove();
}
const entryContainer = document.createElement('div');
entryContainer.className = 'py-2 explanation-entry';
const basicExplanation = document.createElement('div');
basicExplanation.innerHTML = html;
entryContainer.appendChild(basicExplanation);
const geminiButton = document.createElement('button');
geminiButton.className = 'gemini-btn mt-2 bg-purple-600 hover:bg-purple-700 text-white font-semibold py-1 px-3 rounded-lg text-sm transition flex items-center';
geminiButton.innerHTML = '✨ Explain This Step in Detail';
entryContainer.appendChild(geminiButton);
const geminiResponseContainer = document.createElement('div');
geminiResponseContainer.className = 'gemini-response mt-2 text-purple-200 border-l-2 border-purple-400 pl-3 prose prose-sm prose-invert';
entryContainer.appendChild(geminiResponseContainer);
geminiButton.addEventListener('click', async () => {
geminiButton.disabled = true;
geminiButton.innerHTML = `
<svg class="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Generating...
`;
const systemPrompt = `You are an expert on distributed systems and the Raft consensus algorithm. The user is interacting with a visual simulator. You will be given a brief, programmatic explanation of an event that just occurred in the simulation. Your task is to provide a more detailed, conceptual explanation that helps the user understand the significance of this event within the Raft protocol. Keep your explanation concise (2-4 sentences) and easy to understand for someone learning the protocol.`;
const plainTextExplanation = basicExplanation.innerText || basicExplanation.textContent;
const userQuery = `Here is the event that just happened: "${plainTextExplanation}". Please provide a detailed explanation.`;
const fullPrompt = `${systemPrompt}\n\n${userQuery}`;
const detailedExplanation = await callGemini(fullPrompt);
geminiResponseContainer.innerHTML = detailedExplanation.replace(/\n/g, '<br>');
geminiButton.remove();
});
this.explanationBox.prepend(entryContainer);
this.explanationBox.scrollTop = 0; // Scroll to the top to show the newest entry
}
addStepSeparator() {
// Don't add a separator if the placeholder is still visible (i.e., it's the first step)
if (document.getElementById('explanation-placeholder')) {
return;
}
const separator = document.createElement('hr');
separator.className = 'border-t-2 border-red-500 my-2';
this.explanationBox.prepend(separator);
}
clearExplanation() {
// We no longer clear the box, as we want to keep a running log of explanations.
// This function is now intentionally left blank.
}
}
// --- INITIALIZATION ---
document.addEventListener('DOMContentLoaded', () => {
const visArea = document.getElementById('visualization-area');
const logArea = document.getElementById('event-log');
const detailsArea = document.getElementById('nodes-details');
const explanationBox = document.getElementById('explanation-box');
const cluster = new RaftCluster(NUM_NODES, null);
const renderer = new Renderer(cluster, visArea, logArea, detailsArea, explanationBox);
cluster.renderer = renderer;
renderer.initialize();
// Event Listeners
document.getElementById('play-btn').addEventListener('click', () => cluster.play());
document.getElementById('pause-btn').addEventListener('click', () => cluster.pause());
document.getElementById('step-btn').addEventListener('click', () => cluster.step());
document.getElementById('reset-btn').addEventListener('click', () => cluster.reset());
document.getElementById('client-request-btn').addEventListener('click', () => cluster.clientRequest());
document.getElementById('speed-slider').addEventListener('input', (e) => cluster.setSpeed(e.target.value));
// New listener for explanation box expand/collapse
const explanationContainer = document.getElementById('explanation-container');
const explanationHeader = document.getElementById('explanation-header');
const explanationToggleIcon = document.getElementById('explanation-toggle-icon');
const nodesDetailsContainer = document.getElementById('nodes-details-container');
explanationHeader.addEventListener('click', () => {
const isExpanded = explanationContainer.classList.toggle('expanded');
if (isExpanded) {
// Expanded state: grow explanation box, hide node states
explanationContainer.style.height = '420px';
explanationToggleIcon.style.transform = 'rotate(180deg)';
nodesDetailsContainer.style.opacity = '0';
setTimeout(() => {
// Hide after fade-out transition
nodesDetailsContainer.style.display = 'none';
}, 300);
} else {
// Collapsed state: shrink explanation box, show node states
explanationContainer.style.height = '150px';
explanationToggleIcon.style.transform = 'rotate(0deg)';
nodesDetailsContainer.style.display = 'block';
// Use requestAnimationFrame to ensure display is set before starting fade-in
requestAnimationFrame(() => {
nodesDetailsContainer.style.opacity = '1';
});
}
});
window.addEventListener('resize', () => renderer.initialize());
});
</script>
</body>
</html>