Spaces:
Paused

File size: 9,020 Bytes
357bfdf
 
 
 
 
0743ddc
357bfdf
0743ddc
 
357bfdf
579285c
0743ddc
 
357bfdf
579285c
357bfdf
 
 
 
 
 
0743ddc
 
 
 
 
 
 
 
 
 
357bfdf
579285c
0743ddc
357bfdf
0743ddc
357bfdf
 
 
579285c
 
 
 
 
0743ddc
357bfdf
 
0743ddc
 
 
 
 
 
 
 
357bfdf
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
 
0743ddc
357bfdf
579285c
0743ddc
357bfdf
 
 
579285c
0743ddc
 
 
 
 
 
 
 
579285c
357bfdf
 
0743ddc
357bfdf
 
 
 
579285c
0743ddc
357bfdf
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
0743ddc
 
 
 
 
 
 
 
 
 
 
 
 
357bfdf
 
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
 
 
 
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
 
0743ddc
357bfdf
 
0743ddc
357bfdf
 
 
0743ddc
357bfdf
 
 
 
 
0743ddc
357bfdf
 
 
0743ddc
357bfdf
 
 
 
 
 
 
 
 
 
 
0743ddc
357bfdf
0743ddc
357bfdf
 
 
 
 
 
 
0743ddc
357bfdf
 
 
 
0743ddc
357bfdf
 
 
 
0743ddc
357bfdf
579285c
357bfdf
0743ddc
357bfdf
579285c
357bfdf
 
0743ddc
579285c
357bfdf
 
 
 
0743ddc
 
 
 
357bfdf
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
241
242
243
244
245
246
247
248
249
250
251
252
"""
Performance monitoring and metrics collection
Tracks query execution times, API response times, and resource usage
"""

import threading
import time
from collections import defaultdict, deque
from datetime import UTC, datetime, timedelta, timezone
from functools import wraps
from typing import Callable, ClassVar, Dict, List, Optional

import structlog

logger = structlog.get_logger(__name__)


class PerformanceMonitor:
    """
    Thread-safe performance monitoring with rolling window statistics
    """

    _metrics = defaultdict(
        lambda: {  # type: ignore[name-defined, index, return-value, var-annotated]
            "count": 0,
            "total_time": 0.0,
            "min_time": float("inf"),
            "max_time": 0.0,
            "recent_times": deque(maxlen=100),  # Last 100 executions
        }
    )
    _lock = threading.Lock()
    _slow_queries: ClassVar[deque] = deque(maxlen=50)  # Last 50 slow queries

    @classmethod
    def record_execution(cls, operation: str, duration: float, details: dict | None = None):
        """Record execution time for an operation"""
        with cls._lock:
            metrics = cls._metrics[operation]
            metrics["count"] += 1  # type: ignore[misc, operator, valid-type]
            metrics["total_time"] += duration  # type: ignore[misc, operator, valid-type]
            metrics["min_time"] = min(metrics["min_time"], duration)  # type: ignore[call-arg, call-overload, no-redef]
            metrics["max_time"] = max(metrics["max_time"], duration)  # type: ignore[call-arg, call-overload, no-redef]
            metrics["recent_times"].append(duration)  # type: ignore[attr-defined]

            # Track slow queries (>1 second)
            if duration > 1.0:
                cls._slow_queries.append(
                    {
                        "operation": operation,
                        "duration": duration,
                        "timestamp": datetime.now(UTC).isoformat(),
                        "details": details or {},
                    }
                )
                logger.warning(f"Slow operation detected: {operation} took {duration:.2f}s")

    @classmethod
    def get_stats(cls, operation: str | None = None) -> dict:
        """Get performance statistics"""
        with cls._lock:
            if operation:
                if operation not in cls._metrics:
                    return {}

                metrics = cls._metrics[operation]
                recent = list(metrics["recent_times"])  # type: ignore[call-arg, call-overload, no-redef]

                return {
                    "operation": operation,
                    "count": metrics["count"],
                    "total_time": round(metrics["total_time"], 2),  # type: ignore[call-arg, call-overload, no-redef]
                    "avg_time": (
                        round(metrics["total_time"] / metrics["count"], 3)
                        if metrics["count"] > 0
                        else 0
                    ),  # type: ignore[misc, operator, valid-type]
                    "min_time": (
                        round(metrics["min_time"], 3) if metrics["min_time"] != float("inf") else 0
                    ),  # type: ignore[call-arg, call-overload, no-redef]
                    "max_time": round(metrics["max_time"], 3),  # type: ignore[call-arg, call-overload, no-redef]
                    "recent_avg": round(sum(recent) / len(recent), 3) if recent else 0,
                }

            # Return all operations
            return {
                op: {
                    "count": m["count"],
                    "avg_time": round(m["total_time"] / m["count"], 3) if m["count"] > 0 else 0,  # type: ignore[misc, operator, valid-type]
                    "max_time": round(m["max_time"], 3),  # type: ignore[call-arg, call-overload, no-redef]
                }
                for op, m in cls._metrics.items()
            }

    @classmethod
    def get_slow_queries(cls) -> list[dict]:
        """Get recent slow queries"""
        with cls._lock:
            return list(cls._slow_queries)

    @classmethod
    def get_top_operations(cls, limit: int = 10) -> list[dict]:
        """Get top operations by total time"""
        with cls._lock:
            operations = []
            for op, metrics in cls._metrics.items():
                operations.append(
                    {
                        "operation": op,
                        "total_time": round(metrics["total_time"], 2),  # type: ignore[call-arg, call-overload, no-redef]
                        "count": metrics["count"],
                        "avg_time": (
                            round(metrics["total_time"] / metrics["count"], 3)
                            if metrics["count"] > 0
                            else 0
                        ),  # type: ignore[misc, operator, valid-type]
                    }
                )

            # Sort by total time descending
            operations.sort(key=lambda x: x["total_time"], reverse=True)
            return operations[:limit]

    @classmethod
    def reset_stats(cls):
        """Reset all statistics"""
        with cls._lock:
            cls._metrics.clear()
            cls._slow_queries.clear()
            logger.info("Performance statistics reset")


def monitor_performance(operation_name: str, slow_threshold: float = 1.0):
    """
    Decorator to monitor function performance

    Usage:
        @monitor_performance("get_inventory_item", slow_threshold=0.5)
        def get_item(self, item_id):
            ...
    """

    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def sync_wrapper(*args, **kwargs):
            start = time.time()
            try:
                result = func(*args, **kwargs)
                return result
            finally:
                duration = time.time() - start
                PerformanceMonitor.record_execution(
                    operation_name,
                    duration,
                    details={"args_count": len(args), "kwargs_count": len(kwargs)},
                )

                if duration > slow_threshold:
                    logger.warning(
                        f"Operation {operation_name} exceeded threshold: "
                        f"{duration:.2f}s > {slow_threshold}s"
                    )

        @wraps(func)
        async def async_wrapper(*args, **kwargs):
            start = time.time()
            try:
                result = await func(*args, **kwargs)
                return result
            finally:
                duration = time.time() - start
                PerformanceMonitor.record_execution(
                    operation_name,
                    duration,
                    details={"args_count": len(args), "kwargs_count": len(kwargs)},
                )

                if duration > slow_threshold:
                    logger.warning(
                        f"Operation {operation_name} exceeded threshold: "
                        f"{duration:.2f}s > {slow_threshold}s"
                    )

        # Return appropriate wrapper based on function type
        import asyncio

        if asyncio.iscoroutinefunction(func):
            return async_wrapper
        return sync_wrapper

    return decorator


class QueryPerformanceTracker:
    """Track database query performance"""

    @staticmethod
    def track_query(query_type: str, table_name: str):
        """Decorator for tracking query performance"""

        def decorator(func: Callable) -> Callable:
            @wraps(func)
            def wrapper(*args, **kwargs):
                operation = f"query:{query_type}:{table_name}"
                start = time.time()
                try:
                    result = func(*args, **kwargs)
                    return result
                finally:
                    duration = time.time() - start
                    PerformanceMonitor.record_execution(operation, duration)

            return wrapper

        return decorator


# Middleware-compatible timing function
def time_operation(operation_name: str) -> float:
    """
    Context manager for timing operations

    Usage:
        with time_operation("my_operation"):
            # do work
    """

    class TimingContext:
        def __init__(self, op_name: str):
            self.op_name = op_name
            self.start = None

        def __enter__(self):
            self.start = time.time()  # type: ignore[arg-type, assignment]
            return self

        def __exit__(self, exc_type, exc_val, exc_tb):
            duration = time.time() - self.start  # type: ignore[misc, operator, valid-type]
            PerformanceMonitor.record_execution(self.op_name, duration)
            return False

    return TimingContext(operation_name)  # type: ignore[name-defined, index, return-value, var-annotated]


# Export utilities
__all__ = [
    "PerformanceMonitor",
    "monitor_performance",
    "QueryPerformanceTracker",
    "time_operation",
]