Migrate remaining edge functions to wrapper

Refactor process-expired-bans, detect-location, detect-anomalies, rate-limit-metrics, and collect-metrics to use createEdgeFunction wrapper with standardized error handling, tracing, and reduced boilerplate. Update signatures to receive { supabase, span, requestId } (and user where applicable), replace manual logging with span events, remove per-function boilerplate, and ensure consistent wrapper configuration (cors, auth, rate limits, and tracing).
This commit is contained in:
gpt-engineer-app[bot]
2025-11-11 20:30:24 +00:00
parent 4040fd783e
commit de921a5fcf
5 changed files with 197 additions and 376 deletions

View File

@@ -1,6 +1,7 @@
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
import { addSpanEvent } from '../_shared/logger.ts';
import { corsHeaders } from '../_shared/cors.ts';
interface MetricData {
timestamp: string;
@@ -288,13 +289,8 @@ class AnomalyDetector {
}
}
export default createEdgeFunction(
{
name: 'detect-anomalies',
requireAuth: false,
},
async (req, context, supabase) => {
edgeLogger.info('Starting anomaly detection run', { requestId: context.requestId });
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
addSpanEvent(span, 'starting_anomaly_detection', { requestId });
// Get all enabled anomaly detection configurations
const { data: configs, error: configError } = await supabase
@@ -303,14 +299,11 @@ export default createEdgeFunction(
.eq('enabled', true);
if (configError) {
console.error('Error fetching configs:', configError);
addSpanEvent(span, 'error_fetching_configs', { error: configError.message });
throw configError;
}
edgeLogger.info('Processing metric configurations', {
count: configs?.length || 0,
requestId: context.requestId
});
addSpanEvent(span, 'processing_metric_configs', { count: configs?.length || 0 });
const anomaliesDetected: any[] = [];
@@ -327,17 +320,19 @@ export default createEdgeFunction(
.order('timestamp', { ascending: true });
if (metricError) {
console.error(`Error fetching metric data for ${config.metric_name}:`, metricError);
addSpanEvent(span, 'error_fetching_metric_data', {
metric: config.metric_name,
error: metricError.message
});
continue;
}
const data = metricData as MetricData[];
if (!data || data.length < config.min_data_points) {
edgeLogger.info('Insufficient data for metric', {
addSpanEvent(span, 'insufficient_data', {
metric: config.metric_name,
points: data?.length || 0,
requestId: context.requestId
points: data?.length || 0
});
continue;
}
@@ -421,7 +416,10 @@ export default createEdgeFunction(
.single();
if (anomalyError) {
console.error(`Error inserting anomaly for ${config.metric_name}:`, anomalyError);
addSpanEvent(span, 'error_inserting_anomaly', {
metric: config.metric_name,
error: anomalyError.message
});
continue;
}
@@ -453,29 +451,39 @@ export default createEdgeFunction(
.update({ alert_created: true, alert_id: alert.id })
.eq('id', anomaly.id);
console.log(`Created alert for anomaly in ${config.metric_name}`);
addSpanEvent(span, 'alert_created', {
metric: config.metric_name,
alertId: alert.id
});
}
}
console.log(`Anomaly detected: ${config.metric_name} - ${bestResult.anomalyType} (${bestResult.deviationScore.toFixed(2)}σ)`);
addSpanEvent(span, 'anomaly_detected', {
metric: config.metric_name,
type: bestResult.anomalyType,
deviation: bestResult.deviationScore.toFixed(2)
});
}
} catch (error) {
console.error(`Error processing metric ${config.metric_name}:`, error);
addSpanEvent(span, 'error_processing_metric', {
metric: config.metric_name,
error: error instanceof Error ? error.message : String(error)
});
}
}
edgeLogger.info('Anomaly detection complete', {
detected: anomaliesDetected.length,
requestId: context.requestId
});
addSpanEvent(span, 'anomaly_detection_complete', { detected: anomaliesDetected.length });
return new Response(
JSON.stringify({
success: true,
anomalies_detected: anomaliesDetected.length,
anomalies: anomaliesDetected,
}),
{ headers: { 'Content-Type': 'application/json' } }
);
}
);
return {
success: true,
anomalies_detected: anomaliesDetected.length,
anomalies: anomaliesDetected,
};
};
serve(createEdgeFunction({
name: 'detect-anomalies',
requireAuth: false,
corsHeaders,
enableTracing: true,
}, handler));