mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 16:31:13 -05:00
Create Rate Limit Admin Dashboard
Add a React admin dashboard component to visualize rate limit metrics and statistics, including data fetching from the rate-limit-metrics edge function, charts and statistics, and admin routes/integration. Includes setup for routing and UI scaffolding to display total requests, block rate, top blocked IPs/users, and recent activity with interactive charts.
This commit is contained in:
@@ -74,6 +74,7 @@ const AdminEmailSettings = lazy(() => import("./pages/admin/AdminEmailSettings")
|
||||
const ErrorMonitoring = lazy(() => import("./pages/admin/ErrorMonitoring"));
|
||||
const ErrorLookup = lazy(() => import("./pages/admin/ErrorLookup"));
|
||||
const TraceViewer = lazy(() => import("./pages/admin/TraceViewer"));
|
||||
const RateLimitMetrics = lazy(() => import("./pages/admin/RateLimitMetrics"));
|
||||
|
||||
// User routes (lazy-loaded)
|
||||
const Profile = lazy(() => import("./pages/Profile"));
|
||||
@@ -396,6 +397,14 @@ function AppContent(): React.JSX.Element {
|
||||
</AdminErrorBoundary>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/rate-limit-metrics"
|
||||
element={
|
||||
<AdminErrorBoundary section="Rate Limit Metrics">
|
||||
<RateLimitMetrics />
|
||||
</AdminErrorBoundary>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Utility routes - lazy loaded */}
|
||||
<Route path="/force-logout" element={<ForceLogout />} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LayoutDashboard, FileText, Flag, Users, Settings, ArrowLeft, ScrollText, BookOpen, Inbox, Mail, AlertTriangle } from 'lucide-react';
|
||||
import { LayoutDashboard, FileText, Flag, Users, Settings, ArrowLeft, ScrollText, BookOpen, Inbox, Mail, AlertTriangle, Shield } from 'lucide-react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { useUserRole } from '@/hooks/useUserRole';
|
||||
import { useSidebar } from '@/hooks/useSidebar';
|
||||
@@ -53,6 +53,11 @@ export function AdminSidebar() {
|
||||
url: '/admin/error-monitoring',
|
||||
icon: AlertTriangle,
|
||||
},
|
||||
{
|
||||
title: 'Rate Limit Metrics',
|
||||
url: '/admin/rate-limit-metrics',
|
||||
icon: Shield,
|
||||
},
|
||||
{
|
||||
title: 'Users',
|
||||
url: '/admin/users',
|
||||
|
||||
75
src/hooks/useRateLimitMetrics.ts
Normal file
75
src/hooks/useRateLimitMetrics.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
|
||||
export interface RateLimitMetric {
|
||||
timestamp: number;
|
||||
functionName: string;
|
||||
clientIP: string;
|
||||
userId?: string;
|
||||
allowed: boolean;
|
||||
remaining: number;
|
||||
retryAfter?: number;
|
||||
tier: string;
|
||||
}
|
||||
|
||||
export interface MetricsStats {
|
||||
totalRequests: number;
|
||||
allowedRequests: number;
|
||||
blockedRequests: number;
|
||||
blockRate: number;
|
||||
uniqueIPs: number;
|
||||
uniqueUsers: number;
|
||||
topBlockedIPs: Array<{ ip: string; count: number }>;
|
||||
topBlockedUsers: Array<{ userId: string; count: number }>;
|
||||
tierDistribution: Record<string, number>;
|
||||
}
|
||||
|
||||
interface MetricsQueryParams {
|
||||
action: 'stats' | 'recent' | 'function' | 'user' | 'ip';
|
||||
limit?: number;
|
||||
timeWindow?: number;
|
||||
functionName?: string;
|
||||
userId?: string;
|
||||
clientIP?: string;
|
||||
}
|
||||
|
||||
export function useRateLimitMetrics(params: MetricsQueryParams) {
|
||||
return useQuery({
|
||||
queryKey: ['rateLimitMetrics', params],
|
||||
queryFn: async () => {
|
||||
const queryParams = new URLSearchParams();
|
||||
queryParams.set('action', params.action);
|
||||
|
||||
if (params.limit) queryParams.set('limit', params.limit.toString());
|
||||
if (params.timeWindow) queryParams.set('timeWindow', params.timeWindow.toString());
|
||||
if (params.functionName) queryParams.set('functionName', params.functionName);
|
||||
if (params.userId) queryParams.set('userId', params.userId);
|
||||
if (params.clientIP) queryParams.set('clientIP', params.clientIP);
|
||||
|
||||
const { data, error } = await supabase.functions.invoke('rate-limit-metrics', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: queryParams,
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
},
|
||||
refetchInterval: 30000, // Refetch every 30 seconds
|
||||
staleTime: 15000, // Consider data stale after 15 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useRateLimitStats(timeWindow: number = 60000) {
|
||||
return useRateLimitMetrics({ action: 'stats', timeWindow });
|
||||
}
|
||||
|
||||
export function useRecentMetrics(limit: number = 100) {
|
||||
return useRateLimitMetrics({ action: 'recent', limit });
|
||||
}
|
||||
|
||||
export function useFunctionMetrics(functionName: string, limit: number = 100) {
|
||||
return useRateLimitMetrics({ action: 'function', functionName, limit });
|
||||
}
|
||||
337
src/pages/admin/RateLimitMetrics.tsx
Normal file
337
src/pages/admin/RateLimitMetrics.tsx
Normal file
@@ -0,0 +1,337 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useUserRole } from '@/hooks/useUserRole';
|
||||
import { useRateLimitStats, useRecentMetrics } from '@/hooks/useRateLimitMetrics';
|
||||
import { useDocumentTitle } from '@/hooks/useDocumentTitle';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line, Legend } from 'recharts';
|
||||
import { Activity, Shield, TrendingUp, Users, Clock, AlertTriangle } from 'lucide-react';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { format } from 'date-fns';
|
||||
|
||||
const COLORS = ['hsl(var(--primary))', 'hsl(var(--secondary))', 'hsl(var(--accent))', 'hsl(var(--muted))', 'hsl(var(--destructive))'];
|
||||
|
||||
export default function RateLimitMetrics() {
|
||||
useDocumentTitle('Rate Limit Metrics');
|
||||
const navigate = useNavigate();
|
||||
const { user } = useAuth();
|
||||
const { isModerator, loading: rolesLoading } = useUserRole();
|
||||
const [timeWindow, setTimeWindow] = useState(60000); // 1 minute default
|
||||
|
||||
const { data: stats, isLoading: statsLoading, error: statsError } = useRateLimitStats(timeWindow);
|
||||
const { data: recentData, isLoading: recentLoading } = useRecentMetrics(50);
|
||||
|
||||
// Redirect if not authorized
|
||||
if (!rolesLoading && !isModerator()) {
|
||||
navigate('/');
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user || rolesLoading) {
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
<Skeleton className="h-12 w-64" />
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<Skeleton key={i} className="h-32" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const recentMetrics = recentData?.metrics || [];
|
||||
|
||||
// Prepare chart data
|
||||
const tierData = stats?.tierDistribution ? Object.entries(stats.tierDistribution).map(([name, value]) => ({
|
||||
name,
|
||||
value,
|
||||
})) : [];
|
||||
|
||||
const topBlockedIPsData = stats?.topBlockedIPs || [];
|
||||
const topBlockedUsersData = stats?.topBlockedUsers || [];
|
||||
|
||||
// Calculate block rate percentage
|
||||
const blockRatePercentage = stats?.blockRate ? (stats.blockRate * 100).toFixed(1) : '0.0';
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Rate Limit Metrics</h1>
|
||||
<p className="text-muted-foreground">Monitor rate limiting activity and patterns</p>
|
||||
</div>
|
||||
<Select value={timeWindow.toString()} onValueChange={(v) => setTimeWindow(parseInt(v))}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Time window" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="60000">Last minute</SelectItem>
|
||||
<SelectItem value="300000">Last 5 minutes</SelectItem>
|
||||
<SelectItem value="900000">Last 15 minutes</SelectItem>
|
||||
<SelectItem value="3600000">Last hour</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{statsError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Failed to load metrics: {statsError instanceof Error ? statsError.message : 'Unknown error'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Overview Stats */}
|
||||
{statsLoading ? (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<Skeleton key={i} className="h-32" />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Requests</CardTitle>
|
||||
<Activity className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats?.totalRequests || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{stats?.allowedRequests || 0} allowed, {stats?.blockedRequests || 0} blocked
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Block Rate</CardTitle>
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{blockRatePercentage}%</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Percentage of blocked requests
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Unique IPs</CardTitle>
|
||||
<TrendingUp className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats?.uniqueIPs || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Distinct client addresses
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Unique Users</CardTitle>
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats?.uniqueUsers || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Authenticated users
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Tabs defaultValue="overview" className="space-y-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview">Overview</TabsTrigger>
|
||||
<TabsTrigger value="blocked">Blocked Requests</TabsTrigger>
|
||||
<TabsTrigger value="recent">Recent Activity</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="overview" className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Tier Distribution */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tier Distribution</CardTitle>
|
||||
<CardDescription>Requests by rate limit tier</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{tierData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={tierData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
labelLine={false}
|
||||
label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
|
||||
outerRadius={80}
|
||||
fill="hsl(var(--primary))"
|
||||
dataKey="value"
|
||||
>
|
||||
{tierData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
No data available
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Request Status */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Request Status</CardTitle>
|
||||
<CardDescription>Allowed vs blocked requests</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart
|
||||
data={[
|
||||
{ name: 'Allowed', count: stats?.allowedRequests || 0 },
|
||||
{ name: 'Blocked', count: stats?.blockedRequests || 0 },
|
||||
]}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="name" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Bar dataKey="count" fill="hsl(var(--primary))" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="blocked" className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Top Blocked IPs */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Top Blocked IPs</CardTitle>
|
||||
<CardDescription>Most frequently blocked IP addresses</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{topBlockedIPsData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={topBlockedIPsData} layout="vertical">
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis type="number" />
|
||||
<YAxis dataKey="ip" type="category" width={100} />
|
||||
<Tooltip />
|
||||
<Bar dataKey="count" fill="hsl(var(--destructive))" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
No blocked IPs in this time window
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Top Blocked Users */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Top Blocked Users</CardTitle>
|
||||
<CardDescription>Most frequently blocked authenticated users</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{topBlockedUsersData.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{topBlockedUsersData.map((user, idx) => (
|
||||
<div key={idx} className="flex items-center justify-between p-2 border rounded">
|
||||
<span className="text-sm font-mono truncate flex-1">{user.userId}</span>
|
||||
<Badge variant="destructive">{user.count}</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
No blocked users in this time window
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="recent" className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
<CardDescription>Last 50 rate limit checks</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{recentLoading ? (
|
||||
<div className="space-y-2">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-16" />
|
||||
))}
|
||||
</div>
|
||||
) : recentMetrics.length > 0 ? (
|
||||
<div className="space-y-2 max-h-[600px] overflow-y-auto">
|
||||
{recentMetrics.map((metric, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className={`flex items-center justify-between p-3 border rounded ${
|
||||
metric.allowed ? 'border-border' : 'border-destructive/50 bg-destructive/5'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-4 flex-1">
|
||||
<Clock className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-mono text-sm">{metric.functionName}</span>
|
||||
<Badge variant={metric.allowed ? 'secondary' : 'destructive'}>
|
||||
{metric.allowed ? 'Allowed' : 'Blocked'}
|
||||
</Badge>
|
||||
<Badge variant="outline">{metric.tier}</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
IP: {metric.clientIP} {metric.userId && `• User: ${metric.userId.slice(0, 8)}...`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-medium">
|
||||
{metric.allowed ? `${metric.remaining} left` : `Retry: ${metric.retryAfter}s`}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{format(new Date(metric.timestamp), 'HH:mm:ss')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
|
||||
No recent activity
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user