UNPKG

@ahmedhegazee/nestjs-telescope

Version:

Advanced observability and monitoring solution for NestJS applications with ML-powered analytics, enterprise features, and production-ready scaling

381 lines (380 loc) 10 kB
import { OnModuleInit } from '@nestjs/common'; import { Observable } from 'rxjs'; import { TelescopeService } from './telescope.service'; import { PerformanceCorrelationService } from './performance-correlation.service'; export interface AnalyticsData { timestamp: Date; timeRange: { start: Date; end: Date; }; overview: { totalRequests: number; totalErrors: number; totalQueries: number; totalCacheOps: number; totalJobs: number; averageResponseTime: number; errorRate: number; throughput: number; activeUsers: number; peakConcurrency: number; }; performance: { responseTimeDistribution: PerformanceDistribution; slowestEndpoints: EndpointMetrics[]; resourceUsage: ResourceUsage; bottleneckAnalysis: BottleneckSummary[]; }; errors: { errorDistribution: ErrorDistribution; topErrors: ErrorSummary[]; errorTrends: TimeSeries[]; impactAnalysis: ErrorImpact[]; }; database: { queryDistribution: QueryDistribution; slowQueries: QueryMetrics[]; connectionHealth: ConnectionHealth; indexUsage: IndexUsage[]; }; cache: { hitRateDistribution: CacheDistribution; topKeys: CacheKeyMetrics[]; performanceMetrics: CachePerformance; evictionAnalysis: EvictionAnalysis[]; }; jobs: { queueHealth: QueueHealth[]; processingTimes: JobDistribution; failureAnalysis: JobFailureAnalysis[]; throughputMetrics: JobThroughput[]; }; users: { activeUsers: UserMetrics[]; sessionAnalysis: SessionAnalysis; geographicDistribution: GeographicData[]; deviceAnalysis: DeviceAnalysis[]; }; trends: { trafficTrends: TimeSeries[]; performanceTrends: TimeSeries[]; errorTrends: TimeSeries[]; predictions: PredictionData[]; }; alerts: { activeAlerts: AlertSummary[]; alertTrends: TimeSeries[]; anomalies: AnomalyDetection[]; }; } export interface PerformanceDistribution { buckets: Array<{ range: string; count: number; percentage: number; }>; percentiles: { p50: number; p75: number; p90: number; p95: number; p99: number; }; } export interface EndpointMetrics { endpoint: string; method: string; count: number; averageTime: number; p95Time: number; errorRate: number; throughput: number; } export interface ResourceUsage { cpu: TimeSeries[]; memory: TimeSeries[]; connections: TimeSeries[]; diskIO: TimeSeries[]; } export interface BottleneckSummary { component: string; severity: 'low' | 'medium' | 'high' | 'critical'; frequency: number; averageImpact: number; description: string; recommendation: string; } export interface ErrorDistribution { byType: Array<{ type: string; count: number; percentage: number; }>; bySeverity: Array<{ severity: string; count: number; percentage: number; }>; byComponent: Array<{ component: string; count: number; percentage: number; }>; } export interface ErrorSummary { errorType: string; message: string; count: number; firstSeen: Date; lastSeen: Date; impactScore: number; affectedUsers: number; } export interface ErrorImpact { errorType: string; performanceImpact: number; userImpact: number; businessImpact: number; recommendations: string[]; } export interface QueryDistribution { byType: Array<{ type: string; count: number; avgTime: number; }>; byTable: Array<{ table: string; count: number; avgTime: number; }>; byComplexity: Array<{ complexity: string; count: number; avgTime: number; }>; } export interface QueryMetrics { query: string; table: string; count: number; averageTime: number; maxTime: number; indexUsage: string[]; optimizationSuggestions: string[]; } export interface ConnectionHealth { totalConnections: number; activeConnections: number; idleConnections: number; maxConnections: number; healthScore: number; issues: string[]; } export interface IndexUsage { table: string; index: string; usage: number; effectiveness: number; recommendations: string[]; } export interface CacheDistribution { hitRate: number; missRate: number; byOperation: Array<{ operation: string; hitRate: number; count: number; }>; byKeyPattern: Array<{ pattern: string; hitRate: number; count: number; }>; } export interface CacheKeyMetrics { key: string; pattern: string; hitRate: number; accessCount: number; averageTime: number; size: number; ttl: number; } export interface CachePerformance { averageResponseTime: number; throughput: number; memoryUsage: number; evictionRate: number; trends: TimeSeries[]; } export interface EvictionAnalysis { cause: string; frequency: number; impact: number; recommendations: string[]; } export interface QueueHealth { queueName: string; status: 'healthy' | 'warning' | 'critical'; backlog: number; processingRate: number; failureRate: number; averageWaitTime: number; recommendations: string[]; } export interface JobDistribution { byType: Array<{ type: string; count: number; avgTime: number; }>; byQueue: Array<{ queue: string; count: number; avgTime: number; }>; byStatus: Array<{ status: string; count: number; percentage: number; }>; } export interface JobFailureAnalysis { jobType: string; failureCount: number; failureRate: number; commonErrors: string[]; recommendations: string[]; } export interface JobThroughput { queueName: string; throughput: number; trend: 'up' | 'down' | 'stable'; capacity: number; utilizationRate: number; } export interface UserMetrics { userId: string; sessionCount: number; requestCount: number; errorCount: number; averageResponseTime: number; lastActive: Date; } export interface SessionAnalysis { totalSessions: number; averageSessionDuration: number; averageRequestsPerSession: number; bounceRate: number; mostActiveHours: Array<{ hour: number; count: number; }>; } export interface GeographicData { country: string; region: string; requestCount: number; averageResponseTime: number; errorRate: number; } export interface DeviceAnalysis { deviceType: string; userAgent: string; count: number; averageResponseTime: number; errorRate: number; } export interface TimeSeries { timestamp: Date; value: number; label?: string; } export interface PredictionData { metric: string; prediction: number; confidence: number; timeframe: string; factors: string[]; } export interface AlertSummary { id: string; type: string; severity: string; message: string; timestamp: Date; component: string; acknowledged: boolean; } export interface AnomalyDetection { metric: string; currentValue: number; expectedValue: number; deviation: number; severity: 'low' | 'medium' | 'high'; description: string; recommendations: string[]; } export declare class AnalyticsService implements OnModuleInit { private readonly telescopeService; private readonly performanceCorrelationService; private readonly logger; private readonly destroy$; private readonly analyticsSubject; private currentAnalytics; constructor(telescopeService: TelescopeService, performanceCorrelationService: PerformanceCorrelationService); onModuleInit(): Promise<void>; private initializeAnalytics; private startAnalyticsProcessing; private updateAnalytics; private updateOverview; private updatePerformanceAnalytics; private updateErrorAnalytics; private updateDatabaseAnalytics; private updateCacheAnalytics; private updateJobAnalytics; private updateUserAnalytics; private updateTrends; private updateAlertsAndAnomalies; private calculateActiveUsers; private calculatePeakConcurrency; private calculateResponseTimeDistribution; private calculateSlowestEndpoints; private calculateResourceUsage; private calculateBottleneckAnalysis; private getMostCommon; private calculateErrorDistribution; private calculateTopErrors; private calculateErrorImpact; private calculateQueryDistribution; private calculateSlowQueries; private calculateConnectionHealth; private calculateIndexUsage; private calculateCacheDistribution; private calculateTopCacheKeys; private calculateCachePerformance; private calculateEvictionAnalysis; private calculateQueueHealth; private calculateJobDistribution; private calculateJobFailureAnalysis; private calculateJobThroughput; private calculateActiveUserMetrics; private calculateSessionAnalysis; private calculateGeographicDistribution; private calculateDeviceAnalysis; private calculateTrafficTrends; private calculatePerformanceTrends; private calculatePredictions; getAnalytics(): AnalyticsData; getAnalyticsStream(): Observable<AnalyticsData>; getAnalyticsForTimeRange(start: Date, end: Date): Promise<AnalyticsData>; refreshAnalytics(): Promise<void>; onDestroy(): void; private calculateErrorImpactScore; private calculateBusinessImpact; private generateErrorRecommendations; private extractKeyPattern; private convertErrorsToTimeSeries; }