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:
gpt-engineer-app[bot]
2025-11-11 03:30:00 +00:00
parent e28dc97d71
commit 12d2518eb9
3 changed files with 84 additions and 108 deletions

View File

@@ -1,9 +1,6 @@
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
interface MetricData {
timestamp: string;
@@ -291,17 +288,13 @@ class AnomalyDetector {
}
}
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
try {
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseKey);
console.log('Starting anomaly detection run...');
export default createEdgeFunction(
{
name: 'detect-anomalies',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Starting anomaly detection run', { requestId: context.requestId });
// Get all enabled anomaly detection configurations
const { data: configs, error: configError } = await supabase
@@ -314,7 +307,10 @@ Deno.serve(async (req) => {
throw configError;
}
console.log(`Processing ${configs?.length || 0} metric configurations`);
edgeLogger.info('Processing metric configurations', {
count: configs?.length || 0,
requestId: context.requestId
});
const anomaliesDetected: any[] = [];
@@ -338,7 +334,11 @@ Deno.serve(async (req) => {
const data = metricData as MetricData[];
if (!data || data.length < config.min_data_points) {
console.log(`Insufficient data for ${config.metric_name}: ${data?.length || 0} points`);
edgeLogger.info('Insufficient data for metric', {
metric: config.metric_name,
points: data?.length || 0,
requestId: context.requestId
});
continue;
}
@@ -464,7 +464,10 @@ Deno.serve(async (req) => {
}
}
console.log(`Anomaly detection complete. Detected ${anomaliesDetected.length} anomalies`);
edgeLogger.info('Anomaly detection complete', {
detected: anomaliesDetected.length,
requestId: context.requestId
});
return new Response(
JSON.stringify({
@@ -472,16 +475,7 @@ Deno.serve(async (req) => {
anomalies_detected: anomaliesDetected.length,
anomalies: anomaliesDetected,
}),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
} catch (error) {
console.error('Error in detect-anomalies function:', error);
return new Response(
JSON.stringify({ error: error.message }),
{
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
}
{ headers: { 'Content-Type': 'application/json' } }
);
}
});
);