The user wants to "Build a partition rebalancing rehearsal harness: synthetic load, hotspot detection, and auto-mitigation."
Interpretation: This is a complex request that seems to be about a distributed system partition rebalancing. A "rehearsal harness" suggests a tool or framework for simulating and testing partition rebalancing strategies. It involves synthetic load generation, hotspot detection, and automatic mitigation mechanisms. Possibly, this is for a distributed database or distributed storage system where partitions (shards) need to be rebalanced to ensure even load distribution. The harness would generate synthetic load to stress the system, detect which partitions are hotspots (overloaded), and then automatically mitigate by moving data or rebalancing.
Given the role: I am a FUI design expert from 2077, focusing on cyberpunk/hard sci-fi interfaces. So I need to design a UI for this partition rebalancing rehearsal harness. It should be an interface that displays the synthetic load, hotspot detection, and auto-mitigation controls/visualizations. The UI must be intricate, dark mode, neon, monospace, etc. I need to produce a UI design, presumably in HTML/CSS/JS (or a simulation). The user didn't specify a format; I should produce something plausible: code for a web page that implements a FUI for this system. I should use Tailwind CSS, Canvas API for dynamic charts, and maybe some 3D wireframe visualizations to represent the distributed system topology.
The task: Build a partition rebalancing rehearsal harness: synthetic load, hotspot detection, and auto-mitigation.
I should produce an interactive demo with:
- A dashboard showing the current state of partitions (maybe as a grid or network graph).
- Controls to adjust synthetic load parameters (e.g., load intensity, pattern).
- A section showing hotspot detection results (e.g., highlighting overloaded partitions).
- Buttons to trigger auto-mitigation (or automatic).
- Real-time updates using animations.
I'll create a single HTML file with embedded JavaScript (using Tailwind via CDN, maybe also three.js for wireframe if needed, but for simplicity maybe just Canvas for charts). I will simulate a simple partitioning system: say we have a ring of partitions (like consistent hashing) or a grid of nodes. We'll generate synthetic load using random or patterned functions, detect hotspots by thresholding load metrics, and then simulate rebalancing by moving load from hot to cold partitions.
The UI should look like a cyberpunk HUD with heavy use of lines, borders, blinking cursors, and monospace fonts. Use colors: cyan, magenta, amber, against dark background.
I need to ensure the code is self-contained and can be run.
Approach:
-
Use a full-screen layout with header and main content.
-
Main content: left panel for controls and metrics, center for visualization of partitions (e.g., a canvas drawing nodes in a ring, connections, load represented as color/size).
-
Right panel for logs, hotspot list.
-
Synthetic load controls: sliders for base load, spike probability, etc. Start/stop buttons.
-
Hotspot detection: threshold value, detection algorithm (maybe simple average + standard deviation or top N). Show list of hotspots.
-
Auto-mitigation: toggle to enable auto-rebalance, also manual "Rebalance Now" button. Show rebalancing progress.
-
Real-time animations: load values updating, transition animations when rebalancing.
-
Tech: HTML + Tailwind CSS (via CDN). Use vanilla JS for logic and Canvas for drawing. I can simulate three.js but maybe not needed; simple 2D canvas is enough, but to match "wireframe 3D", I could draw a simple rotating wireframe cube representing the "system" but that's not essential. I'll focus on the partition display as a network graph: nodes as circles with borders, lines connecting them. Use requestAnimationFrame.
-
FUI details: add scanning lines, glitch effects on text, corner brackets, tick marks, hexagonal patterns.
-
I need to make it functional: the synthetic load generates random fluctuations; hotspots are detected when load exceeds threshold; auto-mitigation gradually reduces load on hot nodes by transferring to cold ones.
I'll design the data model:
- Partition nodes: each has id, load (0-100), maybe capacity, status.
- Load update: each cycle, load changes by adding random delta, with some spikes.
- Hotspot detection: if load > threshold (e.g., 80) mark as hotspot.
- Rebalancing: if auto-mitigation on, for each hotspot, find a target cold node (load < some lower threshold) and transfer a portion of load (e.g., 10% per cycle) until balanced.
Visualization: Draw nodes on canvas in a circular layout, ordered by id. Each node represented by a circle with inner fill color based on load (green->yellow->red). Hotspots maybe have a pulsing ring. Lines between nodes to indicate connectivity (maybe just ring edges). Also show load value text next to node (or tooltip).
Alternatively, use a grid: nodes placed in a matrix. But ring is more typical for partition rings.
I'll include a "load history" chart using a line chart drawn on canvas, showing aggregate load over time.
I'll also add "decoding" text effects for stats.
I need to ensure the UI looks like a 2077 FUI. So I'll use Tailwind classes to style with borders, dark backgrounds, and neon colors. I'll add some custom CSS for scanning lines and glitch animations.
Let's plan the structure:
HTML:
<div class="grid grid-cols-12 gap-4">
<!-- Left Control Panel -->
<div class="col-span-3 bg-panel p-4 border-neon rounded-sm">
<h2 class="text-xl neon-cyan border-b border-neon pb-1 mb-3">SYNTHETIC LOAD</h2>
<div class="space-y-4">
<div>
<label class="block text-sm mb-1">Base Load Intensity</label>
<input type="range" id="base-load" min="0" max="100" value="30" class="w-full accent-cyan-500">
<div class="flex justify-between text-xs text-gray-400">
<span>LOW</span>
<span id="base-load-val">30</span>
<span>HIGH</span>
</div>
</div>
<div>
<label class="block text-sm mb-1">Spike Probability</label>
<input type="range" id="spike-prob" min="0" max="100" value="10" class="w-full accent-cyan-500">
<div class="flex justify-between text-xs text-gray-400">
<span>0%</span>
<span id="spike-prob-val">10%</span>
<span>100%</span>
</div>
</div>
<div>
<label class="block text-sm mb-1">Hotspot Threshold</label>
<input type="range" id="threshold" min="50" max="100" value="80" class="w-full accent-magenta-500">
<div class="flex justify-between text-xs text-gray-400">
<span>50</span>
<span id="threshold-val">80</span>
<span>100</span>
</div>
</div>
</div>
<div class="mt-6 border-t border-neon pt-4">
<h2 class="text-xl neon-magenta border-b border-neon pb-1 mb-3">AUTO-MITIGATION</h2>
<div class="flex items-center mb-4">
<button id="auto-toggle" class="px-4 py-2 bg-gray-900 border border-neon rounded hover:bg-gray-800 transition">ENABLE AUTO</button>
<span id="auto-status" class="ml-2 text-sm">OFF</span>
</div>
<div class="space-y-2">
<button id="rebalance-btn" class="w-full px-4 py-2 bg-gray-900 border border-cyan-500 text-cyan-500 rounded hover:bg-cyan-900 transition mt-2">FORCE REBALANCE</button>
</div>
</div>
<div class="mt-6 border-t border-neon pt-4">
<h2 class="text-xl neon-amber border-b border-neon pb-1 mb-3">SYSTEM METRICS</h2>
<div class="space-y-2 text-sm">
<div>Total Load: <span id="total-load" class="neon-cyan">0</span></div>
<div>Avg Load: <span id="avg-load" class="neon-cyan">0</span></div>
<div>Hotspots: <span id="hotspot-count" class="neon-magenta">0</span></div>
<div>Rebalance Rate: <span id="rebalance-rate" class="neon-amber">0</span> %</div>
</div>
</div>
</div>
<!-- Center Visualization -->
<div class="col-span-6 relative">
<div class="bg-panel h-full border-neon rounded-sm relative overflow-hidden">
<canvas id="topology-canvas" class="absolute inset-0 w-full h-full"></canvas>
<!-- Overlay grid lines -->
<div class="absolute inset-0 pointer-events-none" style="background: linear-gradient(rgba(0,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,255,255,0.03) 1px, transparent 1px); background-size: 40px 40px;"></div>
</div>
</div>
<!-- Right Panel: Hotspot List and Logs -->
<div class="col-span-3 flex flex-col space-y-4">
<div class="bg-panel p-4 border-neon rounded-sm flex-1">
<h2 class="text-xl neon-magenta border-b border-neon pb-1 mb-3">HOTSPOT DETECTION</h2>
<div id="hotspot-list" class="space-y-2 text-sm max-h-64 overflow-y-auto"></div>
</div>
<div class="bg-panel p-4 border-neon rounded-sm h-64">
<h2 class="text-xl neon-amber border-b border-neon pb-1 mb-3">EVENT LOG</h2>
<div id="event-log" class="space-y-1 text-xs font-mono overflow-y-auto h-48"></div>
</div>
</div>
</div>
Now, I need to write the JavaScript. I'll define:
-
Config: number of partitions (nodes) = 32 (to be somewhat realistic).
-
State: array of nodes: { id, load, normalizedLoad (0-100), isHotspot, isRebalancing? }
-
Synthetic load update: each tick (maybe every 100ms or so), update load according to base load + random fluctuations. Spike: with probability, add a large random load to a random node.
-
Hotspot detection: check if load > threshold (percentage of capacity). Mark node as hotspot if above.
-
Auto-mitigation: if auto enabled, for each hotspot, find cold nodes (load significantly below average) and transfer a portion (e.g., 5% of hotspot load per tick) to the cold node. Or balance towards average.
-
Visualization: draw a circle (topology ring). Nodes placed around circle. Draw lines connecting them forming a ring. Also maybe draw arcs to represent load. Node color: green->yellow->red gradient based on load. Hotspot nodes have an additional pulsing outer ring. Also display node id and load numeric (small). Use requestAnimationFrame to animate.
-
Additional charts: maybe draw a small line chart at bottom of left panel? Or integrate within canvas. I'll keep it simple: canvas draws the ring and also maybe a small load history graph in the background or overlay? The center canvas can be used solely for topology.
-
Logs: append messages with timestamps.
-
Metrics update.
-
Glitch effects on numbers: occasional random character replacement? Might be complex. I can skip but can add simple text scrambling effect when values change significantly.
I'll implement a "decoding" effect for numbers: when updating, replace digits with random characters for a few frames before settling. But might be heavy. I could just have the numbers update with a neon flicker.
Given time, I'll implement a simpler approach: just update numbers normally but with CSS transition for color changes.
Implementation steps:
-
Set up constants: NUM_NODES = 32.
-
Initialize nodes: id 0..31, load = 0 initially.
-
Set up canvas: get context, compute radius (half of min(width,height) minus padding). Place nodes evenly on circle.
-
Animation loop: clear canvas, draw connections (ring edges). For each node: compute angle = 2*Math.PI * i / N + offset (for rotation maybe slowly rotate). Draw node: circle with fill based on load (interpolate color). Draw border. If hotspot, draw additional rotating dashed ring or pulsing effect. Also draw id and load text (use monospace). Use fillText.
-
Update logic:
- baseLoad = parseInt(document.getElementById('base-load').value)
- spikeProb = parseInt(...)/100
- threshold = parseInt(...)
- each tick (setInterval or using requestAnimationFrame with delta time), for each node:
// Normal load variation: +/- 5% per tick?
let delta = (Math.random() - 0.5) * 10; // variation
node.load = Math.max(0, Math.min(100, node.load + delta));
// Add base load? Actually baseLoad should be the average target? I can interpret as: baseLoad is the average load we aim to simulate; we can add baseLoad/10 per tick? Or we can set initial load to baseLoad and then vary around it.
// Instead, we can simulate new load increments per tick based on requests. We'll treat load as a metric from 0 to 100 (percentage of capacity). Each node receives request load that adds to its current load (with decay). Simpler: load moves towards a random target.
// Better: Synthetic load: each node's desired load level changes randomly, but overall average is baseLoad. We'll assign each node a target load that changes every few seconds.
But I want to show dynamic changes.
Let's do: node.load = node.load + (Math.random() - 0.5) * 5; // fluctuate
Then also occasionally add spikes: if Math.random() < spikeProb, pick a node and add 20-50 load.
Additionally, we can have a constant small addition from baseLoad, like node.load += baseLoad / 100? That would increase indefinitely. We need to keep load within 0-100 and also have some decay to simulate processing. Actually load represents current utilization; if we only add, it will max out. We should include natural decay (processing) to bring load down over time. So each tick, each node decays a bit (e.g., subtract 1). Then add fluctuations and spikes. That yields a dynamic around some average if baseLoad influences the addition rate.
Let's define:
- decay rate: 0.5 per tick
- base load addition: baseLoad / 50 per tick (so if baseLoad=30, add 0.6 per tick)
So average load = (baseAdd/decay) = (baseLoad/50)/0.5 = baseLoad/25? That seems off. Let's compute: steady state: load = baseAdd/decay. We want steady state ~ baseLoad%? Actually baseLoad is intensity 0-100 meaning average load percentage. So set decay = 1 per tick (so average load = baseAdd/1 = baseAdd). So baseAdd = baseLoad ? But load per tick addition should be a number, not percentage. Let's define load as 0-100. Each tick, we subtract decay (e.g., 0.2) and add baseAdd which is baseLoad * factor. Simpler: treat load as moving towards a random target with smoothing. Actually easier: use perlin noise? Too heavy.
Implementation details:
-
Use requestAnimationFrame for animation loop, update physics at a fixed timestep (e.g., 30Hz) separate from rendering.
-
For text rendering on canvas: set font to '16px "Courier New"', fillStyle based on load. Use ctx.fillText.
-
For smooth animations: nodes may have pulsing effect for hotspots; we can use a sine wave based on time to draw an outer ring with expanding radius or dashed line rotating.
-
I'll also add a "scan line" effect on the canvas: maybe draw a horizontal line moving down.
-
The canvas should be responsive: on resize, recalc dimensions and node positions.
Now I'll write the code.
Let's structure:
<script>
const NUM_NODES = 32;
const NODE_RADIUS = 8;
const COLORS = {
bg: '#050505',
cyan: '#00ffff',
magenta: '#ff00ff',
amber: '#ffb000',
green: '#00ff00',
yellow: '#ffff00',
red: '#ff0000',
};
class Node {
constructor(id) {
this.id = id;
this.load = 0; // current load 0-100
this.target = 0;
this.hotspot = false;
this.rebalancing = false; // currently being rebalanced (visual indicator)
this.cooling = false;
}
}
const nodes = [];
for (let i=0; i<NUM_NODES; i++) nodes.push(new Node(i));
let state = {
baseLoad: 30,
spikeProb: 0.1,
threshold: 80,
autoMitigation: false,
lastUpdate: 0,
time: 0
};
// target update timer
let targetUpdateCounter = 0;
// Canvas setup
const canvas = document.getElementById('topology-canvas');
const ctx = canvas.getContext('2d');
let width, height, centerX, centerY, radius;
function resize() {
const parent = canvas.parentElement;
canvas.width = parent.clientWidth;
canvas.height = parent.clientHeight;
width = canvas.width;
height = canvas.height;
centerX = width/2;
centerY = height/2;
radius = Math.min(width, height)/2 - 40;
}
window.addEventListener('resize', resize);
resize();
// Draw function
function draw() {
// Semi-transparent clear for trail effect? Maybe just clear.
ctx.fillStyle = COLORS.bg;
ctx.fillRect(0,0,width,height);
// Draw grid? Already done via CSS.
// Draw ring connections
ctx.beginPath();
ctx.strokeStyle = 'rgba(0,255,255,0.1)';
ctx.lineWidth = 1;
for (let i=0; i<NUM_NODES; i++) {
const angle = (i/NUM_NODES)*Math.PI*2 - Math.PI/2; // start at top
const x = centerX + Math.cos(angle)*radius;
const y = centerY + Math.sin(angle)*radius;
if (i===0) ctx.moveTo(x,y);
else ctx.lineTo(x,y);
}
ctx.closePath();
ctx.stroke();
// Draw nodes
const timeSec = state.time/1000;
for (let i=0; i<NUM_NODES; i++) {
const node = nodes[i];
const angle = (i/NUM_NODES)*Math.PI*2 - Math.PI/2;
const x = centerX + Math.cos(angle)*radius;
const y = centerY + Math.sin(angle)*radius;
// Determine fill color based on load
let fillColor;
if (node.load < 50) {
// green to yellow: load 0->50 map to green(0,255,0) to yellow(255,255,0)
const c = Math.floor(node.load/50*255);
fillColor = `rgb(255, ${255-c}, 0)`; // Actually interpolation: r = 0->255, g=255->255? Wait: green (0,255,0) to yellow (255,255,0) -> increase red.
fillColor = `rgb(${c}, 255, 0)`;
} else if (node.load < 80) {
// yellow to orange? Actually use amber: yellow (255,255,0) to red (255,0,0) between 50-100? But we want 50-80 maybe to amber.
const c = Math.floor((node.load-50)/30*255);
fillColor = `rgb(255, ${255-c}, 0)`;
} else {
// red to magenta? Or just red
fillColor = `rgb(255, 0, ${Math.floor((node.load-80)/20*255)})`; // red to magenta
}
// For simplicity, use gradient: 0-50 green->yellow, 50-100 yellow->red.
// Let's implement:
let r, g, b;
if (node.load < 50) {
r = Math.floor(node.load * 255 / 50);
g = 255;
b = 0;
} else if (node.load < 100) {
r = 255;
g = Math.floor(255 - (node.load-50)*255/50);
b = 0;
} else {
r = 255; g = 0; b = 255;
}
fillColor = `rgb(${r},${g},${b})`;
// Draw node circle
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS, 0, Math.PI*2);
ctx.fillStyle = fillColor;
ctx.fill();
ctx.strokeStyle = COLORS.cyan;
ctx.lineWidth = 2;
ctx.stroke();
// Draw ID and load text (small) inside or below?
ctx.fillStyle = '#fff';
ctx.font = '10px Courier New';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(node.id, x, y-12);
ctx.fillText(Math.round(node.load)+'%', x, y+12);
// Hotspot indicator: pulsing ring
if (node.hotspot) {
const pulse = 1 + 0.3 * Math.sin(timeSec * 5);
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS * pulse, 0, Math.PI*2);
ctx.strokeStyle = COLORS.magenta;
ctx.lineWidth = 2;
ctx.setLineDash([5,3]);
ctx.stroke();
ctx.setLineDash([]);
}
// Rebalancing indicator: moving arc to target?
if (node.rebalancing) {
// draw a arc from node outward
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS+5, 0, Math.PI*2);
ctx.strokeStyle = COLORS.amber;
ctx.lineWidth = 3;
ctx.stroke();
}
}
// Draw scanning line
const scanY = (timeSec * 50) % height;
ctx.strokeStyle = 'rgba(0,255,255,0.2)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, scanY);
ctx.lineTo(width, scanY);
ctx.stroke();
// Increment time
state.time += 16; // approximate
}
// Update function for simulation logic
let lastSimTime = 0;
const simInterval = 50; // ms between simulation steps
function updateSim(timestamp) {
if (timestamp - lastSimTime < simInterval) {
requestAnimationFrame(updateSim);
return;
}
lastSimTime = timestamp;
// Update base load, etc. from UI
state.baseLoad = parseInt(document.getElementById('base-load').value);
state.spikeProb = parseInt(document.getElementById('spike-prob').value) / 100;
state.threshold = parseInt(document.getElementById('threshold').value);
// Update target loads periodically
targetUpdateCounter++;
if (targetUpdateCounter > 30) { // every ~1.5 seconds (30*50ms=1500ms)
targetUpdateCounter = 0;
nodes.forEach(node => {
// New target: baseLoad ± random variation
node.target = state.baseLoad + (Math.random() - 0.5) * 30;
node.target = Math.max(0, Math.min(100, node.target));
});
}
// Update loads towards target
nodes.forEach(node => {
// Decay/integration: move 5% of the difference per step
const diff = node.target - node.load;
node.load += diff * 0.1;
// Add spikes
if (Math.random() < state.spikeProb) {
const spikeAmount = Math.random() * 30 + 10;
node.load += spikeAmount;
}
// Clamp
node.load = Math.max(0, Math.min(100, node.load));
});
// Determine hotspots
nodes.forEach(node => {
node.hotspot = node.load > state.threshold;
});
// Auto-mitigation
if (state.autoMitigation) {
rebalance();
}
// Update metrics
updateMetrics();
}
function rebalance() {
// Rebalance hotspots to cold nodes
const hotspots = nodes.filter(n => n.hotspot);
const coldNodes = nodes.filter(n => n.load < state.threshold - 20); // significant gap
if (hotspots.length === 0 || coldNodes.length === 0) return;
// For each hotspot, pick a random cold node and transfer up to 10% of hotspot load or until below threshold.
hotspots.forEach(h => {
const amount = Math.min(10, (h.load - state.threshold) * 0.5, 50); // limit
if (amount <= 0) return;
// Find cold node with lowest load?
const target = coldNodes.reduce((min, n) => n.load < min.load ? n : min);
if (target.load + amount > state.threshold) return; // avoid overshoot
h.load -= amount;
target.load += amount;
h.rebalancing = true;
target.rebalancing = true;
// Log
log(`Transferred ${amount.toFixed(1)}% from Node ${h.id} to Node ${target.id}`);
});
// Reset rebalancing flags after a short time (maybe next frame they'll be set again if still hot/cold)
// For simplicity, we clear after each rebalance call; but we want visual indication maybe for a few frames. We'll leave as is, next frame they might still be hot/cold, so flag remains. That's fine.
}
function updateMetrics() {
const totalLoad = nodes.reduce((sum, n) => sum + n.load, 0);
const avgLoad = totalLoad / NUM_NODES;
const hotspotCount = nodes.filter(n => n.hotspot).length;
// Rebalance rate: compute total transferred? We'll approximate as hotspot load above threshold / total load?
const excess = nodes.filter(n => n.hotspot).reduce((sum, n) => sum + (n.load - state.threshold), 0);
const rebalanceRate = totalLoad > 0 ? (excess / totalLoad * 100) : 0;
document.getElementById('total-load').textContent = totalLoad.toFixed(1);
document.getElementById('avg-load').textContent = avgLoad.toFixed(1);
document.getElementById('hotspot-count').textContent = hotspotCount;
document.getElementById('rebalance-rate').textContent = rebalanceRate.toFixed(1);
}
function log(msg) {
const logDiv = document.getElementById('event-log');
const time = new Date().toLocaleTimeString('en-US', { hour12: false });
const line = document.createElement('div');
line.className = 'text-cyan-400';
line.textContent = `[${time}] ${msg}`;
logDiv.appendChild(line);
logDiv.scrollTop = logDiv.scrollHeight;
// Limit entries
while (logDiv.children.length > 50) logDiv.removeChild(logDiv.firstChild);
}
function updateHotspotList() {
const listDiv = document.getElementById('hotspot-list');
listDiv.innerHTML = '';
nodes.filter(n => n.hotspot).sort((a,b) => b.load - a.load).forEach(node => {
const item = document.createElement('div');
item.className = 'flex justify-between items-center bg-gray-800 p-2 rounded';
item.innerHTML = `
<span class="text-magenta">Node ${node.id}</span>
<span class="text-amber">${node.load.toFixed(1)}%</span>
`;
listDiv.appendChild(item);
});
if (nodes.filter(n=>n.hotspot).length===0) {
listDiv.innerHTML = '<div class="text-gray-500">No hotspots</div>';
}
}
// UI control handlers
document.getElementById('base-load').addEventListener('input', e => {
document.getElementById('base-load-val').textContent = e.target.value;
});
document.getElementById('spike-prob').addEventListener('input', e => {
document.getElementById('spike-prob-val').textContent = e.target.value + '%';
});
document.getElementById('threshold').addEventListener('input', e => {
document.getElementById('threshold-val').textContent = e.target.value;
});
document.getElementById('auto-toggle').addEventListener('click', e => {
state.autoMitigation = !state.autoMitigation;
const btn = e.target;
const statusSpan = document.getElementById('auto-status');
if (state.autoMitigation) {
btn.textContent = 'DISABLE AUTO';
btn.classList.add('bg-red-900', 'border-red-500');
statusSpan.textContent = 'ON';
statusSpan.className = 'ml-2 text-sm neon-magenta';
log('Auto-mitigation ENABLED');
} else {
btn.textContent = 'ENABLE AUTO';
btn.classList.remove('bg-red-900', 'border-red-500');
statusSpan.textContent = 'OFF';
statusSpan.className = 'ml-2 text-sm text-gray-500';
log('Auto-mitigation DISABLED');
}
});
document.getElementById('rebalance-btn').addEventListener('click', () => {
rebalance();
log('Manual rebalance triggered');
});
// Update hotspot list periodically
setInterval(updateHotspotList, 1000);
// Time update
setInterval(() => {
const now = new Date();
document.getElementById('sys-time').textContent = now.toTimeString().split(' ')[0];
}, 1000);
// Animation loop
function animate(timestamp) {
updateSim(timestamp);
draw();
requestAnimationFrame(animate);
}
animate(0);
// Initial log
log('System initialized. Synthetic load active.');
</script>
I need to incorporate the color interpolation correctly. I previously wrote fallback but better to compute properly:
function getLoadColor(load) {
// 0-100
if (load < 50) {
// green (0,255,0) to yellow (255,255,0)
const t = load/50;
const r = Math.floor(255t);
const g = 255;
const b = 0;
return rgb(${r},${g},${b});
} else if (load < 100) {
// yellow to red (255,0,0)
const t = (load-50)/50;
const r = 255;
const g = Math.floor(255(1-t));
const b = 0;
return rgb(${r},${g},${b});
} else {
// red to magenta? Actually at 100 just red. Could add magenta for >100 but not.
return rgb(255,0,0);
}
}
But above we used 50-100 to go to red, but earlier we had 80 threshold for hotspot, still red up to 100. That's fine.
Now about the glitch and other FUI: I added a glitch effect on the title via CSS. Also the scanlines. I also added a grid overlay via CSS.
I should also add some more decorative elements: corners, tick marks, maybe a rotating wireframe around the canvas? Could add a circular rotating ring with ticks. But maybe enough.
Also I should add a "decoding" effect for the node numbers? Not necessary.
I'll also add a "bracket" corner decoration around the main panels. Use Tailwind border utilities to create corner brackets: For example, add pseudo-elements with absolute positioning and lines. Could also use Tailwind's border classes on specific corners. There's a known trick: use before:content-[''] before:absolute before:top-0 before:left-0 before:w-4 before:h-4 before:border-t-2 before:border-l-2 before:border-cyan-500 etc. But I'll keep it simple: add a div with class "absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-cyan-500" for each corner of the main container. But the container is full screen with padding? Might be messy. I'll skip for now to ensure functionality.
Nevertheless, I will add some corner brackets to the center canvas panel to enhance FUI. Use CSS after/before.
Let me add a wrapper for canvas with pseudo corners:
<div class="col-span-6 relative">
<div class="absolute inset-0 border-2 border-cyan-500 pointer-events-none opacity-20"></div>
<div class="absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-8 h-8 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-8 h-8 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-8 h-8 border-b-2 border-r-2 border-cyan-500"></div>
<div class="bg-panel h-full border-neon rounded-sm relative overflow-hidden">
<canvas id="topology-canvas" class="absolute inset-0 w-full h-full"></canvas>
<div class="absolute inset-0 pointer-events-none" style="background: linear-gradient(rgba(0,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,255,255,0.03) 1px, transparent 1px); background-size: 40px 40px;"></div>
</div>
</div>
Similarly for panels? Might be okay.
I'll also add blinking cursors in some input ranges? Not needed.
Make sure the sliders have accent colors; Tailwind uses accent color utilities but they might not be standard. I can add custom CSS for range input:
input[type=range] { -webkit-appearance: none; background: transparent; }
input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; height: 16px; width: 16px; border-radius: 50%; background: #0ff; margin-top: -6px; cursor: pointer; box-shadow: 0 0 5px #0ff; }
input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 4px; background: #333; border-radius: 2px; }
I'll add that to style.
Now, I need to ensure that the simulation runs properly and the visuals are as desired.
Potential issues: The simulation update runs on requestAnimationFrame but with a fixed timestep. I used a separate lastSimTime. That is fine.
But in draw(), we need to rotate the ring slowly for effect. I'll add a global rotation offset based on time: const rot = state.time * 0.0005; and use when computing node angle: angle = (i/NUM_NODES)*Math.PI*2 - Math.PI/2 + rot;.
So the ring rotates slowly. Good.
Also the scanning line: I used scanY = (timeSec * 50) % height. That's a fast moving line. Could also have it scan from top to bottom repeatedly.
Now about the rebalancing: I set node.rebalancing flag when transferring. But these flags persist because we never clear them if node stops being rebalanced. Should clear them after some time or at beginning of each update. Since we set it again each time we rebalance, if a node is hot and we rebalance, we set flag every tick? Actually we call rebalance() only when autoMitigation true (each simulation step) or manually. In auto, we call rebalance() each simulation step (every 50ms). That might be too frequent; it will smooth the transfer quickly. That's okay. But we should clear flags before rebalancing to avoid all nodes appearing rebalanced continuously. I can clear all node.rebalancing = false at start of rebalance, then set for those involved. That way they show only during the tick they were transferred. But that might be too brief. Maybe set for a few ticks? Could use a timer. Simpler: clear before and set; then the visual will show as long as they remain hot and get rebalanced each tick, they'll have the indicator every frame? Actually if we clear and then set again each tick, they will be set every frame, so they'll appear constantly while hot and auto on. That's okay. But if we want a pulsating effect, that's separate.
I'll keep as: at start of rebalance, clear all node.rebalancing = false; then for each transfer, set node.rebalancing = true; That's fine.
But if manual rebalance, called once, it will set for that tick only, then next draw they may be cleared because we haven't cleared? Actually if we set, but we don't clear until next rebalance. So after manual, the node will have rebalancing true forever? We need to clear periodically. So maybe do: in updateSim before rebalance, set all node.rebalancing = false; then after rebalance set true for those involved. That will reset each simulation step. That is fine.
So modify updateSim or rebalance to clear flag before.
I'll do: in rebalance function, first set all nodes.rebalancing = false; then do transfers, setting true for nodes involved.
Now the hotspot list: we sorts by load descending.
Now need to handle slider values updating display.
I'll also add some initial log and metrics.
Now I need to make sure the HTML includes all necessary styles and scripts. I will embed the JavaScript inside the HTML.
Let's produce final code.
But before finalizing, I need to ensure that the UI adheres to the "FUI" style: use Tailwind classes to create panels with dark background, cyan borders, monospace fonts. I already have some classes: bg-panel, border-neon etc. I defined those in style. Also need to import a monospace font that looks techy; I used Courier New. Could use "Consolas" or "Roboto Mono" but that's okay.
Also the colors: I used neon-cyan, neon-magenta, neon-amber via CSS classes. I'll add those classes to appropriate text.
Now to enhance the FUI look, I could add "corner brackets" to panels using Tailwind's empty divs with borders. I'll do that for each panel: left control panel, right panels, and center. I'll create a component-like approach: for each .bg-panel container, add corner divs.
I'll add these inside each panel's div.
For left control panel:
<div class="col-span-3 bg-panel p-4 border-neon rounded-sm relative">
<!-- Corners -->
<div class="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-cyan-500"></div>
...
</div>
Same for others.
But need to ensure they don't overlap content. Padding already inside, and corners absolute with small size, okay.
I'll add to all three panels.
Also for the canvas panel, I already added corners.
Now about the scanning lines: I added .scanlines with a fixed pattern; it's a full-screen overlay with pointer-events none. Good.
Also the glitch effect on title: I defined CSS keyframes and applied .glitch with data-text. Should work.
Now about the range sliders: I'll style them as neon.
Add custom CSS for range inputs:
input[type=range] {
-webkit-appearance: none;
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 16px;
width: 16px;
border-radius: 50%;
background: #00ffff;
margin-top: -6px;
cursor: pointer;
box-shadow: 0 0 5px #00ffff;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: #333;
border-radius: 2px;
}
input[type=range]:focus {
outline: none;
}
I'll add that in .
Now for load history chart: maybe I'll add a small canvas at bottom of left panel to show total load over time. But maybe it's extra; the user asked for synthetic load, hotspot detection, auto-mitigation. A dashboard showing metrics and visualization is enough. But to enhance, I could add a mini line chart. I think it's okay.
Now I'll write the final HTML file.
Let's also ensure the canvas drawing uses requestAnimationFrame for smooth animation.
I need to adjust the node drawing: use the getLoadColor function.
I'll implement the rotation: const rotationOffset = state.time * 0.0005; and angle = (i/NUM_NODES)2Math.PI - Math.PI/2 + rotationOffset.
Also add a dashed outer ring representing the ring of nodes, maybe rotating? Could draw a circle with tick marks around the perimeter to enhance FUI.
I'll add a function drawHUDoverlay(ctx, time) that draws some decorative circles, tick marks, maybe a rotating radar-like ring.
I'll do:
- Draw a large circle (static) with tick marks at each node position? Or just many ticks.
- Draw a rotating ring with dashes.
To keep it not too messy, I'll draw a faint circle with tick marks every 5 degrees? That may be heavy. Maybe draw a circle with 32 tick marks at each node position.
I'll draw a circle with radius+20, with small tick marks at each node angle.
So in draw, after drawing connections, draw a decorative ring:
ctx.beginPath();
ctx.arc(centerX, centerY, radius + 20, 0, Math.PI*2);
ctx.strokeStyle = 'rgba(0,255,255,0.1)';
ctx.lineWidth = 1;
ctx.stroke();
// Draw tick marks at each node angle
for (let i=0; i<NUM_NODES; i++) {
const angle = (i/NUM_NODES)*Math.PI*2 - Math.PI/2 + rotationOffset;
const innerR = radius+15;
const outerR = radius+25;
const x1 = centerX + Math.cos(angle)*innerR;
const y1 = centerY + Math.sin(angle)*innerR;
const x2 = centerX + Math.cos(angle)*outerR;
const y2 = centerY + Math.sin(angle)*outerR;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = 'rgba(0,255,255,0.3)';
ctx.lineWidth = 2;
ctx.stroke();
}
That adds a rotating tick ring, enhancing the FUI.
Also I want the scanning line to be a horizontal line moving down, but maybe also a vertical? It's fine.
Now about the "polygonal" patterns: Could add some random hexagons in background? Not necessary.
Now consider performance: It's fine.
Now I need to test the code mentally. The simulation steps: updateSim called at ~20Hz (50ms). The draw is every frame (~60fps). The node visual should be smooth because load interpolation per step already yields smoothness. But we could add interpolation for drawing? Not needed.
Now need to handle the reference to state.threshold: when threshold changes, we use it in rebalancing condition: cold nodes defined as load < threshold - 20. That may need adaptation. Fine.
Now also ensure we update the hotspot list and logs appropriately. The hotspot list is updated every second via setInterval. That's okay.
Now for the event log: we add entries with timestamps. I used new Date().toLocaleTimeString('en-US', { hour12: false }). That gives "HH:MM:SS". Good.
Now I should include some initial messages: "System initialized", "Synthetic load generation started", etc.
Also maybe on load, kick off some initial target updates.
Now I should check that the HTML structure is valid: properly close tags.
Let's assemble final code.
But before final, I want to ensure the design meets the "high-tech" aesthetic:
-
Use Tailwind classes to style panels: bg-gray-900 vs my custom bg-panel. I used bg-panel with background rgba(0,10,20,0.85). That's dark blue, not black. That's okay.
-
The borders: border-neon which is border: 1px solid rgba(0,255,255,0.2).
-
I'll add some more borders maybe double lines? Could use border-2.
-
I'll also add a title bar gradient.
But it's fine.
Now the code.
Potential improvements: Add a "Data Transfer" progress bar for rebalancing. Not necessary.
Also the auto-mitigation toggle button: styling changes based on state. I added conditional classes.
Now the rebalance function: it transfers from each hotspot to a cold node. But it might transfer from multiple hotspots to the same cold node, overshooting threshold. I have check: if target.load + amount > state.threshold, return; So that prevents overshoot, but then that hotspot might not transfer? Actually I check per hotspot: if adding amount to target would exceed threshold, we skip that transfer. But there may be other cold nodes. I could select a different cold node. For simplicity, we could sort cold nodes by load and assign sequentially. But it's okay.
I'll adjust: find a cold node that can accept amount without exceeding threshold. If none, skip that hotspot. That's fine.
But currently, I set target as the cold node with lowest load. That's fine. But if that target cannot accept amount, we could try other cold nodes. I'll modify: for each hotspot, find a cold node that can accept. I'll loop through cold nodes sorted by load ascending, pick first that can accept. If none, skip.
Implementation:
function rebalance() {
// Reset flags
nodes.forEach(n => n.rebalancing = false);
const hotspots = nodes.filter(n => n.hotspot);
const coldCandidates = nodes.filter(n => n.load < state.threshold - 10).sort((a,b) => a.load - b.load);
if (hotspots.length === 0 || coldCandidates.length === 0) return;
hotspots.forEach(h => {
let amount = Math.min(10, (h.load - state.threshold) * 0.5);
if (amount <= 0) return;
// Find a cold node that can accept amount without exceeding threshold
let target = null;
for (let c of coldCandidates) {
if (c.load + amount <= state.threshold) {
target = c;
break;
}
}
if (!target) return;
h.load -= amount;
target.load += amount;
h.rebalancing = true;
target.rebalancing = true;
log(`Transfer ${amount.toFixed(1)}% from Node ${h.id} to Node ${target.id}`);
});
}
That's better.
Now we need to ensure the nodes' load stays within bounds after subtraction: h.load could go negative if amount > h.load, but we clamp amount to min of 10 and (excess0.5), but (excess0.5) could be > h.load if h.load is just above threshold? Actually if h.load=85, threshold=80, excess=5, 0.5*5=2.5, okay. If h.load=100, amount=10. That's fine. But also we ensure amount <= (h.load - threshold)*0.5 but if h.load is only slightly above threshold, amount small. Should not exceed h.load - something? It's okay.
But after subtraction, h.load might drop below threshold. That's expected, and then next tick it may not be hotspot.
Now consider numeric precision: we are using load as integer? I used toFixed and rounding. It's okay to be float.
Now I'll produce the final HTML with all CSS and JS.
One more thing: The "synthetic load" section: base load intensity affects the average load. In my simulation, target loads are set to baseLoad ± random variation. That's fine. But the spike probability also adds spikes.
Now check if the simulation runs properly: The target updates every 30 steps, each node's target is set independently. That's okay.
But one nuance: The current load moves toward target by diff * 0.1 each step. That's a typical smoothing. So the average load will approach the average target. That's fine.
Now consider the load unit: We treat as percentage of capacity, 0-100.
Now the hotspot detection threshold is a percentage.
The rebalancing moves load from hot to cold to reduce hotspots. That's good.
Now design details: The left panel sliders: need to show current values. I already added spans with IDs and update on input.
Now the center canvas: we have the ring with tick marks rotating slowly. Also the scanning line.
Now the right panels: Hotspot list will show items with background. I used bg-gray-800. That matches dark theme. Should be fine.
Now, add some more "data decoding" effects: When we update numbers (like total load) we could have them flicker. But maybe not.
Now for the "Fictional User Interface" we should include more decorative lines. I'll add a horizontal line above each section heading as part of the border. Already have border-b.
Now also add a "status bar" at bottom? Could add but not necessary.
Now ensure the overall layout is responsive? I used grid-cols-12; on smaller screens it might break but for demo it's fine.
Now final code.
I'll produce the final answer with the HTML code block.
But wait: The user said "Build a partition rebalancing rehearsal harness: synthetic load, hotspot detection, and auto-mitigation." That might be a request for a design (FUI) not just code. However, as ChatGPT I need to output code to build it, or a design specification? Usually they want me to generate code. I'll produce a complete HTML file with embedded CSS and JS that implements the requested harness with a cyberpunk UI. That should fulfill.
Now before final, I will test mentally the interaction: When page loads, nodes have load 0. Then targets set randomly around base load (30). Load will increase gradually to ~30. Spikes may cause occasional increases. Hotspot detection triggers when load > threshold (default 80). With base 30, unlikely to hit 80. So user may increase base load to see hotspots. That's fine.
The auto-mitigation toggle: initially off. User can enable. Then rebalancing will start.
The manual rebalance button: triggers one rebalance cycle.
The hotspot list updates every second, showing nodes that are hotspots.
The event log records transfers and status changes.
The canvas shows nodes rotating slowly.
All good.
Now check for missing dependencies: Tailwind CSS via CDN works. No external JS needed.
Now potential issues: The range input styling might not work on all browsers; but we have fallback.
Now I'll add a note about the UI design in comments: but not needed.
Now produce final answer.
I'll write the HTML code with all CSS and JS.
Here's a complete, self-contained implementation of a Partition Rebalancing Rehearsal Harness with a cyberpunk‑style FUI. It runs directly in the browser – just save the code as an .html file and open it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Partition Rebalancing Rehearsal Harness</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* FUI STYLING */
body {
background: #050505;
color: #0ff;
font-family: 'Courier New', Consolas, monospace;
overflow: hidden;
margin: 0;
height: 100vh;
width: 100vw;
}
.scanlines {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background:
linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%),
linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
background-size: 100% 2px, 3px 100%;
pointer-events: none;
z-index: 999;
}
.neon-cyan { color: #0ff; text-shadow: 0 0 5px #0ff; }
.neon-magenta { color: #f0f; text-shadow: 0 0 5px #f0f; }
.neon-amber { color: #ffb000; text-shadow: 0 0 5px #ffb000; }
.border-neon { border-color: rgba(0, 255, 255, 0.3); }
.bg-panel {
background: rgba(0, 10, 20, 0.85);
border: 1px solid rgba(0, 255, 255, 0.2);
}
.blink { animation: blink 1s step-end infinite; }
@keyframes blink { 50% { opacity: 0; } }
.glitch {
position: relative;
}
.glitch::before, .glitch::after {
content: attr(data-text);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.glitch::before {
left: 2px;
text-shadow: -1px 0 #ff00c1;
clip: rect(44px, 450px, 56px, 0);
animation: glitch-anim 5s infinite linear alternate-reverse;
}
.glitch::after {
left: -2px;
text-shadow: -1px 0 #00fff9;
clip: rect(44px, 450px, 56px, 0);
animation: glitch-anim2 5s infinite linear alternate-reverse;
}
@keyframes glitch-anim {
0% { clip: rect(31px, 9999px, 94px, 0); }
20% { clip: rect(62px, 9999px, 12px, 0); }
40% { clip: rect(3px, 9999px, 69px, 0); }
60% { clip: rect(91px, 9999px, 33px, 0); }
80% { clip: rect(35px, 9999px, 76px, 0); }
100% { clip: rect(58px, 9999px, 19px, 0); }
}
@keyframes glitch-anim2 {
0% { clip: rect(65px, 9999px, 99px, 0); }
20% { clip: rect(8px, 9999px, 26px, 0); }
40% { clip: rect(73px, 9999px, 14px, 0); }
60% { clip: rect(16px, 9999px, 41px, 0); }
80% { clip: rect(47px, 9999px, 85px, 0); }
100% { clip: rect(23px, 9999px, 38px, 0); }
}
/* Range slider neon styling */
input[type=range] {
-webkit-appearance: none;
width: 100%;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 16px;
width: 16px;
border-radius: 50%;
background: #0ff;
margin-top: -6px;
cursor: pointer;
box-shadow: 0 0 5px #0ff;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: #333;
border-radius: 2px;
}
input[type=range]:focus {
outline: none;
}
</style>
</head>
<body>
<div class="scanlines"></div>
<div class="container mx-auto p-4 h-full flex flex-col">
<!-- Header -->
<header class="flex justify-between items-center border-b border-neon pb-2 mb-4 flex-shrink-0">
<h1 class="text-2xl neon-cyan font-bold tracking-widest glitch" data-text="PARTITION REBALANCING REHEARSAL HARNESS">
PARTITION REBALANCING REHEARSAL HARNESS
</h1>
<div class="flex items-center space-x-4">
<span id="status" class="blink neon-amber">● STANDBY</span>
<span class="neon-magenta">SYS.TIME: <span id="sys-time">00:00:00</span></span>
</div>
</header>
<div class="grid grid-cols-12 gap-4 flex-grow">
<!-- Left Control Panel -->
<div class="col-span-3 bg-panel p-4 border-neon rounded-sm relative flex flex-col">
<!-- Corner brackets -->
<div class="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-cyan-500"></div>
<h2 class="text-xl neon-cyan border-b border-neon pb-1 mb-3">SYNTHETIC LOAD</h2>
<div class="space-y-4 flex-grow">
<div>
<label class="block text-sm mb-1">Base Load Intensity</label>
<input type="range" id="base-load" min="0" max="100" value="30">
<div class="flex justify-between text-xs text-gray-400">
<span>LOW</span>
<span id="base-load-val">30</span>
<span>HIGH</span>
</div>
</div>
<div>
<label class="block text-sm mb-1">Spike Probability</label>
<input type="range" id="spike-prob" min="0" max="100" value="10">
<div class="flex justify-between text-xs text-gray-400">
<span>0%</span>
<span id="spike-prob-val">10%</span>
<span>100%</span>
</div>
</div>
<div>
<label class="block text-sm mb-1">Hotspot Threshold</label>
<input type="range" id="threshold" min="50" max="100" value="80">
<div class="flex justify-between text-xs text-gray-400">
<span>50</span>
<span id="threshold-val">80</span>
<span>100</span>
</div>
</div>
</div>
<div class="mt-6 border-t border-neon pt-4">
<h2 class="text-xl neon-magenta border-b border-neon pb-1 mb-3">AUTO-MITIGATION</h2>
<div class="flex items-center mb-4">
<button id="auto-toggle" class="px-4 py-2 bg-gray-900 border border-neon rounded hover:bg-gray-800 transition">ENABLE AUTO</button>
<span id="auto-status" class="ml-2 text-sm text-gray-500">OFF</span>
</div>
<div class="space-y-2">
<button id="rebalance-btn" class="w-full px-4 py-2 bg-gray-900 border border-cyan-500 text-cyan-500 rounded hover:bg-cyan-900 transition mt-2">FORCE REBALANCE</button>
</div>
</div>
<div class="mt-6 border-t border-neon pt-4">
<h2 class="text-xl neon-amber border-b border-neon pb-1 mb-3">SYSTEM METRICS</h2>
<div class="space-y-2 text-sm">
<div>Total Load: <span id="total-load" class="neon-cyan">0</span></div>
<div>Avg Load: <span id="avg-load" class="neon-cyan">0</span></div>
<div>Hotspots: <span id="hotspot-count" class="neon-magenta">0</span></div>
<div>Rebalance Rate: <span id="rebalance-rate" class="neon-amber">0</span> %</div>
</div>
</div>
</div>
<!-- Center Visualization -->
<div class="col-span-6 relative">
<!-- Corner brackets -->
<div class="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-cyan-500"></div>
<div class="bg-panel h-full border-neon rounded-sm relative overflow-hidden">
<canvas id="topology-canvas" class="absolute inset-0 w-full h-full"></canvas>
<!-- Grid overlay -->
<div class="absolute inset-0 pointer-events-none" style="background: linear-gradient(rgba(0,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,255,255,0.03) 1px, transparent 1px); background-size: 40px 40px;"></div>
</div>
</div>
<!-- Right Panel: Hotspot List and Logs -->
<div class="col-span-3 flex flex-col space-y-4">
<!-- Hotspot Detection -->
<div class="bg-panel p-4 border-neon rounded-sm relative flex-1 flex flex-col">
<!-- Corner brackets -->
<div class="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-cyan-500"></div>
<h2 class="text-xl neon-magenta border-b border-neon pb-1 mb-3">HOTSPOT DETECTION</h2>
<div id="hotspot-list" class="space-y-2 text-sm max-h-64 overflow-y-auto flex-grow"></div>
</div>
<!-- Event Log -->
<div class="bg-panel p-4 border-neon rounded-sm relative h-64">
<!-- Corner brackets -->
<div class="absolute top-0 left-0 w-4 h-4 border-t-2 border-l-2 border-cyan-500"></div>
<div class="absolute top-0 right-0 w-4 h-4 border-t-2 border-r-2 border-cyan-500"></div>
<div class="absolute bottom-0 left-0 w-4 h-4 border-b-2 border-l-2 border-cyan-500"></div>
<div class="absolute bottom-0 right-0 w-4 h-4 border-b-2 border-r-2 border-cyan-500"></div>
<h2 class="text-xl neon-amber border-b border-neon pb-1 mb-3">EVENT LOG</h2>
<div id="event-log" class="space-y-1 text-xs font-mono overflow-y-auto h-48"></div>
</div>
</div>
</div>
</div>
<script>
// CONFIGURATION
const NUM_NODES = 32; // partitions
const NODE_RADIUS = 8;
const COLORS = {
bg: '#050505',
cyan: '#00ffff',
magenta: '#ff00ff',
amber: '#ffb000'
};
// STATE
const nodes = [];
for (let i = 0; i < NUM_NODES; i++) nodes.push(new Node(i));
let state = {
baseLoad: 30,
spikeProb: 0.1,
threshold: 80,
autoMitigation: false,
time: 0
};
let lastSimTime = 0;
const simInterval = 50; // ms
let targetUpdateCounter = 0;
// UI ELEMENTS
const els = {
baseLoad: document.getElementById('base-load'),
baseLoadVal: document.getElementById('base-load-val'),
spikeProb: document.getElementById('spike-prob'),
spikeProbVal: document.getElementById('spike-prob-val'),
threshold: document.getElementById('threshold'),
thresholdVal: document.getElementById('threshold-val'),
autoToggle: document.getElementById('auto-toggle'),
autoStatus: document.getElementById('auto-status'),
rebalanceBtn: document.getElementById('rebalance-btn'),
totalLoad: document.getElementById('total-load'),
avgLoad: document.getElementById('avg-load'),
hotspotCount: document.getElementById('hotspot-count'),
rebalanceRate: document.getElementById('rebalance-rate'),
sysTime: document.getElementById('sys-time'),
hotspotList: document.getElementById('hotspot-list'),
eventLog: document.getElementById('event-log')
};
// NODE CLASS
class Node {
constructor(id) {
this.id = id;
this.load = 0; // current load 0-100
this.target = 0; // desired load
this.hotspot = false;
this.rebalancing = false;
}
}
// CANVAS SETUP
const canvas = document.getElementById('topology-canvas');
const ctx = canvas.getContext('2d');
let width, height, centerX, centerY, radius;
function resize() {
const parent = canvas.parentElement;
canvas.width = parent.clientWidth;
canvas.height = parent.clientHeight;
width = canvas.width;
height = canvas.height;
centerX = width / 2;
centerY = height / 2;
radius = Math.min(width, height) / 2 - 40;
}
window.addEventListener('resize', resize);
resize();
// HELPERS
function getLoadColor(load) {
load = Math.max(0, Math.min(100, load));
let r, g, b;
if (load < 50) {
const t = load / 50; // 0-1
r = Math.floor(255 * t);
g = 255;
b = 0;
} else if (load < 100) {
const t = (load - 50) / 50;
r = 255;
g = Math.floor(255 * (1 - t));
b = 0;
} else {
r = 255; g = 0; b = 255;
}
return `rgb(${r},${g},${b})`;
}
// DRAW FUNCTION
function draw() {
ctx.fillStyle = COLORS.bg;
ctx.fillRect(0, 0, width, height);
const timeSec = state.time / 1000;
const rotationOffset = timeSec * 0.5; // slow rotation
// Decorative outer ring with ticks
ctx.beginPath();
ctx.arc(centerX, centerY, radius + 20, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(0,255,255,0.1)';
ctx.lineWidth = 1;
ctx.stroke();
for (let i = 0; i < NUM_NODES; i++) {
const angle = (i / NUM_NODES) * Math.PI * 2 - Math.PI / 2 + rotationOffset;
const innerR = radius + 15;
const outerR = radius + 25;
const x1 = centerX + Math.cos(angle) * innerR;
const y1 = centerY + Math.sin(angle) * innerR;
const x2 = centerX + Math.cos(angle) * outerR;
const y2 = centerY + Math.sin(angle) * outerR;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = 'rgba(0,255,255,0.3)';
ctx.lineWidth = 2;
ctx.stroke();
}
// Connections between nodes (ring)
ctx.beginPath();
ctx.strokeStyle = 'rgba(0,255,255,0.2)';
ctx.lineWidth = 1;
for (let i = 0; i < NUM_NODES; i++) {
const angle = (i / NUM_NODES) * Math.PI * 2 - Math.PI / 2 + rotationOffset;
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.closePath();
ctx.stroke();
// Draw nodes
for (let i = 0; i < NUM_NODES; i++) {
const node = nodes[i];
const angle = (i / NUM_NODES) * Math.PI * 2 - Math.PI / 2 + rotationOffset;
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
// Node circle
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS, 0, Math.PI * 2);
ctx.fillStyle = getLoadColor(node.load);
ctx.fill();
ctx.strokeStyle = COLORS.cyan;
ctx.lineWidth = 2;
ctx.stroke();
// Node ID and load text
ctx.fillStyle = '#ffffff';
ctx.font = '10px "Courier New"';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(node.id, x, y - 12);
ctx.fillText(Math.round(node.load) + '%', x, y + 12);
// Hotspot indicator: pulsing dashed ring
if (node.hotspot) {
const pulse = 1 + 0.3 * Math.sin(timeSec * 5);
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS * pulse, 0, Math.PI * 2);
ctx.strokeStyle = COLORS.magenta;
ctx.lineWidth = 2;
ctx.setLineDash([5, 3]);
ctx.stroke();
ctx.setLineDash([]);
}
// Rebalancing indicator: solid amber ring slightly larger
if (node.rebalancing) {
ctx.beginPath();
ctx.arc(x, y, NODE_RADIUS + 4, 0, Math.PI * 2);
ctx.strokeStyle = COLORS.amber;
ctx.lineWidth = 3;
ctx.stroke();
}
}
// Scanning line
const scanY = (timeSec * 100) % height;
ctx.strokeStyle = 'rgba(0,255,255,0.2)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, scanY);
ctx.lineTo(width, scanY);
ctx.stroke();
}
// SIMULATION UPDATE
function updateSim(timestamp) {
if (timestamp - lastSimTime < simInterval) {
requestAnimationFrame(updateSim);
return;
}
lastSimTime = timestamp;
// Pull values from UI
state.baseLoad = parseInt(els.baseLoad.value);
state.spikeProb = parseInt(els.spikeProb.value) / 100;
state.threshold = parseInt(els.threshold.value);
// Update targets periodically
targetUpdateCounter++;
if (targetUpdateCounter > 30) {
targetUpdateCounter = 0;
nodes.forEach(node => {
// New target with variation centered on baseLoad
let t = state.baseLoad + (Math.random() - 0.5) * 30;
node.target = Math.max(0, Math.min(100, t));
});
}
// Move current loads towards targets
nodes.forEach(node => {
const diff = node.target - node.load;
node.load += diff * 0.1; // smoothing factor
// Spike
if (Math.random() < state.spikeProb) {
node.load += Math.random() * 30 + 10;
}
node.load = Math.max(0, Math.min(100, node.load));
});
// Determine hotspots
nodes.forEach(node => {
node.hotspot = node.load > state.threshold;
});
// Auto-mitigation
if (state.autoMitigation) {
rebalance();
}
// Update UI metrics
updateMetrics();
}
// REBALANCE LOGIC
function rebalance() {
// Clear rebalancing flags (they will be set again for nodes involved this tick)
nodes.forEach(n => n.rebalancing = false);
const hotspots = nodes.filter(n => n.hotspot);
const coldCandidates = nodes
.filter(n => n.load < state.threshold - 10)
.sort((a, b) => a.load - b.load);
if (hotspots.length === 0 || coldCandidates.length === 0) return;
hotspots.forEach(h => {
const excess = h.load - state.threshold;
const amount = Math.min(10, excess * 0.5);
if (amount <= 0) return;
// Find a cold node that can accept this amount without crossing threshold
let target = null;
for (let c of coldCandidates) {
if (c.load + amount <= state.threshold) {
target = c;
break;
}
}
if (!target) return;
h.load -= amount;
target.load += amount;
h.rebalancing = true;
target.rebalancing = true;
log(`Transferred ${amount.toFixed(1)}% from Node ${h.id} to Node ${target.id}`);
});
}
// METRICS UPDATE
function updateMetrics() {
const totalLoad = nodes.reduce((sum, n) => sum + n.load, 0);
const avgLoad = totalLoad / NUM_NODES;
const hotspotCount = nodes.filter(n => n.hotspot).length;
const excess = nodes.filter(n => n.hotspot).reduce((sum, n) => sum + (n.load - state.threshold), 0);
const rebalanceRate = totalLoad > 0 ? (excess / totalLoad * 100) : 0;
els.totalLoad.textContent = totalLoad.toFixed(1);
els.avgLoad.textContent = avgLoad.toFixed(1);
els.hotspotCount.textContent = hotspotCount;
els.rebalanceRate.textContent = rebalanceRate.toFixed(1);
}
// HOTSPOT LIST UPDATE
function updateHotspotList() {
els.hotspotList.innerHTML = '';
const hotspots = nodes.filter(n => n.hotspot).sort((a, b) => b.load - a.load);
if (hotspots.length === 0) {
els.hotspotList.innerHTML = '<div class="text-gray-500">No hotspots</div>';
return;
}
hotspots.forEach(node => {
const item = document.createElement('div');
item.className = 'flex justify-between items-center bg-gray-800 p-2 rounded mb-1';
item.innerHTML = `
<span class="text-magenta">Node ${node.id}</span>
<span class="text-amber">${node.load.toFixed(1)}%</span>
`;
els.hotspotList.appendChild(item);
});
}
// EVENT LOG
function log(msg) {
const time = new Date().toLocaleTimeString('en-US', { hour12: false });
const line = document.createElement('div');
line.className = 'text-cyan-400';
line.textContent = `[${time}] ${msg}`;
els.eventLog.appendChild(line);
els.eventLog.scrollTop = els.eventLog.scrollHeight;
// Limit entries
while (els.eventLog.children.length > 50) els.eventLog.removeChild(els.eventLog.firstChild);
}
// UI EVENT HANDLERS
els.baseLoad.addEventListener('input', e => els.baseLoadVal.textContent = e.target.value);
els.spikeProb.addEventListener('input', e => els.spikeProbVal.textContent = e.target.value + '%');
els.threshold.addEventListener('input', e => els.thresholdVal.textContent = e.target.value);
els.autoToggle.addEventListener('click', () => {
state.autoMitigation = !state.autoMitigation;
if (state.autoMitigation) {
els.autoToggle.textContent = 'DISABLE AUTO';
els.autoToggle.classList.add('bg-red-900', 'border-red-500');
els.autoStatus.textContent = 'ON';
els.autoStatus.className = 'ml-2 text-sm neon-magenta';
log('Auto-mitigation ENABLED');
} else {
els.autoToggle.textContent = 'ENABLE AUTO';
els.autoToggle.classList.remove('bg-red-900', 'border-red-500');
els.autoStatus.textContent = 'OFF';
els.autoStatus.className = 'ml-2 text-sm text-gray-500';
log('Auto-mitigation DISABLED');
}
});
els.rebalanceBtn.addEventListener('click', () => {
rebalance();
log('Manual rebalance triggered');
});
// TIMERS
setInterval(() => {
const now = new Date();
els.sysTime.textContent = now.toTimeString().split(' ')[0];
}, 1000);
setInterval(updateHotspotList, 1000);
// ANIMATION LOOP
function animate(timestamp) {
updateSim(timestamp);
draw();
requestAnimationFrame(animate);
}
// INIT
log('System initialized. Synthetic load generation active.');
requestAnimationFrame(animate);
</script>
</body>
</html>