1. Analyze the Request:
* Goal: Engineer a rate limiter library.
* Features: Token buckets, leaky buckets, sliding window analytics (counter/SlidingLog or sliding window).
* Persona/Role: Natural UI/UX Artist, adhering to Biophilic Design and Wabi-Sabi.
* Constraint: The code is for the library, but the output must be an HTML file (likely a demonstration/documentation page) that embodies the design principles.
* Conflict: The user asks to "Engineer a rate limiter library." Usually, this means writing the JavaScript/Go/Python code for the algorithm. However, my system instructions define me as a frontend engineer and visual designer specialized in "Natural UI/UX." My output must be a "single, self-contained HTML page."
* Resolution: I need to build a visual demonstration and a functional implementation of a rate limiter library within this HTML page. I can't easily output a separate npm package install instruction in a single HTML file context, but I can implement the classes in JavaScript inside the <script> tag and then build a beautiful, interactive dashboard to test them.
* Design Philosophy: Organic shapes, earth tones, textures (noise, paper), slow movement, natural physics, serif fonts, high polishing.
-
Architecture of the Solution:
-
The Library (JS):
TokenBucket: Stores tokens, refills at a fixed rate.
LeakyBucket: Requests enter a queue, leak out at a fixed rate. Queue length or drop rate determines allowance.
SlidingWindowLog or SlidingWindowCounter: Actual analytics implementation to track usage over time. Typically these are "stateful" algorithms. For a library, a SlidingWindow rate limiter that tracks timestamps and calculates a moving average or count over a window is appropriate.
- I'll implement these as ES6 classes.
- I need a
consume(key, cost) method for all.
-
The UI/UX (HTML/CSS/JS):
- Layout: A "Zen Garden" style dashboard.
- Visuals:
- Background: Soft, textured paper effect (CSS noise).
- Colors: Terracotta, Sage Green, Off-white, Slate.
- Shapes: Blob SVGs, organic curves, non-rectangular containers (border-radius variations).
- Typography: Elegant Serif (e.g., Playfair Display, Lora) for headings; clean Sans for code/data (e.g., Lato or Inter).
- Interactions:
- Buttons are rounded, smooth transitions.
- Animations: Smooth fading in, floating organic blobs in the background (slow drift).
- Control Panel: Sliders for rate limits, capacity. Histogram/Chart for usage (custom SVG or Canvas, styled naturally).
- Simulate Traffic: A "burst" button or loop to send requests and see the rate limiter block/drop them, updating the visual stats.
-
Step-by-Step Implementation Plan:
- Step 1: HTML Structure. Header, Main, Controls, Visualizer, Footer.
- Step 2: CSS (Tailwind + Custom).
- Import Tailwind via CDN.
- Define custom classes for "noise" texture.
- Define organic border radius (using
rounded-[50%_40%_60%_45%] type classes).
- Set up the earth tone palette.
- Step 3: Background Animation. Use a simple Canvas or CSS animations to draw wandering "blobs" of semi-transparent color.
- Step 4: The Rate Limiter Logic.
- Write
class TokenBucket.
- Write
class LeakyBucket.
- Write
class SlidingWindow. Self-correction: A full sliding window with high precision might need sorting arrays of timestamps. For a demo, it should be efficient enough.
- Step 5: The Dashboard Logic.
- Connect sliders to limiter configs.
- "Send Request" simulation: Call
limiter.consume('test', 1). Update "Accepted" / "Rejected" counts.
- Visualize: A bar or line graph showing request rate over time (maybe a scrolling canvas).
- Step 6: Polish.
- Add shadows (soft, diffused).
- Add grain texture overlay.
- Ensure typography is readable.
- Error handling simulation (visual cues when rejected).
-
Drafting the Code (Mental or Scratchpad):
-
Colors: bg-stone-100, text-stone-800, accent-emerald-600 (but desaturated), accent-amber-700.
-
Fonts: Google Fonts: 'Cormorant Garamond' (Serif), 'DM Sans' (Sans).
-
Blob Animation:
@keyframes float {
0% { transform: translate(0, 0) rotate(0deg); }
33% { transform: translate(30px, -50px) rotate(120deg); }
66% { transform: translate(-20px, 20px) rotate(240deg); }
100% { transform: translate(0, 0) rotate(360deg); }
}
.blob { animation: float 20s infinite ease-in-out; }
-
Rate Limiter Classes:
class TokenBucket {
constructor(capacity, refillRatePerSec) {
this.capacity = capacity;
this.tokens = capacity;
this.refillRate = refillRatePerSec;
this.lastRefill = Date.now();
}
async tryConsume(cost = 1) {
// refill logic
const now = Date.now();
const delta = (now - this.lastRefill) / 1000;
this.tokens = Math.min(this.capacity, this.tokens + delta * this.refillRate);
this.lastRefill = now;
if (this.tokens >= cost) {
this.tokens -= cost;
return true;
}
return false;
}
}
-
Sliding Window: Better to use SlidingWindowLog (stores timestamps in a queue and removes old ones). It's accurate for the "analytics" part.
-
Refining the Design (Biophilic/Wabi-Sabi):
- Hard corners? No. Use
rounded-3xl or arbitrary radii like rounded-[1rem_2rem_1rem_2rem].
- Flat colors? Add gradients that look like morning light or moss.
- Grid alignment? "Rawness" - maybe slight overlaps. But readability is key for a library demo. Keep layout clean but shapes organic.
- Grain: Use a base64 tiny noise image or an SVG filter. An SVG
<filter> with <feTurbulence> is the cleanest, no external image.
-
Writing the actual code structure (incorporating into the final response):
<!DOCTYPE html>
<head>: Tailwind CDN, Google Fonts, Custom CSS (styles for noise, blobs, custom scrollbars, glassmorphism tweaked to paper texture).
<body>:
- Background container with SVG blobs.
- Noise overlay (fixed pointer-events-none).
- Main container (max-w-4xl, mx-auto, relative).
- Header: "Aether Rate Limiter" (or something nature-y).
- Section 1: Theory (Cards explaining Token, Leaky, Sliding).
- Section 2: Interactive Playground.
- Tabs to switch algorithm.
- Sliders: Capacity (Bucket size), Rate (refill/leak).
- Real-time stats: Tokens remaining, Queue size, Request count (accepted/blocked).
- Chart: A rolling list of request timestamps (visual stream).
- "Simulate Burst" button.
- Footer.
<script>:
class TokenBucket, class LeakyBucket, class SlidingWindowLog.
class DashboardManager: Handles DOM updates, animation loops.
- Logic to handle the chart rendering (simple HTML5 Canvas drawing smooth lines/area fill in earth tones).
-
Detailed Implementation details:
-
The "Paper" Texture:
.noise-overlay {
background: url('data:image/svg+xml;base64,...'); // FeTurbulence noise
}
Actually, better to inline an SVG filter in HTML and apply via CSS filter: url(#noise). I'll generate a subtle noise filter.
-
Chart:
Needs to show the rate of requests over the last few seconds.
X-axis: time (scrolling). Y-axis: requests/sec.
Draw a filled polygon.
-
The "Analytics": The prompt asks for "sliding window analytics." The SlidingWindowLog track timestamps. I can visualize the distribution of requests within the window perhaps? Or just the rate. A time-series graph is standard.
-
Wabi-Sabi in Data Visualization: Don't use standard grid lines. Maybe faint organic guides. Use a brush-stroke style line if possible, or at least a smooth Bezier curve.
-
Penning the Code (Iterative refinement during drafting):
-
Self-Correction on Logic: Leaky bucket usually works as a queue. If a request comes and the queue size < limit, it's accepted; else dropped. Or it's a fixed rate outflow. I'll implement the queue version (FIFO) because it's easier to visualize the growing "water" level.
-
Sliding Window Implementation: Needs windowSize (seconds) and maxRequests. Store timestamps. On tryConsume, remove timestamps older than now - windowSize. If remaining < maxRequests, add current timestamp and return true. For analytics, I can show the "loaded" percentage of the window.
-
Context: The user asked to "Engineer a rate limiter library". I need to provide code. Since I'm making a visual page, I will present the code conceptually via the activity, but the actual product is a working JS implementation in the browser. To satisfy "Engineer", I will ensure the JS code is clean, well-commented, and class-based, suitable for copying if the user inspected the source.
-
Final Polish (Aesthetics):
- Use
text-stone-600 and text-emerald-900 (darker greens).
- Buttons:
bg-[#D4A373] (terracotta/wood), hover with shadow.
- The "Blobs": Use pastel versions of the palette:
#E9EFEC (mint), #F4E1D2 (sand).
- Animations: When a request is accepted, a small circle appears and floats up (like a bubble). When rejected, a fizzle effect.
-
Generating the Code: (This will be a long file. I will structure it carefully.)
- Include Tailwind via CDN.
- Font imports: 'Playfair Display' and 'DM Sans'.
- SVG for noise filter in HTML.
- JS Logic with an init function.
(Self-Correction): Ensure single file. No external images. Use SVG data URIs for any icons.
-
Review against constraints:
- "No native alerts" -> Use a custom "toast" div.
- "Standalone HTML" -> Yes.
- "Biophilic/Wabi-Sabi" -> Yes, organic shapes, textures, slow animations.
- "Functional interactive elements" -> Sliders work, buttons work, chart updates.
-
Final Code Structure Assembly:
<style> for specific overrides and animations.
<body> semantic tags.
<script> containing the library classes and UI glue.
Let's write the code. I will ensure the sliding window uses a circular buffer or array shift for efficiency. For simplicity in a demo, array filter is fine for N < 10000.
Visual Specifics:
- Background:
#F7F5F0 (Warm off-white).
- Dark text:
#3D405B (Dark grey-blue).
- Primary:
#81B29A (Sage).
- Secondary:
#E07A5F (Terracotta).
- Accent:
#F4F1DE (Cream).
Animation:
- Background blobs: CSS keyframes with long duration (30s).
- UI entrance: Fade in, translate.
Interaction:
- User selects algorithm from tabs.
- Adjusts sliders.
- Clicks "Simulate Traffic" (or auto-sim). I'll add an "Auto-Simulate" toggle.
Let's build it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Biomorphic Rate Limiter Library</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts: Playfair Display (Serif) & DM Sans (Sans) -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,300;400;500&family=Playfair+Display:ital,wght@0,400;0,600;1,400&display=swap" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
sage: {
DEFAULT: '#81B29A',
light: '#B8D3C2',
dark: '#5E8A73'
},
terracotta: {
DEFAULT: '#E07A5F',
light: '#EBA690',
dark: '#B85A3E'
},
cream: {
DEFAULT: '#F4F1DE',
dark: '#D9D6C5'
},
slate: {
DEFAULT: '#3D405B',
light: '#525C7A'
}
},
fontFamily: {
serif: ['"Playfair Display"', 'serif'],
sans: ['"DM Sans"', 'sans-serif']
},
boxShadow: {
'soft': '0 10px 40px -10px rgba(61, 64, 91, 0.1)',
'inner-inset': 'inset 2px 2px 5px rgba(0,0,0,0.05), inset -2px -2px 5px rgba(255,255,255,0.8)'
},
borderRadius: {
'blob': '60% 40% 30% 70% / 60% 30% 70% 40%',
'blob-hover': '30% 60% 70% 40% / 50% 60% 30% 60%'
}
}
}
}
</script>
<style>
body {
background-color: #F7F5F0;
color: #3D405B;
overflow-x: hidden;
}
/* Noise Texture Overlay */
.noise-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
opacity: 0.07;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
}
/* Organic Background Blobs */
.blob {
position: absolute;
filter: blur(60px);
opacity: 0.6;
animation: drift 25s infinite alternate ease-in-out;
z-index: 0;
}
@keyframes drift {
0% { transform: translate(0, 0) rotate(0deg) scale(1); border-radius: 60% 40% 30% 70% / 60% 30% 70% 40%; }
50% { border-radius: 30% 60% 70% 40% / 50% 60% 30% 60%; }
100% { transform: translate(50px, -80px) rotate(20deg) scale(1.1); border-radius: 40% 60% 30% 70% / 40% 60% 30% 60%; }
}
/* Slow entering animation */
.fade-in-up {
opacity: 0;
transform: translateY(20px);
animation: fadeInUp 1.2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
@keyframes fadeInUp {
to { opacity: 1; transform: translateY(0); }
}
/* Stylized Chart Canvas */
canvas {
width: 100%;
height: 100%;
display: block;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #F4F1DE;
}
::-webkit-scrollbar-thumb {
background: #D9D6C5;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #C5C0AD;
}
/* Range Slider Styling */
input[type=range] {
-webkit-appearance: none;
background: transparent;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
height: 18px;
width: 18px;
border-radius: 50%;
background: #81B29A;
cursor: pointer;
margin-top: -7px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
transition: transform 0.2s;
}
input[type=range]::-webkit-slider-thumb:hover {
transform: scale(1.1);
background: #5E8A73;
}
input[type=range]::-webkit-slider-runnable-track {
width: 100%;
height: 4px;
cursor: pointer;
background: #D9D6C5;
border-radius: 2px;
}
/* Toast Notification */
.toast-container {
position: fixed;
bottom: 2rem;
right: 2rem;
z-index: 100;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.toast {
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(5px);
padding: 0.75rem 1.25rem;
border-radius: 1rem;
box-shadow: 0 4px 12px rgba(0,0,0,0.05);
font-size: 0.875rem;
border-left: 3px solid #81B29A;
animation: slideIn 0.5s ease-out forwards;
opacity: 0;
transform: translateX(20px);
}
@keyframes slideIn {
to { opacity: 1; transform: translateX(0); }
}
</style>
</head>
<body class="antialiased min-h-screen flex flex-col font-sans">
<!-- Noise Texture -->
<div class="noise-overlay"></div>
<!-- Background Decoration -->
<div class="fixed inset-0 overflow-hidden pointer-events-none -z-10">
<div class="blob w-96 h-96 bg-[#EBA690] top-[-10%] left-[-10%]"></div>
<div class="blob w-80 h-80 bg-[#B8D3C2] top-[40%] right-[-5%] animation-delay-2000"></div>
<div class="blob w-64 h-64 bg-[#D9D6C5] bottom-[-10%] left-[20%]"></div>
</div>
<!-- Header -->
<header class="w-full py-8 px-6 relative z-10 fade-in-up" style="animation-delay: 0.1s">
<div class="max-w-5xl mx-auto flex flex-col md:flex-row justify-between items-center">
<div class="flex items-center gap-3 mb-4 md:mb-0">
<div class="w-10 h-10 rounded-full bg-sage-light flex items-center justify-center text-slate-dark font-serif font-bold text-xl shadow-soft">R</div>
<h1 class="text-3xl md:text-4xl font-serif text-slate">Aether <span class="italic text-terracotta">Rate</span></h1>
</div>
<p class="text-slate-light max-w-lg text-center md:text-right italic font-serif text-lg">
"Limiting flow, like water through stone, with organic grace."
</p>
</div>
</header>
<!-- Main Content -->
<main class="flex-grow w-full max-w-5xl mx-auto px-6 py-8 relative z-10 flex flex-col gap-12">
<!-- Introduction Cards -->
<section class="grid md:grid-cols-3 gap-6 fade-in-up" style="animation-delay: 0.2s">
<div class="bg-white/70 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/40 transition hover:-translate-y-1">
<h3 class="font-serif text-xl text-terracotta mb-2">Token Bucket</h3>
<p class="text-slate-light text-sm leading-relaxed">
Tokens accumulate at a steady rate. Each request consumes a token. If empty, the request is rejected. Allows bursts within capacity.
</p>
</div>
<div class="bg-white/70 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/40 transition hover:-translate-y-1">
<h3 class="font-serif text-xl text-sage mb-2">Leaky Bucket</h3>
<p class="text-slate-light text-sm leading-relaxed">
Requests queue up and drain out at a constant fixed rate. If the queue overflows, requests are dropped. Smoothes out bursts.
</p>
</div>
<div class="bg-white/70 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/40 transition hover:-translate-y-1">
<h3 class="font-serif text-xl text-slate mb-2">Sliding Window</h3>
<p class="text-slate-light text-sm leading-relaxed">
Tracks request timestamps over a sliding time window. Counts requests in the last X seconds. Precise and fair for time-based limits.
</p>
</div>
</section>
<!-- Interactive Playground -->
<section class="flex flex-col gap-6 fade-in-up" style="animation-delay: 0.3s">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 class="text-2xl font-serif text-slate">Interactive Playground</h2>
<div class="flex bg-white rounded-full p-1 shadow-sm border border-stone-200">
<button id="btn-token" class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-500 bg-sage text-white shadow-md" onclick="switchMode('token')">Token Bucket</button>
<button id="btn-leaky" class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-500 text-slate-light hover:text-slate" onclick="switchMode('leaky')">Leaky Bucket</button>
<button id="btn-sliding" class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-500 text-slate-light hover:text-slate" onclick="switchMode('sliding')">Sliding Window</button>
</div>
</div>
<div class="grid lg:grid-cols-3 gap-8 items-start">
<!-- Controls & Stats (Left Column) -->
<div class="lg:col-span-1 flex flex-col gap-6">
<!-- Controls Card -->
<div class="bg-white/50 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/50">
<div class="mb-6">
<div class="flex justify-between mb-2">
<label class="text-sm font-bold text-slate uppercase tracking-wider">Capacity / Max Size</label>
<span id="capacity-val" class="text-sm font-serif text-terracotta font-bold">10</span>
</div>
<input type="range" id="capacity-slider" min="1" max="50" value="10" class="w-full">
<p class="text-xs text-slate-light mt-1">Max tokens or max queue length.</p>
</div>
<div class="mb-6">
<div class="flex justify-between mb-2">
<label class="text-sm font-bold text-slate uppercase tracking-wider">Refill / Leak Rate</label>
<span id="rate-val" class="text-sm font-serif text-terracotta font-bold">5</span>
</div>
<input type="range" id="rate-slider" min="1" max="20" value="5" class="w-full">
<p class="text-xs text-slate-light mt-1">Units per second.</p>
</div>
<div class="mb-6" id="window-container" style="display: none;">
<div class="flex justify-between mb-2">
<label class="text-sm font-bold text-slate uppercase tracking-wider">Time Window (s)</label>
<span id="window-val" class="text-sm font-serif text-terracotta font-bold">10</span>
</div>
<input type="range" id="window-slider" min="1" max="60" value="10" class="w-full">
</div>
<div class="pt-4 border-t border-stone-200">
<button id="burst-btn" class="w-full py-3 bg-slate text-white rounded-xl font-serif italic tracking-wide hover:bg-slate-dark transition-colors shadow-soft">
Send Burst (10 req)
</button>
<div class="flex items-center justify-center mt-4">
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" id="auto-sim-check" class="sr-only peer">
<div class="w-9 h-5 bg-stone-300 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-sage"></div>
<span class="ml-3 text-sm font-serif text-slate">Auto-Simulate</span>
</label>
</div>
</div>
</div>
<!-- Stats Card -->
<div class="bg-white/50 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/50">
<h3 class="font-serif text-lg text-slate mb-4 border-b border-stone-100 pb-2">Live Telemetry</h3>
<div class="space-y-4">
<div>
<div class="flex justify-between text-sm mb-1">
<span class="text-slate-light">Available</span>
<span id="current-val" class="font-serif font-bold text-slate">10</span>
</div>
<div class="h-2 w-full bg-stone-200 rounded-full overflow-hidden">
<div id="current-bar" class="h-full bg-sage transition-all duration-500 ease-out" style="width: 100%"></div>
</div>
</div>
<div>
<div class="flex justify-between text-sm mb-1">
<span class="text-slate-light">Pressure (Requests)</span>
<span id="load-val" class="font-serif font-bold text-slate">0</span>
</div>
<div class="h-2 w-full bg-stone-200 rounded-full overflow-hidden">
<div id="load-bar" class="h-full bg-terracotta transition-all duration-500 ease-out" style="width: 0%"></div>
</div>
</div>
<div class="grid grid-cols-2 gap-4 pt-2">
<div class="text-center p-2 bg-cream rounded-xl">
<div class="text-xs text-slate-light uppercase">Accepted</div>
<div id="accept-count" class="text-xl font-serif text-sage">0</div>
</div>
<div class="text-center p-2 bg-cream rounded-xl">
<div class="text-xs text-slate-light uppercase">Rejected</div>
<div id="reject-count" class="text-xl font-serif text-terracotta">0</div>
</div>
</div>
</div>
</div>
</div>
<!-- Visualization (Right Column) -->
<div class="lg:col-span-2 flex flex-col gap-6">
<!-- Data Stream / Chart -->
<div class="bg-white/40 backdrop-blur-sm p-6 rounded-2xl shadow-soft border border-white/50 relative h-80 flex flex-col">
<h3 class="font-serif text-lg text-slate mb-4">Analytics: Sliding Window Traffic</h3>
<div class="relative flex-grow w-full overflow-hidden">
<canvas id="trafficChart"></canvas>
<!-- Overlay Grid Lines (Organic feel) -->
<div class="absolute inset-0 pointer-events-none" style="background-image: radial-gradient(#D9D6C5 1px, transparent 1px); background-size: 20px 20px; opacity: 0.3;"></div>
</div>
<!-- Legend -->
<div class="flex justify-center gap-6 mt-4 text-xs text-slate-light font-sans">
<span class="flex items-center gap-1">
<span class="w-3 h-3 rounded-full bg-sage"></span> Inbound
</span>
<span class="flex items-center gap-1">
<span class="w-3 h-3 rounded-full bg-terracotta"></span> Rejected
</span>
</div>
</div>
<!-- Performance Log -->
<div class="bg-stone-100/50 p-4 rounded-xl border border-stone-200 h-48 overflow-y-auto font-mono text-xs shadow-inner">
<div id="log-container" class="flex flex-col gap-1 text-slate-dark">
<div class="text-stone-500 italic">// System ready. Waiting for events...</div>
</div>
</div>
</div>
</div>
</section>
</main>
<footer class="w-full py-6 text-center text-stone-500 text-sm font-serif relative z-10">
<p>Design by the Aether Collective • 2023</p>
</footer>
<div class="toast-container" id="toast-container"></div>
<script>
// ==========================================
// CORE RATE LIMITER LIBRARY (The "Product")
// ==========================================
/**
* TokenBucket Algorithm
* Tokens are added to the bucket at a fixed rate. Requests consume tokens.
*/
class TokenBucket {
constructor(capacity, refillRatePerSecond) {
this.capacity = capacity;
this.refillRate = refillRatePerSecond;
this.tokens = capacity;
this.lastRefillTimestamp = Date.now();
}
tryConsume(cost = 1) {
const now = Date.now();
const timePassed = (now - this.lastRefillTimestamp) / 1000;
// Refill based on elapsed time
const refillAmount = timePassed * this.refillRate;
this.tokens = Math.min(this.capacity, this.tokens + refillAmount);
this.lastRefillTimestamp = now;
if (this.tokens >= cost) {
this.tokens -= cost;
return { allowed: true, remaining: this.tokens };
} else {
return { allowed: false, remaining: this.tokens, retryAfter: (cost - this.tokens) / this.refillRate };
}
}
// Utility for dashboard: get fill percentage
getFillRatio() {
return this.tokens / this.capacity;
}
}
/**
* LeakyBucket Algorithm
* Incoming requests fill a queue. A "leak" (draining) process removes items at a fixed rate.
*/
class LeakyBucket {
constructor(capacity, leakRatePerSecond) {
this.capacity = capacity;
this.leakRate = leakRatePerSecond;
this.queueSize = 0;
this.lastLeakTimestamp = Date.now();
}
tryConsume(cost = 1) {
let now = Date.now();
let delta = (now - this.lastLeakTimestamp) / 1000;
// Simulate the leak
let leaked = delta * this.leakRate;
this.queueSize = Math.max(0, this.queueSize - leaked);
this.lastLeakTimestamp = now;
if (this.queueSize < this.capacity) {
this.queueSize += cost;
return { allowed: true, load: this.queueSize / this.capacity };
} else {
return { allowed: false, load: 1.0, retryAfter: (this.queueSize - this.capacity + cost) / this.leakRate };
}
}
getFillRatio() {
return this.queueSize / this.capacity;
}
}
/**
* SlidingWindowLog Algorithm
* Keeps a list of timestamps of accepted requests within a time window.
*/
class SlidingWindowLog {
constructor(maxRequests, windowSizeInSeconds) {
this.maxRequests = maxRequests;
this.windowSize = windowSizeInSeconds * 1000; // ms
this.requests = []; // array of timestamps
}
tryConsume(cost = 1) {
const now = Date.now();
const windowStart = now - this.windowSize;
// Remove old timestamps
this.requests = this.requests.filter(t => t > windowStart);
// Check capacity
if (this.requests.length + cost <= this.maxRequests) {
this.requests.push(now);
return { allowed: true, remaining: this.maxRequests - this.requests.length };
} else {
return { allowed: false, remaining: 0, retryAfter: this._calculateRetry() };
}
}
_calculateRetry() {
// Find the oldest request in the window (earliest)
if (this.requests.length === 0) return 0;
const oldest = Math.min(...this.requests);
return (oldest + this.windowSize - Date.now()) / 1000;
}
getFillRatio() {
return this.requests.length / this.maxRequests;
}
// For analytics: count requests in the last second (smooth rate)
getRecentRate() {
const now = Date.now();
const oneSecAgo = now - 1000;
return this.requests.filter(t => t >= oneSecAgo).length;
}
}
// ==========================================
// UI & VISUALIZATION MANAGER
// ==========================================
// State
let currentMode = 'token';
let limiter = null;
let autoSimulate = false;
let autoSimInterval = null;
// Stats
let stats = {
accepted: 0,
rejected: 0,
history: [] // Array of {time, type} for chart
};
// Chart Configuration
const chartCanvas = document.getElementById('trafficChart');
const chartCtx = chartCanvas.getContext('2d');
const MAX_HISTORY = 100; // points to draw
// Resize observer for canvas
new ResizeObserver(() => {
const rect = chartCanvas.parentElement.getBoundingClientRect();
chartCanvas.width = rect.width;
chartCanvas.height = rect.height;
drawChart();
}).observe(chartCanvas.parentElement);
// Initialize with defaults
function init() {
updateLimiter();
startAnimationLoop();
// Event Listeners
document.getElementById('capacity-slider').addEventListener('input', (e) => {
document.getElementById('capacity-val').innerText = e.target.value;
updateLimiter();
});
document.getElementById('rate-slider').addEventListener('input', (e) => {
document.getElementById('rate-val').innerText = e.target.value;
updateLimiter();
});
document.getElementById('window-slider').addEventListener('input', (e) => {
document.getElementById('window-val').innerText = e.target.value;
updateLimiter();
});
document.getElementById('burst-btn').addEventListener('click', sendBurst);
document.getElementById('auto-sim-check').addEventListener('change', (e) => {
autoSimulate = e.target.checked;
if (autoSimulate) {
autoSimInterval = setInterval(() => sendBurst(1), 400); // Slow, regular requests
} else {
clearInterval(autoSimInterval);
}
});
}
function switchMode(mode) {
currentMode = mode;
// Toggle buttons
['token', 'leaky', 'sliding'].forEach(m => {
const btn = document.getElementById(`btn-${m}`);
const isActive = m === mode;
if (isActive) {
btn.classList.remove('text-slate-light', 'hover:text-slate');
btn.classList.add('bg-sage', 'text-white', 'shadow-md');
btn.style.color = 'white';
} else {
btn.classList.add('text-slate-light', 'hover:text-slate');
btn.classList.remove('bg-sage', 'text-white', 'shadow-md');
btn.style.color = '';
}
});
// Show/hide window slider
const winContainer = document.getElementById('window-container');
winContainer.style.display = mode === 'sliding' ? 'block' : 'none';
updateLimiter();
resetStats();
}
function updateLimiter() {
const cap = parseInt(document.getElementById('capacity-slider').value);
const rate = parseInt(document.getElementById('rate-slider').value);
const win = parseInt(document.getElementById('window-slider').value);
if (currentMode === 'token') {
limiter = new TokenBucket(cap, rate);
} else if (currentMode === 'leaky') {
limiter = new LeakyBucket(cap, rate);
} else if (currentMode === 'sliding') {
limiter = new SlidingWindowLog(cap, win);
}
updateDashboard();
}
function sendBurst(amount = 10) {
for (let i = 0; i < amount; i++) {
setTimeout(() => {
const result = limiter.tryConsume(1);
handleResult(result);
}, i * 50); // Spread slightly to visualize queue
}
}
function handleResult(result) {
const now = Date.now();
if (result.allowed) {
stats.accepted++;
addLogItem('Request accepted', 'success');
} else {
stats.rejected++;
addLogItem(`Request blocked. Retry: ${result.retryAfter.toFixed(2)}s`, 'error');
}
// Add to history for chart
stats.history.push({ time: now, type: result.allowed ? 'accept' : 'reject' });
if (stats.history.length > MAX_HISTORY) stats.history.shift();
updateDashboard();
}
function updateDashboard() {
if (!limiter) return;
let fillRatio = 0;
let currentMetric = 0;
let maxMetric = 1;
if (currentMode === 'token') {
fillRatio = limiter.getFillRatio();
currentMetric = limiter.tokens;
maxMetric = limiter.capacity;
} else if (currentMode === 'leaky') {
fillRatio = limiter.getFillRatio();
currentMetric = limiter.queueSize;
maxMetric = limiter.capacity;
} else if (currentMode === 'sliding') {
fillRatio = limiter.getFillRatio();
currentMetric = limiter.requests.length;
maxMetric = limiter.maxRequests;
}
// Update text
document.getElementById('current-val').innerText = Math.round(currentMetric);
document.getElementById('capacity-val').innerText = maxMetric;
// Update Bars
const currentBar = document.getElementById('current-bar');
currentBar.style.width = `${fillRatio * 100}%`;
// Load Pressure (based on recent accept rate or fill ratio)
// Use fill ratio for simplicity
const loadBar = document.getElementById('load-bar');
loadBar.style.width = `${fillRatio * 100}%`;
// Counts
document.getElementById('accept-count').innerText = stats.accepted;
document.getElementById('reject-count').innerText = stats.rejected;
}
function resetStats() {
stats.accepted = 0;
stats.rejected = 0;
stats.history = [];
document.getElementById('log-container').innerHTML = '<div class="text-stone-500 italic">// System reset. Ready.</div>';
updateDashboard();
}
function addLogItem(msg, type) {
const container = document.getElementById('log-container');
const div = document.createElement('div');
const color = type === 'success' ? 'text-sage' : 'text-terracotta';
const time = new Date().toLocaleTimeString().split(' ')[0];
div.innerHTML = `<span class="text-stone-400">[${time}]</span> <span class="${color}">${msg}</span>`;
container.prepend(div);
// Limit log length
if (container.children.length > 50) container.lastChild.remove();
}
// ==========================================
// CHART ENGINE (Custom Organic Rendering)
// ==========================================
function drawChart() {
const w = chartCanvas.width;
const h = chartCanvas.height;
const ctx = chartCtx;
ctx.clearRect(0, 0, w, h);
if (stats.history.length < 2) {
// Draw empty state text
ctx.font = "italic 16px 'Playfair Display'";
ctx.fillStyle = "#D9D6C5";
ctx.textAlign = "center";
ctx.fillText("Waiting for data stream...", w/2, h/2);
return;
}
// Prepare data points
const points = stats.history.map((h, i) => {
const x = (i / (MAX_HISTORY - 1)) * w;
const y = h.type === 'accept' ? h * 0 : (1.5 * h) - h;
// Let's interpret: Accept = green, Reject = red/terracotta.
// Actually we need to map accept/reject to Y axis differently or color.
// Idea: Draw a line representing "load" (accepted vs rejected ratio) or simply draw a timeline where hits are dots above a line and misses below.
// Simpler: Draw a timeline showing server load (accepted requests as a moving average).
// But user wants analytics. Let's draw the history bars: Accept = Green vertical tick, Reject = Red vertical tick.
return { x, type: h.type };
});
// Draw Area (The "river") showing recent accepted requests intensity
// We'll calculate a simple moving sum of last 10 points
let sum = 0;
const dataVals = stats.history.map((h, i) => {
sum += h.type === 'accept' ? 1 : -0.2; // Weigh accepts positively
if (i >= 10) sum -= stats.history[i-10].type === 'accept' ? 1 : -0.2;
return Math.max(0, sum); // truncated
});
// Normalize to canvas height
const maxVal = Math.max(...dataVals, 1);
// Draw organic curve (bezier)
ctx.beginPath();
ctx.moveTo(0, h);
const stepX = w / (dataVals.length - 1);
for (let i = 0; i < dataVals.length; i++) {
const val = dataVals[i];
const x = i * stepX;
const y = h - (val / maxVal) * (h * 0.8) - 20; // Padding bottom
if (i === 0) ctx.lineTo(x, y);
else {
// Smooth curve using quadratic curve to midpoints
const prevX = (i - 1) * stepX;
const prevY = h - (dataVals[i-1] / maxVal) * (h * 0.8) - 20;
const cpX = (prevX + x) / 2;
const cpY = (prevY + y) / 2;
ctx.quadraticCurveTo(prevX, prevY, cpX, cpY);
}
}
// Complete loop to fill to bottom
ctx.lineTo(w, h);
ctx.closePath();
// Gradient fill
const grad = ctx.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, "rgba(129, 178, 154, 0.6)"); // Sage
grad.addColorStop(1, "rgba(129, 178, 154, 0.0)");
ctx.fillStyle = grad;
ctx.fill();
// Draw the stroke line (watercolor feel)
ctx.beginPath();
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// Re-draw the path without bottom closure
for (let i = 0; i < dataVals.length; i++) {
const val = dataVals[i];
const x = i * stepX;
const y = h - (val / maxVal) * (h * 0.8) - 20;
if (i === 0) ctx.moveTo(x, y);
else {
const prevX = (i - 1) * stepX;
const prevY = h - (dataVals[i-1] / maxVal) * (h * 0.8) - 20;
const cpX = (prevX + x) / 2;
const cpY = (prevY + y) / 2;
ctx.quadraticCurveTo(prevX, prevY, cpX, cpY);
}
}
ctx.strokeStyle = "#5E8A73";
ctx.stroke();
// Draw individual dots for events (Accept=Green, Reject=Red)
for (let i = 0; i < stats.history.length; i++) {
const event = stats.history[i];
const x = i * stepX;
// Slightly randomize y based on type to create "particles"
let yOffset = 0;
if (event.type === 'accept') {
yOffset = -20 - Math.random() * 10; // Above the flow
ctx.fillStyle = "#E07A5F"; // Terracotta for accept actually, or maybe use Terracotta for Reject?
// Let's use palette: Accept = Sage (`#81B29A`), Reject = Terracotta (`#E07A5F`)
} else {
yOffset = h - 10 + Math.random() * 10; // Below the flow
ctx.fillStyle = "#E07A5F"; // Terracotta
}
// Map accept to above baseline, reject below
// Wait, baseline is the flow line. Accept = up, Reject = down.
if (event.type === 'accept') {
const baseline = h - (dataVals[i] / maxVal) * (h * 0.8) - 20;
yOffset = baseline - 15;
ctx.fillStyle = "#81B29A";
} else {
const baseline = h - (dataVals[i] / maxVal) * (h * 0.8) - 20;
yOffset = baseline + 15;
ctx.fillStyle = "#E07A5F";
}
ctx.beginPath();
ctx.arc(x, yOffset, 3, 0, Math.PI * 2);
ctx.fill();
}
}
// Animation Loop for Chart
function startAnimationLoop() {
function loop() {
drawChart();
requestAnimationFrame(loop);
}
loop();
}
// Toast Notification Helper
function showToast(message) {
const container = document.getElementById('toast-container');
const el = document.createElement('div');
el.className = 'toast';
el.innerText = message;
container.appendChild(el);
setTimeout(() => {
el.style.opacity = '0';
el.style.transform = 'translateY(10px)';
setTimeout(() => el.remove(), 500);
}, 3000);
}
// Boot
window.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>