Monitor rate limits progress

Implement monitor-rate-limits edge function to compare metrics against alert configurations, trigger notifications, and record alerts; update config and groundwork for admin UI integration.
This commit is contained in:
gpt-engineer-app[bot]
2025-11-11 00:19:13 +00:00
parent 677d0980dd
commit 28fa2fd0d4
6 changed files with 873 additions and 1 deletions

View File

@@ -0,0 +1,173 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
export interface AlertConfig {
id: string;
metric_type: 'block_rate' | 'total_requests' | 'unique_ips' | 'function_specific';
threshold_value: number;
time_window_ms: number;
function_name?: string;
enabled: boolean;
created_at: string;
updated_at: string;
}
export interface Alert {
id: string;
config_id: string;
metric_type: string;
metric_value: number;
threshold_value: number;
time_window_ms: number;
function_name?: string;
alert_message: string;
resolved_at?: string;
created_at: string;
}
export function useAlertConfigs() {
return useQuery({
queryKey: ['rateLimitAlertConfigs'],
queryFn: async () => {
const { data, error } = await supabase
.from('rate_limit_alert_config')
.select('*')
.order('metric_type');
if (error) throw error;
return data as AlertConfig[];
},
});
}
export function useAlertHistory(limit: number = 50) {
return useQuery({
queryKey: ['rateLimitAlerts', limit],
queryFn: async () => {
const { data, error } = await supabase
.from('rate_limit_alerts')
.select('*')
.order('created_at', { ascending: false })
.limit(limit);
if (error) throw error;
return data as Alert[];
},
refetchInterval: 30000, // Refetch every 30 seconds
});
}
export function useUnresolvedAlerts() {
return useQuery({
queryKey: ['rateLimitAlertsUnresolved'],
queryFn: async () => {
const { data, error } = await supabase
.from('rate_limit_alerts')
.select('*')
.is('resolved_at', null)
.order('created_at', { ascending: false });
if (error) throw error;
return data as Alert[];
},
refetchInterval: 15000, // Refetch every 15 seconds
});
}
export function useUpdateAlertConfig() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ id, updates }: { id: string; updates: Partial<AlertConfig> }) => {
const { data, error } = await supabase
.from('rate_limit_alert_config')
.update(updates)
.eq('id', id)
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['rateLimitAlertConfigs'] });
toast.success('Alert configuration updated');
},
onError: (error) => {
toast.error(`Failed to update alert config: ${error.message}`);
},
});
}
export function useCreateAlertConfig() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (config: Omit<AlertConfig, 'id' | 'created_at' | 'updated_at'>) => {
const { data, error } = await supabase
.from('rate_limit_alert_config')
.insert(config)
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['rateLimitAlertConfigs'] });
toast.success('Alert configuration created');
},
onError: (error) => {
toast.error(`Failed to create alert config: ${error.message}`);
},
});
}
export function useDeleteAlertConfig() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { error } = await supabase
.from('rate_limit_alert_config')
.delete()
.eq('id', id);
if (error) throw error;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['rateLimitAlertConfigs'] });
toast.success('Alert configuration deleted');
},
onError: (error) => {
toast.error(`Failed to delete alert config: ${error.message}`);
},
});
}
export function useResolveAlert() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: string) => {
const { data, error } = await supabase
.from('rate_limit_alerts')
.update({ resolved_at: new Date().toISOString() })
.eq('id', id)
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['rateLimitAlerts'] });
queryClient.invalidateQueries({ queryKey: ['rateLimitAlertsUnresolved'] });
toast.success('Alert resolved');
},
onError: (error) => {
toast.error(`Failed to resolve alert: ${error.message}`);
},
});
}

View File

@@ -3,13 +3,18 @@ import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole';
import { useRateLimitStats, useRecentMetrics } from '@/hooks/useRateLimitMetrics';
import { useAlertConfigs, useAlertHistory, useUnresolvedAlerts, useUpdateAlertConfig, useResolveAlert } from '@/hooks/useRateLimitAlerts';
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 { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 { Activity, Shield, TrendingUp, Users, Clock, AlertTriangle, Bell, BellOff, CheckCircle } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { format } from 'date-fns';
@@ -25,6 +30,12 @@ export default function RateLimitMetrics() {
const { data: stats, isLoading: statsLoading, error: statsError } = useRateLimitStats(timeWindow);
const { data: recentData, isLoading: recentLoading } = useRecentMetrics(50);
const { data: alertConfigs, isLoading: alertConfigsLoading } = useAlertConfigs();
const { data: alertHistory, isLoading: alertHistoryLoading } = useAlertHistory(50);
const { data: unresolvedAlerts } = useUnresolvedAlerts();
const updateConfig = useUpdateAlertConfig();
const resolveAlert = useResolveAlert();
// Redirect if not authorized
if (!rolesLoading && !isModerator()) {
@@ -157,6 +168,13 @@ export default function RateLimitMetrics() {
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="blocked">Blocked Requests</TabsTrigger>
<TabsTrigger value="recent">Recent Activity</TabsTrigger>
<TabsTrigger value="alerts">
Alerts
{unresolvedAlerts && unresolvedAlerts.length > 0 && (
<Badge variant="destructive" className="ml-2">{unresolvedAlerts.length}</Badge>
)}
</TabsTrigger>
<TabsTrigger value="config">Configuration</TabsTrigger>
</TabsList>
<TabsContent value="overview" className="space-y-6">
@@ -331,6 +349,170 @@ export default function RateLimitMetrics() {
</CardContent>
</Card>
</TabsContent>
<TabsContent value="alerts" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Alert History</CardTitle>
<CardDescription>Recent rate limit threshold violations</CardDescription>
</CardHeader>
<CardContent>
{alertHistoryLoading ? (
<div className="space-y-2">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="h-20" />
))}
</div>
) : alertHistory && alertHistory.length > 0 ? (
<div className="space-y-2 max-h-[600px] overflow-y-auto">
{alertHistory.map((alert) => (
<div
key={alert.id}
className={`flex items-start justify-between p-4 border rounded ${
alert.resolved_at ? 'border-border bg-muted/30' : 'border-destructive/50 bg-destructive/5'
}`}
>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
{alert.resolved_at ? (
<CheckCircle className="h-4 w-4 text-muted-foreground" />
) : (
<AlertTriangle className="h-4 w-4 text-destructive" />
)}
<Badge variant={alert.resolved_at ? 'secondary' : 'destructive'}>
{alert.metric_type}
</Badge>
<span className="text-xs text-muted-foreground">
{format(new Date(alert.created_at), 'PPp')}
</span>
</div>
<p className="text-sm mb-2">{alert.alert_message}</p>
<div className="flex gap-4 text-xs text-muted-foreground">
<span>Value: {alert.metric_value.toFixed(2)}</span>
<span>Threshold: {alert.threshold_value.toFixed(2)}</span>
<span>Window: {alert.time_window_ms / 1000}s</span>
</div>
{alert.resolved_at && (
<p className="text-xs text-muted-foreground mt-1">
Resolved: {format(new Date(alert.resolved_at), 'PPp')}
</p>
)}
</div>
{!alert.resolved_at && (
<Button
size="sm"
variant="outline"
onClick={() => resolveAlert.mutate(alert.id)}
>
Resolve
</Button>
)}
</div>
))}
</div>
) : (
<div className="flex h-[300px] items-center justify-center text-muted-foreground">
No alerts triggered yet
</div>
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="config" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Alert Configuration</CardTitle>
<CardDescription>Configure thresholds for automated alerts</CardDescription>
</CardHeader>
<CardContent>
{alertConfigsLoading ? (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
) : alertConfigs && alertConfigs.length > 0 ? (
<div className="space-y-4">
{alertConfigs.map((config) => (
<div key={config.id} className="p-4 border rounded space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Badge variant="outline">{config.metric_type}</Badge>
<Switch
checked={config.enabled}
onCheckedChange={(enabled) =>
updateConfig.mutate({ id: config.id, updates: { enabled } })
}
/>
{config.enabled ? (
<span className="text-sm text-muted-foreground flex items-center gap-1">
<Bell className="h-3 w-3" /> Enabled
</span>
) : (
<span className="text-sm text-muted-foreground flex items-center gap-1">
<BellOff className="h-3 w-3" /> Disabled
</span>
)}
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-xs">Threshold Value</Label>
<Input
type="number"
step="0.01"
value={config.threshold_value}
onChange={(e) => {
const value = parseFloat(e.target.value);
if (!isNaN(value)) {
updateConfig.mutate({
id: config.id,
updates: { threshold_value: value }
});
}
}}
className="mt-1"
/>
<p className="text-xs text-muted-foreground mt-1">
{config.metric_type === 'block_rate' && 'Value between 0 and 1 (e.g., 0.5 = 50%)'}
{config.metric_type === 'total_requests' && 'Number of requests'}
{config.metric_type === 'unique_ips' && 'Number of unique IPs'}
</p>
</div>
<div>
<Label className="text-xs">Time Window (ms)</Label>
<Input
type="number"
step="1000"
value={config.time_window_ms}
onChange={(e) => {
const value = parseInt(e.target.value);
if (!isNaN(value)) {
updateConfig.mutate({
id: config.id,
updates: { time_window_ms: value }
});
}
}}
className="mt-1"
/>
<p className="text-xs text-muted-foreground mt-1">
Currently: {config.time_window_ms / 1000}s
</p>
</div>
</div>
</div>
))}
</div>
) : (
<div className="flex h-[200px] items-center justify-center text-muted-foreground">
No alert configurations found
</div>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);