/** * Environment-Aware Router for Tavus API Integration * * This module implements the environment routing strategy from the Tavus Development Environment Plan. * It routes requests to either fake or real servers based on environment, endpoint safety, and testing mode. */ import { getEnvironmentConfig, isEndpointAllowed, getEndpointFlags, logApiCall, logError, logCreditConsumption, getApiKeyManager, type Environment, type TestingMode, type EndpointFlags } from '@buzztrail/shared-config'; export interface RequestContext { method: string; url: string; path: string; headers: Record; body?: any; environment: Environment; testingMode: TestingMode; endpointFlags: EndpointFlags; customerId?: string; } export interface RoutingDecision { targetServer: 'fake-only' | 'real-only' | 'fake-primary-with-real-validation'; reason: string; serverUrl: string; apiKey: string; shouldLog: boolean; } export class EnvironmentRouter { private config = getEnvironmentConfig(); private apiKeyManager = getApiKeyManager(); /** * Route a request based on environment and endpoint configuration */ async routeRequest(req: Request): Promise { const startTime = Date.now(); const context = this.createRequestContext(req); try { // Check if endpoint is allowed if (!isEndpointAllowed(context.path, context.method)) { const error = new Error(`Endpoint ${context.method} ${context.path} not allowed in ${context.environment} environment`); logError(error, { context }); return new Response(JSON.stringify({ error: error.message }), { status: 403, headers: { 'Content-Type': 'application/json' } }); } // Make routing decision const decision = this.makeRoutingDecision(context); // Route to appropriate server(s) let response: Response; if (decision.targetServer === 'fake-primary-with-real-validation') { response = await this.routeToFakePrimaryWithRealValidation(req, context, decision); } else if (decision.targetServer === 'fake-only') { response = await this.routeToFakeServer(req, context, decision); } else { response = await this.routeToRealServer(req, context, decision); } // Log the API call const duration = Date.now() - startTime; logApiCall( context.method, context.url, response.status, duration, context.environment, decision.targetServer === 'fake-only' ? 'fake' : 'real' ); return response; } catch (error) { const duration = Date.now() - startTime; logError(error as Error, { context, duration }); return new Response(JSON.stringify({ error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } /** * Create request context from incoming request */ private createRequestContext(req: Request): RequestContext { const url = new URL(req.url); const path = url.pathname; const method = req.method; // Extract customer ID from headers or query params const customerId = req.headers.get('x-customer-id') || url.searchParams.get('customer_id') || undefined; return { method, url: req.url, path, headers: Object.fromEntries(req.headers.entries()), environment: this.config.environment, testingMode: this.config.testingMode, endpointFlags: getEndpointFlags(path, method), customerId }; } /** * Make routing decision based on environment and endpoint */ private makeRoutingDecision(context: RequestContext): RoutingDecision { const { environment, testingMode, endpointFlags, method, path } = context; const _endpointKey = `${method} ${path}`; // Development environment if (environment === 'development') { if (testingMode === 'full-testing-with-safe-real') { if (endpointFlags.free || endpointFlags.safe) { return { targetServer: 'fake-primary-with-real-validation', reason: 'Development: Testing both servers for safe/free endpoint', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } else { return { targetServer: 'fake-only', reason: 'Development: Using fake server for non-safe endpoint', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } } else if (testingMode === 'fake-only') { return { targetServer: 'fake-only', reason: 'Development: Fake-only mode', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } else if (testingMode === 'real-only') { if (endpointFlags.free || endpointFlags.safe) { return { targetServer: 'real-only', reason: 'Development: Real-only mode for safe/free endpoint', serverUrl: this.config.realServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } else { return { targetServer: 'fake-only', reason: 'Development: Real-only mode but endpoint not safe, using fake server', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } } } // Staging environment if (environment === 'staging') { if (testingMode === 'full-testing-with-safe-real') { if (endpointFlags.free || endpointFlags.safe) { return { targetServer: 'fake-primary-with-real-validation', reason: 'Staging: Testing both servers for safe/free endpoint', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } else { return { targetServer: 'fake-only', reason: 'Staging: Using fake server for non-safe endpoint', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } } else if (testingMode === 'safe-only') { if (endpointFlags.free || endpointFlags.safe) { return { targetServer: 'real-only', reason: 'Staging: Safe-only mode for safe/free endpoint', serverUrl: this.config.realServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } else { return { targetServer: 'fake-only', reason: 'Staging: Safe-only mode but endpoint not safe, using fake server', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } } } // Production environment if (environment === 'production') { // Check customer authentication if (this.isAuthenticatedCustomer(context)) { return { targetServer: 'real-only', reason: 'Production: Authenticated customer request', serverUrl: this.config.realServerUrl, apiKey: this.getCustomerApiKey(context), shouldLog: true }; } else { return { targetServer: 'fake-only', reason: 'Production: Authentication required, using fake server', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } } // Default fallback return { targetServer: 'fake-only', reason: 'Default: Using fake server', serverUrl: this.config.fakeServerUrl, apiKey: this.apiKeyManager.getApiKey(), shouldLog: true }; } /** * Route request to fake server */ private async routeToFakeServer(req: Request, context: RequestContext, decision: RoutingDecision): Promise { const fakeUrl = new URL(req.url); fakeUrl.hostname = new URL(decision.serverUrl).hostname; fakeUrl.port = new URL(decision.serverUrl).port; fakeUrl.protocol = new URL(decision.serverUrl).protocol; const fakeReq = new Request(fakeUrl.toString(), { method: req.method, headers: req.headers, body: req.body }); return fetch(fakeReq); } /** * Route request to real server */ private async routeToRealServer(req: Request, context: RequestContext, decision: RoutingDecision): Promise { const realUrl = new URL(req.url); realUrl.hostname = new URL(decision.serverUrl).hostname; realUrl.port = new URL(decision.serverUrl).port; realUrl.protocol = new URL(decision.serverUrl).protocol; // Add API key to headers const headers = new Headers(req.headers); headers.set('Authorization', `Bearer ${decision.apiKey}`); const realReq = new Request(realUrl.toString(), { method: req.method, headers, body: req.body }); const response = await fetch(realReq); // Log credit consumption for non-free endpoints if (!context.endpointFlags.free && response.ok) { // Estimate credit consumption (this would need to be refined based on actual API) const estimatedCredits = this.estimateCreditConsumption(context); logCreditConsumption( `${context.method} ${context.path}`, estimatedCredits, context.environment, context.customerId ); } return response; } /** * Route request to fake server first, then validate against real server * STRICT SAFETY: Only allows GET requests to real server, no destructive operations * ALWAYS returns fake response - real server is only used for validation/sync */ private async routeToFakePrimaryWithRealValidation(req: Request, context: RequestContext, decision: RoutingDecision): Promise { // STRICT SAFETY CHECK: Only allow GET requests to real server if (req.method !== 'GET') { console.log(`🚫 SAFETY BLOCKED: ${req.method} ${context.path} - Only GET requests allowed in validation mode`); // Return fake response only for non-GET requests return await this.routeToFakeServer(req, context, decision); } // Additional safety: Only allow specific safe endpoints const safeValidationEndpoints = [ '/v2/health', '/v2/status', '/v2/personas', '/v2/personas/{id}', '/v2/conversations', '/v2/conversations/{id}', '/v2/replicas', '/v2/replicas/{id}' ]; const isSafeForValidation = safeValidationEndpoints.some(endpoint => { // Handle path parameters const endpointPattern = endpoint.replace(/\{.*?\}/g, '[^/]+'); const regex = new RegExp(`^${endpointPattern}$`); return regex.test(context.path); }); if (!isSafeForValidation) { console.log(`🚫 SAFETY BLOCKED: ${req.method} ${context.path} - Not in safe validation endpoints list`); return await this.routeToFakeServer(req, context, decision); } // ALWAYS get fake response first (this is the PRIMARY response) const fakeResponse = await this.routeToFakeServer(req, context, decision); // OPTIONALLY validate against real server (for safe/free endpoints only) if (context.endpointFlags.free || context.endpointFlags.safe) { try { const realResponse = await this.routeToRealServer(req, context, decision); // Compare responses for validation (doesn't affect the returned response) await this.compareResponses(fakeResponse, realResponse, context); // Sync data between fake and real servers (background operation) await this.syncFakeWithReal(req, fakeResponse, realResponse, context); // Log both responses for analysis await this.logDualTest(req, fakeResponse, realResponse, context); console.log(`✅ VALIDATION: Successfully validated fake response against real server for ${context.method} ${context.path}`); } catch (error) { // If real server fails, log error but STILL return fake response // This is expected behavior - fake is primary, real is just for validation logError(error as Error, { context, note: 'Real server validation failed, but continuing with fake response (as expected)' }); console.log(`⚠️ VALIDATION: Real server validation failed for ${context.method} ${context.path}, but fake response is still valid`); } } // ALWAYS return fake response (this is the PRIMARY response) return fakeResponse; } /** * Compare responses from fake and real servers */ private async compareResponses(fakeResponse: Response, realResponse: Response, context: RequestContext): Promise { try { const fakeData = await fakeResponse.clone().json(); const realData = await realResponse.clone().json(); // Basic comparison - could be enhanced with schema validation const fakeKeys = Object.keys(fakeData); const realKeys = Object.keys(realData); if (fakeKeys.length !== realKeys.length) { console.warn(`Response key count mismatch for ${context.method} ${context.path}: fake=${fakeKeys.length}, real=${realKeys.length}`); } // Log comparison results console.log(`Dual test completed for ${context.method} ${context.path}:`, { fakeStatus: fakeResponse.status, realStatus: realResponse.status, fakeKeys, realKeys }); } catch (error) { // Ignore comparison errors console.warn('Failed to compare responses:', error); } } /** * Log dual test results */ private async logDualTest(req: Request, fakeResponse: Response, realResponse: Response, context: RequestContext): Promise { // This would typically send data to Grafana Cloud or other observability platform console.log('Dual test logged:', { endpoint: `${context.method} ${context.path}`, environment: context.environment, fakeStatus: fakeResponse.status, realStatus: realResponse.status, timestamp: new Date().toISOString() }); } /** * Sync fake server data with real server data * This keeps personas, conversations, and other reference data in sync */ private async syncFakeWithReal(req: Request, fakeResponse: Response, realResponse: Response, context: RequestContext): Promise { try { // Only sync on successful responses if (!fakeResponse.ok || !realResponse.ok) { return; } const fakeData = await fakeResponse.clone().json(); const realData = await realResponse.clone().json(); // Sync personas data if (context.path === '/v2/personas' || context.path.match(/^\/v2\/personas\/[^/]+$/)) { await this.syncPersonasData(fakeData, realData, context); } // Sync conversations data if (context.path === '/v2/conversations' || context.path.match(/^\/v2\/conversations\/[^/]+$/)) { await this.syncConversationsData(fakeData, realData, context); } // Sync replicas data if (context.path === '/v2/replicas' || context.path.match(/^\/v2\/replicas\/[^/]+$/)) { await this.syncReplicasData(fakeData, realData, context); } } catch (error) { console.warn('Failed to sync fake with real data:', error); } } /** * Sync personas data between fake and real servers */ private async syncPersonasData(fakeData: any, realData: any, context: RequestContext): Promise { try { // If it's a single persona, wrap in array for consistent processing const fakePersonas = Array.isArray(fakeData) ? fakeData : [fakeData]; const realPersonas = Array.isArray(realData) ? realData : [realData]; // Create a map of real personas by ID for quick lookup const realPersonasMap = new Map(); realPersonas.forEach(persona => { if (persona.id) { realPersonasMap.set(persona.id, persona); } }); // Check for missing personas in fake server const missingPersonas = realPersonas.filter(realPersona => !fakePersonas.some(fakePersona => fakePersona.id === realPersona.id) ); if (missingPersonas.length > 0) { console.log(`🔄 SYNC: Found ${missingPersonas.length} missing personas in fake server`); // Send missing personas to fake server for sync for (const persona of missingPersonas) { await this.sendToFakeServer('/v2/personas', 'POST', persona, context); } } // Check for outdated personas in fake server const outdatedPersonas = fakePersonas.filter(fakePersona => { const realPersona = realPersonasMap.get(fakePersona.id); return realPersona && JSON.stringify(fakePersona) !== JSON.stringify(realPersona); }); if (outdatedPersonas.length > 0) { console.log(`🔄 SYNC: Found ${outdatedPersonas.length} outdated personas in fake server`); // Update outdated personas in fake server for (const persona of outdatedPersonas) { const realPersona = realPersonasMap.get(persona.id); await this.sendToFakeServer(`/v2/personas/${persona.id}`, 'PUT', realPersona, context); } } } catch (error) { console.warn('Failed to sync personas data:', error); } } /** * Sync conversations data between fake and real servers */ private async syncConversationsData(fakeData: any, realData: any, _context: RequestContext): Promise { try { const fakeConversations = Array.isArray(fakeData) ? fakeData : [fakeData]; const realConversations = Array.isArray(realData) ? realData : [realData]; // Create a map of real conversations by ID const realConversationsMap = new Map(); realConversations.forEach(conversation => { if (conversation.id) { realConversationsMap.set(conversation.id, conversation); } }); // Check for missing conversations in fake server const missingConversations = realConversations.filter(realConversation => !fakeConversations.some(fakeConversation => fakeConversation.id === realConversation.id) ); if (missingConversations.length > 0) { console.log(`🔄 SYNC: Found ${missingConversations.length} missing conversations in fake server`); // Note: We don't sync conversations as they contain sensitive data // Just log the count for awareness } } catch (error) { console.warn('Failed to sync conversations data:', error); } } /** * Sync replicas data between fake and real servers */ private async syncReplicasData(fakeData: any, realData: any, context: RequestContext): Promise { try { const fakeReplicas = Array.isArray(fakeData) ? fakeData : [fakeData]; const realReplicas = Array.isArray(realData) ? realData : [realData]; // Create a map of real replicas by ID const realReplicasMap = new Map(); realReplicas.forEach(replica => { if (replica.id) { realReplicasMap.set(replica.id, replica); } }); // Check for missing replicas in fake server const missingReplicas = realReplicas.filter(realReplica => !fakeReplicas.some(fakeReplica => fakeReplica.id === realReplica.id) ); if (missingReplicas.length > 0) { console.log(`🔄 SYNC: Found ${missingReplicas.length} missing replicas in fake server`); // Send missing replicas to fake server for sync for (const replica of missingReplicas) { await this.sendToFakeServer('/v2/replicas', 'POST', replica, context); } } } catch (error) { console.warn('Failed to sync replicas data:', error); } } /** * Send data to fake server for syncing */ private async sendToFakeServer(path: string, method: string, data: any, _context: RequestContext): Promise { try { const fakeUrl = new URL(path, this.config.fakeServerUrl); const response = await fetch(fakeUrl.toString(), { method, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKeyManager.getApiKey()}` }, body: JSON.stringify(data) }); if (!response.ok) { console.warn(`Failed to sync data to fake server: ${method} ${path} - ${response.status}`); } else { console.log(`✅ SYNC: Successfully synced data to fake server: ${method} ${path}`); } } catch (error) { console.warn(`Failed to send data to fake server: ${method} ${path}`, error); } } /** * Check if request is from authenticated customer */ private isAuthenticatedCustomer(context: RequestContext): boolean { if (!context.customerId) { return false; } // Validate customer API key const apiKey = this.extractApiKey(context); if (!apiKey) { return false; } // TODO: Implement proper customer authentication // For now, accept any valid format API key return this.isValidApiKeyFormat(apiKey); } /** * Extract API key from request */ private extractApiKey(context: RequestContext): string | null { // Check Authorization header const authHeader = context.headers.authorization; if (authHeader && authHeader.startsWith('Bearer ')) { return authHeader.substring(7); } // Check X-API-Key header const apiKeyHeader = context.headers['x-api-key']; if (apiKeyHeader) { return apiKeyHeader; } return null; } /** * Validate API key format */ private isValidApiKeyFormat(apiKey: string): boolean { // Basic validation - replace with proper validation later return apiKey.length > 0 && apiKey.includes('_'); } /** * Get customer API key */ private getCustomerApiKey(context: RequestContext): string { if (context.customerId) { const customerKey = this.apiKeyManager.getCustomerApiKey(context.customerId); if (customerKey) { return customerKey; } } // Fall back to environment API key return this.apiKeyManager.getApiKey(); } /** * Estimate credit consumption for an endpoint */ private estimateCreditConsumption(context: RequestContext): number { // This is a rough estimate - would need to be refined based on actual API costs const endpointKey = `${context.method} ${context.path}`; const creditEstimates: Record = { 'POST /v2/conversations': 1, 'POST /v2/personas': 0.5, 'PATCH /v2/personas/{id}': 0.1, 'PATCH /v2/conversations/{id}': 0.1, 'DELETE /v2/personas/{id}': 0.05, 'DELETE /v2/conversations/{id}': 0.05, 'GET /v2/analytics': 0.01, 'GET /v2/usage': 0.01 }; return creditEstimates[endpointKey] || 0.01; } }