import React, { useState, useEffect, useRef } from 'react';
import {
Activity,
ShieldAlert,
Terminal,
Settings,
TrendingUp,
Database,
Network,
Flame,
History,
Map,
Info,
RefreshCw,
Zap,
CheckCircle,
XCircle,
AlertTriangle,
LogOut,
ArrowRight,
Shield,
Lock,
Globe,
Server,
Award
} from 'lucide-react';
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
BarChart,
Bar,
Legend
} from 'recharts';
// Dynamically resolve API and WebSocket endpoints to support network sharing and tunnels
const getBackendUrls = () => {
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const port = window.location.port;
// Check if env variable is defined (e.g. on Vercel deployment)
const envApiUrl = import.meta.env.VITE_API_URL;
if (envApiUrl) {
return {
api: envApiUrl,
ws: envApiUrl.replace('http', 'ws') + '/ws'
};
}
// If accessed directly via Vite dev server port, use port 8000 for backend
if (port === '5173' || port === '5174') {
return {
api: `${protocol}//${hostname}:8000`,
ws: `${protocol === 'https:' ? 'wss:' : 'ws:'}//${hostname}:8000/ws`
};
} else {
// If accessed via Nginx gateway (port 8080) or public tunnel (port 80/443), use relative host/port
const host = window.location.host; // includes port if present (like :8080)
return {
api: `${protocol}//${host}`,
ws: `${protocol === 'https:' ? 'wss:' : 'ws:'}//${host}/ws`
};
}
};
const urls = getBackendUrls();
const API_URL = urls.api;
const WS_URL = urls.ws;
// Interactive Playground Widget for Marketing page
function InteractivePlayground() {
const [crashed, setCrashed] = useState(false);
const [rateLimit, setRateLimit] = useState(100);
const [cbState, setCbState] = useState("CLOSED");
useEffect(() => {
let t;
if (crashed) {
setCbState("OPEN");
setRateLimit(10);
} else {
setCbState("HALF_OPEN");
t = setTimeout(() => {
setCbState("CLOSED");
setRateLimit(100);
}, 3000);
}
return () => clearTimeout(t);
}, [crashed]);
return (
Interactive Resiliency Simulator
Simulate downstream failures to observe automatic circuit breaker state changes and rate limit clamping.
Svc A
Rate: {rateLimit} RPS
Svc C
{crashed ? "CRASHED" : "HEALTHY"}
setCrashed(!crashed)}
className={`w-full py-2.5 rounded-lg text-xs font-bold font-mono transition-all duration-300 ${crashed ? 'bg-emerald-500 text-slate-900 shadow-lg shadow-emerald-500/20 hover:bg-emerald-400' : 'bg-rose-500 text-white shadow-lg shadow-rose-500/20 hover:bg-rose-400'}`}
>
{crashed ? "Recover Service C" : "Simulate Service C Crash"}
);
}
export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(() => {
return localStorage.getItem('pulseguard_logged_in') === 'true';
});
const [activeTab, setActiveTab] = useState('landing');
const [connected, setConnected] = useState(false);
const [data, setData] = useState({
services: {
"service-a": { limit_capacity: 100, limit_rate: 100, circuit_state: "CLOSED", status: "HEALTHY", rps: 0, error_rate: 0, p50: 0, p95: 0, p99: 0, total_requests: 0 },
"service-b": { limit_capacity: 100, limit_rate: 100, circuit_state: "CLOSED", status: "HEALTHY", rps: 0, error_rate: 0, p50: 0, p95: 0, p99: 0, total_requests: 0 },
"service-c": { limit_capacity: 100, limit_rate: 100, circuit_state: "CLOSED", status: "HEALTHY", rps: 0, error_rate: 0, p50: 0, p95: 0, p99: 0, total_requests: 0 }
},
events: [],
audits: []
});
const [benchmarks, setBenchmarks] = useState([]);
const [benchmarkLoading, setBenchmarkLoading] = useState(false);
const [chaosState, setChaosState] = useState({
"service-a": { delay: 0, error_rate: 0, crash: false, cpu_load: 0, memory_load: 0, packet_loss: 0 },
"service-b": { delay: 0, error_rate: 0, crash: false, cpu_load: 0, memory_load: 0, packet_loss: 0 },
"service-c": { delay: 0, error_rate: 0, crash: false, cpu_load: 0, memory_load: 0, packet_loss: 0 }
});
const [generatorRps, setGeneratorRps] = useState(50);
const [history, setHistory] = useState([]); // Real-time charting history
const socketRef = useRef(null);
// Connect to websocket when logged in
useEffect(() => {
if (!isLoggedIn) return;
const connectWS = () => {
socketRef.current = new WebSocket(WS_URL);
socketRef.current.onopen = () => {
setConnected(true);
console.log('WebSocket Connected');
};
socketRef.current.onmessage = (event) => {
try {
const payload = JSON.parse(event.data);
setData(payload);
// Push to charting history
setHistory(prev => {
const newHistory = [...prev, {
time: new Date().toLocaleTimeString(),
"Service A Latency": (payload.services["service-a"]?.p95 || 0) * 1000,
"Service B Latency": (payload.services["service-b"]?.p95 || 0) * 1000,
"Service C Latency": (payload.services["service-c"]?.p95 || 0) * 1000,
"Service A RPS": payload.services["service-a"]?.rps || 0,
"Service B RPS": payload.services["service-b"]?.rps || 0,
"Service C RPS": payload.services["service-c"]?.rps || 0
}];
if (newHistory.length > 20) newHistory.shift();
return newHistory;
});
} catch (err) {
console.error('Error parsing websocket payload:', err);
}
};
socketRef.current.onclose = () => {
setConnected(false);
console.log('WebSocket Disconnected. Reconnecting...');
setTimeout(connectWS, 3000);
};
};
connectWS();
return () => {
if (socketRef.current) socketRef.current.close();
};
}, [isLoggedIn]);
// Fetch benchmarks and chaos configurations when logged in
const fetchBenchmarks = async () => {
try {
const res = await fetch(`${API_URL}/api/benchmarks`);
const body = await res.json();
setBenchmarks(body);
} catch (err) {
console.error(err);
}
};
const fetchChaosStatus = async () => {
try {
const res = await fetch(`${API_URL}/api/chaos/status`);
const body = await res.json();
setChaosState(body);
} catch (err) {
console.error(err);
}
};
useEffect(() => {
if (!isLoggedIn) return;
fetchBenchmarks();
fetchChaosStatus();
const interval = setInterval(() => {
fetchBenchmarks();
fetchChaosStatus();
}, 5000);
return () => clearInterval(interval);
}, [isLoggedIn]);
const triggerChaos = async (service, type, val) => {
const current = chaosState[service] || { delay: 0, error_rate: 0, crash: false, cpu_load: 0, memory_load: 0, packet_loss: 0 };
const payload = { ...current, [type]: val };
try {
await fetch(`${API_URL}/api/chaos/inject/${service}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
fetchChaosStatus();
} catch (err) {
console.error(err);
}
};
const clearChaos = async (service) => {
try {
await fetch(`${API_URL}/api/chaos/clear/${service}`, {
method: 'POST'
});
fetchChaosStatus();
} catch (err) {
console.error(err);
}
};
const updateGeneratorRps = async (rps) => {
setGeneratorRps(rps);
try {
await fetch(`${API_URL}/api/generator/rps?rps=${rps}`, {
method: 'POST'
});
} catch (err) {
console.error(err);
}
};
const runResilienceBenchmark = async (hasProtection) => {
setBenchmarkLoading(true);
try {
await fetch(`${API_URL}/api/benchmark/start?test_name=${hasProtection ? "With PulseGuard Protection" : "Without Protection"}&has_protection=${hasProtection}`, {
method: 'POST'
});
alert("Benchmark started! It will run in the background for 30s. Observe metrics live.");
setTimeout(() => {
fetchBenchmarks();
setBenchmarkLoading(false);
}, 28000);
} catch (err) {
console.error(err);
setBenchmarkLoading(false);
}
};
const handleLogin = () => {
setIsLoggedIn(true);
localStorage.setItem('pulseguard_logged_in', 'true');
};
const handleLogout = () => {
setIsLoggedIn(false);
localStorage.setItem('pulseguard_logged_in', 'false');
};
const getStatusColor = (status) => {
if (status === 'HEALTHY') return 'text-emerald-400';
if (status === 'DEGRADED') return 'text-amber-400';
if (status === 'CRITICAL') return 'text-red-400';
return 'text-blue-400';
};
const getStatusBg = (status) => {
if (status === 'HEALTHY') return 'glass-panel-glow-green border-emerald-500/20';
if (status === 'DEGRADED') return 'bg-amber-500/5 border-amber-500/20 shadow-glow-yellow';
if (status === 'CRITICAL') return 'glass-panel-glow-red border-red-500/20';
return 'glass-panel-glow-blue border-blue-500/20';
};
const getCircuitColor = (state) => {
if (state === 'CLOSED') return 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30';
if (state === 'OPEN') return 'bg-rose-500/20 text-rose-400 border border-rose-500/30';
return 'bg-blue-500/20 text-blue-400 border border-blue-500/30';
};
// 1. PUBLIC MARKETING LANDING PAGE
if (!isLoggedIn) {
return (
{/* Navbar */}
{/* Hero Section */}
SOC2 Type II Compliant Autonomous Plane
Self-Healing Resiliency for Microservices
Stop cascading service failures in real time. PulseGuard X intercepts downstream bottlenecks, propagates upstream backpressure, manages token-bucket rate limits, and automatically heals degraded states.
{/* Features Section */}
Enterprise Architecture
Engineered for Microservice Autonomy
Built to protect complex, distributed call chains (A → B → C) without human operator latency.
Token Bucket Lua Engine
Distributed, high-concurrency rate limiting executing atomic refill operations in Redis Lua. Prevents race conditions.
Cascading Backpressure
Automatic upstream limit clamps and custom HTTP backpressure header propagation to prevent cascading connection queue locks.
Anti-Flapping Controls
Exponential Moving Average (EMA) latency monitoring and multi-tick validation prevent circuit breakers from flapping under transient spikes.
{/* Simulator CTA */}
Experience Self-Healing Actions Live
Launch the live cockpit to run traffic generators, inject real chaos CPU/RAM loads, and analyze live Prometheus and Grafana dashboards in real time.
Enter Sandbox Cockpit
{/* Pricing Section */}
SaaS Licensing
Transparent Plans for Every Stack
{/* Free Tier */}
Developer Sandbox
$0
Free Forever
✓ Service Chain: A → B → C
✓ Real Redis Token Bucket
✓ Live Chaos Injector
Launch Sandbox
{/* Pro Tier */}
Most Popular
Production Pro
$49/mo
Per cluster node
✓ Everything in Free
✓ Persistent Postgres Logs
✓ Dynamic SLO Overrides
✓ Slack/OpsGenie Alerts
Upgrade to Pro
{/* Enterprise Tier */}
Custom Enterprise
Custom
Custom SLA contract
✓ Unlimited Clusters
✓ Custom Lua Scripts
✓ 24/7 SRE Phone Support
Contact Sales
{/* Footer */}
);
}
// 2. DASHBOARD APPLICATION COCKPIT (AFTER LOGIN)
return (
{/* Sidebar */}
{/* Main Content Area */}
{/* Header */}
{/* Tab Switchboard */}
{/* Landing Page (Cockpit Overview) */}
{activeTab === 'landing' && (
PulseGuard X Reliability Control Plane
You are logged into the active cluster node cockpit. PulseGuard X manages distributed token-bucket rate limits, circuit breakers, and cascading backpressure propagation across this service grid.
setActiveTab('dashboard')}
className="px-5 py-2.5 rounded-lg bg-emerald-500 text-slate-900 font-semibold text-sm hover:bg-emerald-400 transition-all flex items-center gap-2 shadow-lg shadow-emerald-500/20"
>
Enter Dashboard
setActiveTab('chaos')}
className="px-5 py-2.5 rounded-lg bg-slate-800 border border-slate-700 text-slate-200 font-semibold text-sm hover:bg-slate-700 transition-all"
>
Launch Chaos Testing
{/* Core Capabilities */}
Core Platform Capabilities
01. Distributed Token Bucket Lua Rate Limiter
02. Dynamic Latency & Error Rate Clamping
03. Closed/Open/Half-Open Circuit Breaker States
04. Real-time Cascading Backpressure Clamps
05. Statistical Anomaly Detection & Flapping Protections
Production Environment Stack
Backend Service
FastAPI, AsyncIO, Uvicorn
Distributed Cache
Redis Cluster (Lua Scripts)
Relational Database
PostgreSQL (SQLAlchemy)
Telemetry & Scraping
Prometheus & Grafana
{/* SLO & Compliance */}
Service Level Objectives (SLO) & Security Compliance
SYSTEM SLO TARGET
99.99% Availability
Active threshold monitoring & self-healing active
MUTUAL TLS (mTLS)
ENFORCED (100%)
All downstream calls protected by mTLS encryption
AUDIT COMPLIANCE
SOC2 TYPE II COMPLIANT
Historical decision records stored in persistent SQL store
)}
{/* Reliability Dashboard */}
{activeTab === 'dashboard' && (
{/* Active Pipeline visualization */}
Service-to-Service Chain
{/* SVG Live pipeline with particle animations */}
{/* Path Client -> A */}
{/* Path A -> B */}
{/* Path B -> C */}
{/* Animated Particles flowing. Speed depends on RPS. */}
{data.services["service-a"]?.rps > 0 && (
)}
{data.services["service-b"]?.rps > 0 && data.services["service-b"]?.circuit_state !== 'OPEN' && (
)}
{data.services["service-c"]?.rps > 0 && data.services["service-c"]?.circuit_state !== 'OPEN' && (
)}
{/* Node: Client */}
Source
Client / Gen
RPS: {generatorRps}
{/* Node: Service A */}
Microservice A
Ingress Proxy
RPS: {data.services["service-a"]?.rps.toFixed(1)}
Limit: {data.services["service-a"]?.limit_capacity} RPS
P95: {((data.services["service-a"]?.p95 || 0) * 1000).toFixed(0)}ms
{/* Node: Service B */}
Microservice B
Auth / Routing
RPS: {data.services["service-b"]?.rps.toFixed(1)}
CB state: {data.services["service-b"]?.circuit_state}
P95: {((data.services["service-b"]?.p95 || 0) * 1000).toFixed(0)}ms
{/* Node: Service C */}
Microservice C
Database Hop
RPS: {data.services["service-c"]?.rps.toFixed(1)}
CB state: {data.services["service-c"]?.circuit_state}
P95: {((data.services["service-c"]?.p95 || 0) * 1000).toFixed(0)}ms
{/* Grid of details for A, B, C */}
{['service-a', 'service-b', 'service-c'].map((s) => {
const sData = data.services[s];
if (!sData) return null;
return (
{s}
{sData.status}
Current RPS
{sData.rps.toFixed(1)}
Token Limit
{sData.limit_capacity} RPS
Error Rate
0 ? 'text-red-400' : 'text-slate-300'}`}>
{(sData.error_rate * 100).toFixed(1)}%
P95 Latency
{(sData.p95 * 1000).toFixed(0)}ms
{/* Circuit Breaker Status Indicator */}
Circuit Breaker:
{sData.circuit_state}
);
})}
{/* Real-time latency chart */}
Real-Time Latency Trends (P95 ms)
{history.length === 0 ? (
Collecting telemetry streams...
) : (
)}
)}
{/* Network Topology Map */}
{activeTab === 'topology' && (
Interactive Service Map
● Green: Healthy operation
● Yellow: Latency threshold breached / degraded limit applied
● Red: Critical failures / circuit open
{/* Service A */}
Service A
Limits: {data.services["service-a"]?.limit_capacity} RPS
{/* Service B */}
Service B
{data.services["service-b"]?.circuit_state}
{/* Service C */}
Service C
{data.services["service-c"]?.circuit_state}
)}
{/* Chaos Engineering */}
{activeTab === 'chaos' && (
Service Traffic Injection Panel
Adjust Client Traffic Rate (RPS):
{[10, 50, 100, 200, 500, 1000].map(val => (
updateGeneratorRps(val)}
className={`px-3 py-1.5 rounded text-xs font-mono font-bold transition-all ${generatorRps === val ? 'bg-emerald-500 text-slate-950 shadow-md shadow-emerald-500/10' : 'bg-slate-800 text-slate-400 hover:text-white'}`}
>
{val} RPS
))}
{['service-b', 'service-c'].map(service => {
const status = chaosState[service] || {};
return (
{service} Injection
clearChaos(service)}
className="text-[10px] font-bold text-slate-900 bg-rose-400 hover:bg-rose-300 px-3 py-1 rounded uppercase tracking-wider font-mono"
>
Reset Service
{status.crash && CRASHED }
{status.delay > 0 && DELAY: {status.delay}s }
{status.error_rate > 0 && ERRORS: {status.error_rate * 100}% }
{status.cpu_load > 0 && CPU: {status.cpu_load * 100}% }
Crash Service:
triggerChaos(service, 'crash', !status.crash)}
className={`px-4 py-1.5 rounded text-xs font-mono font-bold transition-all ${status.crash ? 'bg-red-500 text-white' : 'bg-slate-800 text-slate-400 hover:text-white'}`}
>
{status.crash ? "Crashed (Recover)" : "Inject Crash"}
);
})}
)}
{/* Control Decisions */}
{activeTab === 'control-plane' && (
Controller Decision Engine (Audit Logs)
Timestamp
Service
Action
Transition
Reason
{data.audits.length === 0 ? (
No decisions logs in database yet. Run traffic to trigger limits.
) : (
data.audits.map(a => (
{new Date(a.timestamp).toLocaleTimeString()}
{a.service}
{a.action}
{a.old_value} → {a.new_value}
{a.reason}
))
)}
)}
{/* Reliability Timeline */}
{activeTab === 'timeline' && (
Real-Time Event Log
{data.events.length === 0 ? (
No events captured yet.
) : (
data.events.map(e => (
{new Date(e.timestamp).toLocaleTimeString()}
{e.event_type}
{e.service}
{e.message}
))
)}
)}
{/* System Architecture Map */}
{activeTab === 'architecture' && (
System Components Interconnect
{/* Left Column: Client */}
Client Ingress
Load Generator
Generates simulated customer traffic
{/* Mid Column: Backend Stack */}
Service Grid
FastAPI Container Chain
Service A → B → C (Runs telemetry & rate check)
Redis Cluster
Executes token bucket Lua & handles buffers
{/* Right Column: Reliability Controller */}
Control Plane
Reliability Controller
Loops every 2s, executes self-healing overrides
PostgreSQL DB
Maintains event audit trails & benchmarks
)}
{/* Resilience Benchmarks */}
{activeTab === 'benchmarks' && (
Platform Resilience Benchmarks
Trigger automated runs simulating failure injection on Service C under heavy traffic.
Compare statistics between unprotected setups (flapping, cascading timeouts) and protected configurations (automated limits, fail-fast, backpressure).
runResilienceBenchmark(true)}
className="px-5 py-2.5 rounded-lg bg-emerald-500 text-slate-900 font-bold text-xs hover:bg-emerald-400 transition-all flex items-center gap-2"
>
{benchmarkLoading ? "Running..." : "Run Test (WITH PROTECTION)"}
runResilienceBenchmark(false)}
className="px-5 py-2.5 rounded-lg bg-rose-500 text-white font-bold text-xs hover:bg-rose-400 transition-all flex items-center gap-2"
>
{benchmarkLoading ? "Running..." : "Run Test (NO PROTECTION)"}
{/* Benchmark results database table */}
Historical Runs
{benchmarks.length === 0 ? (
No benchmark data. Trigger a run to generate reports.
) : (
Availability / Success Rate (%)
{benchmarks.map(b => (
{b.test_name}
{b.has_protection ? "PROTECTED" : "UNPROTECTED"}
{new Date(b.timestamp).toLocaleString()}
Success: {(b.success_rate * 100).toFixed(1)}%
P95 Latency: {(b.p95_latency * 1000).toFixed(0)}ms
Requests: {b.total_requests}
))}
)}
)}
{/* Observability Hub */}
{activeTab === 'observability' && (
{/* Prometheus embedded Frame */}
{/* Grafana embedded Frame */}
)}
);
}