/** * CacheAnalytics - Comprehensive Cache Analytics & Monitoring * * Real-time analytics and reporting for cache performance and usage. * Provides visualization, trend analysis, alerting, and cost analysis capabilities. * * Operations: * 1. dashboard - Get real-time dashboard data * 2. metrics - Get detailed metrics * 3. trends - Analyze trends over time * 4. alerts - Configure and check alerts * 5. heatmap - Generate access heatmap * 6. bottlenecks - Identify performance bottlenecks * 7. cost-analysis - Analyze caching costs * 8. export-data - Export analytics data * * Token Reduction Target: 88%+ */ import { CacheEngine } from '../../core/cache-engine.js'; import { TokenCounter } from '../../core/token-counter.js'; import { MetricsCollector } from '../../core/metrics.js'; import { EventEmitter } from 'events'; export type AnalyticsOperation = 'dashboard' | 'metrics' | 'trends' | 'alerts' | 'heatmap' | 'bottlenecks' | 'cost-analysis' | 'export-data'; export type TimeGranularity = 'second' | 'minute' | 'hour' | 'day'; export type MetricType = 'performance' | 'usage' | 'efficiency' | 'cost' | 'health'; export type AggregationType = 'sum' | 'avg' | 'min' | 'max' | 'p95' | 'p99'; export type ExportFormat = 'json' | 'csv' | 'prometheus'; export type HeatmapType = 'temporal' | 'key-correlation' | 'memory'; export interface CacheAnalyticsOptions { operation: AnalyticsOperation; timeRange?: { start: number; end: number; }; granularity?: TimeGranularity; metricTypes?: MetricType[]; aggregation?: AggregationType; compareWith?: 'previous-period' | 'last-week' | 'last-month'; trendType?: 'absolute' | 'percentage' | 'rate'; alertType?: 'threshold' | 'anomaly' | 'trend'; threshold?: number; alertConfig?: AlertConfiguration; heatmapType?: HeatmapType; resolution?: 'low' | 'medium' | 'high'; format?: ExportFormat; filePath?: string; useCache?: boolean; cacheTTL?: number; } export interface CacheAnalyticsResult { success: boolean; operation: AnalyticsOperation; data: { dashboard?: DashboardData; metrics?: MetricCollection; trends?: TrendAnalysis; alerts?: Alert[]; heatmap?: HeatmapData; bottlenecks?: Bottleneck[]; costAnalysis?: CostBreakdown; exportData?: string; }; metadata: { tokensUsed: number; tokensSaved: number; cacheHit: boolean; executionTime: number; }; } export interface DashboardData { timestamp: number; performance: PerformanceMetrics; usage: UsageMetrics; efficiency: EfficiencyMetrics; cost: CostMetrics; health: HealthMetrics; recentActivity: ActivityLog[]; } export interface PerformanceMetrics { hitRate: number; latencyP50: number; latencyP95: number; latencyP99: number; throughput: number; operationsPerSecond: number; averageResponseTime: number; } export interface UsageMetrics { totalKeys: number; totalSize: number; keyAccessFrequency: Map; valueSizeDistribution: SizeDistribution; topAccessedKeys: Array<{ key: string; hits: number; }>; recentlyAdded: Array<{ key: string; timestamp: number; }>; } export interface EfficiencyMetrics { memoryUtilization: number; evictionRate: number; evictionPatterns: EvictionPattern[]; compressionRatio: number; fragmentationIndex: number; } export interface CostMetrics { memoryCost: number; diskCost: number; networkCost: number; totalCost: number; costPerOperation: number; costTrend: number; } export interface HealthMetrics { errorRate: number; timeoutRate: number; fragmentationLevel: number; warningCount: number; criticalIssues: string[]; healthScore: number; } export interface ActivityLog { timestamp: number; operation: string; key?: string; duration: number; status: 'success' | 'error' | 'timeout'; } export interface SizeDistribution { small: number; medium: number; large: number; xlarge: number; } export interface EvictionPattern { reason: string; count: number; percentage: number; trend: 'increasing' | 'stable' | 'decreasing'; } export interface MetricCollection { timestamp: number; timeRange: { start: number; end: number; }; performance?: PerformanceMetrics; usage?: UsageMetrics; efficiency?: EfficiencyMetrics; cost?: CostMetrics; health?: HealthMetrics; aggregatedData: AggregatedMetrics; } export interface AggregatedMetrics { totalOperations: number; successfulOperations: number; failedOperations: number; averageDuration: number; totalCacheHits: number; totalCacheMisses: number; tokensSaved: number; compressionSavings: number; } export interface TrendAnalysis { timestamp: number; timeRange: { start: number; end: number; }; metrics: TrendMetric[]; anomalies: Anomaly[]; predictions: Prediction[]; regression: RegressionResult; seasonality: SeasonalityPattern; } export interface TrendMetric { name: string; current: number; previous: number; change: number; changePercent: number; trend: 'up' | 'down' | 'stable'; velocity: number; } export interface Anomaly { timestamp: number; metric: string; value: number; expected: number; deviation: number; severity: 'low' | 'medium' | 'high'; confidence: number; } export interface Prediction { metric: string; timestamp: number; predictedValue: number; confidenceInterval: { lower: number; upper: number; }; confidence: number; } export interface RegressionResult { slope: number; intercept: number; rSquared: number; equation: string; } export interface SeasonalityPattern { detected: boolean; period: number; strength: number; peaks: number[]; troughs: number[]; } export interface Alert { id: string; type: 'threshold' | 'anomaly' | 'trend'; metric: string; severity: 'info' | 'warning' | 'critical'; message: string; timestamp: number; value: number; threshold?: number; triggered: boolean; } export interface AlertConfiguration { metric: string; condition: 'gt' | 'lt' | 'eq' | 'ne'; threshold: number; severity: 'info' | 'warning' | 'critical'; enabled: boolean; } export interface HeatmapData { type: HeatmapType; dimensions: { width: number; height: number; }; data: number[][]; labels: { x: string[]; y: string[]; }; colorScale: { min: number; max: number; }; summary: { hotspots: Array<{ x: number; y: number; value: number; }>; avgIntensity: number; maxIntensity: number; }; } export interface Bottleneck { type: 'slow-operation' | 'hot-key' | 'memory-pressure' | 'high-eviction'; severity: 'low' | 'medium' | 'high'; description: string; impact: number; recommendation: string; affectedKeys?: string[]; metrics: { current: number; threshold: number; duration: number; }; } export interface CostBreakdown { timestamp: number; timeRange: { start: number; end: number; }; storage: StorageCost; network: NetworkCost; compute: ComputeCost; total: TotalCost; projections: CostProjection[]; optimizations: CostOptimization[]; } export interface StorageCost { memoryCost: number; diskCost: number; totalStorage: number; utilizationPercent: number; } export interface NetworkCost { ingressCost: number; egressCost: number; totalTraffic: number; bandwidthUtilization: number; } export interface ComputeCost { cpuCost: number; operationCost: number; totalOperations: number; efficiency: number; } export interface TotalCost { current: number; projected: number; trend: number; costPerGB: number; costPerOperation: number; } export interface CostProjection { period: string; estimatedCost: number; confidence: number; } export interface CostOptimization { category: string; potentialSavings: number; effort: 'low' | 'medium' | 'high'; recommendation: string; } /** * CacheAnalytics - Comprehensive analytics and monitoring tool */ export declare class CacheAnalyticsTool extends EventEmitter { private cache; private tokenCounter; private metrics; private alertConfigs; private historicalData; private readonly maxHistoricalEntries; private timeSeriesData; private keyAccessLog; constructor(cache: CacheEngine, tokenCounter: TokenCounter, metrics: MetricsCollector); /** * Initialize default alert configurations */ private initializeDefaults; /** * Main entry point for cache analytics operations */ run(options: CacheAnalyticsOptions): Promise; /** * Get real-time dashboard data */ private getDashboard; /** * Get performance metrics */ private getPerformanceMetrics; /** * Get usage metrics */ private getUsageMetrics; /** * Get efficiency metrics */ private getEfficiencyMetrics; /** * Get cost metrics */ private getCostMetrics; /** * Get health metrics */ private getHealthMetrics; /** * Get recent activity */ private getRecentActivity; /** * Get detailed metrics */ private getMetrics; /** * Analyze trends over time */ private analyzeTrends; /** * Calculate trend metrics */ private calculateTrendMetrics; /** * Create trend metric */ private createTrendMetric; /** * Detect anomalies */ private detectAnomalies; /** * Generate predictions */ private generatePredictions; /** * Calculate simple linear trend */ private calculateSimpleTrend; /** * Calculate regression */ private calculateRegression; /** * Detect seasonality */ private detectSeasonality; /** * Check alerts and return triggered ones */ private checkAlerts; /** * Extract metric value from metrics collection */ private extractMetricValue; /** * Evaluate alert condition */ private evaluateAlertCondition; /** * Generate access heatmap */ private generateHeatmap; /** * Generate temporal heatmap (hour x day of week) */ private generateTemporalHeatmap; /** * Generate key correlation heatmap */ private generateKeyCorrelationHeatmap; /** * Generate memory usage heatmap */ private generateMemoryHeatmap; /** * Identify performance bottlenecks */ private identifyBottlenecks; /** * Analyze caching costs */ private analyzeCosts; /** * Export analytics data */ private exportData; /** * Convert to CSV format */ private convertToCSV; /** * Convert to Prometheus format */ private convertToPrometheus; /** * Extract key from operation metadata */ private extractKeyFromMetadata; /** * Update time-series data */ private updateTimeSeries; /** * Calculate fragmentation index */ private calculateFragmentation; /** * Calculate eviction trend */ private calculateEvictionTrend; /** * Calculate cost trend */ private calculateCostTrend; /** * Get previous time range for comparison */ private getPreviousTimeRange; /** * Determine if operation is cacheable */ private isCacheableOperation; /** * Get cache key parameters for operation */ private getCacheKeyParams; /** * Cleanup and dispose */ dispose(): void; } export declare function getCacheAnalyticsTool(cache: CacheEngine, tokenCounter: TokenCounter, metrics: MetricsCollector): CacheAnalyticsTool; export declare const CACHE_ANALYTICS_TOOL_DEFINITION: { readonly name: "cache_analytics"; readonly description: "Comprehensive cache analytics with 88%+ token reduction. Real-time dashboards, trend analysis, alerting, heatmaps, bottleneck detection, and cost optimization."; readonly inputSchema: { readonly type: "object"; readonly properties: { readonly operation: { readonly type: "string"; readonly enum: readonly ["dashboard", "metrics", "trends", "alerts", "heatmap", "bottlenecks", "cost-analysis", "export-data"]; readonly description: "Analytics operation to perform"; }; readonly timeRange: { readonly type: "object"; readonly properties: { readonly start: { readonly type: "number"; readonly description: "Start timestamp in milliseconds"; }; readonly end: { readonly type: "number"; readonly description: "End timestamp in milliseconds"; }; }; readonly description: "Time range for analysis"; }; readonly granularity: { readonly type: "string"; readonly enum: readonly ["second", "minute", "hour", "day"]; readonly description: "Time granularity for aggregation"; }; readonly metricTypes: { readonly type: "array"; readonly items: { readonly type: "string"; readonly enum: readonly ["performance", "usage", "efficiency", "cost", "health"]; }; readonly description: "Types of metrics to collect"; }; readonly aggregation: { readonly type: "string"; readonly enum: readonly ["sum", "avg", "min", "max", "p95", "p99"]; readonly description: "Aggregation method for metrics"; }; readonly compareWith: { readonly type: "string"; readonly enum: readonly ["previous-period", "last-week", "last-month"]; readonly description: "Period to compare trends with"; }; readonly trendType: { readonly type: "string"; readonly enum: readonly ["absolute", "percentage", "rate"]; readonly description: "Type of trend analysis"; }; readonly alertType: { readonly type: "string"; readonly enum: readonly ["threshold", "anomaly", "trend"]; readonly description: "Type of alert to check"; }; readonly threshold: { readonly type: "number"; readonly description: "Threshold value for alerts"; }; readonly alertConfig: { readonly type: "object"; readonly properties: { readonly metric: { readonly type: "string"; }; readonly condition: { readonly type: "string"; readonly enum: readonly ["gt", "lt", "eq", "ne"]; }; readonly threshold: { readonly type: "number"; }; readonly severity: { readonly type: "string"; readonly enum: readonly ["info", "warning", "critical"]; }; readonly enabled: { readonly type: "boolean"; }; }; readonly description: "Alert configuration"; }; readonly heatmapType: { readonly type: "string"; readonly enum: readonly ["temporal", "key-correlation", "memory"]; readonly description: "Type of heatmap to generate"; }; readonly resolution: { readonly type: "string"; readonly enum: readonly ["low", "medium", "high"]; readonly description: "Heatmap resolution"; }; readonly format: { readonly type: "string"; readonly enum: readonly ["json", "csv", "prometheus"]; readonly description: "Export data format"; }; readonly filePath: { readonly type: "string"; readonly description: "File path for data export"; }; readonly useCache: { readonly type: "boolean"; readonly description: "Enable caching of analytics results (default: true)"; readonly default: true; }; readonly cacheTTL: { readonly type: "number"; readonly description: "Cache TTL in seconds (default: 30)"; readonly default: 30; }; }; readonly required: readonly ["operation"]; }; }; export declare function runCacheAnalytics(options: CacheAnalyticsOptions, cache: CacheEngine, tokenCounter: TokenCounter, metrics: MetricsCollector): Promise; //# sourceMappingURL=cache-analytics.d.ts.map