-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmetrics.py
More file actions
1749 lines (1554 loc) · 58.5 KB
/
Copy pathmetrics.py
File metadata and controls
1749 lines (1554 loc) · 58.5 KB
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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Prometheus metrics primitives and helpers.
"""
from __future__ import annotations
import json
import logging
import time
from contextlib import contextmanager
from datetime import datetime
from typing import Any, Dict, Optional, List, Tuple
import os
import threading
import time as _time
from collections import deque
from urllib.parse import urlparse
# Structured event emission (no dependency loop back to metrics)
try:
from observability import emit_event # type: ignore
except Exception: # pragma: no cover - observability not always available in tests
def emit_event(event: str, severity: str = "info", **fields): # type: ignore
return None
# Optional DB-backed metrics storage (fail-open stubs if unavailable)
try: # pragma: no cover
from monitoring.metrics_storage import (
enqueue_request_metric as _db_enqueue_request_metric,
flush as _db_metrics_flush,
) # type: ignore
except Exception: # pragma: no cover
def _db_enqueue_request_metric(status_code: int, duration_seconds: float, *, request_id: str | None = None, extra=None): # type: ignore
return None
def _db_metrics_flush(force: bool = False) -> None: # type: ignore
return None
# Best-effort access to current structlog contextvars for correlation
try: # pragma: no cover
from structlog.contextvars import get_contextvars as _get_structlog_ctx # type: ignore
except Exception: # pragma: no cover
def _get_structlog_ctx(): # type: ignore
return {}
try:
from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST
except Exception: # pragma: no cover - prometheus optional in some envs
Counter = Histogram = Gauge = None # type: ignore
def generate_latest(): # type: ignore
return b""
CONTENT_TYPE_LATEST = "text/plain; version=0.0.4; charset=utf-8" # type: ignore
# Logger for structured warnings around anomalies
logger = logging.getLogger(__name__)
# --- OpenTelemetry metrics (best-effort, fail-open) ---
_OTEL_HTTP_LOCK = threading.Lock()
_OTEL_HTTP_INIT_DONE: bool = False
_OTEL_HTTP_REQUESTS_COUNTER = None
_OTEL_HTTP_DURATION_HIST = None
_OTEL_HTTP_QUEUE_DELAY_HIST = None
def _otel_init_http_metrics():
"""Best-effort init of OpenTelemetry HTTP instruments (idempotent)."""
global _OTEL_HTTP_INIT_DONE, _OTEL_HTTP_REQUESTS_COUNTER, _OTEL_HTTP_DURATION_HIST, _OTEL_HTTP_QUEUE_DELAY_HIST
if _OTEL_HTTP_INIT_DONE:
return
with _OTEL_HTTP_LOCK:
if _OTEL_HTTP_INIT_DONE:
return
try:
from opentelemetry import metrics as _otel_metrics # type: ignore
except Exception:
_OTEL_HTTP_INIT_DONE = True
return
try:
meter = _otel_metrics.get_meter("codebot.metrics")
except Exception:
_OTEL_HTTP_INIT_DONE = True
return
try:
_OTEL_HTTP_REQUESTS_COUNTER = meter.create_counter(
"codebot.http.server.requests",
description="Total incoming request outcomes (best-effort)",
unit="1",
)
except Exception:
_OTEL_HTTP_REQUESTS_COUNTER = None
try:
_OTEL_HTTP_DURATION_HIST = meter.create_histogram(
"codebot.http.server.duration",
description="Incoming request duration in seconds (best-effort)",
unit="s",
)
except Exception:
_OTEL_HTTP_DURATION_HIST = None
try:
_OTEL_HTTP_QUEUE_DELAY_HIST = meter.create_histogram(
"codebot.http.server.queue_delay",
description="Incoming request queue delay in seconds (best-effort)",
unit="s",
)
except Exception:
_OTEL_HTTP_QUEUE_DELAY_HIST = None
_OTEL_HTTP_INIT_DONE = True
def _otel_record_http_outcome(
*,
status_code: int,
duration_seconds: float,
endpoint: str,
method: str,
source: str | None = None,
status_bucket: str | None = None,
queue_delay_ms: int | None = None,
) -> None:
"""Record a single request outcome to OpenTelemetry metrics (never raises)."""
try:
_otel_init_http_metrics()
attrs: dict[str, object] = {
"http.method": (method or "").upper() or "GET",
"http.route": str(endpoint or "unknown")[:160],
"http.status_code": int(status_code),
}
if source:
attrs["codebot.source"] = str(source)[:64]
if status_bucket:
attrs["codebot.status_bucket"] = str(status_bucket)[:16]
if _OTEL_HTTP_REQUESTS_COUNTER is not None:
try:
_OTEL_HTTP_REQUESTS_COUNTER.add(1, attrs) # type: ignore[attr-defined]
except Exception:
pass
if _OTEL_HTTP_DURATION_HIST is not None:
try:
_OTEL_HTTP_DURATION_HIST.record(max(0.0, float(duration_seconds)), attrs) # type: ignore[attr-defined]
except Exception:
pass
if queue_delay_ms is not None and _OTEL_HTTP_QUEUE_DELAY_HIST is not None:
try:
_OTEL_HTTP_QUEUE_DELAY_HIST.record(max(0.0, float(queue_delay_ms)) / 1000.0, attrs) # type: ignore[attr-defined]
except Exception:
pass
except Exception:
return
# Core metrics (names chosen to be generic and reusable)
errors_total = Counter("errors_total", "Total error count", ["code"]) if Counter else None
operation_latency_seconds = (
Histogram(
"operation_latency_seconds",
"Operation latency in seconds",
["operation", "repo"],
)
if Histogram
else None
)
telegram_updates_total = (
Counter(
"telegram_updates_total",
"Total Telegram updates processed",
["type", "status"],
)
if Counter
else None
)
active_indexes = Gauge("active_indexes", "Active DB indexes") if Gauge else None
# Health check gauges exposed via /metrics
health_mongo_status = (
Gauge("health_mongo_status", "1 when MongoDB is connected, else 0") if Gauge else None
)
health_ping_ms = (
Gauge("health_ping_ms", "MongoDB ping latency reported by /healthz (milliseconds)")
if Gauge
else None
)
health_indexes_total = (
Gauge("health_indexes_total", "Healthy index count reported by /healthz") if Gauge else None
)
health_latency_ewma = (
Gauge("health_latency_ewma", "Application EWMA latency in milliseconds reported by /healthz")
if Gauge
else None
)
# Startup metrics (milliseconds) to track cold-start regressions
startup_stage_duration_ms = (
Gauge(
"startup_stage_duration_ms",
"Duration of individual startup stages in milliseconds",
["stage"],
)
if Gauge
else None
)
startup_total_duration_ms = (
Gauge("startup_total_duration_ms", "Total application startup duration in milliseconds")
if Gauge
else None
)
# Optional business events counter for high-level analytics
business_events_total = (
Counter(
"business_events_total",
"Count of business-domain events",
["metric"],
)
if Counter
else None
)
# Observability v6: predicted vs actual incidents counters
predicted_incidents_total = (
Counter(
"predicted_incidents_total",
"Count of predictive incidents detected",
["metric"],
)
if Counter
else None
)
actual_incidents_total = (
Counter(
"actual_incidents_total",
"Count of actual critical incidents",
["metric"],
)
if Counter
else None
)
# Observability v7: Feedback & Prevention
# Gauge for prediction accuracy over a recent window (e.g., 24h)
prediction_accuracy_percent = (
Gauge(
"prediction_accuracy_percent",
"Prediction accuracy percent over recent window",
)
if Gauge
else None
)
# Counter for prevented incidents over time (labeled by metric)
prevented_incidents_total = (
Counter(
"prevented_incidents_total",
"Count of incidents likely prevented by preemptive actions",
["metric"],
)
if Counter
else None
)
# --- CodeBot Stage 2: Unified service metrics ---
# Visible in both Flask and AIOHTTP services under /metrics
codebot_active_users_total = Gauge("codebot_active_users_total", "Number of active users recently") if Gauge else None
codebot_failed_requests_total = Counter("codebot_failed_requests_total", "Total failed HTTP requests (status >= 500)") if Counter else None
codebot_avg_response_time_seconds = Gauge("codebot_avg_response_time_seconds", "Smoothed average response time (EWMA) in seconds") if Gauge else None
codebot_active_requests_total = Gauge("codebot_active_requests_total", "Number of in-flight HTTP requests") if Gauge else None
# Internal helper: total requests for uptime calculation (not externally required but useful)
codebot_requests_total = Counter("codebot_requests_total", "Total HTTP requests processed") if Counter else None
codebot_external_error_rate_percent = (
Gauge(
"codebot_external_error_rate_percent",
"Rolling 5m error rate percent for traffic attributed to external services",
)
if Gauge
else None
)
# Rate limiting metrics (used by both Flask and Telegram bot)
rate_limit_hits = (
Counter(
"rate_limit_hits_total",
"Total rate limit checks",
["source", "scope", "limit", "result"],
)
if Counter
else None
)
rate_limit_blocked = (
Counter(
"rate_limit_blocked_total",
"Total blocked requests by rate limiter",
["source", "scope", "limit"],
)
if Counter
else None
)
# --- Phase 3: HTTP-level metrics for SLOs ---
# Standard, well-known Prometheus metric names for HTTP instrumentation.
# Labels kept intentionally small to avoid high cardinality: method, endpoint, status
http_requests_total = (
Counter(
"http_requests_total",
"Total HTTP requests",
["method", "endpoint", "status"],
)
if Counter
else None
)
http_request_duration_seconds = (
Histogram(
"http_request_duration_seconds",
"HTTP request duration in seconds",
["method", "endpoint"],
)
if Histogram
else None
)
# Queue delay (time from ingress to app handling) as measured from X-Request-Start/X-Queue-Start.
http_request_queue_duration_seconds = (
Histogram(
"http_request_queue_duration_seconds",
"HTTP request queue delay in seconds",
["method", "endpoint"],
)
if Histogram
else None
)
# --- Stage 4: outbound dependency resilience metrics ---
outbound_request_duration_seconds = (
Histogram(
"request_duration_seconds",
"Outbound request duration in seconds",
["service", "endpoint", "status"],
)
if Histogram
else None
)
outbound_retries_total = (
Counter(
"retries_total",
"Total outbound request retries",
["service", "endpoint"],
)
if Counter
else None
)
circuit_state_metric = (
Gauge(
"circuit_state",
"Circuit breaker state (0=closed,1=half_open,2=open)",
["service", "endpoint"],
)
if Gauge
else None
)
circuit_success_rate_metric = (
Gauge(
"circuit_success_rate",
"Recent success rate for outbound requests (0-1)",
["service", "endpoint"],
)
if Gauge
else None
)
# --- Stage 6: unified handler/command/db metrics ---
codebot_handler_requests_total = (
Counter(
"codebot_handler_requests_total",
"Total web handler invocations",
["handler", "status", "cache_hit"],
)
if Counter
else None
)
codebot_handler_latency_seconds = (
Histogram(
"codebot_handler_latency_seconds",
"Web handler latency in seconds",
["handler", "status", "cache_hit"],
)
if Histogram
else None
)
codebot_command_requests_total = (
Counter(
"codebot_command_requests_total",
"Total Telegram command executions",
["command", "status", "cache_hit"],
)
if Counter
else None
)
codebot_command_latency_seconds = (
Histogram(
"codebot_command_latency_seconds",
"Telegram command latency in seconds",
["command", "status", "cache_hit"],
)
if Histogram
else None
)
codebot_db_requests_total = (
Counter(
"codebot_db_requests_total",
"Total database operations",
["operation", "status"],
)
if Counter
else None
)
codebot_db_latency_seconds = (
Histogram(
"codebot_db_latency_seconds",
"Database operation latency in seconds",
["operation", "status"],
)
if Histogram
else None
)
# --- Startup / cold-start metrics ---
# Capture process boot monotonic timestamp as early as metrics import occurs.
_BOOT_T0_MONOTONIC: float = _time.perf_counter()
app_startup_seconds = (
Gauge(
"app_startup_seconds",
"Application startup duration (seconds) from process boot to ready",
)
if Gauge
else None
)
first_request_latency_seconds = (
Gauge(
"first_request_latency_seconds",
"Latency (seconds) from process boot to first completed HTTP request",
)
if Gauge
else None
)
startup_completed = (
Gauge(
"startup_completed",
"1 if application finished startup/preload, else 0",
)
if Gauge
else None
)
# Dependency initialization timing (e.g., mongodb, redis, templates)
dependency_init_seconds = (
Histogram(
"dependency_init_seconds",
"Initialization time for external/internal dependencies",
["dependency"],
)
if Histogram
else None
)
# In-memory assistance structures (fail-open, best-effort)
_ACTIVE_USERS: set[int] = set()
_ACTIVE_REQUESTS: int = 0
_ACTIVE_REQUESTS_LOCK = threading.Lock()
_EWMA_ALPHA: float = float(os.getenv("METRICS_EWMA_ALPHA", "0.2"))
_EWMA_RT: float | None = None
_HTTP_SAMPLE_BUFFER = int(os.getenv("HTTP_SAMPLE_BUFFER", "2000"))
_HTTP_REQUEST_SAMPLES: deque[Tuple[float, str, str, float, int]] = deque(maxlen=max(100, _HTTP_SAMPLE_BUFFER))
_HTTP_SAMPLES_LOCK = threading.Lock()
_HTTP_SAMPLE_RETENTION_SECONDS: int = int(os.getenv("HTTP_SAMPLE_RETENTION_SECONDS", "600"))
_ERROR_HISTORY_SECONDS: int = max(60, int(os.getenv("ERROR_HISTORY_SECONDS", "600")))
_ERROR_HISTORY_MAX_SAMPLES: int = int(os.getenv("ERROR_HISTORY_MAX_SAMPLES", "2000"))
_ERR_TIMESTAMPS: deque[float] = deque(maxlen=max(200, _ERROR_HISTORY_MAX_SAMPLES))
_ERR_TIMESTAMPS_LOCK = threading.Lock()
_ANOMALY_COOLDOWN_SEC: int = int(os.getenv("ALERT_COOLDOWN_SECONDS", "300"))
_ANOMALY_LAST_TS: float = 0.0
_ERRS_PER_MIN_THRESHOLD: int = int(os.getenv("ALERT_ERRORS_PER_MINUTE", "20"))
_AVG_RT_THRESHOLD: float = float(os.getenv("ALERT_AVG_RESPONSE_TIME", "3.0"))
_DEPLOY_AVG_RT_THRESHOLD: float = float(os.getenv("ALERT_AVG_RESPONSE_TIME_DEPLOY", "10.0"))
_DEPLOY_GRACE_PERIOD_SECONDS: int = int(os.getenv("DEPLOY_GRACE_PERIOD_SECONDS", "120"))
_LAST_DEPLOYMENT_TS: float | None = None
# Endpoints to exclude from EWMA + slow-endpoint sampling (but still record Prometheus metrics).
# IMPORTANT: do not import `config.py` here (it has required settings and can break docs/tests).
_ANOMALY_IGNORE_ENDPOINTS_ENV: str = "ANOMALY_IGNORE_ENDPOINTS"
_ANOMALY_IGNORE_ENDPOINTS_RAW: str | None = None
_ANOMALY_IGNORE_ENDPOINTS_SET: set[str] = set()
_ANOMALY_IGNORE_ENDPOINTS_LOCK = threading.Lock()
def _normalize_anomaly_ignore_token(value: Any) -> str:
"""Normalize a configured ignore token (path or endpoint name)."""
try:
s = str(value or "").strip()
except Exception:
return ""
if not s:
return ""
# Allow full URL values by extracting the path part
if "://" in s:
try:
parsed = urlparse(s)
if parsed and parsed.path:
s = parsed.path
except Exception:
pass
# Drop query/hash to match request.path semantics
try:
s = s.split("?", 1)[0].split("#", 1)[0].strip()
except Exception:
pass
if not s:
return ""
# Normalize trailing slash for paths (keep "/" as-is)
if s.startswith("/") and len(s) > 1:
s = s.rstrip("/")
return s
def _parse_anomaly_ignore_endpoints(raw: str | None) -> set[str]:
try:
text = str(raw or "").strip()
except Exception:
text = ""
if not text:
return set()
tokens: list[Any]
if text.startswith("["):
try:
parsed = json.loads(text)
if isinstance(parsed, list):
tokens = list(parsed)
else:
tokens = [parsed]
except Exception:
tokens = [p.strip() for p in text.split(",")]
else:
tokens = [p.strip() for p in text.split(",")]
out: set[str] = set()
for token in tokens:
normalized = _normalize_anomaly_ignore_token(token)
if normalized:
out.add(normalized)
return out
def _get_anomaly_ignore_endpoints() -> set[str]:
"""Return the current ignore set, reloading if env changed (thread-safe)."""
global _ANOMALY_IGNORE_ENDPOINTS_RAW, _ANOMALY_IGNORE_ENDPOINTS_SET
raw = os.getenv(_ANOMALY_IGNORE_ENDPOINTS_ENV, "") or ""
if _ANOMALY_IGNORE_ENDPOINTS_RAW is not None and raw == _ANOMALY_IGNORE_ENDPOINTS_RAW:
return _ANOMALY_IGNORE_ENDPOINTS_SET
with _ANOMALY_IGNORE_ENDPOINTS_LOCK:
raw2 = os.getenv(_ANOMALY_IGNORE_ENDPOINTS_ENV, "") or ""
if _ANOMALY_IGNORE_ENDPOINTS_RAW is not None and raw2 == _ANOMALY_IGNORE_ENDPOINTS_RAW:
return _ANOMALY_IGNORE_ENDPOINTS_SET
_ANOMALY_IGNORE_ENDPOINTS_RAW = raw2
_ANOMALY_IGNORE_ENDPOINTS_SET = _parse_anomaly_ignore_endpoints(raw2)
return _ANOMALY_IGNORE_ENDPOINTS_SET
def _is_anomaly_ignored(*, path: str | None = None, endpoint: str | None = None) -> bool:
"""True if the request should be ignored for EWMA/slow-endpoint sampling."""
ignore_set = _get_anomaly_ignore_endpoints()
if not ignore_set:
return False
for candidate in (path, endpoint):
normalized = _normalize_anomaly_ignore_token(candidate)
if normalized and normalized in ignore_set:
return True
return False
@contextmanager
def track_performance(operation: str, labels: Optional[Dict[str, str]] = None):
start = time.time()
try:
yield
finally:
if operation_latency_seconds is not None:
try:
# בחר רק לייבלים שמוגדרים במטריקה ואל תאפשר דריסה של 'operation'
allowed = set(getattr(operation_latency_seconds, "_labelnames", []) or [])
target = {"operation": operation}
if labels:
for k, v in labels.items():
if k in allowed and k != "operation":
target[k] = v
# ספק ערכי ברירת מחדל לכל לייבל חסר (למשל repo="") כדי לשמור תאימות לאחור
for name in allowed:
if name not in target:
if name == "operation":
# כבר סופק לעיל
continue
# ברירת מחדל: מיתר סמנטיקה, מונע ValueError על חוסר בלייבל
target[name] = ""
operation_latency_seconds.labels(**target).observe(time.time() - start)
except Exception:
# avoid breaking app on label mistakes
pass
def metrics_endpoint_bytes() -> bytes:
return generate_latest()
def metrics_content_type() -> str:
return CONTENT_TYPE_LATEST
# --- Unified helpers for services instrumentation ---
def note_active_user(user_id: int) -> None:
"""Record that a specific user was active recently, and update the gauge.
This uses a simple in-memory set per-process. It is a best-effort indicator and
does not attempt cross-process aggregation. Good enough for basic dashboards/tests.
"""
try:
_ACTIVE_USERS.add(int(user_id))
if codebot_active_users_total is not None:
codebot_active_users_total.set(len(_ACTIVE_USERS))
except Exception:
return
def _update_active_requests_gauge(value: int) -> None:
try:
if codebot_active_requests_total is not None:
codebot_active_requests_total.set(max(0.0, float(value)))
except Exception:
pass
def note_request_started() -> None:
"""Increment the in-flight requests gauge (best-effort)."""
global _ACTIVE_REQUESTS
try:
with _ACTIVE_REQUESTS_LOCK:
_ACTIVE_REQUESTS += 1
current = _ACTIVE_REQUESTS
_update_active_requests_gauge(current)
except Exception:
return
def note_request_finished() -> None:
"""Decrement the in-flight requests gauge (never negative)."""
global _ACTIVE_REQUESTS
try:
with _ACTIVE_REQUESTS_LOCK:
_ACTIVE_REQUESTS = max(0, _ACTIVE_REQUESTS - 1)
current = _ACTIVE_REQUESTS
_update_active_requests_gauge(current)
except Exception:
return
def get_active_requests_count() -> int:
"""Return the current in-flight request count (best-effort)."""
try:
with _ACTIVE_REQUESTS_LOCK:
return max(0, int(_ACTIVE_REQUESTS))
except Exception:
return 0
def get_current_memory_usage() -> float:
"""Return current process RSS in MB (best-effort)."""
try:
import psutil # type: ignore
process = psutil.Process()
return float(process.memory_info().rss) / 1024.0 / 1024.0
except Exception:
return 0.0
def _record_error_timestamp(ts: float | None = None) -> None:
"""Record an error timestamp with retention and max sample cap."""
try:
value = float(ts if ts is not None else _time.time())
except Exception:
value = _time.time()
cutoff = value - float(_ERROR_HISTORY_SECONDS)
try:
with _ERR_TIMESTAMPS_LOCK:
_ERR_TIMESTAMPS.append(value)
while _ERR_TIMESTAMPS and _ERR_TIMESTAMPS[0] < cutoff:
_ERR_TIMESTAMPS.popleft()
except Exception:
return
def get_recent_errors_count(minutes: int = 5) -> int:
"""Return the number of 5xx errors recorded in the last X minutes."""
if minutes is None:
minutes = 5
try:
window = max(0, int(minutes)) * 60
if window <= 0:
return 0
cutoff = _time.time() - float(window)
except Exception:
return 0
try:
with _ERR_TIMESTAMPS_LOCK:
return sum(1 for ts in _ERR_TIMESTAMPS if ts >= cutoff)
except Exception:
return 0
def _note_http_request_sample(
method: str,
endpoint: str,
status_code: int,
duration_seconds: float,
*,
ts: float | None = None,
) -> None:
"""Store a lightweight sample for slow-endpoint summaries (best-effort)."""
try:
timestamp = float(ts if ts is not None else _time.time())
sample = (
timestamp,
(method or "").upper() or "GET",
endpoint or "unknown",
max(0.0, float(duration_seconds)),
int(status_code),
)
except Exception:
return
cutoff = timestamp - float(max(60, _HTTP_SAMPLE_RETENTION_SECONDS))
try:
with _HTTP_SAMPLES_LOCK:
_HTTP_REQUEST_SAMPLES.append(sample)
while _HTTP_REQUEST_SAMPLES and _HTTP_REQUEST_SAMPLES[0][0] < cutoff:
_HTTP_REQUEST_SAMPLES.popleft()
except Exception:
return
def _recent_http_samples(window_seconds: Optional[int] = None) -> List[Tuple[float, str, str, float, int]]:
try:
with _HTTP_SAMPLES_LOCK:
samples = list(_HTTP_REQUEST_SAMPLES)
except Exception:
return []
if not samples:
return []
try:
window = int(window_seconds) if window_seconds is not None else _HTTP_SAMPLE_RETENTION_SECONDS
cutoff = _time.time() - float(max(1, window))
except Exception:
cutoff = _time.time() - float(_HTTP_SAMPLE_RETENTION_SECONDS)
return [sample for sample in samples if sample[0] >= cutoff]
def get_top_slow_endpoints(limit: int = 5, window_seconds: Optional[int] = None) -> List[Dict[str, Any]]:
"""Return the slowest endpoints observed recently (best-effort)."""
try:
max_items = max(0, int(limit))
except Exception:
max_items = 5
if max_items <= 0:
return []
samples = _recent_http_samples(window_seconds)
stats: Dict[Tuple[str, str], Dict[str, float]] = {}
for _ts, method, endpoint, duration, _status in samples:
key = (method or "GET", endpoint or "unknown")
data = stats.setdefault(key, {"count": 0.0, "sum": 0.0, "max": 0.0})
data["count"] += 1.0
data["sum"] += float(duration)
data["max"] = max(data["max"], float(duration))
results: List[Dict[str, Any]] = []
for (method, endpoint), data in stats.items():
count = max(1.0, data["count"])
avg = data["sum"] / count
results.append(
{
"method": method,
"endpoint": endpoint,
"count": int(count),
"avg_duration": float(avg),
"max_duration": float(data["max"]),
}
)
results.sort(key=lambda item: item.get("max_duration", 0.0), reverse=True)
return results[:max_items]
def get_slowest_endpoint() -> str:
"""Return a formatted string describing the slowest endpoint recently seen."""
top = get_top_slow_endpoints(limit=1)
if not top:
return "unknown"
entry = top[0]
try:
method = str(entry.get("method", "GET"))
endpoint = str(entry.get("endpoint", "unknown"))
max_dur = float(entry.get("max_duration", 0.0))
return f"{method} {endpoint} ({max_dur:.3f}s)"
except Exception:
return "unknown"
def _emit_deployment_alert(summary: str, *, name: str) -> None:
try:
from internal_alerts import emit_internal_alert # type: ignore
emit_internal_alert(name=name, severity="info", summary=str(summary))
except Exception:
try:
emit_event(name, severity="info", summary=str(summary))
except Exception:
pass
def note_deployment_started(summary: str = "Service starting up") -> None:
"""Mark the start of a deployment and emit an informational alert."""
global _LAST_DEPLOYMENT_TS
try:
_LAST_DEPLOYMENT_TS = _time.time()
except Exception:
_LAST_DEPLOYMENT_TS = None
_emit_deployment_alert(summary, name="deployment_event")
def note_deployment_shutdown(summary: str = "Service shutting down") -> None:
"""Emit a shutdown deployment event (does not reset latency grace period)."""
_emit_deployment_alert(summary, name="deployment_event")
def _current_latency_threshold(now_ts: float) -> float:
"""Return the dynamic latency threshold depending on deploy grace period."""
try:
if (
_DEPLOY_GRACE_PERIOD_SECONDS > 0
and _LAST_DEPLOYMENT_TS is not None
and (now_ts - float(_LAST_DEPLOYMENT_TS)) < float(_DEPLOY_GRACE_PERIOD_SECONDS)
and _DEPLOY_AVG_RT_THRESHOLD > 0
):
return float(_DEPLOY_AVG_RT_THRESHOLD)
except Exception:
pass
return float(_AVG_RT_THRESHOLD)
def _update_ewma(duration_seconds: float) -> float:
global _EWMA_RT
try:
if _EWMA_RT is None:
_EWMA_RT = float(duration_seconds)
else:
_EWMA_RT = (_EWMA_ALPHA * float(duration_seconds)) + ((1.0 - _EWMA_ALPHA) * _EWMA_RT)
if codebot_avg_response_time_seconds is not None:
codebot_avg_response_time_seconds.set(max(0.0, float(_EWMA_RT)))
return float(_EWMA_RT)
except Exception:
return float(duration_seconds)
def get_avg_response_time_seconds() -> float:
"""Return the smoothed average HTTP response time (seconds)."""
try:
return max(0.0, float(_EWMA_RT or 0.0))
except Exception:
return 0.0
def _should_update_latency_ewma(*, status_code: int, status_label: str | None = None) -> bool:
"""Decide whether a request should affect EWMA latency.
We intentionally exclude failures/timeouts so EWMA represents *served* latency
and doesn't get skewed by gateway/worker timeouts or internal errors.
"""
try:
sc = int(status_code)
except Exception:
sc = 0
# Unknown/invalid status: don't touch EWMA.
if sc <= 0:
return False
# Failures (5xx) often include timeouts/retries and would distort "avg served latency".
if sc >= 500:
return False
try:
label = str(status_label or "").strip().lower()
except Exception:
label = ""
if label:
# Defensive: if callers pass a custom label that indicates timeout/failure, exclude.
if "timeout" in label or label in {"worker_timeout", "gateway_timeout"}:
return False
return True
def _status_label_from_code(status_code: int | None, override: str | None = None) -> str:
try:
if override:
return _normalize_metric_label(str(override), "unknown_status")
except Exception:
pass
try:
if status_code is None:
return "unknown"
bucket = int(status_code) // 100
if bucket == 0:
return _normalize_metric_label(str(status_code), "unknown")
return f"{bucket}xx"
except Exception:
return "unknown"
def _cache_hit_label(cache_hit: bool | str | None) -> str:
try:
if isinstance(cache_hit, str):
value = cache_hit.strip().lower()
if value in {"hit", "miss", "warm", "cold", "partial", "unknown"}:
return value
if value in {"true", "yes", "1"}:
return "hit"
if value in {"false", "no", "0"}:
return "miss"
return "unknown"
if cache_hit is True:
return "hit"
if cache_hit is False:
return "miss"
except Exception:
return "unknown"
return "unknown"
def _attach_source(name: str | None, source: str | None, *, default: str) -> str:
base = _normalize_metric_label(name, default)
try:
src = (source or "").strip()
if not src:
return base
prefixed = f"{src}:{base}"
return _normalize_metric_label(prefixed, default)
except Exception:
return base
def _load_external_service_keywords() -> set[str]:
defaults = {
"uptime",
"uptimerobot",
"uptime_robot",
"betteruptime",
"statuscake",
"pingdom",
"external_monitor",
"github api",
"github_api",
}
extra = os.getenv("ALERT_EXTERNAL_SERVICES", "")
extra_tokens = {token.strip().lower() for token in str(extra or "").split(",") if token.strip()}
return {token for token in defaults.union(extra_tokens) if token}
_EXTERNAL_SERVICE_KEYWORDS = _load_external_service_keywords()
def _matches_external_service_keyword(value: Optional[str]) -> bool:
try:
text = str(value or "").strip().lower()
except Exception:
text = ""
if not text:
return False
for keyword in _EXTERNAL_SERVICE_KEYWORDS:
if keyword in text:
return True
return False
def _classify_request_source(