···
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cachet Analytics Dashboard</title>
7
-
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
7
+
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
8
+
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
···
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
18
-
background: #f5f5f5;
19
+
background: #f8fafc;
25
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
27
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
justify-content: space-between;
32
+
border-bottom: 1px solid #e2e8f0;
···
52
+
justify-content: center;
53
+
align-items: center;
53
-
padding: 0.5rem 1rem;
55
-
border: 1px solid #ddd;
60
+
padding: 0.75rem 1.25rem;
61
+
border: 1px solid #d1d5db;
65
+
font-size: 0.875rem;
67
+
transition: all 0.2s ease;
70
+
.controls select:hover,
71
+
.controls select:focus {
72
+
border-color: #3b82f6;
74
+
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
62
-
background: #3498db;
78
+
background: #3b82f6;
68
-
background: #2980b9;
84
+
background: #2563eb;
85
+
transform: translateY(-1px);
88
+
.controls button:disabled {
89
+
background: #9ca3af;
90
+
cursor: not-allowed;
···
88
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
110
+
border-radius: 12px;
111
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
113
+
border: 1px solid #e2e8f0;
114
+
transition: all 0.2s ease;
115
+
position: relative;
118
+
flex-direction: column;
119
+
justify-content: center;
124
+
transform: translateY(-2px);
125
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
128
+
.stat-card.loading {
132
+
.stat-card.loading::after {
134
+
position: absolute;
139
+
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
140
+
animation: shimmer 1.5s infinite;
143
+
@keyframes shimmer {
144
+
0% { left: -100%; }
145
+
100% { left: 100%; }
151
+
margin-bottom: 0.25rem;
152
+
word-break: break-word;
153
+
overflow-wrap: break-word;
156
+
/* Responsive font sizing using clamp() */
157
+
font-size: clamp(1.25rem, 4vw, 2.5rem);
166
+
/* Responsive font sizing for labels */
167
+
font-size: clamp(0.75rem, 2vw, 0.875rem);
170
+
/* Container query support for modern browsers */
171
+
@supports (container-type: inline-size) {
173
+
container-type: inline-size;
176
+
@container (max-width: 250px) {
178
+
font-size: 1.25rem;
181
+
font-size: 0.75rem;
185
+
@container (min-width: 300px) {
190
+
font-size: 0.875rem;
194
+
@container (min-width: 400px) {
···
211
+
@media (max-width: 480px) {
213
+
grid-template-columns: 1fr;
221
+
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
230
+
font-size: clamp(0.9rem, 4vw, 1.5rem) !important;
234
+
font-size: clamp(0.65rem, 2.5vw, 0.75rem) !important;
113
-
border-radius: 8px;
114
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
241
+
border-radius: 12px;
242
+
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
243
+
border: 1px solid #e2e8f0;
244
+
position: relative;
249
+
flex-direction: column;
252
+
.chart-container.loading {
254
+
align-items: center;
255
+
justify-content: center;
258
+
.chart-container.loading::before {
259
+
content: 'Loading chart...';
261
+
font-size: 0.875rem;
265
+
font-size: 1.125rem;
273
+
word-break: break-word;
274
+
overflow-wrap: break-word;
277
+
.chart-title-with-indicator {
279
+
align-items: center;
280
+
justify-content: space-between;
283
+
margin-bottom: 1rem;
286
+
.chart-title-with-indicator .chart-title {
294
+
text-align: center;
296
+
font-size: 0.875rem;
306
+
display: inline-block;
309
+
border: 3px solid #e2e8f0;
310
+
border-radius: 50%;
311
+
border-top-color: #3b82f6;
312
+
animation: spin 1s ease-in-out infinite;
313
+
margin-bottom: 1rem;
317
+
to { transform: rotate(360deg); }
130
-
background: #e74c3c;
321
+
background: #fef2f2;
133
-
border-radius: 4px;
324
+
border-radius: 8px;
326
+
border: 1px solid #fecaca;
141
-
justify-content: center;
333
+
font-size: 0.875rem;
.auto-refresh input[type="checkbox"] {
146
-
transform: scale(1.2);
338
+
transform: scale(1.1);
339
+
accent-color: #3b82f6;
342
+
.performance-indicator {
343
+
display: inline-flex;
344
+
align-items: center;
346
+
font-size: 0.75rem;
350
+
.performance-indicator.good { color: #059669; }
351
+
.performance-indicator.warning { color: #d97706; }
352
+
.performance-indicator.error { color: #dc2626; }
357
+
align-items: center;
358
+
justify-content: center;
359
+
background: #f8fafc;
360
+
border-radius: 8px;
364
+
.lazy-chart.visible {
365
+
background: transparent;
@media (max-width: 768px) {
···
385
+
flex-direction: column;
386
+
align-items: stretch;
395
+
font-size: clamp(1rem, 5vw, 1.75rem) !important;
399
+
font-size: clamp(0.7rem, 3vw, 0.8rem) !important;
409
+
flex-direction: column;
410
+
align-items: flex-start;
418
+
background: #1f2937;
420
+
padding: 0.75rem 1rem;
421
+
border-radius: 8px;
422
+
font-size: 0.875rem;
424
+
transform: translateX(100%);
425
+
transition: transform 0.3s ease;
429
+
transform: translateX(0);
433
+
background: #059669;
437
+
background: #dc2626;
···
<option value="7" selected>Last 7 days</option>
<option value="30">Last 30 days</option>
183
-
<button onclick="loadData()">Refresh</button>
458
+
<button id="refreshBtn" onclick="loadData()">Refresh</button>
<div class="auto-refresh">
<input type="checkbox" id="autoRefresh" />
<label for="autoRefresh">Auto-refresh (30s)</label>
190
-
<div id="loading" class="loading">Loading analytics data...</div>
465
+
<div id="loading" class="loading">
466
+
<div class="loading-spinner"></div>
467
+
Loading analytics data...
<div id="error" class="error" style="display: none"></div>
<div id="content" style="display: none">
472
+
<!-- Key Metrics Overview -->
<div class="chart-container" style="margin-bottom: 2rem; height: 450px">
195
-
<div class="chart-title">Traffic Overview - All Routes Over Time</div>
474
+
<div class="chart-title-with-indicator">
475
+
<div class="chart-title">Traffic Overview - All Routes Over Time</div>
476
+
<span class="performance-indicator" id="trafficPerformance"></span>
id="trafficOverviewChart"
style="padding-bottom: 2rem"
484
+
<!-- Stats Grid -->
203
-
<div class="stat-card">
486
+
<div class="stat-card" id="totalRequestsCard">
<div class="stat-number" id="totalRequests">-</div>
<div class="stat-label">Total Requests</div>
207
-
<div class="stat-card">
490
+
<div class="stat-card" id="avgResponseTimeCard">
<div class="stat-number" id="avgResponseTime">-</div>
<div class="stat-label">Avg Response Time (ms)</div>
211
-
<div class="stat-card">
494
+
<div class="stat-card" id="p95ResponseTimeCard">
<div class="stat-number" id="p95ResponseTime">-</div>
<div class="stat-label">P95 Response Time (ms)</div>
215
-
<div class="stat-card">
498
+
<div class="stat-card" id="uniqueEndpointsCard">
<div class="stat-number" id="uniqueEndpoints">-</div>
<div class="stat-label">Unique Endpoints</div>
219
-
<div class="stat-card">
502
+
<div class="stat-card" id="errorRateCard">
<div class="stat-number" id="errorRate">-</div>
<div class="stat-label">Error Rate (%)</div>
223
-
<div class="stat-card">
506
+
<div class="stat-card" id="fastRequestsCard">
<div class="stat-number" id="fastRequests">-</div>
<div class="stat-label">Fast Requests (<100ms)</div>
227
-
<div class="stat-card">
510
+
<div class="stat-card" id="uptimeCard">
<div class="stat-number" id="uptime">-</div>
<div class="stat-label">Uptime (%)</div>
231
-
<div class="stat-card">
514
+
<div class="stat-card" id="throughputCard">
<div class="stat-number" id="throughput">-</div>
<div class="stat-label">Throughput (req/hr)</div>
235
-
<div class="stat-card">
518
+
<div class="stat-card" id="apdexCard">
<div class="stat-number" id="apdex">-</div>
<div class="stat-label">APDEX Score</div>
239
-
<div class="stat-card">
522
+
<div class="stat-card" id="cacheHitRateCard">
<div class="stat-number" id="cacheHitRate">-</div>
<div class="stat-label">Cache Hit Rate (%)</div>
528
+
<!-- Peak Traffic Stats -->
246
-
<div class="stat-card">
530
+
<div class="stat-card" id="peakHourCard">
<div class="stat-number" id="peakHour">-</div>
<div class="stat-label">Peak Hour</div>
250
-
<div class="stat-card">
534
+
<div class="stat-card" id="peakHourRequestsCard">
<div class="stat-number" id="peakHourRequests">-</div>
<div class="stat-label">Peak Hour Requests</div>
254
-
<div class="stat-card">
538
+
<div class="stat-card" id="peakDayCard">
<div class="stat-number" id="peakDay">-</div>
<div class="stat-label">Peak Day</div>
258
-
<div class="stat-card">
542
+
<div class="stat-card" id="peakDayRequestsCard">
<div class="stat-number" id="peakDayRequests">-</div>
<div class="stat-label">Peak Day Requests</div>
262
-
<div class="stat-card">
546
+
<div class="stat-card" id="dashboardRequestsCard">
<div class="stat-number" id="dashboardRequests">-</div>
<div class="stat-label">Dashboard Requests</div>
552
+
<!-- Charts Grid with Lazy Loading -->
<div class="charts-grid">
269
-
<div class="chart-container">
554
+
<div class="chart-container lazy-chart" data-chart="timeChart">
<div class="chart-title">Requests Over Time</div>
<canvas id="timeChart"></canvas>
274
-
<div class="chart-container">
559
+
<div class="chart-container lazy-chart" data-chart="latencyTimeChart">
<div class="chart-title">Latency Over Time (Hourly)</div>
<canvas id="latencyTimeChart"></canvas>
279
-
<div class="chart-container">
564
+
<div class="chart-container lazy-chart" data-chart="latencyDistributionChart">
<div class="chart-title">Response Time Distribution</div>
<canvas id="latencyDistributionChart"></canvas>
284
-
<div class="chart-container">
569
+
<div class="chart-container lazy-chart" data-chart="percentilesChart">
<div class="chart-title">Latency Percentiles</div>
<canvas id="percentilesChart"></canvas>
289
-
<div class="chart-container">
574
+
<div class="chart-container lazy-chart" data-chart="endpointChart">
<div class="chart-title">Top Endpoints</div>
<canvas id="endpointChart"></canvas>
294
-
<div class="chart-container">
579
+
<div class="chart-container lazy-chart" data-chart="slowestEndpointsChart">
<div class="chart-title">Slowest Endpoints</div>
<canvas id="slowestEndpointsChart"></canvas>
299
-
<div class="chart-container">
584
+
<div class="chart-container lazy-chart" data-chart="statusChart">
<div class="chart-title">Status Codes</div>
<canvas id="statusChart"></canvas>
304
-
<div class="chart-container">
589
+
<div class="chart-container lazy-chart" data-chart="userAgentChart">
<div class="chart-title">Top User Agents</div>
<canvas id="userAgentChart"></canvas>
···
600
+
let currentData = null;
601
+
let isLoading = false;
602
+
let visibleCharts = new Set();
603
+
let intersectionObserver;
605
+
// Performance monitoring
606
+
const performance = {
612
+
// Initialize intersection observer for lazy loading
613
+
function initLazyLoading() {
614
+
intersectionObserver = new IntersectionObserver((entries) => {
615
+
entries.forEach(entry => {
616
+
if (entry.isIntersecting) {
617
+
const chartContainer = entry.target;
618
+
const chartType = chartContainer.dataset.chart;
620
+
if (!visibleCharts.has(chartType) && currentData) {
621
+
visibleCharts.add(chartType);
622
+
chartContainer.classList.add('visible');
623
+
loadChart(chartType, currentData);
628
+
rootMargin: '50px',
632
+
// Observe all lazy chart containers
633
+
document.querySelectorAll('.lazy-chart').forEach(container => {
634
+
intersectionObserver.observe(container);
638
+
// Show toast notification
639
+
function showToast(message, type = 'info') {
640
+
const toast = document.createElement('div');
641
+
toast.className = `toast ${type}`;
642
+
toast.textContent = message;
643
+
document.body.appendChild(toast);
645
+
setTimeout(() => toast.classList.add('show'), 100);
647
+
toast.classList.remove('show');
648
+
setTimeout(() => document.body.removeChild(toast), 300);
652
+
// Update loading states for stat cards
653
+
function setStatCardLoading(cardId, loading) {
654
+
const card = document.getElementById(cardId);
657
+
card.classList.add('loading');
659
+
card.classList.remove('loading');
664
+
// Debounced resize handler for charts
666
+
function handleResize() {
667
+
clearTimeout(resizeTimeout);
668
+
resizeTimeout = setTimeout(() => {
669
+
Object.values(charts).forEach(chart => {
670
+
if (chart && typeof chart.resize === 'function') {
677
+
window.addEventListener('resize', handleResize);
async function loadData() {
680
+
if (isLoading) return;
683
+
performance.startTime = Date.now();
const days = document.getElementById("daysSelect").value;
const loading = document.getElementById("loading");
const error = document.getElementById("error");
const content = document.getElementById("content");
689
+
const refreshBtn = document.getElementById("refreshBtn");
loading.style.display = "block";
error.style.display = "none";
content.style.display = "none";
695
+
refreshBtn.disabled = true;
696
+
refreshBtn.textContent = "Loading...";
698
+
// Set all stat cards to loading state
699
+
const statCards = [
700
+
'totalRequestsCard', 'avgResponseTimeCard', 'p95ResponseTimeCard',
701
+
'uniqueEndpointsCard', 'errorRateCard', 'fastRequestsCard',
702
+
'uptimeCard', 'throughputCard', 'apdexCard', 'cacheHitRateCard',
703
+
'peakHourCard', 'peakHourRequestsCard', 'peakDayCard',
704
+
'peakDayRequestsCard', 'dashboardRequestsCard'
706
+
statCards.forEach(cardId => setStatCardLoading(cardId, true));
const response = await fetch(`/stats?days=${days}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
713
+
currentData = data;
715
+
performance.endTime = Date.now();
716
+
performance.loadTime = performance.endTime - performance.startTime;
loading.style.display = "none";
content.style.display = "block";
723
+
showToast(`Dashboard updated in ${performance.loadTime}ms`, 'success');
loading.style.display = "none";
error.style.display = "block";
error.textContent = `Failed to load data: ${err.message}`;
728
+
showToast(`Error: ${err.message}`, 'error');
731
+
refreshBtn.disabled = false;
732
+
refreshBtn.textContent = "Refresh";
734
+
// Remove loading state from stat cards
735
+
statCards.forEach(cardId => setStatCardLoading(cardId, false));
function updateDashboard(data) {
344
-
document.getElementById("totalRequests").textContent =
345
-
data.totalRequests.toLocaleString();
346
-
document.getElementById("avgResponseTime").textContent =
347
-
data.averageResponseTime
348
-
? Math.round(data.averageResponseTime)
350
-
document.getElementById("p95ResponseTime").textContent = data
351
-
.latencyAnalytics.percentiles.p95
352
-
? Math.round(data.latencyAnalytics.percentiles.p95)
354
-
document.getElementById("uniqueEndpoints").textContent =
355
-
data.requestsByEndpoint.length;
740
+
// Update main metrics with animation
741
+
updateStatWithAnimation("totalRequests", data.totalRequests.toLocaleString());
742
+
updateStatWithAnimation("avgResponseTime",
743
+
data.averageResponseTime ? Math.round(data.averageResponseTime) : "N/A");
744
+
updateStatWithAnimation("p95ResponseTime",
745
+
data.latencyAnalytics.percentiles.p95 ? Math.round(data.latencyAnalytics.percentiles.p95) : "N/A");
746
+
updateStatWithAnimation("uniqueEndpoints", data.requestsByEndpoint.length);
const errorRequests = data.requestsByStatus
.filter((s) => s.status >= 400)
.reduce((sum, s) => sum + s.count, 0);
361
-
data.totalRequests > 0
362
-
? ((errorRequests / data.totalRequests) * 100).toFixed(1)
364
-
document.getElementById("errorRate").textContent = errorRate;
751
+
const errorRate = data.totalRequests > 0
752
+
? ((errorRequests / data.totalRequests) * 100).toFixed(1)
754
+
updateStatWithAnimation("errorRate", errorRate);
// Calculate fast requests percentage
const fastRequestsData = data.latencyAnalytics.distribution
.filter((d) => d.range === "0-50ms" || d.range === "50-100ms")
.reduce((sum, d) => sum + d.percentage, 0);
370
-
document.getElementById("fastRequests").textContent =
371
-
fastRequestsData.toFixed(1) + "%";
760
+
updateStatWithAnimation("fastRequests", fastRequestsData.toFixed(1) + "%");
374
-
document.getElementById("uptime").textContent =
375
-
data.performanceMetrics.uptime.toFixed(1);
376
-
document.getElementById("throughput").textContent = Math.round(
377
-
data.performanceMetrics.throughput,
379
-
document.getElementById("apdex").textContent =
380
-
data.performanceMetrics.apdex.toFixed(2);
381
-
document.getElementById("cacheHitRate").textContent =
382
-
data.performanceMetrics.cachehitRate.toFixed(1);
763
+
updateStatWithAnimation("uptime", data.performanceMetrics.uptime.toFixed(1));
764
+
updateStatWithAnimation("throughput", Math.round(data.performanceMetrics.throughput));
765
+
updateStatWithAnimation("apdex", data.performanceMetrics.apdex.toFixed(2));
766
+
updateStatWithAnimation("cacheHitRate", data.performanceMetrics.cachehitRate.toFixed(1));
385
-
document.getElementById("peakHour").textContent =
386
-
data.peakTraffic.peakHour;
387
-
document.getElementById("peakHourRequests").textContent =
388
-
data.peakTraffic.peakRequests.toLocaleString();
389
-
document.getElementById("peakDay").textContent =
390
-
data.peakTraffic.peakDay;
391
-
document.getElementById("peakDayRequests").textContent =
392
-
data.peakTraffic.peakDayRequests.toLocaleString();
769
+
updateStatWithAnimation("peakHour", data.peakTraffic.peakHour);
770
+
updateStatWithAnimation("peakHourRequests", data.peakTraffic.peakRequests.toLocaleString());
771
+
updateStatWithAnimation("peakDay", data.peakTraffic.peakDay);
772
+
updateStatWithAnimation("peakDayRequests", data.peakTraffic.peakDayRequests.toLocaleString());
773
+
updateStatWithAnimation("dashboardRequests", data.dashboardMetrics.statsRequests.toLocaleString());
775
+
// Update performance indicator
776
+
updatePerformanceIndicator(data);
778
+
// Load main traffic overview chart immediately
779
+
const days = parseInt(document.getElementById("daysSelect").value);
780
+
updateTrafficOverviewChart(data.trafficOverview, days);
782
+
// Other charts will be loaded lazily when they come into view
785
+
function updateStatWithAnimation(elementId, value) {
786
+
const element = document.getElementById(elementId);
787
+
if (element && element.textContent !== value.toString()) {
788
+
element.style.transform = 'scale(1.1)';
789
+
element.style.transition = 'transform 0.2s ease';
792
+
element.textContent = value;
793
+
element.style.transform = 'scale(1)';
798
+
function updatePerformanceIndicator(data) {
799
+
const indicator = document.getElementById('trafficPerformance');
800
+
const avgResponseTime = data.averageResponseTime || 0;
801
+
const errorRate = data.requestsByStatus
802
+
.filter((s) => s.status >= 400)
803
+
.reduce((sum, s) => sum + s.count, 0) / data.totalRequests * 100;
806
+
if (avgResponseTime < 100 && errorRate < 1) {
808
+
text = '🟢 Excellent';
809
+
} else if (avgResponseTime < 300 && errorRate < 5) {
810
+
status = 'warning';
814
+
text = '🔴 Needs Attention';
394
-
// Dashboard metrics
395
-
document.getElementById("dashboardRequests").textContent =
396
-
data.dashboardMetrics.statsRequests.toLocaleString();
817
+
indicator.className = `performance-indicator ${status}`;
818
+
indicator.textContent = text;
398
-
// Determine if we're showing hourly or daily data
821
+
// Load individual charts (called by intersection observer)
822
+
function loadChart(chartType, data) {
const days = parseInt(document.getElementById("daysSelect").value);
const isHourly = days === 1;
402
-
updateTrafficOverviewChart(data.trafficOverview, days);
403
-
updateTimeChart(data.requestsByDay, isHourly);
404
-
updateLatencyTimeChart(data.latencyAnalytics.latencyOverTime, isHourly);
405
-
updateLatencyDistributionChart(data.latencyAnalytics.distribution);
406
-
updatePercentilesChart(data.latencyAnalytics.percentiles);
407
-
updateEndpointChart(data.requestsByEndpoint.slice(0, 10));
408
-
updateSlowestEndpointsChart(data.latencyAnalytics.slowestEndpoints);
409
-
updateStatusChart(data.requestsByStatus);
410
-
updateUserAgentChart(data.topUserAgents.slice(0, 5));
827
+
switch(chartType) {
829
+
updateTimeChart(data.requestsByDay, isHourly);
831
+
case 'latencyTimeChart':
832
+
updateLatencyTimeChart(data.latencyAnalytics.latencyOverTime, isHourly);
834
+
case 'latencyDistributionChart':
835
+
updateLatencyDistributionChart(data.latencyAnalytics.distribution);
837
+
case 'percentilesChart':
838
+
updatePercentilesChart(data.latencyAnalytics.percentiles);
840
+
case 'endpointChart':
841
+
updateEndpointChart(data.requestsByEndpoint.slice(0, 10));
843
+
case 'slowestEndpointsChart':
844
+
updateSlowestEndpointsChart(data.latencyAnalytics.slowestEndpoints);
846
+
case 'statusChart':
847
+
updateStatusChart(data.requestsByStatus);
849
+
case 'userAgentChart':
850
+
updateUserAgentChart(data.topUserAgents.slice(0, 5));
854
+
console.error(`Error loading chart ${chartType}:`, error);
855
+
const container = document.querySelector(`[data-chart="${chartType}"]`);
857
+
container.innerHTML = `<div class="chart-error">Error loading chart: ${error.message}</div>`;
function updateTrafficOverviewChart(data, days) {
414
-
const ctx = document
415
-
.getElementById("trafficOverviewChart")
863
+
const canvas = document.getElementById("trafficOverviewChart");
865
+
console.warn('trafficOverviewChart canvas not found');
869
+
const ctx = canvas.getContext("2d");
871
+
console.warn('Could not get 2d context for trafficOverviewChart');
418
-
if (charts.trafficOverview) charts.trafficOverview.destroy();
875
+
if (charts.trafficOverview) {
876
+
charts.trafficOverview.destroy();
// Update chart title based on granularity
421
-
const chartTitle = document
422
-
.querySelector("#trafficOverviewChart")
423
-
.parentElement.querySelector(".chart-title");
880
+
const chartTitleElement = document.querySelector(".chart-title-with-indicator .chart-title");
let titleText = "Traffic Overview - All Routes Over Time";
titleText += " (Hourly)";
···
432
-
chartTitle.textContent = titleText;
889
+
if (chartTitleElement) {
890
+
chartTitleElement.textContent = titleText;
// Get all unique routes across all time periods
const allRoutes = new Set();
···
// Define colors for different route types
444
-
Dashboard: "#3498db",
445
-
"User Data": "#2ecc71",
446
-
"User Redirects": "#27ae60",
447
-
"Emoji Data": "#e74c3c",
448
-
"Emoji Redirects": "#c0392b",
449
-
"Emoji List": "#e67e22",
450
-
"Health Check": "#f39c12",
451
-
"API Documentation": "#9b59b6",
452
-
"Cache Management": "#34495e",
903
+
Dashboard: "#3b82f6",
904
+
"User Data": "#10b981",
905
+
"User Redirects": "#059669",
906
+
"Emoji Data": "#ef4444",
907
+
"Emoji Redirects": "#dc2626",
908
+
"Emoji List": "#f97316",
909
+
"Health Check": "#f59e0b",
910
+
"API Documentation": "#8b5cf6",
911
+
"Cache Management": "#6b7280",
// Create datasets for each route
const datasets = Array.from(allRoutes).map((route) => {
457
-
const color = routeColors[route] || "#95a5a6";
916
+
const color = routeColors[route] || "#9ca3af";
data: data.map((timePoint) => timePoint.routes[route] || 0),
462
-
backgroundColor: color + "20", // Add transparency
921
+
backgroundColor: color + "20",
···
// Format labels based on time granularity
const labels = data.map((timePoint) => {
473
-
// Show just hour for 24h view
return timePoint.time.split(" ")[1] || timePoint.time;
476
-
// Show day and hour for 7-day view
const parts = timePoint.time.split(" ");
478
-
const date = parts[0].split("-")[2]; // Get day
935
+
const date = parts[0].split("-")[2];
const hour = parts[1] || "00:00";
return `${date} ${hour}`;
482
-
// Show full date for longer periods
···
maintainAspectRatio: false,
962
+
easing: 'easeInOutQuart'
···
979
+
generateLabels: function(chart) {
980
+
const original = Chart.defaults.plugins.legend.labels.generateLabels;
981
+
const labels = original.call(this, chart);
983
+
// Add total request count to legend labels
984
+
labels.forEach((label, index) => {
985
+
const dataset = chart.data.datasets[index];
986
+
const total = dataset.data.reduce((sum, val) => sum + val, 0);
987
+
label.text += ` (${total.toLocaleString()})`;
997
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
998
+
titleColor: 'white',
999
+
bodyColor: 'white',
1000
+
borderColor: 'rgba(255, 255, 255, 0.1)',
515
-
afterLabel: function (context) {
516
-
const timePoint = data[context.dataIndex];
517
-
return `Total: ${timePoint.total} requests`;
1003
+
title: function(context) {
1004
+
return `Time: ${context[0].label}`;
1006
+
afterBody: function(context) {
1007
+
const timePoint = data[context[0].dataIndex];
1009
+
`Total Requests: ${timePoint.total.toLocaleString()}`,
1010
+
`Peak Route: ${Object.entries(timePoint.routes).sort((a, b) => b[1] - a[1])[0]?.[0] || 'N/A'}`
···
text: days === 1 ? "Hour" : days <= 7 ? "Day & Hour" : "Date",
1027
+
maxTicksLimit: window.innerWidth < 768 ? 8 : 20,
1028
+
maxRotation: 0, // Don't rotate labels
1030
+
callback: function(value, index, values) {
1031
+
const label = this.getLabelForValue(value);
1032
+
// Truncate long labels
1033
+
if (label.length > 8) {
1035
+
return label; // Hours are usually short
1037
+
// For longer periods, abbreviate
1038
+
return label.substring(0, 6) + '...';
1045
+
color: 'rgba(0, 0, 0, 0.05)',
···
1059
+
color: 'rgba(0, 0, 0, 0.05)',
1062
+
callback: function(value) {
1063
+
return value.toLocaleString();
function updateTimeChart(data, isHourly) {
552
-
const ctx = document.getElementById("timeChart").getContext("2d");
1083
+
const canvas = document.getElementById("timeChart");
1085
+
console.warn('timeChart canvas not found');
1089
+
const ctx = canvas.getContext("2d");
1091
+
console.warn('Could not get 2d context for timeChart');
if (charts.time) charts.time.destroy();
556
-
// Update chart title
const chartTitle = document
.querySelector("#timeChart")
.parentElement.querySelector(".chart-title");
560
-
chartTitle.textContent = isHourly
561
-
? "Requests Over Time (Hourly)"
562
-
: "Requests Over Time (Daily)";
1101
+
chartTitle.textContent = isHourly
1102
+
? "Requests Over Time (Hourly)"
1103
+
: "Requests Over Time (Daily)";
charts.time = new Chart(ctx, {
···
data: data.map((d) => d.count),
572
-
borderColor: "#3498db",
573
-
backgroundColor: "rgba(52, 152, 219, 0.1)",
1114
+
borderColor: "#3b82f6",
1115
+
backgroundColor: "rgba(59, 130, 246, 0.1)",
1119
+
pointHoverRadius: 6,
1120
+
pointBackgroundColor: "#3b82f6",
1121
+
pointBorderColor: "#ffffff",
1122
+
pointBorderWidth: 2,
1128
+
maintainAspectRatio: false,
1134
+
bottom: 50 // Extra space for rotated labels
1139
+
easing: 'easeInOutQuart'
1143
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
1144
+
titleColor: 'white',
1145
+
bodyColor: 'white',
1146
+
borderColor: 'rgba(255, 255, 255, 0.1)',
1149
+
title: function(context) {
1150
+
const point = data[context[0].dataIndex];
1151
+
return isHourly ? `Hour: ${context[0].label}` : `Date: ${context[0].label}`;
1153
+
label: function(context) {
1154
+
const point = data[context.dataIndex];
1156
+
`Requests: ${context.parsed.y.toLocaleString()}`,
1157
+
`Avg Response Time: ${Math.round(point.averageResponseTime || 0)}ms`
1164
+
generateLabels: function(chart) {
1165
+
const total = data.reduce((sum, d) => sum + d.count, 0);
1166
+
const avg = Math.round(data.reduce((sum, d) => sum + (d.averageResponseTime || 0), 0) / data.length);
1168
+
text: `Requests (Total: ${total.toLocaleString()}, Avg RT: ${avg}ms)`,
1169
+
fillStyle: '#3b82f6',
1170
+
strokeStyle: '#3b82f6',
1172
+
pointStyle: 'circle'
1182
+
text: isHourly ? 'Hour of Day' : 'Date',
1183
+
font: { weight: 'bold' }
1186
+
maxTicksLimit: window.innerWidth < 768 ? 6 : 12,
1187
+
maxRotation: 0, // Don't rotate labels
1189
+
callback: function(value, index, values) {
1190
+
const label = this.getLabelForValue(value);
1191
+
// Truncate long labels for better fit
1193
+
return label; // Hours are short
1195
+
// For dates, show abbreviated format
1196
+
const date = new Date(label);
1197
+
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
1202
+
color: 'rgba(0, 0, 0, 0.05)',
1208
+
text: 'Number of Requests',
1209
+
font: { weight: 'bold' }
1213
+
color: 'rgba(0, 0, 0, 0.05)',
1216
+
callback: function(value) {
1217
+
return value.toLocaleString();
···
function updateEndpointChart(data) {
591
-
const ctx = document.getElementById("endpointChart").getContext("2d");
1227
+
const canvas = document.getElementById("endpointChart");
1229
+
console.warn('endpointChart canvas not found');
1233
+
const ctx = canvas.getContext("2d");
1235
+
console.warn('Could not get 2d context for endpointChart');
if (charts.endpoint) charts.endpoint.destroy();
···
data: data.map((d) => d.count),
603
-
backgroundColor: "#2ecc71",
1249
+
backgroundColor: "#10b981",
1256
+
maintainAspectRatio: false,
1262
+
bottom: 60 // Extra space for labels
1267
+
easing: 'easeInOutQuart'
1274
+
text: 'Endpoints',
1275
+
font: { weight: 'bold' }
1278
+
maxRotation: 0, // Don't rotate
1280
+
callback: function(value, index, values) {
1281
+
const label = this.getLabelForValue(value);
1282
+
// Truncate long labels but show full in tooltip
1283
+
return label.length > 12 ? label.substring(0, 9) + '...' : label;
1287
+
color: 'rgba(0, 0, 0, 0.05)',
1293
+
text: 'Number of Requests',
1294
+
font: { weight: 'bold' }
1298
+
color: 'rgba(0, 0, 0, 0.05)',
1301
+
callback: function(value) {
1302
+
return value.toLocaleString();
1309
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
1310
+
titleColor: 'white',
1311
+
bodyColor: 'white',
1312
+
borderColor: 'rgba(255, 255, 255, 0.1)',
1315
+
title: function(context) {
1316
+
return context[0].label; // Show full label in tooltip
1318
+
label: function(context) {
1319
+
return `Requests: ${context.parsed.y.toLocaleString()}`;
1325
+
generateLabels: function(chart) {
1326
+
const total = data.reduce((sum, d) => sum + d.count, 0);
1328
+
text: `Total Requests: ${total.toLocaleString()}`,
1329
+
fillStyle: '#10b981',
1330
+
strokeStyle: '#10b981',
1332
+
pointStyle: 'rect'
···
if (charts.status) charts.status.destroy();
const colors = data.map((d) => {
625
-
if (d.status >= 200 && d.status < 300) return "#2ecc71";
626
-
if (d.status >= 300 && d.status < 400) return "#f39c12";
627
-
if (d.status >= 400 && d.status < 500) return "#e74c3c";
1348
+
if (d.status >= 200 && d.status < 300) return "#10b981";
1349
+
if (d.status >= 300 && d.status < 400) return "#f59e0b";
1350
+
if (d.status >= 400 && d.status < 500) return "#ef4444";
charts.status = new Chart(ctx, {
···
data: data.map((d) => d.count),
1363
+
borderColor: '#fff'
1371
+
easing: 'easeInOutQuart'
···
data: data.map((d) => d.count),
1402
+
borderColor: '#fff'
1410
+
easing: 'easeInOutQuart'
function updateLatencyTimeChart(data, isHourly) {
682
-
const ctx = document
683
-
.getElementById("latencyTimeChart")
1417
+
const ctx = document.getElementById("latencyTimeChart").getContext("2d");
if (charts.latencyTime) charts.latencyTime.destroy();
688
-
// Update chart title
const chartTitle = document
.querySelector("#latencyTimeChart")
.parentElement.querySelector(".chart-title");
692
-
chartTitle.textContent = isHourly
693
-
? "Latency Over Time (Hourly)"
694
-
: "Latency Over Time (Daily)";
1425
+
chartTitle.textContent = isHourly
1426
+
? "Latency Over Time (Hourly)"
1427
+
: "Latency Over Time (Daily)";
charts.latencyTime = new Chart(ctx, {
···
label: "Average Response Time",
data: data.map((d) => d.averageResponseTime),
704
-
borderColor: "#3498db",
705
-
backgroundColor: "rgba(52, 152, 219, 0.1)",
1438
+
borderColor: "#3b82f6",
1439
+
backgroundColor: "rgba(59, 130, 246, 0.1)",
1443
+
pointHoverRadius: 6,
1444
+
pointBackgroundColor: "#3b82f6",
1445
+
pointBorderColor: "#ffffff",
1446
+
pointBorderWidth: 2,
label: "P95 Response Time",
data: data.map((d) => d.p95),
712
-
borderColor: "#e74c3c",
713
-
backgroundColor: "rgba(231, 76, 60, 0.1)",
1451
+
borderColor: "#ef4444",
1452
+
backgroundColor: "rgba(239, 68, 68, 0.1)",
1456
+
pointHoverRadius: 6,
1457
+
pointBackgroundColor: "#ef4444",
1458
+
pointBorderColor: "#ffffff",
1459
+
pointBorderWidth: 2,
1465
+
maintainAspectRatio: false,
1476
+
easing: 'easeInOutQuart'
1480
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
1481
+
titleColor: 'white',
1482
+
bodyColor: 'white',
1483
+
borderColor: 'rgba(255, 255, 255, 0.1)',
1486
+
title: function(context) {
1487
+
return isHourly ? `Hour: ${context[0].label}` : `Date: ${context[0].label}`;
1489
+
afterBody: function(context) {
1490
+
const point = data[context[0].dataIndex];
1492
+
`Request Count: ${point.count.toLocaleString()}`,
1493
+
`Performance: ${point.averageResponseTime < 100 ? 'Excellent' : point.averageResponseTime < 300 ? 'Good' : 'Needs Attention'}`
1500
+
generateLabels: function(chart) {
1501
+
const avgAvg = Math.round(data.reduce((sum, d) => sum + d.averageResponseTime, 0) / data.length);
1502
+
const avgP95 = Math.round(data.reduce((sum, d) => sum + (d.p95 || 0), 0) / data.length);
1505
+
text: `Average Response Time (Overall: ${avgAvg}ms)`,
1506
+
fillStyle: '#3b82f6',
1507
+
strokeStyle: '#3b82f6',
1509
+
pointStyle: 'circle'
1512
+
text: `P95 Response Time (Overall: ${avgP95}ms)`,
1513
+
fillStyle: '#ef4444',
1514
+
strokeStyle: '#ef4444',
1516
+
pointStyle: 'circle'
1527
+
text: isHourly ? 'Hour of Day' : 'Date',
1528
+
font: { weight: 'bold' }
1531
+
maxTicksLimit: window.innerWidth < 768 ? 6 : 12,
1534
+
callback: function(value, index, values) {
1535
+
const label = this.getLabelForValue(value);
1539
+
const date = new Date(label);
1540
+
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
1545
+
color: 'rgba(0, 0, 0, 0.05)',
text: "Response Time (ms)",
1552
+
font: { weight: 'bold' }
1554
+
beginAtZero: true,
1556
+
color: 'rgba(0, 0, 0, 0.05)',
1559
+
callback: function(value) {
1560
+
return Math.round(value) + 'ms';
···
function updateLatencyDistributionChart(data) {
735
-
const ctx = document
736
-
.getElementById("latencyDistributionChart")
1570
+
const ctx = document.getElementById("latencyDistributionChart").getContext("2d");
if (charts.latencyDistribution) charts.latencyDistribution.destroy();
···
data: data.map((d) => d.count),
749
-
backgroundColor: "#2ecc71",
1582
+
backgroundColor: "#10b981",
1591
+
easing: 'easeInOutQuart'
···
function updatePercentilesChart(percentiles) {
765
-
const ctx = document
766
-
.getElementById("percentilesChart")
1603
+
const ctx = document.getElementById("percentilesChart").getContext("2d");
if (charts.percentiles) charts.percentiles.destroy();
772
-
{ label: "P50", value: percentiles.p50 },
1608
+
{ label: "P50 (Median)", value: percentiles.p50 },
{ label: "P75", value: percentiles.p75 },
{ label: "P90", value: percentiles.p90 },
{ label: "P95", value: percentiles.p95 },
···
label: "Response Time (ms)",
data: data.map((d) => d.value),
1624
+
"#10b981", // P50 - Green (good)
1625
+
"#3b82f6", // P75 - Blue
1626
+
"#f59e0b", // P90 - Yellow (warning)
1627
+
"#ef4444", // P95 - Red (concerning)
1628
+
"#8b5cf6", // P99 - Purple (critical)
1632
+
borderColor: '#ffffff',
1638
+
maintainAspectRatio: false,
1641
+
easing: 'easeInOutQuart'
1645
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
1646
+
titleColor: 'white',
1647
+
bodyColor: 'white',
1648
+
borderColor: 'rgba(255, 255, 255, 0.1)',
1651
+
label: function(context) {
1652
+
const percentile = context.label;
1653
+
const value = Math.round(context.parsed.y);
1654
+
let interpretation = '';
1656
+
if (percentile.includes('P50')) {
1657
+
interpretation = '50% of requests are faster than this';
1658
+
} else if (percentile.includes('P95')) {
1659
+
interpretation = '95% of requests are faster than this';
1660
+
} else if (percentile.includes('P99')) {
1661
+
interpretation = '99% of requests are faster than this';
1665
+
`${percentile}: ${value}ms`,
1672
+
display: false // Hide legend since colors are self-explanatory
1679
+
text: 'Response Time Percentiles',
1680
+
font: { weight: 'bold' }
1683
+
color: 'rgba(0, 0, 0, 0.05)',
1689
+
text: 'Response Time (ms)',
1690
+
font: { weight: 'bold' }
1694
+
color: 'rgba(0, 0, 0, 0.05)',
1697
+
callback: function(value) {
1698
+
return Math.round(value) + 'ms';
···
function updateSlowestEndpointsChart(data) {
809
-
const ctx = document
810
-
.getElementById("slowestEndpointsChart")
1708
+
const ctx = document.getElementById("slowestEndpointsChart").getContext("2d");
if (charts.slowestEndpoints) charts.slowestEndpoints.destroy();
···
label: "Avg Response Time (ms)",
data: data.map((d) => d.averageResponseTime),
823
-
backgroundColor: "#e74c3c",
1720
+
backgroundColor: "#ef4444",
1727
+
maintainAspectRatio: false,
1730
+
easing: 'easeInOutQuart'
1732
+
indexAxis: "x", // Changed from "y" to "x" to put labels on top
1737
+
text: 'Endpoints',
1738
+
font: { weight: 'bold' }
1743
+
callback: function(value, index, values) {
1744
+
const label = this.getLabelForValue(value);
1745
+
return label.length > 15 ? label.substring(0, 12) + '...' : label;
1749
+
color: 'rgba(0, 0, 0, 0.05)',
1755
+
text: 'Response Time (ms)',
1756
+
font: { weight: 'bold' }
1760
+
color: 'rgba(0, 0, 0, 0.05)',
1763
+
callback: function(value) {
1764
+
return Math.round(value) + 'ms';
1771
+
backgroundColor: 'rgba(0, 0, 0, 0.8)',
1772
+
titleColor: 'white',
1773
+
bodyColor: 'white',
1774
+
borderColor: 'rgba(255, 255, 255, 0.1)',
1777
+
title: function(context) {
1778
+
return context[0].label; // Show full label in tooltip
1780
+
label: function(context) {
1781
+
const point = data[context.dataIndex];
1783
+
`Avg Response Time: ${Math.round(context.parsed.y)}ms`,
1784
+
`Request Count: ${point.count.toLocaleString()}`
1791
+
generateLabels: function(chart) {
1792
+
const avgTime = Math.round(data.reduce((sum, d) => sum + d.averageResponseTime, 0) / data.length);
1794
+
text: `Average Response Time: ${avgTime}ms`,
1795
+
fillStyle: '#ef4444',
1796
+
strokeStyle: '#ef4444',
1798
+
pointStyle: 'rect'
840
-
.getElementById("autoRefresh")
841
-
.addEventListener("change", function () {
842
-
if (this.checked) {
843
-
autoRefreshInterval = setInterval(loadData, 30000);
845
-
clearInterval(autoRefreshInterval);
1808
+
document.getElementById("autoRefresh").addEventListener("change", function () {
1809
+
if (this.checked) {
1810
+
autoRefreshInterval = setInterval(loadData, 30000);
1811
+
showToast('Auto-refresh enabled', 'success');
1813
+
clearInterval(autoRefreshInterval);
1814
+
showToast('Auto-refresh disabled', 'info');
1818
+
// Days selector change handler
1819
+
document.getElementById("daysSelect").addEventListener("change", function() {
1820
+
// Reset visible charts when changing time period
1821
+
visibleCharts.clear();
1825
+
// Initialize dashboard
1826
+
document.addEventListener('DOMContentLoaded', function() {
1827
+
initLazyLoading();
1831
+
// Cleanup on page unload
1832
+
window.addEventListener('beforeunload', function() {
1833
+
if (intersectionObserver) {
1834
+
intersectionObserver.disconnect();
1836
+
clearInterval(autoRefreshInterval);
1838
+
// Destroy all charts to prevent memory leaks
1839
+
Object.values(charts).forEach(chart => {
1840
+
if (chart && typeof chart.destroy === 'function') {
851
-
.getElementById("daysSelect")
852
-
.addEventListener("change", loadData);