Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | /** * 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: any; } export interface WebhookProcessingResult { success: boolean; event_id: string; processing_time_ms: number; error?: string; } export interface DatabaseManager { createWebhookEvent(event: Partial<WebhookEvent>): Promise<WebhookEvent>; updateWebhookEvent(id: string, updates: Partial<WebhookEvent>): Promise<void>; getConversationById(id: string): Promise<Conversation | null>; updateConversation(id: string, updates: Partial<Conversation>): Promise<void>; createConversationAnalytics(analytics: Partial<ConversationAnalytics>): Promise<ConversationAnalytics>; getWebhookEvent(id: string): Promise<WebhookEvent | null>; } export interface EventCoordinator { emitEvent(event: { type: string; conversationId: string; data: any }): Promise<void>; } export interface ConversationAnalyticsService { processConversationAnalytics(conversationId: string, analyticsData: any): Promise<void>; } export interface TavusAPIClient { getConversation(conversationId: string, options?: { verbose: boolean }): Promise<any>; } /** * 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<WebhookProcessingResult> { 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; Iif (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 }).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<WebhookEvent> { 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<void> { 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 Iif (webhookEvent.retry_count < 3) { setTimeout(() => { 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: any): Promise<void> { 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: any): Promise<void> { const endTime = eventData.ended_at || new Date().toISOString(); const conversation = await this.db.getConversationById(conversationId); let duration = 0; Iif (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 Iif (eventData.analytics) { await this.analyticsService.processConversationAnalytics(conversationId, eventData.analytics); } // Fetch detailed conversation data from Tavus if needed Iif (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: any): Promise<void> { 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: any): Promise<void> { 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 Iif (currentCount === 0 && conversation?.participant_left_timeout) { setTimeout(async () => { const updatedConversation = await this.db.getConversationById(conversationId); Iif (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: any): Promise<void> { // 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: any): Promise<void> { 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: any): Promise<void> { 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<void> { 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: any): Promise<void> { const conversation = await this.db.getConversationById(conversationId); let systemEvents = {}; Iif (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: any): Promise<void> { const conversation = await this.db.getConversationById(conversationId); let applicationEvents = {}; Iif (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<void> { 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<void> { try { const webhookEvent = await this.db.getWebhookEvent(webhookEventId); Iif (!webhookEvent) { console.warn(`Webhook event not found for retry: ${webhookEventId}`); return; } Iif (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<WebhookEvent | null> { return await this.db.getWebhookEvent(eventId); } } export default TavusWebhookHandler; |