/** * Tavus Webhook Handler Service * * Comprehensive webhook handling system for real-time conversation events * from Tavus API with robust error handling and retry mechanisms. */ import { v4 as uuidv4 } from 'uuid'; import type { WebhookEvent, Conversation, ConversationAnalytics } from '@buzztrail/shared-database'; export interface TavusWebhookEvent { event_type: string; conversation_id?: string; timestamp: string; data: Record; } export interface WebhookProcessingResult { success: boolean; event_id: string; processing_time_ms: number; error?: string; } export interface DatabaseManager { createWebhookEvent(event: Partial): Promise; updateWebhookEvent(id: string, updates: Partial): Promise; getConversationById(id: string): Promise; updateConversation(id: string, updates: Partial): Promise; createConversationAnalytics(analytics: Partial): Promise; getWebhookEvent(id: string): Promise; } export interface EventCoordinator { emitEvent(event: { type: string; conversationId: string; data: Record }): Promise; } export interface ConversationAnalyticsService { processConversationAnalytics(conversationId: string, analyticsData: Record): Promise; } export interface TavusAPIClient { getConversation(conversationId: string, options?: { verbose: boolean }): Promise>; } /** * Tavus Webhook Handler * * Handles all webhook events from Tavus API with comprehensive processing * and error handling capabilities. */ export class TavusWebhookHandler { private db: DatabaseManager; private eventCoordinator: EventCoordinator; private analyticsService: ConversationAnalyticsService; private tavusClient: TavusAPIClient; constructor( db: DatabaseManager, eventCoordinator: EventCoordinator, analyticsService: ConversationAnalyticsService, tavusClient: TavusAPIClient ) { this.db = db; this.eventCoordinator = eventCoordinator; this.analyticsService = analyticsService; this.tavusClient = tavusClient; } /** * Handle incoming webhook event */ async handleWebhookEvent( conversationId: string, eventData: TavusWebhookEvent ): Promise { const startTime = Date.now(); let webhookEvent: WebhookEvent | null = null; try { // Store webhook event immediately webhookEvent = await this.storeWebhookEvent(conversationId, eventData); // Process webhook asynchronously await this.processWebhookEvent(webhookEvent); const processingTime = Date.now() - startTime; return { success: true, event_id: webhookEvent.id, processing_time_ms: processingTime }; } catch (error) { const processingTime = Date.now() - startTime; if (webhookEvent) { // Mark webhook as failed await this.db.updateWebhookEvent(webhookEvent.id, { processing_status: 'failed', processing_error: error instanceof Error ? error.message : 'Unknown error', retry_count: 0 // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch(() => {}); // Ignore errors in error handling } return { success: false, event_id: webhookEvent?.id || 'unknown', processing_time_ms: processingTime, error: error instanceof Error ? error.message : 'Unknown error' }; } } /** * Store webhook event in database */ private async storeWebhookEvent(conversationId: string, eventData: TavusWebhookEvent): Promise { const conversation = await this.db.getConversationById(conversationId); return await this.db.createWebhookEvent({ id: uuidv4(), conversation_id: conversationId, customer_id: conversation?.customer_id || 'unknown', event_type: eventData.event_type, event_data: JSON.stringify(eventData), received_at: new Date().toISOString(), processing_status: 'pending' }); } /** * Process webhook event based on type */ private async processWebhookEvent(webhookEvent: WebhookEvent): Promise { try { const eventData = JSON.parse(webhookEvent.event_data); switch (webhookEvent.event_type) { case 'conversation.started': await this.handleConversationStarted(webhookEvent.conversation_id!, eventData); break; case 'conversation.ended': await this.handleConversationEnded(webhookEvent.conversation_id!, eventData); break; case 'participant.joined': await this.handleParticipantJoined(webhookEvent.conversation_id!, eventData); break; case 'participant.left': await this.handleParticipantLeft(webhookEvent.conversation_id!, eventData); break; case 'replica.joined': await this.handleReplicaJoined(webhookEvent.conversation_id!, eventData); break; case 'system.shutdown': await this.handleSystemShutdown(webhookEvent.conversation_id!, eventData); break; case 'perception.analysis': await this.handlePerceptionAnalysis(webhookEvent.conversation_id!, eventData); break; default: console.warn(`Unknown webhook event type: ${webhookEvent.event_type}`); } // Mark webhook as processed await this.db.updateWebhookEvent(webhookEvent.id, { processing_status: 'processed', processed_at: new Date().toISOString() }); } catch (error) { // Mark webhook as failed and schedule retry await this.db.updateWebhookEvent(webhookEvent.id, { processing_status: 'failed', processing_error: error instanceof Error ? error.message : 'Unknown error', retry_count: webhookEvent.retry_count + 1 }); // Schedule retry if under limit if (webhookEvent.retry_count < 3) { setTimeout(() => { void this.retryWebhookEvent(webhookEvent.id); }, Math.pow(2, webhookEvent.retry_count) * 1000); // Exponential backoff } throw error; } } /** * Handle conversation started event */ private async handleConversationStarted(conversationId: string, eventData: Record): Promise { await this.db.updateConversation(conversationId, { status: 'active', started_at: eventData.started_at || new Date().toISOString(), participant_count: eventData.participant_count || 1 }); // Update system events await this.updateSystemEvents(conversationId, { conversation_started: { timestamp: eventData.started_at, participant_count: eventData.participant_count } }); // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'conversation.started', conversationId, data: eventData }); console.log(`✅ Conversation started: ${conversationId}`); } /** * Handle conversation ended event */ private async handleConversationEnded(conversationId: string, eventData: Record): Promise { const endTime = eventData.ended_at || new Date().toISOString(); const conversation = await this.db.getConversationById(conversationId); let duration = 0; if (conversation?.started_at) { duration = Math.floor( (new Date(endTime).getTime() - new Date(conversation.started_at).getTime()) / 1000 ); } await this.db.updateConversation(conversationId, { status: 'ended', ended_at: endTime, duration_seconds: duration, shutdown_reason: eventData.shutdown_reason, transcript: JSON.stringify(eventData.transcript || {}), perception_analysis: JSON.stringify(eventData.perception_analysis || {}) }); // Process analytics if available if (eventData.analytics) { await this.analyticsService.processConversationAnalytics(conversationId, eventData.analytics); } // Fetch detailed conversation data from Tavus if needed if (eventData.fetch_detailed_data) { await this.fetchDetailedConversationData(conversationId); } // Emit completion event await this.eventCoordinator.emitEvent({ type: 'conversation.ended', conversationId, data: { duration, shutdown_reason: eventData.shutdown_reason } }); console.log(`✅ Conversation ended: ${conversationId} (duration: ${duration}s)`); } /** * Handle participant joined event */ private async handleParticipantJoined(conversationId: string, eventData: Record): Promise { const conversation = await this.db.getConversationById(conversationId); const currentCount = conversation?.participant_count || 0; await this.db.updateConversation(conversationId, { participant_count: currentCount + 1 }); // Update system events await this.updateSystemEvents(conversationId, { participant_joined: { timestamp: eventData.timestamp || new Date().toISOString(), participant_id: eventData.participant_id, participant_count: currentCount + 1 } }); // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'participant.joined', conversationId, data: eventData }); console.log(`✅ Participant joined: ${conversationId}`); } /** * Handle participant left event */ private async handleParticipantLeft(conversationId: string, eventData: Record): Promise { const conversation = await this.db.getConversationById(conversationId); const currentCount = Math.max(0, (conversation?.participant_count || 1) - 1); await this.db.updateConversation(conversationId, { participant_count: currentCount }); // Update system events await this.updateSystemEvents(conversationId, { participant_left: { timestamp: eventData.timestamp || new Date().toISOString(), participant_id: eventData.participant_id, participant_count: currentCount, reason: eventData.reason } }); // If no participants left and timeout is configured, handle conversation timeout if (currentCount === 0 && conversation?.participant_left_timeout) { setTimeout(() => { void (async () => { const updatedConversation = await this.db.getConversationById(conversationId); if (updatedConversation?.participant_count === 0 && updatedConversation.status === 'active') { await this.handleConversationTimeout(conversationId); } })(); }, conversation.participant_left_timeout * 1000); } // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'participant.left', conversationId, data: eventData }); console.log(`✅ Participant left: ${conversationId}`); } /** * Handle replica joined event */ private async handleReplicaJoined(conversationId: string, eventData: Record): Promise { // Update system events await this.updateSystemEvents(conversationId, { replica_joined: { timestamp: eventData.timestamp || new Date().toISOString(), replica_id: eventData.replica_id } }); // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'replica.joined', conversationId, data: eventData }); console.log(`✅ Replica joined: ${conversationId}`); } /** * Handle system shutdown event */ private async handleSystemShutdown(conversationId: string, eventData: Record): Promise { await this.db.updateConversation(conversationId, { status: 'ended', ended_at: eventData.timestamp || new Date().toISOString(), shutdown_reason: eventData.reason || 'system_shutdown' }); // Update system events await this.updateSystemEvents(conversationId, { system_shutdown: { timestamp: eventData.timestamp || new Date().toISOString(), reason: eventData.reason } }); // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'system.shutdown', conversationId, data: eventData }); console.log(`✅ System shutdown: ${conversationId}`); } /** * Handle perception analysis event */ private async handlePerceptionAnalysis(conversationId: string, eventData: Record): Promise { await this.db.updateConversation(conversationId, { perception_analysis: JSON.stringify(eventData.analysis || {}) }); // Update application events await this.updateApplicationEvents(conversationId, { perception_analysis: { timestamp: eventData.timestamp || new Date().toISOString(), analysis: eventData.analysis } }); // Emit real-time event await this.eventCoordinator.emitEvent({ type: 'perception.analysis', conversationId, data: eventData }); console.log(`✅ Perception analysis: ${conversationId}`); } /** * Handle conversation timeout */ private async handleConversationTimeout(conversationId: string): Promise { await this.db.updateConversation(conversationId, { status: 'ended', ended_at: new Date().toISOString(), shutdown_reason: 'participant_timeout' }); // Emit timeout event await this.eventCoordinator.emitEvent({ type: 'conversation.timeout', conversationId, data: { reason: 'participant_timeout' } }); console.log(`⏰ Conversation timeout: ${conversationId}`); } /** * Update system events for conversation */ private async updateSystemEvents(conversationId: string, newEvent: Record): Promise { const conversation = await this.db.getConversationById(conversationId); let systemEvents = {}; if (conversation?.system_events) { try { systemEvents = JSON.parse(conversation.system_events); } catch (error) { console.warn('Failed to parse existing system events:', error); } } const updatedEvents = { ...systemEvents, ...newEvent }; await this.db.updateConversation(conversationId, { system_events: JSON.stringify(updatedEvents) }); } /** * Update application events for conversation */ private async updateApplicationEvents(conversationId: string, newEvent: Record): Promise { const conversation = await this.db.getConversationById(conversationId); let applicationEvents = {}; if (conversation?.application_events) { try { applicationEvents = JSON.parse(conversation.application_events); } catch (error) { console.warn('Failed to parse existing application events:', error); } } const updatedEvents = { ...applicationEvents, ...newEvent }; await this.db.updateConversation(conversationId, { application_events: JSON.stringify(updatedEvents) }); } /** * Fetch detailed conversation data from Tavus API */ private async fetchDetailedConversationData(conversationId: string): Promise { try { const detailedData = await this.tavusClient.getConversation(conversationId, { verbose: true }); await this.db.updateConversation(conversationId, { transcript: JSON.stringify(detailedData.transcript || {}), system_events: JSON.stringify({ replica_joined: detailedData.system?.replica_joined, shutdown: detailedData.system?.shutdown }), application_events: JSON.stringify(detailedData.application || {}), perception_analysis: JSON.stringify(detailedData.application?.perception_analysis || {}) }); console.log(`✅ Detailed data fetched: ${conversationId}`); } catch (error) { console.error(`Failed to fetch detailed data for conversation ${conversationId}:`, error); } } /** * Retry failed webhook event */ private async retryWebhookEvent(webhookEventId: string): Promise { try { const webhookEvent = await this.db.getWebhookEvent(webhookEventId); if (!webhookEvent) { console.warn(`Webhook event not found for retry: ${webhookEventId}`); return; } if (webhookEvent.retry_count >= 3) { console.warn(`Max retries exceeded for webhook event: ${webhookEventId}`); return; } console.log(`Retrying webhook event: ${webhookEventId} (attempt ${webhookEvent.retry_count + 1})`); // Reset processing status await this.db.updateWebhookEvent(webhookEventId, { processing_status: 'pending', processing_error: undefined }); // Process the event again await this.processWebhookEvent(webhookEvent); } catch (error) { console.error(`Failed to retry webhook event ${webhookEventId}:`, error); } } /** * Validate webhook signature (if using webhook signatures) */ validateWebhookSignature(_payload: string, _signature: string, _secret: string): boolean { // Implementation depends on Tavus webhook signature method // This is a placeholder for security validation return true; } /** * Get webhook processing status */ async getWebhookStatus(eventId: string): Promise { return await this.db.getWebhookEvent(eventId); } } export default TavusWebhookHandler;