diff --git a/src/components/moderation/RealtimeConnectionStatus.tsx b/src/components/moderation/RealtimeConnectionStatus.tsx index 48a583c7..4152236b 100644 --- a/src/components/moderation/RealtimeConnectionStatus.tsx +++ b/src/components/moderation/RealtimeConnectionStatus.tsx @@ -1,7 +1,8 @@ import { RefreshCw, Wifi, WifiOff, AlertCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; -import { ConnectionState } from '@/hooks/useEnhancedRealtime'; + +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; interface RealtimeConnectionStatusProps { connectionState: ConnectionState; diff --git a/src/hooks/useEnhancedRealtime.ts b/src/hooks/useEnhancedRealtime.ts deleted file mode 100644 index b2d141b2..00000000 --- a/src/hooks/useEnhancedRealtime.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { useEffect, useState, useRef, useCallback } from 'react'; -import { supabase } from '@/integrations/supabase/client'; -import { RealtimeChannel } from '@supabase/supabase-js'; -import { toast } from '@/hooks/use-toast'; - -export type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; - -interface UseEnhancedRealtimeOptions { - enabled?: boolean; - channelName: string; - debug?: boolean; - retryAttempts?: number; - retryDelay?: number; - maxRetryDelay?: number; - onConnectionChange?: (state: ConnectionState) => void; -} - -interface UseEnhancedRealtimeReturn { - channel: RealtimeChannel | null; - connectionState: ConnectionState; - reconnect: () => void; - disconnect: () => void; -} - -const activeChannels = new Map(); - -export const useEnhancedRealtime = ( - options: UseEnhancedRealtimeOptions -): UseEnhancedRealtimeReturn => { - const { - enabled = true, - channelName, - debug = false, - retryAttempts = 5, - retryDelay = 1000, - maxRetryDelay = 30000, - onConnectionChange, - } = options; - - const [channel, setChannel] = useState(null); - const [connectionState, setConnectionState] = useState('disconnected'); - const retryCountRef = useRef(0); - const retryTimeoutRef = useRef(null); - const onConnectionChangeRef = useRef(onConnectionChange); - - // Update callback ref - useEffect(() => { - onConnectionChangeRef.current = onConnectionChange; - }, [onConnectionChange]); - - const log = useCallback((...args: any[]) => { - if (debug) { - console.log(`[Realtime:${channelName}]`, ...args); - } - }, [debug, channelName]); - - const updateConnectionState = useCallback((state: ConnectionState) => { - setConnectionState(state); - onConnectionChangeRef.current?.(state); - log('Connection state:', state); - }, [log]); - - const calculateRetryDelay = useCallback((attempt: number): number => { - // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 30s (max) - const delay = Math.min(retryDelay * Math.pow(2, attempt), maxRetryDelay); - return delay; - }, [retryDelay, maxRetryDelay]); - - const cleanup = useCallback(() => { - if (retryTimeoutRef.current) { - clearTimeout(retryTimeoutRef.current); - retryTimeoutRef.current = null; - } - - const existingChannel = activeChannels.get(channelName); - if (existingChannel) { - log('Cleaning up existing channel'); - supabase.removeChannel(existingChannel); - activeChannels.delete(channelName); - } - - setChannel(null); - }, [channelName, log]); - - const connect = useCallback(() => { - if (!enabled) { - log('Realtime disabled'); - return; - } - - // Check if channel already exists - if (activeChannels.has(channelName)) { - log('Channel already exists, reusing'); - const existingChannel = activeChannels.get(channelName)!; - setChannel(existingChannel); - updateConnectionState('connected'); - return; - } - - log('Creating new channel'); - updateConnectionState('connecting'); - - const newChannel = supabase.channel(channelName); - - // Store channel immediately to prevent duplicates - activeChannels.set(channelName, newChannel); - setChannel(newChannel); - - // Subscribe with status monitoring - newChannel.subscribe((status) => { - log('Subscription status:', status); - - if (status === 'SUBSCRIBED') { - updateConnectionState('connected'); - retryCountRef.current = 0; // Reset retry count on successful connection - - if (retryCountRef.current > 0) { - toast({ - title: "Connection Restored", - description: "Live updates are now active", - }); - } - } else if (status === 'CHANNEL_ERROR') { - updateConnectionState('error'); - log('Channel error, attempting retry'); - - // Attempt reconnection - if (retryCountRef.current < retryAttempts) { - const delay = calculateRetryDelay(retryCountRef.current); - log(`Retrying in ${delay}ms (attempt ${retryCountRef.current + 1}/${retryAttempts})`); - - retryTimeoutRef.current = setTimeout(() => { - retryCountRef.current++; - cleanup(); - connect(); - }, delay); - } else { - log('Max retry attempts reached'); - toast({ - title: "Connection Failed", - description: "Unable to establish live updates. Please refresh the page.", - variant: "destructive", - }); - } - } else if (status === 'TIMED_OUT') { - updateConnectionState('disconnected'); - log('Connection timed out'); - - // Attempt reconnection - if (retryCountRef.current < retryAttempts) { - retryCountRef.current++; - cleanup(); - connect(); - } - } else if (status === 'CLOSED') { - updateConnectionState('disconnected'); - log('Connection closed'); - } - }); - }, [enabled, channelName, log, updateConnectionState, retryAttempts, calculateRetryDelay, cleanup]); - - const reconnect = useCallback(() => { - log('Manual reconnect triggered'); - retryCountRef.current = 0; - cleanup(); - connect(); - }, [log, cleanup, connect]); - - const disconnect = useCallback(() => { - log('Manual disconnect triggered'); - cleanup(); - updateConnectionState('disconnected'); - }, [log, cleanup, updateConnectionState]); - - // Connect on mount or when enabled changes - useEffect(() => { - if (enabled) { - connect(); - } else { - cleanup(); - updateConnectionState('disconnected'); - } - - return () => { - cleanup(); - }; - }, [enabled]); // Only depend on enabled, not connect/cleanup to avoid loops - - return { - channel, - connectionState, - reconnect, - disconnect, - }; -}; diff --git a/src/hooks/useRealtimeModerationStats.ts b/src/hooks/useRealtimeModerationStats.ts index a1a83807..8172b55f 100644 --- a/src/hooks/useRealtimeModerationStats.ts +++ b/src/hooks/useRealtimeModerationStats.ts @@ -1,8 +1,10 @@ import { useEffect, useState, useRef, useCallback } from 'react'; import { supabase } from '@/integrations/supabase/client'; -import { useEnhancedRealtime, ConnectionState } from './useEnhancedRealtime'; +import { RealtimeChannel } from '@supabase/supabase-js'; import { useUserRole } from './useUserRole'; +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; + interface ModerationStats { pendingSubmissions: number; openReports: number; @@ -23,6 +25,8 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp openReports: 0, flaggedContent: 0, }); + const [channel, setChannel] = useState(null); + const [connectionState, setConnectionState] = useState('disconnected'); const updateTimerRef = useRef(null); const onStatsChangeRef = useRef(onStatsChange); @@ -71,29 +75,23 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp updateTimerRef.current = setTimeout(fetchStats, debounceMs); }, [fetchStats, debounceMs]); - const { channel, connectionState, reconnect } = useEnhancedRealtime({ - enabled: realtimeEnabled, - channelName: 'moderation-stats-changes', - debug: true, - onConnectionChange: (state: ConnectionState) => { - // Fallback to polling when disconnected - if (state === 'disconnected' || state === 'error') { - console.log('Realtime disconnected, falling back to polling'); - // Could implement polling here if needed - } - }, - }); + const reconnect = useCallback(() => { + if (channel) { + supabase.removeChannel(channel); + } + setConnectionState('connecting'); + fetchStats(); + }, [channel, fetchStats]); + // Initial fetch and polling fallback useEffect(() => { if (!enabled) return; - // Initial fetch fetchStats(); - // Set up polling interval as fallback (only when connected state is not 'connected') let pollInterval: NodeJS.Timeout | null = null; if (connectionState !== 'connected') { - pollInterval = setInterval(fetchStats, 30000); // Poll every 30 seconds + pollInterval = setInterval(fetchStats, 30000); } return () => { @@ -106,10 +104,18 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp }; }, [enabled, fetchStats, connectionState]); + // Set up realtime connection with all listeners configured before subscribing useEffect(() => { - if (!channel) return; + if (!realtimeEnabled) { + console.log('[Realtime:moderation-stats-changes] Realtime disabled'); + return; + } - channel + console.log('[Realtime:moderation-stats-changes] Creating new channel'); + setConnectionState('connecting'); + + const newChannel = supabase + .channel('moderation-stats-changes') .on( 'postgres_changes', { @@ -119,14 +125,12 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp }, (payload) => { console.log('Content submission inserted'); - // Optimistic update: increment pending submissions if (payload.new.status === 'pending') { setStats(prev => ({ ...prev, pendingSubmissions: prev.pendingSubmissions + 1 })); } - // Debounced sync as backup debouncedFetchStats(); } ) @@ -139,7 +143,6 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp }, (payload) => { console.log('Content submission updated'); - // Optimistic update: adjust counter based on status change const oldStatus = payload.old.status; const newStatus = payload.new.status; @@ -167,7 +170,6 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp }, (payload) => { console.log('Content submission deleted'); - // Optimistic update: decrement if was pending if (payload.old.status === 'pending') { setStats(prev => ({ ...prev, @@ -298,8 +300,28 @@ export const useRealtimeModerationStats = (options: UseRealtimeModerationStatsOp } debouncedFetchStats(); } - ); - }, [channel, debouncedFetchStats]); + ) + .subscribe((status) => { + console.log('[Realtime:moderation-stats-changes] Subscription status:', status); + + if (status === 'SUBSCRIBED') { + setConnectionState('connected'); + } else if (status === 'CHANNEL_ERROR') { + setConnectionState('error'); + } else if (status === 'TIMED_OUT') { + setConnectionState('disconnected'); + } else if (status === 'CLOSED') { + setConnectionState('disconnected'); + } + }); + + setChannel(newChannel); + + return () => { + console.log('[Realtime:moderation-stats-changes] Cleaning up channel'); + supabase.removeChannel(newChannel); + }; + }, [realtimeEnabled, debouncedFetchStats]); return { stats, refresh: fetchStats, connectionState, reconnect }; }; diff --git a/src/hooks/useRealtimeSubmissionItems.ts b/src/hooks/useRealtimeSubmissionItems.ts index d2ec1d69..807d3385 100644 --- a/src/hooks/useRealtimeSubmissionItems.ts +++ b/src/hooks/useRealtimeSubmissionItems.ts @@ -1,5 +1,8 @@ -import { useEffect, useRef } from 'react'; -import { useEnhancedRealtime, ConnectionState } from './useEnhancedRealtime'; +import { useEffect, useRef, useState, useCallback } from 'react'; +import { supabase } from '@/integrations/supabase/client'; +import { RealtimeChannel } from '@supabase/supabase-js'; + +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; interface UseRealtimeSubmissionItemsOptions { submissionId?: string; @@ -10,6 +13,9 @@ interface UseRealtimeSubmissionItemsOptions { export const useRealtimeSubmissionItems = (options: UseRealtimeSubmissionItemsOptions = {}) => { const { submissionId, onUpdate, enabled = true } = options; + const [channel, setChannel] = useState(null); + const [connectionState, setConnectionState] = useState('disconnected'); + // Use ref to store latest callback without triggering re-subscriptions const onUpdateRef = useRef(onUpdate); @@ -18,29 +24,58 @@ export const useRealtimeSubmissionItems = (options: UseRealtimeSubmissionItemsOp onUpdateRef.current = onUpdate; }, [onUpdate]); - const { channel, connectionState, reconnect } = useEnhancedRealtime({ - enabled: enabled && !!submissionId, - channelName: `submission-items-${submissionId || 'none'}`, - debug: true, - }); + const reconnect = useCallback(() => { + if (channel) { + supabase.removeChannel(channel); + } + setConnectionState('connecting'); + }, [channel]); useEffect(() => { - if (!channel || !submissionId) return; + if (!enabled || !submissionId) { + console.log('[Realtime:submission-items] Disabled or no submission ID'); + return; + } - channel.on( - 'postgres_changes', - { - event: 'UPDATE', - schema: 'public', - table: 'submission_items', - filter: `submission_id=eq.${submissionId}`, - }, - (payload) => { - console.log('Submission item updated:', payload); - onUpdateRef.current?.(payload); - } - ); - }, [channel, submissionId]); + console.log('[Realtime:submission-items] Creating new channel for submission:', submissionId); + setConnectionState('connecting'); + + const newChannel = supabase + .channel(`submission-items-${submissionId}`) + .on( + 'postgres_changes', + { + event: 'UPDATE', + schema: 'public', + table: 'submission_items', + filter: `submission_id=eq.${submissionId}`, + }, + (payload) => { + console.log('Submission item updated:', payload); + onUpdateRef.current?.(payload); + } + ) + .subscribe((status) => { + console.log(`[Realtime:submission-items-${submissionId}] Subscription status:`, status); + + if (status === 'SUBSCRIBED') { + setConnectionState('connected'); + } else if (status === 'CHANNEL_ERROR') { + setConnectionState('error'); + } else if (status === 'TIMED_OUT') { + setConnectionState('disconnected'); + } else if (status === 'CLOSED') { + setConnectionState('disconnected'); + } + }); + + setChannel(newChannel); + + return () => { + console.log('[Realtime:submission-items] Cleaning up channel'); + supabase.removeChannel(newChannel); + }; + }, [enabled, submissionId]); return { channel, connectionState, reconnect }; }; diff --git a/src/hooks/useRealtimeSubmissions.ts b/src/hooks/useRealtimeSubmissions.ts index fffb1b77..c398c814 100644 --- a/src/hooks/useRealtimeSubmissions.ts +++ b/src/hooks/useRealtimeSubmissions.ts @@ -1,7 +1,10 @@ -import { useEffect, useRef } from 'react'; -import { useEnhancedRealtime, ConnectionState } from './useEnhancedRealtime'; +import { useEffect, useRef, useState, useCallback } from 'react'; +import { supabase } from '@/integrations/supabase/client'; +import { RealtimeChannel } from '@supabase/supabase-js'; import { useUserRole } from './useUserRole'; +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; + interface UseRealtimeSubmissionsOptions { onInsert?: (payload: any) => void; onUpdate?: (payload: any) => void; @@ -13,6 +16,9 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = const { onInsert, onUpdate, onDelete, enabled = true } = options; const { isModerator, loading: roleLoading } = useUserRole(); + const [channel, setChannel] = useState(null); + const [connectionState, setConnectionState] = useState('disconnected'); + // Only enable realtime when user is confirmed as moderator const realtimeEnabled = enabled && !roleLoading && isModerator(); @@ -28,16 +34,24 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = onDeleteRef.current = onDelete; }, [onInsert, onUpdate, onDelete]); - const { channel, connectionState, reconnect } = useEnhancedRealtime({ - enabled: realtimeEnabled, - channelName: 'content-submissions-changes', - debug: true, - }); + const reconnect = useCallback(() => { + if (channel) { + supabase.removeChannel(channel); + } + setConnectionState('connecting'); + }, [channel]); useEffect(() => { - if (!channel) return; + if (!realtimeEnabled) { + console.log('[Realtime:content-submissions-changes] Realtime disabled'); + return; + } - channel + console.log('[Realtime:content-submissions-changes] Creating new channel'); + setConnectionState('connecting'); + + const newChannel = supabase + .channel('content-submissions-changes') .on( 'postgres_changes', { @@ -73,8 +87,28 @@ export const useRealtimeSubmissions = (options: UseRealtimeSubmissionsOptions = console.log('Submission deleted:', payload); onDeleteRef.current?.(payload); } - ); - }, [channel]); + ) + .subscribe((status) => { + console.log('[Realtime:content-submissions-changes] Subscription status:', status); + + if (status === 'SUBSCRIBED') { + setConnectionState('connected'); + } else if (status === 'CHANNEL_ERROR') { + setConnectionState('error'); + } else if (status === 'TIMED_OUT') { + setConnectionState('disconnected'); + } else if (status === 'CLOSED') { + setConnectionState('disconnected'); + } + }); + + setChannel(newChannel); + + return () => { + console.log('[Realtime:content-submissions-changes] Cleaning up channel'); + supabase.removeChannel(newChannel); + }; + }, [realtimeEnabled]); return { channel, connectionState, reconnect }; };