Migrate complex functions in batches

Batch 1 of Phase 2: migrate 3-4 edge functions to use createEdgeFunction wrapper (process-selective-approval, process-selective-rejection, rate-limit-metrics) to enable automatic error logging, CORS, auth, and reduced boilerplate; preserve existing logic where applicable and prepare for subsequent batches.
This commit is contained in:
gpt-engineer-app[bot]
2025-11-11 19:17:21 +00:00
parent fa57d497af
commit afe7a93f69
3 changed files with 475 additions and 1212 deletions

View File

@@ -5,8 +5,7 @@
* Requires admin/moderator authentication.
*/
import { createClient } from 'jsr:@supabase/supabase-js@2';
import { withRateLimit, rateLimiters } from '../_shared/rateLimiter.ts';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import {
getRecentMetrics,
getMetricsStats,
@@ -16,11 +15,6 @@ import {
clearMetrics,
} from '../_shared/rateLimitMetrics.ts';
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};
interface QueryParams {
action?: string;
limit?: string;
@@ -30,171 +24,106 @@ interface QueryParams {
clientIP?: string;
}
async function handler(req: Request): Promise<Response> {
// Handle CORS preflight
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
const handler = async (req: Request, context: { supabase: any; user: any; span: any; requestId: string }) => {
const { supabase, user } = context;
// Check if user has admin or moderator role
const { data: roles } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', user.id);
const userRoles = roles?.map((r: any) => r.role) || [];
const isAuthorized = userRoles.some((role: string) =>
['admin', 'moderator', 'superuser'].includes(role)
);
if (!isAuthorized) {
throw new Error('Insufficient permissions');
}
try {
// Verify authentication
const authHeader = req.headers.get('Authorization');
if (!authHeader) {
return new Response(
JSON.stringify({ error: 'Authentication required' }),
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// Parse query parameters
const url = new URL(req.url);
const action = url.searchParams.get('action') || 'stats';
const limit = parseInt(url.searchParams.get('limit') || '100', 10);
const timeWindow = parseInt(url.searchParams.get('timeWindow') || '60000', 10);
const functionName = url.searchParams.get('functionName');
const userId = url.searchParams.get('userId');
const clientIP = url.searchParams.get('clientIP');
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
global: {
headers: { Authorization: authHeader },
},
});
let responseData: any;
// Get authenticated user
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return new Response(
JSON.stringify({ error: 'Invalid authentication' }),
{ status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// Route to appropriate metrics handler
switch (action) {
case 'recent':
responseData = {
metrics: getRecentMetrics(limit),
count: getRecentMetrics(limit).length,
};
break;
// Check if user has admin or moderator role
const { data: roles } = await supabase
.from('user_roles')
.select('role')
.eq('user_id', user.id);
case 'stats':
responseData = getMetricsStats(timeWindow);
break;
const userRoles = roles?.map(r => r.role) || [];
const isAuthorized = userRoles.some(role =>
['admin', 'moderator', 'superuser'].includes(role)
);
if (!isAuthorized) {
return new Response(
JSON.stringify({ error: 'Insufficient permissions' }),
{ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// Parse query parameters
const url = new URL(req.url);
const action = url.searchParams.get('action') || 'stats';
const limit = parseInt(url.searchParams.get('limit') || '100', 10);
const timeWindow = parseInt(url.searchParams.get('timeWindow') || '60000', 10);
const functionName = url.searchParams.get('functionName');
const userId = url.searchParams.get('userId');
const clientIP = url.searchParams.get('clientIP');
let responseData: any;
// Route to appropriate metrics handler
switch (action) {
case 'recent':
responseData = {
metrics: getRecentMetrics(limit),
count: getRecentMetrics(limit).length,
};
break;
case 'stats':
responseData = getMetricsStats(timeWindow);
break;
case 'function':
if (!functionName) {
return new Response(
JSON.stringify({ error: 'functionName parameter required for function action' }),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
responseData = {
functionName,
metrics: getFunctionMetrics(functionName, limit),
count: getFunctionMetrics(functionName, limit).length,
};
break;
case 'user':
if (!userId) {
return new Response(
JSON.stringify({ error: 'userId parameter required for user action' }),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
responseData = {
userId,
metrics: getUserMetrics(userId, limit),
count: getUserMetrics(userId, limit).length,
};
break;
case 'ip':
if (!clientIP) {
return new Response(
JSON.stringify({ error: 'clientIP parameter required for ip action' }),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
responseData = {
clientIP,
metrics: getIPMetrics(clientIP, limit),
count: getIPMetrics(clientIP, limit).length,
};
break;
case 'clear':
// Only superusers can clear metrics
const isSuperuser = userRoles.includes('superuser');
if (!isSuperuser) {
return new Response(
JSON.stringify({ error: 'Only superusers can clear metrics' }),
{ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
clearMetrics();
responseData = { success: true, message: 'Metrics cleared' };
break;
default:
return new Response(
JSON.stringify({
error: 'Invalid action',
validActions: ['recent', 'stats', 'function', 'user', 'ip', 'clear']
}),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify(responseData),
{
status: 200,
headers: {
...corsHeaders,
'Content-Type': 'application/json',
}
case 'function':
if (!functionName) {
throw new Error('functionName parameter required for function action');
}
);
responseData = {
functionName,
metrics: getFunctionMetrics(functionName, limit),
count: getFunctionMetrics(functionName, limit).length,
};
break;
} catch (error) {
console.error('Error in rate-limit-metrics function:', error);
return new Response(
JSON.stringify({
error: 'Internal server error',
message: error instanceof Error ? error.message : 'Unknown error'
}),
{
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
case 'user':
if (!userId) {
throw new Error('userId parameter required for user action');
}
);
responseData = {
userId,
metrics: getUserMetrics(userId, limit),
count: getUserMetrics(userId, limit).length,
};
break;
case 'ip':
if (!clientIP) {
throw new Error('clientIP parameter required for ip action');
}
responseData = {
clientIP,
metrics: getIPMetrics(clientIP, limit),
count: getIPMetrics(clientIP, limit).length,
};
break;
case 'clear':
// Only superusers can clear metrics
const isSuperuser = userRoles.includes('superuser');
if (!isSuperuser) {
throw new Error('Only superusers can clear metrics');
}
clearMetrics();
responseData = { success: true, message: 'Metrics cleared' };
break;
default:
throw new Error('Invalid action. Valid actions: recent, stats, function, user, ip, clear');
}
}
// Apply rate limiting (lenient tier for admin monitoring)
Deno.serve(withRateLimit(handler, rateLimiters.lenient, corsHeaders, 'rate-limit-metrics'));
return responseData;
};
// Create edge function with automatic error handling, CORS, auth, and logging
createEdgeFunction(
{
name: 'rate-limit-metrics',
requireAuth: true,
corsEnabled: true,
enableTracing: false,
rateLimitTier: 'lenient'
},
handler
);