mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-29 05:27:08 -05:00
Compare commits
3 Commits
4040fd783e
...
96b7594738
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96b7594738 | ||
|
|
8ee548fd27 | ||
|
|
de921a5fcf |
@@ -1,6 +1,7 @@
|
|||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { edgeLogger } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
|
|
||||||
interface MetricRecord {
|
interface MetricRecord {
|
||||||
metric_name: string;
|
metric_name: string;
|
||||||
@@ -9,13 +10,8 @@ interface MetricRecord {
|
|||||||
timestamp: string;
|
timestamp: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default createEdgeFunction(
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
{
|
addSpanEvent(span, 'starting_metrics_collection', { requestId });
|
||||||
name: 'collect-metrics',
|
|
||||||
requireAuth: false,
|
|
||||||
},
|
|
||||||
async (req, context, supabase) => {
|
|
||||||
edgeLogger.info('Starting metrics collection', { requestId: context.requestId });
|
|
||||||
|
|
||||||
const metrics: MetricRecord[] = [];
|
const metrics: MetricRecord[] = [];
|
||||||
const timestamp = new Date().toISOString();
|
const timestamp = new Date().toISOString();
|
||||||
@@ -152,26 +148,23 @@ export default createEdgeFunction(
|
|||||||
.insert(metrics);
|
.insert(metrics);
|
||||||
|
|
||||||
if (insertError) {
|
if (insertError) {
|
||||||
edgeLogger.error('Error inserting metrics', {
|
addSpanEvent(span, 'error_inserting_metrics', { error: insertError.message });
|
||||||
error: insertError,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
throw insertError;
|
throw insertError;
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Successfully recorded metrics', {
|
addSpanEvent(span, 'metrics_recorded', { count: metrics.length });
|
||||||
count: metrics.length,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
metrics_collected: metrics.length,
|
metrics_collected: metrics.length,
|
||||||
metrics: metrics.map(m => ({ name: m.metric_name, value: m.metric_value })),
|
metrics: metrics.map(m => ({ name: m.metric_name, value: m.metric_value })),
|
||||||
}),
|
};
|
||||||
{ headers: { 'Content-Type': 'application/json' } }
|
};
|
||||||
);
|
|
||||||
}
|
serve(createEdgeFunction({
|
||||||
);
|
name: 'collect-metrics',
|
||||||
|
requireAuth: false,
|
||||||
|
corsHeaders,
|
||||||
|
enableTracing: true,
|
||||||
|
}, handler));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { edgeLogger } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
|
|
||||||
interface MetricData {
|
interface MetricData {
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
@@ -288,13 +289,8 @@ class AnomalyDetector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default createEdgeFunction(
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
{
|
addSpanEvent(span, 'starting_anomaly_detection', { requestId });
|
||||||
name: 'detect-anomalies',
|
|
||||||
requireAuth: false,
|
|
||||||
},
|
|
||||||
async (req, context, supabase) => {
|
|
||||||
edgeLogger.info('Starting anomaly detection run', { requestId: context.requestId });
|
|
||||||
|
|
||||||
// Get all enabled anomaly detection configurations
|
// Get all enabled anomaly detection configurations
|
||||||
const { data: configs, error: configError } = await supabase
|
const { data: configs, error: configError } = await supabase
|
||||||
@@ -303,14 +299,11 @@ export default createEdgeFunction(
|
|||||||
.eq('enabled', true);
|
.eq('enabled', true);
|
||||||
|
|
||||||
if (configError) {
|
if (configError) {
|
||||||
console.error('Error fetching configs:', configError);
|
addSpanEvent(span, 'error_fetching_configs', { error: configError.message });
|
||||||
throw configError;
|
throw configError;
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Processing metric configurations', {
|
addSpanEvent(span, 'processing_metric_configs', { count: configs?.length || 0 });
|
||||||
count: configs?.length || 0,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
const anomaliesDetected: any[] = [];
|
const anomaliesDetected: any[] = [];
|
||||||
|
|
||||||
@@ -327,17 +320,19 @@ export default createEdgeFunction(
|
|||||||
.order('timestamp', { ascending: true });
|
.order('timestamp', { ascending: true });
|
||||||
|
|
||||||
if (metricError) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = metricData as MetricData[];
|
const data = metricData as MetricData[];
|
||||||
|
|
||||||
if (!data || data.length < config.min_data_points) {
|
if (!data || data.length < config.min_data_points) {
|
||||||
edgeLogger.info('Insufficient data for metric', {
|
addSpanEvent(span, 'insufficient_data', {
|
||||||
metric: config.metric_name,
|
metric: config.metric_name,
|
||||||
points: data?.length || 0,
|
points: data?.length || 0
|
||||||
requestId: context.requestId
|
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -421,7 +416,10 @@ export default createEdgeFunction(
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (anomalyError) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,29 +451,39 @@ export default createEdgeFunction(
|
|||||||
.update({ alert_created: true, alert_id: alert.id })
|
.update({ alert_created: true, alert_id: alert.id })
|
||||||
.eq('id', anomaly.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) {
|
} 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
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new Response(
|
addSpanEvent(span, 'anomaly_detection_complete', { detected: anomaliesDetected.length });
|
||||||
JSON.stringify({
|
|
||||||
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
anomalies_detected: anomaliesDetected.length,
|
anomalies_detected: anomaliesDetected.length,
|
||||||
anomalies: anomaliesDetected,
|
anomalies: anomaliesDetected,
|
||||||
}),
|
};
|
||||||
{ headers: { 'Content-Type': 'application/json' } }
|
};
|
||||||
);
|
|
||||||
}
|
serve(createEdgeFunction({
|
||||||
);
|
name: 'detect-anomalies',
|
||||||
|
requireAuth: false,
|
||||||
|
corsHeaders,
|
||||||
|
enableTracing: true,
|
||||||
|
}, handler));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from "../_shared/logger.ts";
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { formatEdgeError } from "../_shared/errorFormatter.ts";
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
|
||||||
interface IPLocationResponse {
|
interface IPLocationResponse {
|
||||||
country: string;
|
country: string;
|
||||||
@@ -11,86 +11,47 @@ interface IPLocationResponse {
|
|||||||
|
|
||||||
// Simple in-memory rate limiter
|
// Simple in-memory rate limiter
|
||||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
||||||
const RATE_LIMIT_WINDOW = 60000; // 1 minute in milliseconds
|
const RATE_LIMIT_WINDOW = 60000; // 1 minute
|
||||||
const MAX_REQUESTS = 10; // 10 requests per minute per IP
|
const MAX_REQUESTS = 10; // 10 requests per minute per IP
|
||||||
const MAX_MAP_SIZE = 10000; // Maximum number of IPs to track
|
const MAX_MAP_SIZE = 10000;
|
||||||
|
|
||||||
// Cleanup failure tracking to prevent silent failures
|
|
||||||
let cleanupFailureCount = 0;
|
let cleanupFailureCount = 0;
|
||||||
const MAX_CLEANUP_FAILURES = 5; // Threshold before forcing drastic cleanup
|
const MAX_CLEANUP_FAILURES = 5;
|
||||||
const CLEANUP_FAILURE_RESET_INTERVAL = 300000; // Reset failure count every 5 minutes
|
const CLEANUP_FAILURE_RESET_INTERVAL = 300000; // 5 minutes
|
||||||
|
|
||||||
function cleanupExpiredEntries() {
|
function cleanupExpiredEntries() {
|
||||||
try {
|
try {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
let deletedCount = 0;
|
|
||||||
const mapSizeBefore = rateLimitMap.size;
|
|
||||||
|
|
||||||
for (const [ip, data] of rateLimitMap.entries()) {
|
for (const [ip, data] of rateLimitMap.entries()) {
|
||||||
if (now > data.resetAt) {
|
if (now > data.resetAt) {
|
||||||
rateLimitMap.delete(ip);
|
rateLimitMap.delete(ip);
|
||||||
deletedCount++;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cleanup runs silently unless there are issues
|
|
||||||
if (cleanupFailureCount > 0) {
|
if (cleanupFailureCount > 0) {
|
||||||
cleanupFailureCount = 0;
|
cleanupFailureCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
// CRITICAL: Increment failure counter and log detailed error information
|
|
||||||
cleanupFailureCount++;
|
cleanupFailureCount++;
|
||||||
|
|
||||||
const errorMessage = formatEdgeError(error);
|
|
||||||
|
|
||||||
edgeLogger.error('Cleanup error', {
|
|
||||||
attempt: cleanupFailureCount,
|
|
||||||
maxAttempts: MAX_CLEANUP_FAILURES,
|
|
||||||
error: errorMessage,
|
|
||||||
mapSize: rateLimitMap.size
|
|
||||||
});
|
|
||||||
|
|
||||||
// FALLBACK MECHANISM: If cleanup fails repeatedly, force clear to prevent memory leak
|
|
||||||
if (cleanupFailureCount >= MAX_CLEANUP_FAILURES) {
|
if (cleanupFailureCount >= MAX_CLEANUP_FAILURES) {
|
||||||
edgeLogger.error('Cleanup critical - forcing emergency cleanup', {
|
|
||||||
consecutiveFailures: cleanupFailureCount,
|
|
||||||
mapSize: rateLimitMap.size
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Emergency: Clear oldest 50% of entries to prevent unbounded growth
|
|
||||||
const entriesToClear = Math.floor(rateLimitMap.size * 0.5);
|
const entriesToClear = Math.floor(rateLimitMap.size * 0.5);
|
||||||
const sortedEntries = Array.from(rateLimitMap.entries())
|
const sortedEntries = Array.from(rateLimitMap.entries())
|
||||||
.sort((a, b) => a[1].resetAt - b[1].resetAt);
|
.sort((a, b) => a[1].resetAt - b[1].resetAt);
|
||||||
|
|
||||||
let clearedCount = 0;
|
|
||||||
for (let i = 0; i < entriesToClear && i < sortedEntries.length; i++) {
|
for (let i = 0; i < entriesToClear && i < sortedEntries.length; i++) {
|
||||||
rateLimitMap.delete(sortedEntries[i][0]);
|
rateLimitMap.delete(sortedEntries[i][0]);
|
||||||
clearedCount++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.warn('Emergency cleanup completed', { clearedCount, newMapSize: rateLimitMap.size });
|
|
||||||
|
|
||||||
// Reset failure count after emergency cleanup
|
|
||||||
cleanupFailureCount = 0;
|
cleanupFailureCount = 0;
|
||||||
|
} catch {
|
||||||
} catch (emergencyError) {
|
|
||||||
// Last resort: If even emergency cleanup fails, clear everything
|
|
||||||
const originalSize = rateLimitMap.size;
|
|
||||||
rateLimitMap.clear();
|
rateLimitMap.clear();
|
||||||
|
|
||||||
edgeLogger.error('Emergency cleanup failed - cleared entire map', {
|
|
||||||
originalSize,
|
|
||||||
error: emergencyError instanceof Error ? emergencyError.message : String(emergencyError)
|
|
||||||
});
|
|
||||||
cleanupFailureCount = 0;
|
cleanupFailureCount = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset cleanup failure count periodically to avoid permanent emergency state
|
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (cleanupFailureCount > 0) {
|
if (cleanupFailureCount > 0) {
|
||||||
cleanupFailureCount = 0;
|
cleanupFailureCount = 0;
|
||||||
@@ -101,7 +62,6 @@ function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const existing = rateLimitMap.get(ip);
|
const existing = rateLimitMap.get(ip);
|
||||||
|
|
||||||
// Handle existing entries (most common case - early return for performance)
|
|
||||||
if (existing && now <= existing.resetAt) {
|
if (existing && now <= existing.resetAt) {
|
||||||
if (existing.count >= MAX_REQUESTS) {
|
if (existing.count >= MAX_REQUESTS) {
|
||||||
const retryAfter = Math.ceil((existing.resetAt - now) / 1000);
|
const retryAfter = Math.ceil((existing.resetAt - now) / 1000);
|
||||||
@@ -111,89 +71,40 @@ function checkRateLimit(ip: string): { allowed: boolean; retryAfter?: number } {
|
|||||||
return { allowed: true };
|
return { allowed: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Need to add new entry or reset expired one
|
|
||||||
// Only perform cleanup if we're at capacity AND adding a new IP
|
|
||||||
if (!existing && rateLimitMap.size >= MAX_MAP_SIZE) {
|
if (!existing && rateLimitMap.size >= MAX_MAP_SIZE) {
|
||||||
// First try cleaning expired entries
|
|
||||||
cleanupExpiredEntries();
|
cleanupExpiredEntries();
|
||||||
|
|
||||||
// If still at capacity after cleanup, remove oldest entries (LRU eviction)
|
|
||||||
if (rateLimitMap.size >= MAX_MAP_SIZE) {
|
if (rateLimitMap.size >= MAX_MAP_SIZE) {
|
||||||
try {
|
try {
|
||||||
const toDelete = Math.floor(MAX_MAP_SIZE * 0.3); // Remove 30% of entries
|
const toDelete = Math.floor(MAX_MAP_SIZE * 0.3);
|
||||||
const sortedEntries = Array.from(rateLimitMap.entries())
|
const sortedEntries = Array.from(rateLimitMap.entries())
|
||||||
.sort((a, b) => a[1].resetAt - b[1].resetAt);
|
.sort((a, b) => a[1].resetAt - b[1].resetAt);
|
||||||
|
|
||||||
let deletedCount = 0;
|
|
||||||
for (let i = 0; i < toDelete && i < sortedEntries.length; i++) {
|
for (let i = 0; i < toDelete && i < sortedEntries.length; i++) {
|
||||||
rateLimitMap.delete(sortedEntries[i][0]);
|
rateLimitMap.delete(sortedEntries[i][0]);
|
||||||
deletedCount++;
|
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
edgeLogger.warn('Rate limit map at capacity - evicted entries', {
|
|
||||||
maxSize: MAX_MAP_SIZE,
|
|
||||||
deletedCount,
|
|
||||||
newSize: rateLimitMap.size
|
|
||||||
});
|
|
||||||
} catch (evictionError) {
|
|
||||||
// CRITICAL: LRU eviction failed - log error and attempt emergency clear
|
|
||||||
edgeLogger.error('LRU eviction failed', {
|
|
||||||
error: evictionError instanceof Error ? evictionError.message : String(evictionError),
|
|
||||||
mapSize: rateLimitMap.size
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Emergency: Clear first 30% of entries without sorting
|
|
||||||
const targetSize = Math.floor(MAX_MAP_SIZE * 0.7);
|
|
||||||
const keysToDelete: string[] = [];
|
|
||||||
|
|
||||||
for (const [key] of rateLimitMap.entries()) {
|
|
||||||
if (rateLimitMap.size <= targetSize) break;
|
|
||||||
keysToDelete.push(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
keysToDelete.forEach(key => rateLimitMap.delete(key));
|
|
||||||
|
|
||||||
edgeLogger.warn('Emergency eviction completed', {
|
|
||||||
clearedCount: keysToDelete.length,
|
|
||||||
newSize: rateLimitMap.size
|
|
||||||
});
|
|
||||||
} catch (emergencyError) {
|
|
||||||
edgeLogger.error('Emergency eviction failed - clearing entire map', {
|
|
||||||
error: emergencyError instanceof Error ? emergencyError.message : String(emergencyError)
|
|
||||||
});
|
|
||||||
rateLimitMap.clear();
|
rateLimitMap.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Create new entry or reset expired entry
|
|
||||||
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
|
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
|
||||||
return { allowed: true };
|
return { allowed: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clean up old entries periodically to prevent memory leak
|
setInterval(cleanupExpiredEntries, Math.min(RATE_LIMIT_WINDOW / 2, 30000));
|
||||||
// Run cleanup more frequently to catch expired entries sooner
|
|
||||||
setInterval(cleanupExpiredEntries, Math.min(RATE_LIMIT_WINDOW / 2, 30000)); // Every 30 seconds or half the window
|
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { span, requestId }: EdgeFunctionContext) => {
|
||||||
// Handle CORS preflight requests
|
// Get client IP
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
const tracking = startRequest('detect-location');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get the client's IP address
|
|
||||||
const forwarded = req.headers.get('x-forwarded-for');
|
const forwarded = req.headers.get('x-forwarded-for');
|
||||||
const realIP = req.headers.get('x-real-ip');
|
const realIP = req.headers.get('x-real-ip');
|
||||||
const clientIP = forwarded?.split(',')[0] || realIP || '8.8.8.8'; // fallback to Google DNS for testing
|
const clientIP = forwarded?.split(',')[0] || realIP || '8.8.8.8';
|
||||||
|
|
||||||
// Check rate limit
|
// Check rate limit
|
||||||
const rateLimit = checkRateLimit(clientIP);
|
const rateLimit = checkRateLimit(clientIP);
|
||||||
if (!rateLimit.allowed) {
|
if (!rateLimit.allowed) {
|
||||||
|
addSpanEvent(span, 'rate_limit_exceeded', { clientIP: clientIP.substring(0, 8) + '...' });
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
error: 'Rate limit exceeded',
|
error: 'Rate limit exceeded',
|
||||||
@@ -203,19 +114,15 @@ serve(async (req) => {
|
|||||||
{
|
{
|
||||||
status: 429,
|
status: 429,
|
||||||
headers: {
|
headers: {
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Retry-After': String(rateLimit.retryAfter || 60)
|
'Retry-After': String(rateLimit.retryAfter || 60)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PII Note: Do not log full IP addresses in production
|
addSpanEvent(span, 'detecting_location', { requestId });
|
||||||
edgeLogger.info('Detecting location for request', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
// Use configurable geolocation service with proper error handling
|
// Use configurable geolocation service
|
||||||
// Defaults to ip-api.com if not configured
|
|
||||||
const geoApiUrl = Deno.env.get('GEOLOCATION_API_URL') || 'http://ip-api.com/json';
|
const geoApiUrl = Deno.env.get('GEOLOCATION_API_URL') || 'http://ip-api.com/json';
|
||||||
const geoApiFields = Deno.env.get('GEOLOCATION_API_FIELDS') || 'status,country,countryCode';
|
const geoApiFields = Deno.env.get('GEOLOCATION_API_FIELDS') || 'status,country,countryCode';
|
||||||
|
|
||||||
@@ -223,10 +130,7 @@ serve(async (req) => {
|
|||||||
try {
|
try {
|
||||||
geoResponse = await fetch(`${geoApiUrl}/${clientIP}?fields=${geoApiFields}`);
|
geoResponse = await fetch(`${geoApiUrl}/${clientIP}?fields=${geoApiFields}`);
|
||||||
} catch (fetchError) {
|
} catch (fetchError) {
|
||||||
edgeLogger.error('Network error fetching location data', {
|
addSpanEvent(span, 'network_error', { error: fetchError instanceof Error ? fetchError.message : String(fetchError) });
|
||||||
error: fetchError instanceof Error ? fetchError.message : String(fetchError),
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
|
||||||
throw new Error('Network error: Unable to reach geolocation service');
|
throw new Error('Network error: Unable to reach geolocation service');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,10 +142,7 @@ serve(async (req) => {
|
|||||||
try {
|
try {
|
||||||
geoData = await geoResponse.json();
|
geoData = await geoResponse.json();
|
||||||
} catch (parseError) {
|
} catch (parseError) {
|
||||||
edgeLogger.error('Failed to parse geolocation response', {
|
addSpanEvent(span, 'parse_error', { error: parseError instanceof Error ? parseError.message : String(parseError) });
|
||||||
error: parseError instanceof Error ? parseError.message : String(parseError),
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
|
||||||
throw new Error('Invalid response format from geolocation service');
|
throw new Error('Invalid response format from geolocation service');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,7 +151,7 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Countries that primarily use imperial system
|
// Countries that primarily use imperial system
|
||||||
const imperialCountries = ['US', 'LR', 'MM']; // USA, Liberia, Myanmar
|
const imperialCountries = ['US', 'LR', 'MM'];
|
||||||
const measurementSystem = imperialCountries.includes(geoData.countryCode) ? 'imperial' : 'metric';
|
const measurementSystem = imperialCountries.includes(geoData.countryCode) ? 'imperial' : 'metric';
|
||||||
|
|
||||||
const result: IPLocationResponse = {
|
const result: IPLocationResponse = {
|
||||||
@@ -259,65 +160,19 @@ serve(async (req) => {
|
|||||||
measurementSystem
|
measurementSystem
|
||||||
};
|
};
|
||||||
|
|
||||||
edgeLogger.info('Location detected', {
|
addSpanEvent(span, 'location_detected', {
|
||||||
country: result.country,
|
country: result.country,
|
||||||
countryCode: result.countryCode,
|
countryCode: result.countryCode,
|
||||||
measurementSystem: result.measurementSystem,
|
measurementSystem: result.measurementSystem
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
endRequest(tracking);
|
return result;
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({ ...result, requestId: tracking.requestId }),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
} catch (error: unknown) {
|
|
||||||
// Enhanced error logging for better visibility and debugging
|
|
||||||
const errorMessage = formatEdgeError(error);
|
|
||||||
|
|
||||||
edgeLogger.error('Location detection error', {
|
|
||||||
error: errorMessage,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
|
||||||
const errorSpan = startSpan('detect-location-error', 'SERVER');
|
|
||||||
endSpan(errorSpan, 'error', error);
|
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
|
||||||
|
|
||||||
endRequest(tracking);
|
|
||||||
|
|
||||||
// Return default (metric) with 500 status to indicate error occurred
|
|
||||||
// This allows proper error monitoring while still providing fallback data
|
|
||||||
const defaultResult: IPLocationResponse = {
|
|
||||||
country: 'Unknown',
|
|
||||||
countryCode: 'XX',
|
|
||||||
measurementSystem: 'metric'
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return new Response(
|
serve(createEdgeFunction({
|
||||||
JSON.stringify({
|
name: 'detect-location',
|
||||||
...defaultResult,
|
requireAuth: false,
|
||||||
error: errorMessage,
|
corsHeaders,
|
||||||
fallback: true,
|
enableTracing: true,
|
||||||
requestId: tracking.requestId
|
logRequests: true,
|
||||||
}),
|
}, handler));
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { sanitizeError } from '../_shared/errorSanitizer.ts';
|
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
|
||||||
import { formatEdgeError } from '../_shared/errorFormatter.ts';
|
|
||||||
|
|
||||||
interface ExportOptions {
|
interface ExportOptions {
|
||||||
include_reviews: boolean;
|
include_reviews: boolean;
|
||||||
@@ -14,76 +11,12 @@ interface ExportOptions {
|
|||||||
format: 'json';
|
format: 'json';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apply strict rate limiting (5 req/min) for expensive data export operations
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
// This prevents abuse and manages server load from large data exports
|
addSpanEvent(span, 'processing_export_request', { userId: user.id });
|
||||||
serve(withRateLimit(async (req) => {
|
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
// Handle CORS preflight requests
|
// Additional rate limiting - max 1 export per hour
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseClient = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{
|
|
||||||
global: {
|
|
||||||
headers: { Authorization: req.headers.get('Authorization')! },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Get authenticated user
|
|
||||||
const {
|
|
||||||
data: { user },
|
|
||||||
error: authError,
|
|
||||||
} = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (authError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Authentication failed', {
|
|
||||||
action: 'export_auth',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database
|
|
||||||
const authErrorSpan = startSpan('export-user-data-auth-error', 'SERVER');
|
|
||||||
endSpan(authErrorSpan, 'error', authError);
|
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
error: 'Unauthorized',
|
|
||||||
success: false,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 401,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Processing export request', {
|
|
||||||
action: 'export_start',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check rate limiting - max 1 export per hour
|
|
||||||
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString();
|
||||||
const { data: recentExports, error: rateLimitError } = await supabaseClient
|
const { data: recentExports, error: rateLimitError } = await supabase
|
||||||
.from('profile_audit_log')
|
.from('profile_audit_log')
|
||||||
.select('created_at')
|
.select('created_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -92,35 +25,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (rateLimitError) {
|
if (rateLimitError) {
|
||||||
edgeLogger.error('Rate limit check failed', { action: 'export_rate_limit', requestId: tracking.requestId, error: rateLimitError });
|
addSpanEvent(span, 'rate_limit_check_failed', { error: rateLimitError.message });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (recentExports && recentExports.length > 0) {
|
if (recentExports && recentExports.length > 0) {
|
||||||
const duration = endRequest(tracking);
|
|
||||||
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
|
const nextAvailableAt = new Date(new Date(recentExports[0].created_at).getTime() + 60 * 60 * 1000).toISOString();
|
||||||
edgeLogger.warn('Rate limit exceeded for export', {
|
addSpanEvent(span, 'rate_limit_exceeded', { nextAvailableAt });
|
||||||
action: 'export_rate_limit',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
duration,
|
|
||||||
nextAvailableAt
|
|
||||||
});
|
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Rate limited. You can export your data once per hour.',
|
error: 'Rate limited. You can export your data once per hour.',
|
||||||
rate_limited: true,
|
rate_limited: true,
|
||||||
next_available_at: nextAvailableAt,
|
next_available_at: nextAvailableAt,
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{ status: 429 }
|
||||||
status: 429,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,40 +53,32 @@ serve(withRateLimit(async (req) => {
|
|||||||
format: 'json'
|
format: 'json'
|
||||||
};
|
};
|
||||||
|
|
||||||
edgeLogger.info('Export options', {
|
addSpanEvent(span, 'export_options_parsed', { options });
|
||||||
action: 'export_options',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch profile data
|
// Fetch profile data
|
||||||
const { data: profile, error: profileError } = await supabaseClient
|
const { data: profile, error: profileError } = await supabase
|
||||||
.from('profiles')
|
.from('profiles')
|
||||||
.select('username, display_name, bio, preferred_pronouns, personal_location, timezone, preferred_language, theme_preference, privacy_level, ride_count, coaster_count, park_count, review_count, reputation_score, created_at, updated_at')
|
.select('username, display_name, bio, preferred_pronouns, personal_location, timezone, preferred_language, theme_preference, privacy_level, ride_count, coaster_count, park_count, review_count, reputation_score, created_at, updated_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (profileError) {
|
if (profileError) {
|
||||||
edgeLogger.error('Profile fetch failed', {
|
addSpanEvent(span, 'profile_fetch_failed', { error: profileError.message });
|
||||||
action: 'export_profile',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
throw new Error('Failed to fetch profile data');
|
throw new Error('Failed to fetch profile data');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch statistics
|
// Fetch statistics
|
||||||
const { count: photoCount } = await supabaseClient
|
const { count: photoCount } = await supabase
|
||||||
.from('photos')
|
.from('photos')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('submitted_by', user.id);
|
.eq('submitted_by', user.id);
|
||||||
|
|
||||||
const { count: listCount } = await supabaseClient
|
const { count: listCount } = await supabase
|
||||||
.from('user_lists')
|
.from('user_lists')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('user_id', user.id);
|
.eq('user_id', user.id);
|
||||||
|
|
||||||
const { count: submissionCount } = await supabaseClient
|
const { count: submissionCount } = await supabase
|
||||||
.from('content_submissions')
|
.from('content_submissions')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('user_id', user.id);
|
.eq('user_id', user.id);
|
||||||
@@ -188,7 +99,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch reviews if requested
|
// Fetch reviews if requested
|
||||||
let reviews = [];
|
let reviews = [];
|
||||||
if (options.include_reviews) {
|
if (options.include_reviews) {
|
||||||
const { data: reviewsData, error: reviewsError } = await supabaseClient
|
const { data: reviewsData, error: reviewsError } = await supabase
|
||||||
.from('reviews')
|
.from('reviews')
|
||||||
.select(`
|
.select(`
|
||||||
id,
|
id,
|
||||||
@@ -216,7 +127,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch lists if requested
|
// Fetch lists if requested
|
||||||
let lists = [];
|
let lists = [];
|
||||||
if (options.include_lists) {
|
if (options.include_lists) {
|
||||||
const { data: listsData, error: listsError } = await supabaseClient
|
const { data: listsData, error: listsError } = await supabase
|
||||||
.from('user_lists')
|
.from('user_lists')
|
||||||
.select('id, name, description, is_public, created_at')
|
.select('id, name, description, is_public, created_at')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -225,7 +136,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
if (!listsError && listsData) {
|
if (!listsError && listsData) {
|
||||||
lists = await Promise.all(
|
lists = await Promise.all(
|
||||||
listsData.map(async (list) => {
|
listsData.map(async (list) => {
|
||||||
const { count } = await supabaseClient
|
const { count } = await supabase
|
||||||
.from('user_list_items')
|
.from('user_list_items')
|
||||||
.select('*', { count: 'exact', head: true })
|
.select('*', { count: 'exact', head: true })
|
||||||
.eq('list_id', list.id);
|
.eq('list_id', list.id);
|
||||||
@@ -246,7 +157,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
// Fetch activity log if requested
|
// Fetch activity log if requested
|
||||||
let activity_log = [];
|
let activity_log = [];
|
||||||
if (options.include_activity_log) {
|
if (options.include_activity_log) {
|
||||||
const { data: activityData, error: activityError } = await supabaseClient
|
const { data: activityData, error: activityError } = await supabase
|
||||||
.from('profile_audit_log')
|
.from('profile_audit_log')
|
||||||
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
|
.select('id, action, changes, created_at, changed_by, ip_address_hash, user_agent')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -267,7 +178,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (options.include_preferences) {
|
if (options.include_preferences) {
|
||||||
const { data: prefsData } = await supabaseClient
|
const { data: prefsData } = await supabase
|
||||||
.from('user_preferences')
|
.from('user_preferences')
|
||||||
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
|
.select('unit_preferences, accessibility_options, notification_preferences, privacy_settings')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -308,7 +219,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Log the export action
|
// Log the export action
|
||||||
await supabaseClient.from('profile_audit_log').insert([{
|
await supabase.from('profile_audit_log').insert([{
|
||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
changed_by: user.id,
|
changed_by: user.id,
|
||||||
action: 'data_exported',
|
action: 'data_exported',
|
||||||
@@ -316,17 +227,11 @@ serve(withRateLimit(async (req) => {
|
|||||||
export_options: options,
|
export_options: options,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
data_size: JSON.stringify(exportData).length,
|
data_size: JSON.stringify(exportData).length,
|
||||||
requestId: tracking.requestId
|
requestId
|
||||||
}
|
}
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'export_completed', {
|
||||||
edgeLogger.info('Export completed successfully', {
|
|
||||||
action: 'export_complete',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
traceId: tracking.traceId,
|
|
||||||
userId: user.id,
|
|
||||||
duration,
|
|
||||||
dataSize: JSON.stringify(exportData).length
|
dataSize: JSON.stringify(exportData).length
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -334,47 +239,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: true,
|
success: true,
|
||||||
data: exportData,
|
data: exportData,
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
status: 200,
|
|
||||||
headers: {
|
headers: {
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
|
'Content-Disposition': `attachment; filename="thrillwiki-data-export-${new Date().toISOString().split('T')[0]}.json"`,
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'export-user-data',
|
||||||
edgeLogger.error('Export error', {
|
requireAuth: true,
|
||||||
action: 'export_error',
|
corsHeaders,
|
||||||
requestId: tracking.requestId,
|
enableTracing: true,
|
||||||
duration,
|
logRequests: true,
|
||||||
error: formatEdgeError(error)
|
logResponses: true,
|
||||||
});
|
rateLimitTier: 'strict', // 5 requests per minute
|
||||||
|
}, handler));
|
||||||
// Persist error to database for monitoring
|
|
||||||
const errorSpan = startSpan('export-user-data-error', 'SERVER');
|
|
||||||
endSpan(errorSpan, 'error', error);
|
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
|
||||||
const sanitized = sanitizeError(error, 'export-user-data');
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
...sanitized,
|
|
||||||
success: false,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 500,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, rateLimiters.strict, corsHeaders));
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { createErrorResponse, sanitizeError } from '../_shared/errorSanitizer.ts';
|
|
||||||
|
|
||||||
interface MergeTicketsRequest {
|
interface MergeTicketsRequest {
|
||||||
primaryTicketId: string;
|
primaryTicketId: string;
|
||||||
@@ -18,56 +17,7 @@ interface MergeTicketsResponse {
|
|||||||
deletedTickets: string[];
|
deletedTickets: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authHeader = req.headers.get('Authorization');
|
|
||||||
if (!authHeader) {
|
|
||||||
throw new Error('Missing authorization header');
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{ global: { headers: { Authorization: authHeader } } }
|
|
||||||
);
|
|
||||||
|
|
||||||
// Authenticate user
|
|
||||||
const { data: { user }, error: authError } = await supabase.auth.getUser();
|
|
||||||
if (authError || !user) {
|
|
||||||
throw new Error('Unauthorized');
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Merge tickets request started', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check if user has moderator/admin role
|
|
||||||
const { data: hasRole, error: roleError } = await supabase.rpc('has_role', {
|
|
||||||
_user_id: user.id,
|
|
||||||
_role: 'moderator'
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: isAdmin, error: adminError } = await supabase.rpc('has_role', {
|
|
||||||
_user_id: user.id,
|
|
||||||
_role: 'admin'
|
|
||||||
});
|
|
||||||
|
|
||||||
const { data: isSuperuser, error: superuserError } = await supabase.rpc('has_role', {
|
|
||||||
_user_id: user.id,
|
|
||||||
_role: 'superuser'
|
|
||||||
});
|
|
||||||
|
|
||||||
if (roleError || adminError || superuserError || (!hasRole && !isAdmin && !isSuperuser)) {
|
|
||||||
throw new Error('Insufficient permissions. Moderator role required.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse request body
|
// Parse request body
|
||||||
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
const { primaryTicketId, mergeTicketIds, mergeReason }: MergeTicketsRequest = await req.json();
|
||||||
|
|
||||||
@@ -84,6 +34,11 @@ serve(async (req) => {
|
|||||||
throw new Error('Maximum 10 tickets can be merged at once');
|
throw new Error('Maximum 10 tickets can be merged at once');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'merge_tickets_started', {
|
||||||
|
primaryTicketId,
|
||||||
|
mergeCount: mergeTicketIds.length
|
||||||
|
});
|
||||||
|
|
||||||
// Start transaction-like operations
|
// Start transaction-like operations
|
||||||
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
const allTicketIds = [primaryTicketId, ...mergeTicketIds];
|
||||||
|
|
||||||
@@ -105,7 +60,7 @@ serve(async (req) => {
|
|||||||
throw new Error('Primary ticket not found');
|
throw new Error('Primary ticket not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if any ticket already has merged_ticket_numbers (prevent re-merging)
|
// Check if any ticket already has merged_ticket_numbers
|
||||||
const alreadyMerged = tickets.find(t =>
|
const alreadyMerged = tickets.find(t =>
|
||||||
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
t.merged_ticket_numbers && t.merged_ticket_numbers.length > 0
|
||||||
);
|
);
|
||||||
@@ -113,15 +68,13 @@ serve(async (req) => {
|
|||||||
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
throw new Error(`Ticket ${alreadyMerged.ticket_number} has already been used in a merge`);
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Starting merge process', {
|
addSpanEvent(span, 'tickets_validated', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
mergeTicketCount: mergeTickets.length,
|
mergeTicketCount: mergeTickets.length
|
||||||
});
|
});
|
||||||
|
|
||||||
// Step 1: Move all email threads to primary ticket
|
// Step 1: Move all email threads to primary ticket
|
||||||
edgeLogger.info('Step 1: Moving email threads', {
|
addSpanEvent(span, 'moving_email_threads', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
fromTickets: mergeTickets.map(t => t.ticket_number)
|
fromTickets: mergeTickets.map(t => t.ticket_number)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -135,21 +88,13 @@ serve(async (req) => {
|
|||||||
|
|
||||||
const threadsMovedCount = movedThreads?.length || 0;
|
const threadsMovedCount = movedThreads?.length || 0;
|
||||||
|
|
||||||
edgeLogger.info('Threads moved successfully', {
|
addSpanEvent(span, 'threads_moved', { threadsMovedCount });
|
||||||
requestId: tracking.requestId,
|
|
||||||
threadsMovedCount
|
|
||||||
});
|
|
||||||
|
|
||||||
if (threadsMovedCount === 0) {
|
if (threadsMovedCount === 0) {
|
||||||
edgeLogger.warn('No email threads found to move', {
|
addSpanEvent(span, 'no_threads_found', { mergeTicketIds });
|
||||||
requestId: tracking.requestId,
|
|
||||||
mergeTicketIds
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 2: Consolidate admin notes
|
// Step 2: Consolidate admin notes
|
||||||
edgeLogger.info('Step 2: Consolidating admin notes', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
let consolidatedNotes = primaryTicket.admin_notes || '';
|
let consolidatedNotes = primaryTicket.admin_notes || '';
|
||||||
|
|
||||||
for (const ticket of mergeTickets) {
|
for (const ticket of mergeTickets) {
|
||||||
@@ -161,8 +106,6 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: Recalculate metadata from consolidated threads
|
// Step 3: Recalculate metadata from consolidated threads
|
||||||
edgeLogger.info('Step 3: Recalculating metadata from threads', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
const { data: threadStats, error: statsError } = await supabase
|
const { data: threadStats, error: statsError } = await supabase
|
||||||
.from('contact_email_threads')
|
.from('contact_email_threads')
|
||||||
.select('direction, created_at')
|
.select('direction, created_at')
|
||||||
@@ -178,8 +121,7 @@ serve(async (req) => {
|
|||||||
?.filter(t => t.direction === 'inbound')
|
?.filter(t => t.direction === 'inbound')
|
||||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0]?.created_at;
|
||||||
|
|
||||||
edgeLogger.info('Metadata recalculated', {
|
addSpanEvent(span, 'metadata_recalculated', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
outboundCount,
|
outboundCount,
|
||||||
lastAdminResponse,
|
lastAdminResponse,
|
||||||
lastUserResponse
|
lastUserResponse
|
||||||
@@ -189,8 +131,6 @@ serve(async (req) => {
|
|||||||
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
const mergedTicketNumbers = mergeTickets.map(t => t.ticket_number);
|
||||||
|
|
||||||
// Step 4: Update primary ticket with consolidated data
|
// Step 4: Update primary ticket with consolidated data
|
||||||
edgeLogger.info('Step 4: Updating primary ticket', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('contact_submissions')
|
.from('contact_submissions')
|
||||||
.update({
|
.update({
|
||||||
@@ -207,14 +147,9 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (updateError) throw updateError;
|
if (updateError) throw updateError;
|
||||||
|
|
||||||
edgeLogger.info('Primary ticket updated successfully', { requestId: tracking.requestId });
|
addSpanEvent(span, 'primary_ticket_updated', { primaryTicket: primaryTicket.ticket_number });
|
||||||
|
|
||||||
// Step 5: Delete merged tickets
|
// Step 5: Delete merged tickets
|
||||||
edgeLogger.info('Step 5: Deleting merged tickets', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
ticketsToDelete: mergeTicketIds.length
|
|
||||||
});
|
|
||||||
|
|
||||||
const { error: deleteError } = await supabase
|
const { error: deleteError } = await supabase
|
||||||
.from('contact_submissions')
|
.from('contact_submissions')
|
||||||
.delete()
|
.delete()
|
||||||
@@ -222,14 +157,12 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (deleteError) throw deleteError;
|
if (deleteError) throw deleteError;
|
||||||
|
|
||||||
edgeLogger.info('Merged tickets deleted successfully', { requestId: tracking.requestId });
|
addSpanEvent(span, 'merged_tickets_deleted', { count: mergeTicketIds.length });
|
||||||
|
|
||||||
// Step 6: Audit log
|
// Step 6: Audit log
|
||||||
edgeLogger.info('Step 6: Creating audit log', { requestId: tracking.requestId });
|
|
||||||
|
|
||||||
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
const { error: auditError } = await supabase.from('admin_audit_log').insert({
|
||||||
admin_user_id: user.id,
|
admin_user_id: user.id,
|
||||||
target_user_id: user.id, // No specific target user for this action
|
target_user_id: user.id,
|
||||||
action: 'merge_contact_tickets',
|
action: 'merge_contact_tickets',
|
||||||
details: {
|
details: {
|
||||||
primary_ticket_id: primaryTicketId,
|
primary_ticket_id: primaryTicketId,
|
||||||
@@ -243,20 +176,12 @@ serve(async (req) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (auditError) {
|
if (auditError) {
|
||||||
edgeLogger.warn('Failed to create audit log for merge', {
|
addSpanEvent(span, 'audit_log_failed', { error: auditError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: auditError.message,
|
|
||||||
primaryTicket: primaryTicket.ticket_number
|
|
||||||
});
|
|
||||||
// Don't throw - merge already succeeded
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'merge_completed', {
|
||||||
edgeLogger.info('Merge tickets completed successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
primaryTicket: primaryTicket.ticket_number,
|
primaryTicket: primaryTicket.ticket_number,
|
||||||
mergedCount: mergeTickets.length,
|
mergedCount: mergeTickets.length
|
||||||
});
|
});
|
||||||
|
|
||||||
const response: MergeTicketsResponse = {
|
const response: MergeTicketsResponse = {
|
||||||
@@ -267,24 +192,14 @@ serve(async (req) => {
|
|||||||
deletedTickets: mergedTicketNumbers,
|
deletedTickets: mergedTicketNumbers,
|
||||||
};
|
};
|
||||||
|
|
||||||
return new Response(JSON.stringify(response), {
|
return response;
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
};
|
||||||
status: 200,
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'merge-contact-tickets',
|
||||||
edgeLogger.error('Merge tickets failed', {
|
requireAuth: true,
|
||||||
requestId: tracking.requestId,
|
requiredRoles: ['superuser', 'admin', 'moderator'],
|
||||||
duration,
|
corsHeaders,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error',
|
enableTracing: true,
|
||||||
});
|
logRequests: true,
|
||||||
|
}, handler));
|
||||||
// Persist error to database for monitoring
|
|
||||||
const errorSpan = startSpan('merge-contact-tickets-error', 'SERVER');
|
|
||||||
endSpan(errorSpan, 'error', error);
|
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
|
||||||
|
|
||||||
return createErrorResponse(error, 500, corsHeaders, 'merge_contact_tickets');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface NotificationPayload {
|
interface NotificationPayload {
|
||||||
@@ -15,27 +15,13 @@ interface NotificationPayload {
|
|||||||
entityPreview: string;
|
entityPreview: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
const tracking = startRequest('notify-moderators-report');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
||||||
|
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
|
||||||
|
|
||||||
const payload: NotificationPayload = await req.json();
|
const payload: NotificationPayload = await req.json();
|
||||||
|
|
||||||
edgeLogger.info('Processing report notification', {
|
addSpanEvent(span, 'processing_report_notification', {
|
||||||
action: 'notify_moderators_report',
|
|
||||||
reportId: payload.reportId,
|
reportId: payload.reportId,
|
||||||
reportType: payload.reportType,
|
reportType: payload.reportType,
|
||||||
reportedEntityType: payload.reportedEntityType,
|
reportedEntityType: payload.reportedEntityType
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Calculate relative time
|
// Calculate relative time
|
||||||
@@ -76,21 +62,18 @@ serve(async (req) => {
|
|||||||
.maybeSingle();
|
.maybeSingle();
|
||||||
|
|
||||||
if (templateError) {
|
if (templateError) {
|
||||||
edgeLogger.error('Error fetching workflow', { action: 'notify_moderators_report', requestId: tracking.requestId, error: templateError });
|
addSpanEvent(span, 'workflow_fetch_failed', { error: templateError.message });
|
||||||
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
throw new Error(`Failed to fetch workflow: ${templateError.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!template) {
|
if (!template) {
|
||||||
edgeLogger.warn('No active report-alert workflow found', { action: 'notify_moderators_report', requestId: tracking.requestId });
|
addSpanEvent(span, 'no_active_workflow', {});
|
||||||
return new Response(
|
return new Response(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
success: false,
|
success: false,
|
||||||
error: 'No active report-alert workflow configured',
|
error: 'No active report-alert workflow configured',
|
||||||
}),
|
}),
|
||||||
{
|
{ status: 400 }
|
||||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
||||||
status: 400,
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +98,6 @@ serve(async (req) => {
|
|||||||
|
|
||||||
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
reportedEntityName = profile?.display_name || profile?.username || 'User Profile';
|
||||||
} else if (payload.reportedEntityType === 'content_submission') {
|
} else if (payload.reportedEntityType === 'content_submission') {
|
||||||
// Query submission_metadata table for the name instead of dropped content JSONB column
|
|
||||||
const { data: metadata } = await supabase
|
const { data: metadata } = await supabase
|
||||||
.from('submission_metadata')
|
.from('submission_metadata')
|
||||||
.select('metadata_value')
|
.select('metadata_value')
|
||||||
@@ -126,7 +108,9 @@ serve(async (req) => {
|
|||||||
reportedEntityName = metadata?.metadata_value || 'Submission';
|
reportedEntityName = metadata?.metadata_value || 'Submission';
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
edgeLogger.warn('Could not fetch entity name', { action: 'notify_moderators_report', requestId: tracking.requestId, error });
|
addSpanEvent(span, 'entity_name_fetch_failed', {
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build enhanced notification payload
|
// Build enhanced notification payload
|
||||||
@@ -145,7 +129,10 @@ serve(async (req) => {
|
|||||||
priority,
|
priority,
|
||||||
};
|
};
|
||||||
|
|
||||||
edgeLogger.info('Triggering notification with payload', { action: 'notify_moderators_report', requestId: tracking.requestId });
|
addSpanEvent(span, 'triggering_notification', {
|
||||||
|
workflowId: template.workflow_id,
|
||||||
|
priority
|
||||||
|
});
|
||||||
|
|
||||||
// Invoke the trigger-notification function with retry
|
// Invoke the trigger-notification function with retry
|
||||||
const result = await withEdgeRetry(
|
const result = await withEdgeRetry(
|
||||||
@@ -170,49 +157,24 @@ serve(async (req) => {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'trigger-report-notification'
|
'trigger-report-notification'
|
||||||
);
|
);
|
||||||
|
|
||||||
edgeLogger.info('Notification triggered successfully', { action: 'notify_moderators_report', requestId: tracking.requestId, result });
|
addSpanEvent(span, 'notification_sent', { transactionId: result?.transactionId });
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
return {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
transactionId: result?.transactionId,
|
transactionId: result?.transactionId,
|
||||||
payload: notificationPayload,
|
payload: notificationPayload,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error: any) {
|
|
||||||
edgeLogger.error('Error in notify-moderators-report', { action: 'notify_moderators_report', requestId: tracking.requestId, error: error.message });
|
|
||||||
|
|
||||||
endRequest(tracking, 500, error.message);
|
serve(createEdgeFunction({
|
||||||
|
name: 'notify-moderators-report',
|
||||||
return new Response(
|
requireAuth: false,
|
||||||
JSON.stringify({
|
useServiceRole: true,
|
||||||
success: false,
|
corsHeaders,
|
||||||
error: error.message,
|
enableTracing: true,
|
||||||
requestId: tracking.requestId
|
logRequests: true,
|
||||||
}),
|
}, handler));
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface NotificationPayload {
|
interface NotificationPayload {
|
||||||
@@ -16,24 +16,7 @@ interface NotificationPayload {
|
|||||||
is_escalated: boolean;
|
is_escalated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
||||||
|
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
|
||||||
|
|
||||||
const payload: NotificationPayload = await req.json();
|
const payload: NotificationPayload = await req.json();
|
||||||
const {
|
const {
|
||||||
submission_id,
|
submission_id,
|
||||||
@@ -47,12 +30,9 @@ serve(async (req) => {
|
|||||||
is_escalated
|
is_escalated
|
||||||
} = payload;
|
} = payload;
|
||||||
|
|
||||||
edgeLogger.info('Notifying moderators about submission via topic', {
|
addSpanEvent(span, 'processing_moderator_notification', {
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
submission_id,
|
submission_id,
|
||||||
submission_type,
|
submission_type
|
||||||
content_preview
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Calculate relative time and priority
|
// Calculate relative time and priority
|
||||||
@@ -85,28 +65,8 @@ serve(async (req) => {
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (workflowError || !workflow) {
|
if (workflowError || !workflow) {
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'workflow_fetch_failed', { error: workflowError?.message });
|
||||||
edgeLogger.error('Error fetching workflow', {
|
throw new Error('Workflow not found or not active');
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: workflowError
|
|
||||||
});
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: false,
|
|
||||||
error: 'Workflow not found or not active',
|
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate idempotency key for duplicate prevention
|
// Generate idempotency key for duplicate prevention
|
||||||
@@ -114,7 +74,7 @@ serve(async (req) => {
|
|||||||
.rpc('generate_notification_idempotency_key', {
|
.rpc('generate_notification_idempotency_key', {
|
||||||
p_notification_type: 'moderation_submission',
|
p_notification_type: 'moderation_submission',
|
||||||
p_entity_id: submission_id,
|
p_entity_id: submission_id,
|
||||||
p_recipient_id: '00000000-0000-0000-0000-000000000000', // Topic-based, use placeholder
|
p_recipient_id: '00000000-0000-0000-0000-000000000000',
|
||||||
p_event_data: { submission_type, action }
|
p_event_data: { submission_type, action }
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -129,62 +89,46 @@ serve(async (req) => {
|
|||||||
.maybeSingle();
|
.maybeSingle();
|
||||||
|
|
||||||
if (existingLog) {
|
if (existingLog) {
|
||||||
// Duplicate detected - log and skip
|
// Duplicate detected
|
||||||
await supabase.from('notification_logs').update({
|
await supabase.from('notification_logs').update({
|
||||||
is_duplicate: true
|
is_duplicate: true
|
||||||
}).eq('id', existingLog.id);
|
}).eq('id', existingLog.id);
|
||||||
|
|
||||||
edgeLogger.info('Duplicate notification prevented', {
|
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
submission_id
|
submission_id
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Duplicate notification prevented',
|
message: 'Duplicate notification prevented',
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare enhanced notification payload
|
// Prepare enhanced notification payload
|
||||||
const notificationPayload = {
|
const notificationPayload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
// Basic info
|
|
||||||
itemType: submission_type,
|
itemType: submission_type,
|
||||||
submitterName: submitter_name,
|
submitterName: submitter_name,
|
||||||
submissionId: submission_id,
|
submissionId: submission_id,
|
||||||
action: action || 'create',
|
action: action || 'create',
|
||||||
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
moderationUrl: 'https://www.thrillwiki.com/admin/moderation',
|
||||||
|
|
||||||
// Enhanced content
|
|
||||||
contentPreview: content_preview,
|
contentPreview: content_preview,
|
||||||
|
|
||||||
// Timing information
|
|
||||||
submittedAt: submitted_at,
|
submittedAt: submitted_at,
|
||||||
relativeTime: relativeTime,
|
relativeTime: relativeTime,
|
||||||
priority: priority,
|
priority: priority,
|
||||||
|
|
||||||
// Additional metadata
|
|
||||||
hasPhotos: has_photos,
|
hasPhotos: has_photos,
|
||||||
itemCount: item_count,
|
itemCount: item_count,
|
||||||
isEscalated: is_escalated,
|
isEscalated: is_escalated,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
addSpanEvent(span, 'triggering_notification', {
|
||||||
|
workflowId: workflow.workflow_id,
|
||||||
|
priority
|
||||||
|
});
|
||||||
|
|
||||||
// Send ONE notification to the moderation-submissions topic with retry
|
// Send ONE notification to the moderation-submissions topic with retry
|
||||||
// All subscribers (moderators) will receive it automatically
|
|
||||||
const data = await withEdgeRetry(
|
const data = await withEdgeRetry(
|
||||||
async () => {
|
async () => {
|
||||||
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
const { data: result, error } = await supabase.functions.invoke('trigger-notification', {
|
||||||
@@ -204,13 +148,13 @@ serve(async (req) => {
|
|||||||
return result;
|
return result;
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1000 },
|
{ maxAttempts: 3, baseDelay: 1000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'trigger-submission-notification'
|
'trigger-submission-notification'
|
||||||
);
|
);
|
||||||
|
|
||||||
// Log notification in notification_logs with idempotency key
|
// Log notification with idempotency key
|
||||||
const { error: logError } = await supabase.from('notification_logs').insert({
|
const { error: logError } = await supabase.from('notification_logs').insert({
|
||||||
user_id: '00000000-0000-0000-0000-000000000000', // Topic-based
|
user_id: '00000000-0000-0000-0000-000000000000',
|
||||||
notification_type: 'moderation_submission',
|
notification_type: 'moderation_submission',
|
||||||
idempotency_key: idempotencyKey,
|
idempotency_key: idempotencyKey,
|
||||||
is_duplicate: false,
|
is_duplicate: false,
|
||||||
@@ -222,69 +166,27 @@ serve(async (req) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (logError) {
|
if (logError) {
|
||||||
// Non-blocking - notification was sent successfully, log failure shouldn't fail the request
|
addSpanEvent(span, 'log_insertion_failed', { error: logError.message });
|
||||||
edgeLogger.warn('Failed to log notification in notification_logs', {
|
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: logError.message,
|
|
||||||
submissionId: submission_id
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'notification_sent', {
|
||||||
edgeLogger.info('Successfully notified all moderators via topic', {
|
transactionId: data?.transactionId,
|
||||||
action: 'notify_moderators',
|
topicKey: 'moderation-submissions'
|
||||||
requestId: tracking.requestId,
|
|
||||||
traceId: tracking.traceId,
|
|
||||||
duration,
|
|
||||||
transactionId: data?.transactionId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Moderator notifications sent via topic',
|
message: 'Moderator notifications sent via topic',
|
||||||
topicKey: 'moderation-submissions',
|
topicKey: 'moderation-submissions',
|
||||||
transactionId: data?.transactionId,
|
transactionId: data?.transactionId,
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error: any) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error in notify-moderators-submission', {
|
|
||||||
action: 'notify_moderators',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: error.message
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('notify-moderators-submission-error', 'SERVER');
|
name: 'notify-moderators-submission',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: false,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
useServiceRole: true,
|
||||||
|
corsHeaders,
|
||||||
return new Response(
|
enableTracing: true,
|
||||||
JSON.stringify({
|
logRequests: true,
|
||||||
success: false,
|
}, handler));
|
||||||
error: error.message,
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeadersWithTracing as corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest } from "../_shared/logger.ts";
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
|
||||||
interface RequestBody {
|
interface RequestBody {
|
||||||
submission_id: string;
|
submission_id: string;
|
||||||
@@ -81,21 +81,15 @@ async function constructEntityURL(
|
|||||||
return `${baseURL}`;
|
return `${baseURL}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
const tracking = startRequest('notify-user-submission-status');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
|
|
||||||
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
||||||
|
|
||||||
const supabase = createClient(supabaseUrl, supabaseServiceKey);
|
|
||||||
|
|
||||||
const { submission_id, user_id, submission_type, status, reviewer_notes } = await req.json() as RequestBody;
|
const { submission_id, user_id, submission_type, status, reviewer_notes } = await req.json() as RequestBody;
|
||||||
|
|
||||||
|
addSpanEvent(span, 'notification_request', {
|
||||||
|
submissionId: submission_id,
|
||||||
|
userId: user_id,
|
||||||
|
status
|
||||||
|
});
|
||||||
|
|
||||||
// Fetch submission items to get entity data
|
// Fetch submission items to get entity data
|
||||||
const { data: items, error: itemsError } = await supabase
|
const { data: items, error: itemsError } = await supabase
|
||||||
.from('submission_items')
|
.from('submission_items')
|
||||||
@@ -126,7 +120,6 @@ serve(async (req) => {
|
|||||||
let payload: Record<string, string>;
|
let payload: Record<string, string>;
|
||||||
|
|
||||||
if (status === 'approved') {
|
if (status === 'approved') {
|
||||||
// Approval payload
|
|
||||||
payload = {
|
payload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
entityType,
|
entityType,
|
||||||
@@ -136,7 +129,6 @@ serve(async (req) => {
|
|||||||
moderationNotes: reviewer_notes || '',
|
moderationNotes: reviewer_notes || '',
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Rejection payload
|
|
||||||
payload = {
|
payload = {
|
||||||
baseUrl: 'https://www.thrillwiki.com',
|
baseUrl: 'https://www.thrillwiki.com',
|
||||||
rejectionReason: reviewer_notes || 'No reason provided',
|
rejectionReason: reviewer_notes || 'No reason provided',
|
||||||
@@ -172,42 +164,22 @@ serve(async (req) => {
|
|||||||
is_duplicate: true
|
is_duplicate: true
|
||||||
}).eq('id', existingLog.id);
|
}).eq('id', existingLog.id);
|
||||||
|
|
||||||
edgeLogger.info('Duplicate notification prevented', {
|
addSpanEvent(span, 'duplicate_notification_prevented', {
|
||||||
action: 'notify_user_submission_status',
|
|
||||||
userId: user_id,
|
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
submissionId: submission_id,
|
submissionId: submission_id
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
return {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Duplicate notification prevented',
|
message: 'Duplicate notification prevented',
|
||||||
idempotencyKey,
|
idempotencyKey,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Sending notification to user', {
|
addSpanEvent(span, 'sending_notification', {
|
||||||
action: 'notify_user_submission_status',
|
|
||||||
userId: user_id,
|
|
||||||
workflowId,
|
workflowId,
|
||||||
entityName,
|
entityName,
|
||||||
status,
|
idempotencyKey
|
||||||
idempotencyKey,
|
|
||||||
requestId: tracking.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Call trigger-notification function
|
// Call trigger-notification function
|
||||||
@@ -239,45 +211,21 @@ serve(async (req) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
edgeLogger.info('User notification sent successfully', { action: 'notify_user_submission_status', requestId: tracking.requestId, result: notificationResult });
|
addSpanEvent(span, 'notification_sent', {
|
||||||
|
transactionId: notificationResult?.transactionId
|
||||||
|
});
|
||||||
|
|
||||||
endRequest(tracking, 200);
|
return {
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
transactionId: notificationResult?.transactionId,
|
transactionId: notificationResult?.transactionId,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 200,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
||||||
edgeLogger.error('Error notifying user about submission status', { action: 'notify_user_submission_status', requestId: tracking.requestId, error: errorMessage });
|
|
||||||
|
|
||||||
endRequest(tracking, 500, errorMessage);
|
serve(createEdgeFunction({
|
||||||
|
name: 'notify-user-submission-status',
|
||||||
return new Response(
|
requireAuth: false,
|
||||||
JSON.stringify({
|
useServiceRole: true,
|
||||||
success: false,
|
corsHeaders,
|
||||||
error: errorMessage,
|
enableTracing: true,
|
||||||
requestId: tracking.requestId
|
logRequests: true,
|
||||||
}),
|
}, handler));
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
status: 500,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,16 +1,10 @@
|
|||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { edgeLogger } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
|
|
||||||
export default createEdgeFunction(
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
{
|
addSpanEvent(span, 'processing_expired_bans', { requestId });
|
||||||
name: 'process-expired-bans',
|
|
||||||
requireAuth: false,
|
|
||||||
},
|
|
||||||
async (req, context, supabase) => {
|
|
||||||
edgeLogger.info('Processing expired bans', {
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
@@ -23,25 +17,18 @@ export default createEdgeFunction(
|
|||||||
.lte('ban_expires_at', now);
|
.lte('ban_expires_at', now);
|
||||||
|
|
||||||
if (fetchError) {
|
if (fetchError) {
|
||||||
edgeLogger.error('Error fetching expired bans', {
|
addSpanEvent(span, 'error_fetching_expired_bans', { error: fetchError.message });
|
||||||
error: fetchError,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
throw fetchError;
|
throw fetchError;
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Found expired bans to process', {
|
addSpanEvent(span, 'found_expired_bans', { count: expiredBans?.length || 0 });
|
||||||
count: expiredBans?.length || 0,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
// Unban users with expired bans
|
// Unban users with expired bans
|
||||||
const unbannedUsers: string[] = [];
|
const unbannedUsers: string[] = [];
|
||||||
for (const profile of expiredBans || []) {
|
for (const profile of expiredBans || []) {
|
||||||
edgeLogger.info('Unbanning user', {
|
addSpanEvent(span, 'unbanning_user', {
|
||||||
username: profile.username,
|
username: profile.username,
|
||||||
userId: profile.user_id,
|
userId: profile.user_id
|
||||||
requestId: context.requestId
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const { error: unbanError } = await supabase
|
const { error: unbanError } = await supabase
|
||||||
@@ -54,10 +41,9 @@ export default createEdgeFunction(
|
|||||||
.eq('user_id', profile.user_id);
|
.eq('user_id', profile.user_id);
|
||||||
|
|
||||||
if (unbanError) {
|
if (unbanError) {
|
||||||
edgeLogger.error('Failed to unban user', {
|
addSpanEvent(span, 'failed_to_unban_user', {
|
||||||
username: profile.username,
|
username: profile.username,
|
||||||
error: unbanError,
|
error: unbanError.message
|
||||||
requestId: context.requestId
|
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -76,29 +62,28 @@ export default createEdgeFunction(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (logError) {
|
if (logError) {
|
||||||
edgeLogger.error('Failed to log auto-unban', {
|
addSpanEvent(span, 'failed_to_log_auto_unban', {
|
||||||
username: profile.username,
|
username: profile.username,
|
||||||
error: logError,
|
error: logError.message
|
||||||
requestId: context.requestId
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
unbannedUsers.push(profile.username);
|
unbannedUsers.push(profile.username);
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Successfully unbanned users', {
|
addSpanEvent(span, 'successfully_unbanned_users', { count: unbannedUsers.length });
|
||||||
count: unbannedUsers.length,
|
|
||||||
requestId: context.requestId
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
unbanned_count: unbannedUsers.length,
|
unbanned_count: unbannedUsers.length,
|
||||||
unbanned_users: unbannedUsers,
|
unbanned_users: unbannedUsers,
|
||||||
processed_at: now
|
processed_at: now
|
||||||
}),
|
};
|
||||||
{ headers: { 'Content-Type': 'application/json' } }
|
};
|
||||||
);
|
|
||||||
}
|
serve(createEdgeFunction({
|
||||||
);
|
name: 'process-expired-bans',
|
||||||
|
requireAuth: false,
|
||||||
|
corsHeaders,
|
||||||
|
enableTracing: true,
|
||||||
|
}, handler));
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
/**
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
* Rate Limit Metrics API
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
*
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
* Exposes rate limiting metrics for monitoring and analysis.
|
|
||||||
* Requires admin/moderator authentication.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
|
|
||||||
import {
|
import {
|
||||||
getRecentMetrics,
|
getRecentMetrics,
|
||||||
getMetricsStats,
|
getMetricsStats,
|
||||||
@@ -15,18 +10,7 @@ import {
|
|||||||
clearMetrics,
|
clearMetrics,
|
||||||
} from '../_shared/rateLimitMetrics.ts';
|
} from '../_shared/rateLimitMetrics.ts';
|
||||||
|
|
||||||
interface QueryParams {
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
action?: string;
|
|
||||||
limit?: string;
|
|
||||||
timeWindow?: string;
|
|
||||||
functionName?: string;
|
|
||||||
userId?: string;
|
|
||||||
clientIP?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
// Check if user has admin or moderator role
|
||||||
const { data: roles } = await supabase
|
const { data: roles } = await supabase
|
||||||
.from('user_roles')
|
.from('user_roles')
|
||||||
@@ -116,14 +100,10 @@ const handler = async (req: Request, context: { supabase: any; user: any; span:
|
|||||||
return responseData;
|
return responseData;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create edge function with automatic error handling, CORS, auth, and logging
|
serve(createEdgeFunction({
|
||||||
createEdgeFunction(
|
|
||||||
{
|
|
||||||
name: 'rate-limit-metrics',
|
name: 'rate-limit-metrics',
|
||||||
requireAuth: true,
|
requireAuth: true,
|
||||||
corsEnabled: true,
|
corsHeaders,
|
||||||
enableTracing: false,
|
enableTracing: true,
|
||||||
rateLimitTier: 'lenient'
|
rateLimitTier: 'lenient',
|
||||||
},
|
}, handler));
|
||||||
handler
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -1,63 +1,13 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.190.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { rateLimiters, withRateLimit } from '../_shared/rateLimiter.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
|
||||||
|
|
||||||
// Apply moderate rate limiting (10 req/min) to prevent deletion code spam
|
const handler = async (req: Request, { supabase, user, span, requestId }: EdgeFunctionContext) => {
|
||||||
// Protects against abuse while allowing legitimate resend requests
|
addSpanEvent(span, 'resending_deletion_code', { userId: user.id });
|
||||||
serve(withRateLimit(async (req) => {
|
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseClient = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{
|
|
||||||
global: {
|
|
||||||
headers: { Authorization: req.headers.get('Authorization')! },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Get authenticated user
|
|
||||||
const {
|
|
||||||
data: { user },
|
|
||||||
error: userError,
|
|
||||||
} = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (userError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Authentication failed', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database
|
|
||||||
const authErrorSpan = startSpan('resend-deletion-code-auth-error', 'SERVER');
|
|
||||||
endSpan(authErrorSpan, 'error', userError);
|
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
|
||||||
throw new Error('Unauthorized');
|
|
||||||
}
|
|
||||||
|
|
||||||
edgeLogger.info('Resending deletion code for user', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Find pending deletion request
|
// Find pending deletion request
|
||||||
const { data: deletionRequest, error: requestError } = await supabaseClient
|
const { data: deletionRequest, error: requestError } = await supabase
|
||||||
.from('account_deletion_requests')
|
.from('account_deletion_requests')
|
||||||
.select('*')
|
.select('*')
|
||||||
.eq('user_id', user.id)
|
.eq('user_id', user.id)
|
||||||
@@ -68,17 +18,21 @@ serve(withRateLimit(async (req) => {
|
|||||||
throw new Error('No pending deletion request found');
|
throw new Error('No pending deletion request found');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check rate limiting (max 3 resends per hour)
|
// Check rate limiting (max 3 resends per hour - ~20 minutes between resends)
|
||||||
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
|
const lastSent = new Date(deletionRequest.confirmation_code_sent_at);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
|
const hoursSinceLastSend = (now.getTime() - lastSent.getTime()) / (1000 * 60 * 60);
|
||||||
|
|
||||||
if (hoursSinceLastSend < 0.33) { // ~20 minutes between resends
|
if (hoursSinceLastSend < 0.33) {
|
||||||
|
addSpanEvent(span, 'resend_rate_limited', {
|
||||||
|
hoursSinceLastSend,
|
||||||
|
minRequired: 0.33
|
||||||
|
});
|
||||||
throw new Error('Please wait at least 20 minutes between resend requests');
|
throw new Error('Please wait at least 20 minutes between resend requests');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate new confirmation code
|
// Generate new confirmation code
|
||||||
const { data: codeData, error: codeError } = await supabaseClient
|
const { data: codeData, error: codeError } = await supabase
|
||||||
.rpc('generate_deletion_confirmation_code');
|
.rpc('generate_deletion_confirmation_code');
|
||||||
|
|
||||||
if (codeError) {
|
if (codeError) {
|
||||||
@@ -88,7 +42,7 @@ serve(withRateLimit(async (req) => {
|
|||||||
const confirmationCode = codeData as string;
|
const confirmationCode = codeData as string;
|
||||||
|
|
||||||
// Update deletion request with new code
|
// Update deletion request with new code
|
||||||
const { error: updateError } = await supabaseClient
|
const { error: updateError } = await supabase
|
||||||
.from('account_deletion_requests')
|
.from('account_deletion_requests')
|
||||||
.update({
|
.update({
|
||||||
confirmation_code: confirmationCode,
|
confirmation_code: confirmationCode,
|
||||||
@@ -102,6 +56,10 @@ serve(withRateLimit(async (req) => {
|
|||||||
|
|
||||||
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
const scheduledDate = new Date(deletionRequest.scheduled_deletion_at);
|
||||||
|
|
||||||
|
addSpanEvent(span, 'new_code_generated', {
|
||||||
|
scheduledDeletionDate: scheduledDate.toISOString()
|
||||||
|
});
|
||||||
|
|
||||||
// Send email with new code
|
// Send email with new code
|
||||||
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
|
||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||||
@@ -130,64 +88,27 @@ serve(withRateLimit(async (req) => {
|
|||||||
`,
|
`,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
edgeLogger.info('New confirmation code email sent', { requestId: tracking.requestId });
|
addSpanEvent(span, 'email_sent', { email: user.email });
|
||||||
} catch (emailError) {
|
} catch (emailError) {
|
||||||
edgeLogger.error('Failed to send email', {
|
addSpanEvent(span, 'email_send_failed', {
|
||||||
requestId: tracking.requestId,
|
error: emailError instanceof Error ? emailError.message : String(emailError)
|
||||||
error: emailError.message
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'resend_completed', { userId: user.id });
|
||||||
edgeLogger.info('New confirmation code sent successfully', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'New confirmation code sent successfully',
|
message: 'New confirmation code sent successfully',
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error resending code', {
|
|
||||||
action: 'resend_deletion_code',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: error.message
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('resend-deletion-code-error', 'SERVER');
|
name: 'resend-deletion-code',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: true,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
corsHeaders,
|
||||||
return new Response(
|
enableTracing: true,
|
||||||
JSON.stringify({
|
logRequests: true,
|
||||||
error: error.message,
|
rateLimitTier: 'moderate', // 10 requests per minute
|
||||||
requestId: tracking.requestId
|
}, handler));
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 400,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, rateLimiters.moderate, corsHeaders));
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
|
||||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.57.4";
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
import { withEdgeRetry } from '../_shared/retryHelper.ts';
|
||||||
|
|
||||||
interface EscalationRequest {
|
interface EscalationRequest {
|
||||||
@@ -10,27 +10,10 @@ interface EscalationRequest {
|
|||||||
escalatedBy: string;
|
escalatedBy: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { supabase, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, { headers: corsHeaders });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabase = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
|
||||||
);
|
|
||||||
|
|
||||||
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
const { submissionId, escalationReason, escalatedBy }: EscalationRequest = await req.json();
|
||||||
|
|
||||||
edgeLogger.info('Processing escalation notification', {
|
addSpanEvent(span, 'processing_escalation', { submissionId, escalatedBy });
|
||||||
requestId: tracking.requestId,
|
|
||||||
submissionId,
|
|
||||||
escalatedBy,
|
|
||||||
action: 'send_escalation'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch submission details
|
// Fetch submission details
|
||||||
const { data: submission, error: submissionError } = await supabase
|
const { data: submission, error: submissionError } = await supabase
|
||||||
@@ -51,11 +34,7 @@ serve(async (req) => {
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (escalatorError) {
|
if (escalatorError) {
|
||||||
edgeLogger.error('Failed to fetch escalator profile', {
|
addSpanEvent(span, 'escalator_profile_fetch_failed', { error: escalatorError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: escalatorError.message,
|
|
||||||
escalatedBy
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch submission items count
|
// Fetch submission items count
|
||||||
@@ -65,11 +44,7 @@ serve(async (req) => {
|
|||||||
.eq('submission_id', submissionId);
|
.eq('submission_id', submissionId);
|
||||||
|
|
||||||
if (countError) {
|
if (countError) {
|
||||||
edgeLogger.error('Failed to fetch items count', {
|
addSpanEvent(span, 'items_count_fetch_failed', { error: countError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: countError.message,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prepare email content
|
// Prepare email content
|
||||||
@@ -175,6 +150,8 @@ serve(async (req) => {
|
|||||||
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
throw new Error('Email configuration is incomplete. Please check environment variables.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addSpanEvent(span, 'sending_escalation_email', { adminEmail });
|
||||||
|
|
||||||
const emailResult = await withEdgeRetry(
|
const emailResult = await withEdgeRetry(
|
||||||
async () => {
|
async () => {
|
||||||
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
const emailResponse = await fetch('https://api.forwardemail.net/v1/emails', {
|
||||||
@@ -196,7 +173,7 @@ serve(async (req) => {
|
|||||||
let errorText;
|
let errorText;
|
||||||
try {
|
try {
|
||||||
errorText = await emailResponse.text();
|
errorText = await emailResponse.text();
|
||||||
} catch (parseError) {
|
} catch {
|
||||||
errorText = 'Unable to parse error response';
|
errorText = 'Unable to parse error response';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,19 +182,16 @@ serve(async (req) => {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await emailResponse.json();
|
return await emailResponse.json();
|
||||||
return result;
|
|
||||||
},
|
},
|
||||||
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
{ maxAttempts: 3, baseDelay: 1500, maxDelay: 10000 },
|
||||||
tracking.requestId,
|
requestId,
|
||||||
'send-escalation-email'
|
'send-escalation-email'
|
||||||
);
|
);
|
||||||
edgeLogger.info('Email sent successfully', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
emailId: emailResult.id
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update submission with notification status
|
addSpanEvent(span, 'email_sent', { emailId: emailResult.id });
|
||||||
|
|
||||||
|
// Update submission with escalation status
|
||||||
const { error: updateError } = await supabase
|
const { error: updateError } = await supabase
|
||||||
.from('content_submissions')
|
.from('content_submissions')
|
||||||
.update({
|
.update({
|
||||||
@@ -229,57 +203,26 @@ serve(async (req) => {
|
|||||||
.eq('id', submissionId);
|
.eq('id', submissionId);
|
||||||
|
|
||||||
if (updateError) {
|
if (updateError) {
|
||||||
edgeLogger.error('Failed to update submission escalation status', {
|
addSpanEvent(span, 'submission_update_failed', { error: updateError.message });
|
||||||
requestId: tracking.requestId,
|
|
||||||
error: updateError.message,
|
|
||||||
submissionId
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'escalation_notification_complete', {
|
||||||
edgeLogger.info('Escalation notification sent', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
emailId: emailResult.id,
|
emailId: emailResult.id,
|
||||||
submissionId
|
submissionId
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Escalation notification sent successfully',
|
message: 'Escalation notification sent successfully',
|
||||||
emailId: emailResult.id,
|
emailId: emailResult.id,
|
||||||
requestId: tracking.requestId
|
};
|
||||||
}),
|
};
|
||||||
{ headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
} }
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Error in send-escalation-notification', {
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration,
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error'
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
serve(createEdgeFunction({
|
||||||
const errorSpan = startSpan('send-escalation-notification-error', 'SERVER');
|
name: 'send-escalation-notification',
|
||||||
endSpan(errorSpan, 'error', error);
|
requireAuth: false,
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
useServiceRole: true,
|
||||||
return new Response(
|
corsHeaders,
|
||||||
JSON.stringify({
|
enableTracing: true,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
logRequests: true,
|
||||||
details: 'Failed to send escalation notification',
|
}, handler));
|
||||||
requestId: tracking.requestId
|
|
||||||
}),
|
|
||||||
{ status: 500, headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
} }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
|
||||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
|
import { createEdgeFunction, type EdgeFunctionContext } from '../_shared/edgeFunctionWrapper.ts';
|
||||||
import { corsHeaders } from '../_shared/cors.ts';
|
import { corsHeaders } from '../_shared/cors.ts';
|
||||||
import { edgeLogger, startRequest, endRequest, logSpanToDatabase, startSpan, endSpan } from '../_shared/logger.ts';
|
import { addSpanEvent } from '../_shared/logger.ts';
|
||||||
|
|
||||||
interface EmailRequest {
|
interface EmailRequest {
|
||||||
email: string;
|
email: string;
|
||||||
@@ -9,58 +9,14 @@ interface EmailRequest {
|
|||||||
username?: string;
|
username?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
serve(async (req) => {
|
const handler = async (req: Request, { user, span, requestId }: EdgeFunctionContext) => {
|
||||||
const tracking = startRequest();
|
|
||||||
|
|
||||||
if (req.method === 'OPTIONS') {
|
|
||||||
return new Response(null, {
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const supabaseClient = createClient(
|
|
||||||
Deno.env.get('SUPABASE_URL') ?? '',
|
|
||||||
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
||||||
{
|
|
||||||
global: {
|
|
||||||
headers: { Authorization: req.headers.get('Authorization')! },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const { data: { user }, error: userError } = await supabaseClient.auth.getUser();
|
|
||||||
|
|
||||||
if (userError || !user) {
|
|
||||||
const duration = endRequest(tracking);
|
|
||||||
edgeLogger.error('Authentication failed', {
|
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database
|
|
||||||
const authErrorSpan = startSpan('send-password-added-email-auth-error', 'SERVER');
|
|
||||||
endSpan(authErrorSpan, 'error', userError);
|
|
||||||
logSpanToDatabase(authErrorSpan, tracking.requestId);
|
|
||||||
throw new Error('Unauthorized');
|
|
||||||
}
|
|
||||||
|
|
||||||
const { email, displayName, username }: EmailRequest = await req.json();
|
const { email, displayName, username }: EmailRequest = await req.json();
|
||||||
|
|
||||||
if (!email) {
|
if (!email) {
|
||||||
throw new Error('Email is required');
|
throw new Error('Email is required');
|
||||||
}
|
}
|
||||||
|
|
||||||
edgeLogger.info('Sending password added email', {
|
addSpanEvent(span, 'sending_password_email', { userId: user.id, email });
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
email
|
|
||||||
});
|
|
||||||
|
|
||||||
const recipientName = displayName || username || 'there';
|
const recipientName = displayName || username || 'there';
|
||||||
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
const siteUrl = Deno.env.get('SITE_URL') || 'https://thrillwiki.com';
|
||||||
@@ -139,7 +95,7 @@ serve(async (req) => {
|
|||||||
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';
|
||||||
|
|
||||||
if (!forwardEmailKey) {
|
if (!forwardEmailKey) {
|
||||||
edgeLogger.error('FORWARDEMAIL_API_KEY not configured', { requestId: tracking.requestId });
|
addSpanEvent(span, 'email_config_missing', {});
|
||||||
throw new Error('Email service not configured');
|
throw new Error('Email service not configured');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,67 +115,25 @@ serve(async (req) => {
|
|||||||
|
|
||||||
if (!emailResponse.ok) {
|
if (!emailResponse.ok) {
|
||||||
const errorText = await emailResponse.text();
|
const errorText = await emailResponse.text();
|
||||||
edgeLogger.error('ForwardEmail API error', {
|
addSpanEvent(span, 'email_send_failed', {
|
||||||
requestId: tracking.requestId,
|
|
||||||
status: emailResponse.status,
|
status: emailResponse.status,
|
||||||
errorText
|
error: errorText
|
||||||
});
|
});
|
||||||
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
throw new Error(`Failed to send email: ${emailResponse.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const duration = endRequest(tracking);
|
addSpanEvent(span, 'email_sent_successfully', { email });
|
||||||
edgeLogger.info('Password addition email sent successfully', {
|
|
||||||
action: 'send_password_email',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
userId: user.id,
|
|
||||||
email,
|
|
||||||
duration
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Response(
|
return {
|
||||||
JSON.stringify({
|
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Password addition email sent successfully',
|
message: 'Password addition email sent successfully',
|
||||||
requestId: tracking.requestId,
|
};
|
||||||
}),
|
};
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
} catch (error) {
|
serve(createEdgeFunction({
|
||||||
const duration = endRequest(tracking);
|
name: 'send-password-added-email',
|
||||||
edgeLogger.error('Error in send-password-added-email function', {
|
requireAuth: true,
|
||||||
action: 'send_password_email',
|
corsHeaders,
|
||||||
requestId: tracking.requestId,
|
enableTracing: true,
|
||||||
duration,
|
logRequests: true,
|
||||||
error: error instanceof Error ? error.message : 'Unknown error'
|
}, handler));
|
||||||
});
|
|
||||||
|
|
||||||
// Persist error to database for monitoring
|
|
||||||
const errorSpan = startSpan('send-password-added-email-error', 'SERVER');
|
|
||||||
endSpan(errorSpan, 'error', error);
|
|
||||||
logSpanToDatabase(errorSpan, tracking.requestId);
|
|
||||||
|
|
||||||
return new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
success: false,
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error',
|
|
||||||
requestId: tracking.requestId,
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status: 500,
|
|
||||||
headers: {
|
|
||||||
...corsHeaders,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Request-ID': tracking.requestId
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|||||||
Reference in New Issue
Block a user