All files / shared/config/src opentelemetry.ts

0% Statements 0/57
0% Branches 0/18
0% Functions 0/9
0% Lines 0/57

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * OpenTelemetry configuration for Grafana Cloud integration
 * 
 * This module provides OpenTelemetry setup for comprehensive observability
 * across development, staging, and production environments.
 */
 
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { getEnvironmentConfig } from './environment';
 
/**
 * Initialize OpenTelemetry with Grafana Cloud configuration
 */
export function initializeOpenTelemetry(): NodeSDK | null {
  const config = getEnvironmentConfig();
  
  // Only initialize if OpenTelemetry is enabled
  Iif (!config.enableOpenTelemetry) {
    console.log('OpenTelemetry disabled - skipping initialization');
    return null;
  }
  
  // Check if Grafana configuration is available
  Iif (!config.grafanaConfig?.endpoint || !config.grafanaConfig?.apiToken) {
    console.warn('Grafana Cloud configuration missing - OpenTelemetry disabled');
    return null;
  }
  
  try {
    // Create the OTLP exporter
    const traceExporter = new OTLPTraceExporter({
      url: config.grafanaConfig.endpoint,
      headers: {
        'Authorization': `Basic ${Buffer.from(`1357149:${config.grafanaConfig.apiToken}`).toString('base64')}`
      }
    });
    
    // Create the resource with service information
    const resource = new Resource({
      [SemanticResourceAttributes.SERVICE_NAME]: 'buzztrail-tavus-api',
      [SemanticResourceAttributes.SERVICE_NAMESPACE]: 'buzztrail-video-integration',
      [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: config.environment,
      [SemanticResourceAttributes.SERVICE_VERSION]: process.env.npm_package_version || '1.0.0'
    });
    
    // Create and configure the SDK
    const sdk = new NodeSDK({
      resource,
      traceExporter,
      instrumentations: [
        getNodeAutoInstrumentations({
          // Configure auto-instrumentations
          '@opentelemetry/instrumentation-http': {
            ignoreIncomingPaths: ['/health', '/metrics'],
            ignoreOutgoingUrls: ['/health', '/metrics']
          },
          '@opentelemetry/instrumentation-fs': {
            enabled: false // Disable file system instrumentation to reduce noise
          }
        })
      ]
    });
    
    // Initialize the SDK
    sdk.start();
    
    console.log(`OpenTelemetry initialized for environment: ${config.environment}`);
    console.log(`Grafana Cloud endpoint: ${config.grafanaConfig.endpoint}`);
    
    // Graceful shutdown
    process.on('SIGTERM', () => {
      sdk.shutdown()
        .then(() => console.log('OpenTelemetry SDK terminated'))
        .catch((error) => console.log('Error terminating OpenTelemetry SDK', error))
        .finally(() => process.exit(0));
    });
    
    return sdk;
  } catch (error) {
    console.error('Failed to initialize OpenTelemetry:', error);
    return null;
  }
}
 
/**
 * Create a custom span for API calls
 */
export function createApiSpan(operationName: string, attributes: Record<string, any> = {}) {
  const { trace, SpanStatusCode } = require('@opentelemetry/api');
  const tracer = trace.getTracer('buzztrail-tavus-api');
  
  return tracer.startSpan(operationName, {
    attributes: {
      'service.name': 'buzztrail-tavus-api',
      'service.namespace': 'buzztrail-video-integration',
      ...attributes
    }
  });
}
 
/**
 * Log API call with OpenTelemetry
 */
export function logApiCall(
  method: string,
  url: string,
  statusCode: number,
  duration: number,
  environment: string,
  serverType: 'fake' | 'real'
) {
  const { trace, SpanStatusCode } = require('@opentelemetry/api');
  const tracer = trace.getTracer('buzztrail-tavus-api');
  
  const span = tracer.startSpan('api_call', {
    attributes: {
      'http.method': method,
      'http.url': url,
      'http.status_code': statusCode,
      'http.duration_ms': duration,
      'environment': environment,
      'server.type': serverType,
      'service.name': 'buzztrail-tavus-api'
    }
  });
  
  // Set status based on status code
  if (statusCode >= 200 && statusCode < 400) {
    span.setStatus({ code: SpanStatusCode.OK });
  } else {
    span.setStatus({ 
      code: SpanStatusCode.ERROR, 
      message: `HTTP ${statusCode}` 
    });
  }
  
  span.end();
}
 
/**
 * Log error with OpenTelemetry
 */
export function logError(error: Error, context: Record<string, any> = {}) {
  const { trace, SpanStatusCode } = require('@opentelemetry/api');
  const tracer = trace.getTracer('buzztrail-tavus-api');
  
  const span = tracer.startSpan('error', {
    attributes: {
      'error.type': error.name,
      'error.message': error.message,
      'error.stack': error.stack,
      'service.name': 'buzztrail-tavus-api',
      ...context
    }
  });
  
  span.setStatus({ 
    code: SpanStatusCode.ERROR, 
    message: error.message 
  });
  
  span.recordException(error);
  span.end();
}
 
/**
 * Log credit consumption (for monitoring)
 */
export function logCreditConsumption(
  endpoint: string,
  creditsUsed: number,
  environment: string,
  customerId?: string
) {
  const { trace, SpanStatusCode } = require('@opentelemetry/api');
  const tracer = trace.getTracer('buzztrail-tavus-api');
  
  const span = tracer.startSpan('credit_consumption', {
    attributes: {
      'tavus.endpoint': endpoint,
      'tavus.credits_used': creditsUsed,
      'environment': environment,
      'customer.id': customerId || 'unknown',
      'service.name': 'buzztrail-tavus-api'
    }
  });
  
  // Alert on unexpected credit consumption in development/staging
  if (environment !== 'production' && creditsUsed > 0) {
    span.setStatus({ 
      code: SpanStatusCode.ERROR, 
      message: `Unexpected credit consumption in ${environment} environment` 
    });
  } else {
    span.setStatus({ code: SpanStatusCode.OK });
  }
  
  span.end();
}
 
/**
 * Environment-specific OpenTelemetry configuration
 */
export const OPENTELEMETRY_CONFIG = {
  development: {
    enabled: true,
    logLevel: 'debug',
    sampleRate: 1.0, // 100% sampling in development
    attributes: {
      'deployment.environment': 'development',
      'service.name': 'buzztrail-tavus-api',
      'service.namespace': 'buzztrail-video-integration'
    }
  },
  staging: {
    enabled: true,
    logLevel: 'info',
    sampleRate: 0.5, // 50% sampling in staging
    attributes: {
      'deployment.environment': 'staging',
      'service.name': 'buzztrail-tavus-api',
      'service.namespace': 'buzztrail-video-integration'
    }
  },
  production: {
    enabled: true,
    logLevel: 'warn',
    sampleRate: 0.1, // 10% sampling in production
    attributes: {
      'deployment.environment': 'production',
      'service.name': 'buzztrail-tavus-api',
      'service.namespace': 'buzztrail-video-integration'
    }
  }
} as const;