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
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
"""

Performance monitoring API routes.



This module provides endpoints for monitoring system performance,

connection pool status, cache statistics, and other performance metrics.

"""

import logging
from datetime import datetime
from typing import Dict, Any

from flask import Blueprint, jsonify, current_app
from flask_limiter import Limiter

from ..utils.connection_pool import get_connection_pool_manager
from ..services.cache_service import get_cache_service
from .middleware import require_auth, create_limiter
from ..utils.response_optimization import cache_response, compress_response

logger = logging.getLogger(__name__)

# Create blueprint
performance_bp = Blueprint('performance', __name__, url_prefix='/api/v1/performance')

# Initialize rate limiter
limiter = create_limiter()


@performance_bp.route('/status', methods=['GET'])
@limiter.limit("30 per minute")
@cache_response(max_age=60, cache_type='private')  # Cache for 1 minute
@compress_response
def get_performance_status():
    """

    Get overall system performance status.

    

    Returns:

        JSON response with performance metrics

    """
    try:
        status = {
            'timestamp': datetime.utcnow().isoformat(),
            'status': 'healthy',
            'services': {}
        }
        
        # Database connection pool status
        connection_pool_manager = get_connection_pool_manager()
        if connection_pool_manager:
            pool_status = connection_pool_manager.get_status()
            status['services']['database'] = {
                'status': 'connected',
                'pool_stats': pool_status['database']
            }
            
            if pool_status['redis']:
                status['services']['redis'] = {
                    'status': 'connected' if pool_status['redis']['healthy'] else 'unhealthy',
                    'pool_stats': pool_status['redis']
                }
            else:
                status['services']['redis'] = {
                    'status': 'disabled'
                }
        else:
            status['services']['database'] = {'status': 'no_pool_manager'}
            status['services']['redis'] = {'status': 'no_pool_manager'}
        
        # Cache service status
        cache_service = get_cache_service()
        if cache_service:
            cache_stats = cache_service.get_cache_stats()
            status['services']['cache'] = {
                'status': 'enabled' if cache_stats['redis_enabled'] else 'disabled',
                'stats': cache_stats
            }
        else:
            status['services']['cache'] = {'status': 'not_initialized'}
        
        # Application configuration
        status['configuration'] = {
            'compression_enabled': current_app.config.get('ENABLE_COMPRESSION', False),
            'caching_enabled': current_app.config.get('ENABLE_CACHING', False),
            'performance_monitoring': current_app.config.get('ENABLE_PERFORMANCE_MONITORING', False),
            'db_pool_size': current_app.config.get('DB_POOL_SIZE', 10),
            'redis_max_connections': current_app.config.get('REDIS_MAX_CONNECTIONS', 20)
        }
        
        return jsonify(status)
        
    except Exception as e:
        logger.error(f"Error getting performance status: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'status': 'error',
            'error': str(e)
        }), 500


@performance_bp.route('/database', methods=['GET'])
@limiter.limit("20 per minute")
@require_auth
@cache_response(max_age=30, cache_type='private')
@compress_response
def get_database_performance():
    """

    Get database performance metrics.

    

    Returns:

        JSON response with database performance data

    """
    try:
        connection_pool_manager = get_connection_pool_manager()
        
        if not connection_pool_manager:
            return jsonify({
                'error': 'Connection pool manager not available'
            }), 503
        
        # Get database pool status
        pool_status = connection_pool_manager.get_status()
        database_stats = pool_status['database']
        
        # Calculate pool utilization
        total_connections = database_stats['pool_size'] + database_stats['overflow']
        active_connections = database_stats['checked_out']
        utilization = (active_connections / total_connections * 100) if total_connections > 0 else 0
        
        response_data = {
            'timestamp': datetime.utcnow().isoformat(),
            'pool_stats': database_stats,
            'utilization': {
                'active_connections': active_connections,
                'total_connections': total_connections,
                'utilization_percent': round(utilization, 2)
            },
            'health': {
                'status': 'healthy' if utilization < 80 else 'warning' if utilization < 95 else 'critical',
                'invalid_connections': database_stats['invalid']
            }
        }
        
        return jsonify(response_data)
        
    except Exception as e:
        logger.error(f"Error getting database performance: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        }), 500


@performance_bp.route('/redis', methods=['GET'])
@limiter.limit("20 per minute")
@require_auth
@cache_response(max_age=30, cache_type='private')
@compress_response
def get_redis_performance():
    """

    Get Redis performance metrics.

    

    Returns:

        JSON response with Redis performance data

    """
    try:
        connection_pool_manager = get_connection_pool_manager()
        
        if not connection_pool_manager:
            return jsonify({
                'error': 'Connection pool manager not available'
            }), 503
        
        redis_client = connection_pool_manager.get_redis_client()
        
        if not redis_client:
            return jsonify({
                'status': 'disabled',
                'message': 'Redis is not configured'
            })
        
        # Get Redis pool status
        pool_status = connection_pool_manager.get_status()
        redis_stats = pool_status['redis']
        
        # Get Redis server info
        try:
            redis_info = redis_client.info()
            server_stats = {
                'version': redis_info.get('redis_version', 'unknown'),
                'uptime_seconds': redis_info.get('uptime_in_seconds', 0),
                'connected_clients': redis_info.get('connected_clients', 0),
                'used_memory': redis_info.get('used_memory_human', 'unknown'),
                'keyspace_hits': redis_info.get('keyspace_hits', 0),
                'keyspace_misses': redis_info.get('keyspace_misses', 0),
                'total_commands_processed': redis_info.get('total_commands_processed', 0)
            }
            
            # Calculate hit rate
            total_keyspace_ops = server_stats['keyspace_hits'] + server_stats['keyspace_misses']
            hit_rate = (server_stats['keyspace_hits'] / total_keyspace_ops * 100) if total_keyspace_ops > 0 else 0
            
        except Exception as e:
            logger.warning(f"Failed to get Redis server info: {e}")
            server_stats = {'error': 'Failed to get server info'}
            hit_rate = 0
        
        response_data = {
            'timestamp': datetime.utcnow().isoformat(),
            'pool_stats': redis_stats,
            'server_stats': server_stats,
            'performance': {
                'hit_rate_percent': round(hit_rate, 2),
                'health_status': redis_stats.get('healthy', False)
            }
        }
        
        return jsonify(response_data)
        
    except Exception as e:
        logger.error(f"Error getting Redis performance: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        }), 500


@performance_bp.route('/cache', methods=['GET'])
@limiter.limit("20 per minute")
@require_auth
@cache_response(max_age=60, cache_type='private')
@compress_response
def get_cache_performance():
    """

    Get cache performance metrics.

    

    Returns:

        JSON response with cache performance data

    """
    try:
        cache_service = get_cache_service()
        
        if not cache_service:
            return jsonify({
                'status': 'not_initialized',
                'message': 'Cache service not initialized'
            })
        
        cache_stats = cache_service.get_cache_stats()
        
        # Add performance analysis
        performance_analysis = {
            'efficiency': 'excellent' if cache_stats['hit_rate_percent'] >= 80 else
                         'good' if cache_stats['hit_rate_percent'] >= 60 else
                         'fair' if cache_stats['hit_rate_percent'] >= 40 else 'poor',
            'recommendations': []
        }
        
        if cache_stats['hit_rate_percent'] < 60:
            performance_analysis['recommendations'].append('Consider increasing cache TTL')
            performance_analysis['recommendations'].append('Review cache key strategies')
        
        if cache_stats['cache_errors'] > 0:
            performance_analysis['recommendations'].append('Investigate cache errors')
        
        response_data = {
            'timestamp': datetime.utcnow().isoformat(),
            'cache_stats': cache_stats,
            'performance_analysis': performance_analysis
        }
        
        return jsonify(response_data)
        
    except Exception as e:
        logger.error(f"Error getting cache performance: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        }), 500


@performance_bp.route('/metrics', methods=['GET'])
@limiter.limit("10 per minute")
@require_auth
@cache_response(max_age=120, cache_type='private')  # Cache for 2 minutes
@compress_response
def get_comprehensive_metrics():
    """

    Get comprehensive performance metrics.

    

    Returns:

        JSON response with all performance metrics

    """
    try:
        metrics = {
            'timestamp': datetime.utcnow().isoformat(),
            'system': {},
            'database': {},
            'redis': {},
            'cache': {},
            'application': {}
        }
        
        # System metrics
        try:
            import psutil
            import os
            
            process = psutil.Process(os.getpid())
            cpu_percent = process.cpu_percent()
            memory_info = process.memory_info()
            
            metrics['system'] = {
                'cpu_percent': cpu_percent,
                'memory_rss_mb': round(memory_info.rss / 1024 / 1024, 2),
                'memory_vms_mb': round(memory_info.vms / 1024 / 1024, 2),
                'num_threads': process.num_threads(),
                'num_fds': process.num_fds() if hasattr(process, 'num_fds') else 'N/A'
            }
        except ImportError:
            metrics['system'] = {'error': 'psutil not available'}
        except Exception as e:
            metrics['system'] = {'error': str(e)}
        
        # Database metrics
        connection_pool_manager = get_connection_pool_manager()
        if connection_pool_manager:
            pool_status = connection_pool_manager.get_status()
            metrics['database'] = pool_status['database']
            metrics['redis'] = pool_status['redis'] or {'status': 'disabled'}
        
        # Cache metrics
        cache_service = get_cache_service()
        if cache_service:
            metrics['cache'] = cache_service.get_cache_stats()
        
        # Application metrics
        metrics['application'] = {
            'config': {
                'compression_enabled': current_app.config.get('ENABLE_COMPRESSION', False),
                'caching_enabled': current_app.config.get('ENABLE_CACHING', False),
                'debug_mode': current_app.config.get('DEBUG', False)
            },
            'flask': {
                'testing': current_app.testing,
                'debug': current_app.debug
            }
        }
        
        return jsonify(metrics)
        
    except Exception as e:
        logger.error(f"Error getting comprehensive metrics: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        }), 500


@performance_bp.route('/health', methods=['GET'])
@limiter.limit("60 per minute")
def performance_health_check():
    """

    Quick health check for performance monitoring.

    

    Returns:

        JSON response with health status

    """
    try:
        health_status = {
            'timestamp': datetime.utcnow().isoformat(),
            'status': 'healthy',
            'checks': {}
        }
        
        # Database health
        try:
            from sqlalchemy import text
            from ..models.base import db
            db.session.execute(text('SELECT 1'))
            health_status['checks']['database'] = 'healthy'
        except Exception as e:
            health_status['checks']['database'] = f'unhealthy: {str(e)}'
            health_status['status'] = 'degraded'
        
        # Redis health
        connection_pool_manager = get_connection_pool_manager()
        if connection_pool_manager:
            redis_client = connection_pool_manager.get_redis_client()
            if redis_client:
                try:
                    redis_client.ping()
                    health_status['checks']['redis'] = 'healthy'
                except Exception as e:
                    health_status['checks']['redis'] = f'unhealthy: {str(e)}'
                    health_status['status'] = 'degraded'
            else:
                health_status['checks']['redis'] = 'disabled'
        else:
            health_status['checks']['redis'] = 'no_pool_manager'
        
        # Cache service health
        cache_service = get_cache_service()
        if cache_service:
            cache_stats = cache_service.get_cache_stats()
            if cache_stats['cache_errors'] > 100:  # Arbitrary threshold
                health_status['checks']['cache'] = 'degraded'
                health_status['status'] = 'degraded'
            else:
                health_status['checks']['cache'] = 'healthy'
        else:
            health_status['checks']['cache'] = 'not_initialized'
        
        return jsonify(health_status)
        
    except Exception as e:
        logger.error(f"Performance health check failed: {e}")
        return jsonify({
            'timestamp': datetime.utcnow().isoformat(),
            'status': 'unhealthy',
            'error': str(e)
        }), 503


# Error handlers
@performance_bp.errorhandler(429)
def handle_rate_limit_exceeded(error):
    """Handle rate limit exceeded errors."""
    return jsonify({
        'error': 'Rate limit exceeded',
        'message': 'Too many requests to performance endpoints. Please try again later.'
    }), 429


@performance_bp.errorhandler(500)
def handle_internal_error(error):
    """Handle internal server errors."""
    logger.error(f"Performance endpoint internal error: {error}")
    return jsonify({
        'error': 'Internal server error',
        'timestamp': datetime.utcnow().isoformat()
    }), 500