mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 02:51:12 -05:00
Migrate Phase 2 Batch 1
Migrate 3 Phase 2 monitoring functions (collect-metrics, detect-anomalies, monitor-rate-limits) to use wrapEdgeFunction with smaller batch updates, replacing manual handlers, adding shared logging/tracing, and standardizing error handling.
This commit is contained in:
@@ -8,13 +8,10 @@
|
||||
*/
|
||||
|
||||
import { createClient } from 'jsr:@supabase/supabase-js@2';
|
||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
||||
import { edgeLogger } from '../_shared/logger.ts';
|
||||
import { getMetricsStats } from '../_shared/rateLimitMetrics.ts';
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
interface AlertConfig {
|
||||
id: string;
|
||||
metric_type: 'block_rate' | 'total_requests' | 'unique_ips' | 'function_specific';
|
||||
@@ -159,19 +156,14 @@ async function sendNotification(
|
||||
}
|
||||
}
|
||||
|
||||
async function handler(req: Request): Promise<Response> {
|
||||
// Handle CORS preflight
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
console.log('Rate limit monitor starting...');
|
||||
|
||||
try {
|
||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
||||
export default createEdgeFunction(
|
||||
{
|
||||
name: 'monitor-rate-limits',
|
||||
requireAuth: false,
|
||||
},
|
||||
async (req, context, supabase) => {
|
||||
const startTime = Date.now();
|
||||
edgeLogger.info('Rate limit monitor starting', { requestId: context.requestId });
|
||||
|
||||
// Fetch enabled alert configurations
|
||||
const { data: configs, error: configError } = await supabase
|
||||
@@ -180,41 +172,48 @@ async function handler(req: Request): Promise<Response> {
|
||||
.eq('enabled', true);
|
||||
|
||||
if (configError) {
|
||||
console.error('Failed to fetch alert configs:', configError);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Failed to fetch alert configurations',
|
||||
details: configError.message
|
||||
}),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
edgeLogger.error('Failed to fetch alert configs', {
|
||||
error: configError,
|
||||
requestId: context.requestId
|
||||
});
|
||||
throw configError;
|
||||
}
|
||||
|
||||
if (!configs || configs.length === 0) {
|
||||
console.log('No enabled alert configurations found');
|
||||
edgeLogger.info('No enabled alert configurations found', {
|
||||
requestId: context.requestId
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: 'No enabled alert configurations',
|
||||
checked: 0
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`Checking ${configs.length} alert configurations...`);
|
||||
edgeLogger.info('Checking alert configurations', {
|
||||
count: configs.length,
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Check all alert conditions
|
||||
const checks = await checkAlertConditions(configs);
|
||||
const exceededChecks = checks.filter(c => c.exceeded);
|
||||
|
||||
console.log(`Found ${exceededChecks.length} threshold violations`);
|
||||
edgeLogger.info('Threshold violations found', {
|
||||
count: exceededChecks.length,
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Process exceeded thresholds
|
||||
const alertResults = [];
|
||||
for (const check of exceededChecks) {
|
||||
console.log(`Processing alert: ${check.message}`);
|
||||
edgeLogger.info('Processing alert', {
|
||||
message: check.message,
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
// Check if we've already sent a recent alert for this config
|
||||
const { data: recentAlerts } = await supabase
|
||||
@@ -227,7 +226,10 @@ async function handler(req: Request): Promise<Response> {
|
||||
.limit(1);
|
||||
|
||||
if (recentAlerts && recentAlerts.length > 0) {
|
||||
console.log(`Skipping alert - recent unresolved alert exists for config ${check.configId}`);
|
||||
edgeLogger.info('Skipping alert - recent unresolved alert exists', {
|
||||
configId: check.configId,
|
||||
requestId: context.requestId
|
||||
});
|
||||
alertResults.push({
|
||||
configId: check.configId,
|
||||
skipped: true,
|
||||
@@ -253,7 +255,10 @@ async function handler(req: Request): Promise<Response> {
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
console.log(`Monitor completed in ${duration}ms`);
|
||||
edgeLogger.info('Monitor completed', {
|
||||
duration,
|
||||
requestId: context.requestId
|
||||
});
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
@@ -263,20 +268,7 @@ async function handler(req: Request): Promise<Response> {
|
||||
alerts: alertResults,
|
||||
duration_ms: duration,
|
||||
}),
|
||||
{ status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error in rate limit monitor:', error);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: 'Internal server error',
|
||||
message: error instanceof Error ? error.message : 'Unknown error',
|
||||
}),
|
||||
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Deno.serve(handler);
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user