debug-agent-py 0.4.0__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/PKG-INFO +1 -1
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/pyproject.toml +1 -1
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/__init__.py +5 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/error_tracking.py +205 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/health_inspector.py +124 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/scheduler_inspector.py +227 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/security_inspector.py +251 -0
- debug_agent_py-0.5.0/src/debug_agent/inspectors/websocket_inspector.py +225 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/PKG-INFO +1 -1
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/SOURCES.txt +5 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/README.md +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/setup.cfg +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/__init__.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/chat_session.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/config.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/context_compressor.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/engine.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/async_tasks.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/cache_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/celery.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/database.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/django.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/fastapi_ext.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/fd_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/flask_ext.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/framework.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/http_client_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/http_tracker.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/jinja2.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/logging_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/memory.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/metrics_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/modules.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/redis.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/runtime.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/signals.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/system.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/threads.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/warnings_inspector.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/llm_client.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/middleware.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/system_prompt_builder.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/tool_registry.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/web/__init__.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/web/chat_page.py +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/dependency_links.txt +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/requires.txt +0 -0
- {debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/top_level.txt +0 -0
|
@@ -6,10 +6,12 @@ from debug_agent.inspectors import ( # noqa: F401
|
|
|
6
6
|
celery,
|
|
7
7
|
database,
|
|
8
8
|
django,
|
|
9
|
+
error_tracking,
|
|
9
10
|
fastapi_ext,
|
|
10
11
|
fd_inspector,
|
|
11
12
|
flask_ext,
|
|
12
13
|
framework,
|
|
14
|
+
health_inspector,
|
|
13
15
|
http_client_inspector,
|
|
14
16
|
http_tracker,
|
|
15
17
|
jinja2,
|
|
@@ -19,8 +21,11 @@ from debug_agent.inspectors import ( # noqa: F401
|
|
|
19
21
|
modules,
|
|
20
22
|
redis,
|
|
21
23
|
runtime,
|
|
24
|
+
scheduler_inspector,
|
|
25
|
+
security_inspector,
|
|
22
26
|
signals,
|
|
23
27
|
system,
|
|
24
28
|
threads,
|
|
25
29
|
warnings_inspector,
|
|
30
|
+
websocket_inspector,
|
|
26
31
|
)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Error tracking inspector: capture and analyse unhandled exceptions.
|
|
2
|
+
|
|
3
|
+
Installs a global ``sys.excepthook`` and provides helpers to hook into
|
|
4
|
+
Flask / WSGI for request-scoped errors. A ring buffer (max 50) keeps the
|
|
5
|
+
most recent exceptions for inspection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import traceback as tb_mod
|
|
15
|
+
from collections import Counter, deque
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# ─── Ring buffer & state ──────────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
_MAX_BUFFER = 50
|
|
25
|
+
_error_buffer: deque = deque(maxlen=_MAX_BUFFER)
|
|
26
|
+
_buffer_lock = threading.Lock()
|
|
27
|
+
_original_excepthook = sys.excepthook
|
|
28
|
+
_installed = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ─── Capture helpers ──────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def capture_error(
|
|
35
|
+
exc_type: type,
|
|
36
|
+
value: BaseException,
|
|
37
|
+
tb: Any,
|
|
38
|
+
request_path: str | None = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Append an exception to the ring buffer."""
|
|
41
|
+
entry = {
|
|
42
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
43
|
+
"epoch": time.time(),
|
|
44
|
+
"type": exc_type.__name__ if exc_type else "Unknown",
|
|
45
|
+
"message": str(value),
|
|
46
|
+
"traceback": "".join(tb_mod.format_exception(exc_type, value, tb)),
|
|
47
|
+
"request_path": request_path,
|
|
48
|
+
}
|
|
49
|
+
with _buffer_lock:
|
|
50
|
+
_error_buffer.append(entry)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _excepthook(exc_type, value, tb): # noqa: A002 (tb shadows stdlib name)
|
|
54
|
+
"""Replacement sys.excepthook that records the exception before delegating."""
|
|
55
|
+
capture_error(exc_type, value, tb)
|
|
56
|
+
_original_excepthook(exc_type, value, tb)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def install_error_hooks() -> None:
|
|
60
|
+
"""Install the global ``sys.excepthook`` override (idempotent)."""
|
|
61
|
+
global _installed
|
|
62
|
+
if _installed:
|
|
63
|
+
return
|
|
64
|
+
sys.excepthook = _excepthook
|
|
65
|
+
_installed = True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def install_flask_error_handler(app: Any) -> None:
|
|
69
|
+
"""Register a catch-all Flask error handler that records exceptions."""
|
|
70
|
+
try:
|
|
71
|
+
from flask import request, jsonify # type: ignore
|
|
72
|
+
except ImportError:
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
@app.errorhandler(Exception)
|
|
76
|
+
def _capture_flask_error(e): # noqa: ANN202
|
|
77
|
+
capture_error(
|
|
78
|
+
type(e), e, e.__traceback__,
|
|
79
|
+
request_path=request.path if request else None,
|
|
80
|
+
)
|
|
81
|
+
# Re-raise so existing handlers / Flask defaults still apply
|
|
82
|
+
try:
|
|
83
|
+
return app.handle_exception(e)
|
|
84
|
+
except Exception:
|
|
85
|
+
return jsonify({"error": type(e).__name__, "message": str(e)}), 500
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def install_wsgi_middleware(app: Any) -> Any:
|
|
89
|
+
"""Wrap a WSGI app so unhandled exceptions are captured."""
|
|
90
|
+
|
|
91
|
+
def middleware(environ, start_response):
|
|
92
|
+
try:
|
|
93
|
+
return app(environ, start_response)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
capture_error(
|
|
96
|
+
type(exc), exc, exc.__traceback__,
|
|
97
|
+
request_path=environ.get("PATH_INFO"),
|
|
98
|
+
)
|
|
99
|
+
raise
|
|
100
|
+
|
|
101
|
+
return middleware
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Auto-install the global excepthook on import
|
|
105
|
+
install_error_hooks()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _get_all() -> list[dict]:
|
|
112
|
+
with _buffer_lock:
|
|
113
|
+
return list(_error_buffer)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@debug_tool(
|
|
117
|
+
"get_recent_errors",
|
|
118
|
+
"Get recent unhandled exceptions from the in-memory ring buffer (max 50)",
|
|
119
|
+
)
|
|
120
|
+
def get_recent_errors(
|
|
121
|
+
limit: int = ToolParam("Max results to return", required=False),
|
|
122
|
+
) -> dict:
|
|
123
|
+
errors = _get_all()
|
|
124
|
+
if limit:
|
|
125
|
+
errors = errors[-limit:]
|
|
126
|
+
return {
|
|
127
|
+
"total_captured": len(_error_buffer),
|
|
128
|
+
"buffer_max": _MAX_BUFFER,
|
|
129
|
+
"errors": list(reversed(errors)),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@debug_tool(
|
|
134
|
+
"get_error_stats",
|
|
135
|
+
"Get error statistics: total, rate per minute, top error types",
|
|
136
|
+
)
|
|
137
|
+
def get_error_stats() -> dict:
|
|
138
|
+
errors = _get_all()
|
|
139
|
+
if not errors:
|
|
140
|
+
return {"total": 0, "message": "No errors captured yet"}
|
|
141
|
+
|
|
142
|
+
now = time.time()
|
|
143
|
+
oldest = min(e["epoch"] for e in errors)
|
|
144
|
+
elapsed_minutes = max((now - oldest) / 60, 1 / 60) # avoid div-by-zero
|
|
145
|
+
|
|
146
|
+
type_counts = Counter(e["type"] for e in errors)
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
"total": len(errors),
|
|
150
|
+
"buffer_max": _MAX_BUFFER,
|
|
151
|
+
"rate_per_minute": round(len(errors) / elapsed_minutes, 2),
|
|
152
|
+
"time_window_minutes": round(elapsed_minutes, 1),
|
|
153
|
+
"top_error_types": type_counts.most_common(10),
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@debug_tool(
|
|
158
|
+
"get_error_patterns",
|
|
159
|
+
"Group similar errors by exception type and message pattern",
|
|
160
|
+
)
|
|
161
|
+
def get_error_patterns() -> dict:
|
|
162
|
+
errors = _get_all()
|
|
163
|
+
if not errors:
|
|
164
|
+
return {"patterns": [], "message": "No errors captured yet"}
|
|
165
|
+
|
|
166
|
+
def _normalise_message(msg: str) -> str:
|
|
167
|
+
"""Collapse variable parts of an error message for grouping."""
|
|
168
|
+
import re
|
|
169
|
+
# Replace IDs, numbers, hex, file paths, and quoted strings
|
|
170
|
+
msg = re.sub(r"\b[0-9a-f]{8,}\b", "<hex>", msg, flags=re.IGNORECASE)
|
|
171
|
+
msg = re.sub(r"\b\d+\b", "<N>", msg)
|
|
172
|
+
msg = re.sub(r"/[/^\s]+", "<path>", msg)
|
|
173
|
+
msg = re.sub(r"'[^']*'", "'<str>'", msg)
|
|
174
|
+
msg = re.sub(r'"[^"]*"', '"<str>"', msg)
|
|
175
|
+
return msg[:200]
|
|
176
|
+
|
|
177
|
+
groups: dict[str, dict[str, Any]] = {}
|
|
178
|
+
for err in errors:
|
|
179
|
+
pattern_key = f"{err['type']}: {_normalise_message(err['message'])}"
|
|
180
|
+
if pattern_key not in groups:
|
|
181
|
+
groups[pattern_key] = {
|
|
182
|
+
"pattern": pattern_key,
|
|
183
|
+
"count": 0,
|
|
184
|
+
"type": err["type"],
|
|
185
|
+
"example_message": err["message"],
|
|
186
|
+
"first_seen": err["timestamp"],
|
|
187
|
+
"last_seen": err["timestamp"],
|
|
188
|
+
"request_paths": set(),
|
|
189
|
+
}
|
|
190
|
+
g = groups[pattern_key]
|
|
191
|
+
g["count"] += 1
|
|
192
|
+
g["last_seen"] = err["timestamp"]
|
|
193
|
+
if err.get("request_path"):
|
|
194
|
+
g["request_paths"].add(err["request_path"])
|
|
195
|
+
|
|
196
|
+
# Sort by count desc and convert sets to lists
|
|
197
|
+
sorted_groups = sorted(groups.values(), key=lambda x: -x["count"])
|
|
198
|
+
for g in sorted_groups:
|
|
199
|
+
g["request_paths"] = sorted(g["request_paths"])
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
"pattern_count": len(sorted_groups),
|
|
203
|
+
"total_errors": len(errors),
|
|
204
|
+
"patterns": sorted_groups,
|
|
205
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Health inspector: pluggable health checks with UP / DOWN / DEGRADED status.
|
|
2
|
+
|
|
3
|
+
Register health checks via decorator:
|
|
4
|
+
|
|
5
|
+
from debug_agent.inspectors.health_inspector import register_health_check
|
|
6
|
+
|
|
7
|
+
@register_health_check("database")
|
|
8
|
+
def check_database():
|
|
9
|
+
# ... run check ...
|
|
10
|
+
return {"status": "UP", "details": {"latency_ms": 2.1}}
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import time
|
|
16
|
+
from typing import Any, Callable
|
|
17
|
+
|
|
18
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ─── Registration ─────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
_health_checks: dict[str, Callable[..., Any]] = {}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def register_health_check(name: str):
|
|
27
|
+
"""Decorator: register *fn* as a health check under *name*."""
|
|
28
|
+
|
|
29
|
+
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
30
|
+
_health_checks[name] = fn
|
|
31
|
+
return fn
|
|
32
|
+
|
|
33
|
+
return decorator
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
_VALID_STATUSES = {"UP", "DOWN", "DEGRADED"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _run_check(name: str, fn: Callable[..., Any]) -> dict:
|
|
43
|
+
start = time.time()
|
|
44
|
+
try:
|
|
45
|
+
result = fn()
|
|
46
|
+
elapsed_ms = round((time.time() - start) * 1000, 2)
|
|
47
|
+
|
|
48
|
+
if isinstance(result, dict):
|
|
49
|
+
status = str(result.get("status", "UP")).upper()
|
|
50
|
+
if status not in _VALID_STATUSES:
|
|
51
|
+
status = "UP"
|
|
52
|
+
return {
|
|
53
|
+
"name": name,
|
|
54
|
+
"status": status,
|
|
55
|
+
"latency_ms": elapsed_ms,
|
|
56
|
+
"details": result.get("details", {k: v for k, v in result.items() if k != "status"}),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# Non-dict truthy / falsy results
|
|
60
|
+
if result in _VALID_STATUSES:
|
|
61
|
+
status = result
|
|
62
|
+
elif result:
|
|
63
|
+
status = "UP"
|
|
64
|
+
else:
|
|
65
|
+
status = "DOWN"
|
|
66
|
+
return {"name": name, "status": status, "latency_ms": elapsed_ms}
|
|
67
|
+
|
|
68
|
+
except Exception as exc:
|
|
69
|
+
elapsed_ms = round((time.time() - start) * 1000, 2)
|
|
70
|
+
return {
|
|
71
|
+
"name": name,
|
|
72
|
+
"status": "DOWN",
|
|
73
|
+
"latency_ms": elapsed_ms,
|
|
74
|
+
"error": f"{type(exc).__name__}: {exc}",
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@debug_tool(
|
|
82
|
+
"get_health_status",
|
|
83
|
+
"Run all registered health checks and return UP/DOWN/DEGRADED per component",
|
|
84
|
+
)
|
|
85
|
+
def get_health_status() -> dict:
|
|
86
|
+
if not _health_checks:
|
|
87
|
+
return {
|
|
88
|
+
"components": [],
|
|
89
|
+
"overall": "UNKNOWN",
|
|
90
|
+
"message": "No health checks registered. Use @register_health_check(name).",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
results = [_run_check(name, fn) for name, fn in _health_checks.items()]
|
|
94
|
+
|
|
95
|
+
statuses = [r["status"] for r in results]
|
|
96
|
+
if all(s == "UP" for s in statuses):
|
|
97
|
+
overall = "UP"
|
|
98
|
+
elif any(s == "DOWN" for s in statuses):
|
|
99
|
+
overall = "DOWN"
|
|
100
|
+
else:
|
|
101
|
+
overall = "DEGRADED"
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
"overall": overall,
|
|
105
|
+
"components_checked": len(results),
|
|
106
|
+
"components": results,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@debug_tool(
|
|
111
|
+
"get_health_detail",
|
|
112
|
+
"Deep-dive into a specific health check component",
|
|
113
|
+
)
|
|
114
|
+
def get_health_detail(
|
|
115
|
+
component_name: str = ToolParam("Name of the health check component to inspect"),
|
|
116
|
+
) -> dict:
|
|
117
|
+
fn = _health_checks.get(component_name)
|
|
118
|
+
if fn is None:
|
|
119
|
+
return {
|
|
120
|
+
"error": f"No health check registered for '{component_name}'",
|
|
121
|
+
"available": list(_health_checks.keys()),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return _run_check(component_name, fn)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Scheduler inspector: scheduled jobs from APScheduler, Celery beat, or custom.
|
|
2
|
+
|
|
3
|
+
Register custom scheduled jobs at runtime:
|
|
4
|
+
|
|
5
|
+
from debug_agent.inspectors.scheduler_inspector import register_scheduled_job
|
|
6
|
+
register_scheduled_job("cleanup", "every 30s")
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ─── Registration ─────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
_scheduled_jobs: dict[str, dict[str, Any]] = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_scheduled_job(name: str, schedule: str, job_fn=None) -> None:
|
|
23
|
+
"""Register a scheduled job for introspection.
|
|
24
|
+
|
|
25
|
+
*schedule* is a human-readable string (e.g. ``"every 30s"``, ``"*/5 * * * *"``).
|
|
26
|
+
*job_fn* is optional — pass the actual callable for richer introspection.
|
|
27
|
+
"""
|
|
28
|
+
_scheduled_jobs[name] = {
|
|
29
|
+
"schedule": schedule,
|
|
30
|
+
"next_run": None,
|
|
31
|
+
"last_run": None,
|
|
32
|
+
"last_status": None,
|
|
33
|
+
"history": [],
|
|
34
|
+
"job_fn": job_fn,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def record_job_run(name: str, status: str, details: Any = None) -> None:
|
|
39
|
+
"""Record an execution for a registered job (call from the scheduler loop)."""
|
|
40
|
+
job = _scheduled_jobs.get(name)
|
|
41
|
+
if job is None:
|
|
42
|
+
return
|
|
43
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
44
|
+
job["last_run"] = now
|
|
45
|
+
job["last_status"] = status
|
|
46
|
+
job["history"].append({"timestamp": now, "status": status, "details": details})
|
|
47
|
+
# Cap history to last 100 runs
|
|
48
|
+
if len(job["history"]) > 100:
|
|
49
|
+
job["history"] = job["history"][-100:]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def set_next_run(name: str, next_run: str | None) -> None:
|
|
53
|
+
"""Update the *next_run* timestamp for a registered job."""
|
|
54
|
+
job = _scheduled_jobs.get(name)
|
|
55
|
+
if job is not None:
|
|
56
|
+
job["next_run"] = next_run
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ─── Framework auto-detection ─────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _detect_apscheduler() -> list[dict] | None:
|
|
63
|
+
try:
|
|
64
|
+
from apscheduler.schedulers.base import BaseScheduler # type: ignore
|
|
65
|
+
|
|
66
|
+
results: list[dict] = []
|
|
67
|
+
for scheduler in _find_instances(BaseScheduler):
|
|
68
|
+
for job in scheduler.get_jobs(): # type: ignore[attr-defined]
|
|
69
|
+
results.append({
|
|
70
|
+
"name": str(job.id),
|
|
71
|
+
"schedule": str(job.trigger),
|
|
72
|
+
"next_run": job.next_run_time.isoformat() if job.next_run_time else None,
|
|
73
|
+
"func": str(job.func),
|
|
74
|
+
"source": "APScheduler",
|
|
75
|
+
})
|
|
76
|
+
return results if results else None
|
|
77
|
+
except Exception:
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _detect_celery_beat() -> list[dict] | None:
|
|
82
|
+
try:
|
|
83
|
+
from celery import Celery # type: ignore
|
|
84
|
+
|
|
85
|
+
results: list[dict] = []
|
|
86
|
+
for app in _find_instances(Celery):
|
|
87
|
+
beat = getattr(app.conf, "beat_schedule", None)
|
|
88
|
+
if not beat:
|
|
89
|
+
continue
|
|
90
|
+
for task_name, entry in beat.items():
|
|
91
|
+
results.append({
|
|
92
|
+
"name": task_name,
|
|
93
|
+
"schedule": str(entry.get("schedule", "")),
|
|
94
|
+
"task": entry.get("task", ""),
|
|
95
|
+
"source": "Celery Beat",
|
|
96
|
+
})
|
|
97
|
+
return results if results else None
|
|
98
|
+
except Exception:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _find_instances(base_cls: type) -> list:
|
|
103
|
+
"""Scan gc objects for live instances of *base_cls* (best-effort)."""
|
|
104
|
+
try:
|
|
105
|
+
import gc
|
|
106
|
+
return [obj for obj in gc.get_objects() if isinstance(obj, base_cls)]
|
|
107
|
+
except Exception:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@debug_tool(
|
|
115
|
+
"get_scheduled_jobs",
|
|
116
|
+
"List scheduled jobs from APScheduler, Celery beat, or custom registrations",
|
|
117
|
+
)
|
|
118
|
+
def get_scheduled_jobs() -> dict:
|
|
119
|
+
jobs: list[dict] = []
|
|
120
|
+
|
|
121
|
+
# Registered custom jobs
|
|
122
|
+
for name, job in _scheduled_jobs.items():
|
|
123
|
+
jobs.append({
|
|
124
|
+
"name": name,
|
|
125
|
+
"schedule": job.get("schedule"),
|
|
126
|
+
"next_run": job.get("next_run"),
|
|
127
|
+
"last_run": job.get("last_run"),
|
|
128
|
+
"last_status": job.get("last_status"),
|
|
129
|
+
"source": "custom",
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
# APScheduler
|
|
133
|
+
aps = _detect_apscheduler()
|
|
134
|
+
if aps:
|
|
135
|
+
jobs.extend(aps)
|
|
136
|
+
|
|
137
|
+
# Celery beat
|
|
138
|
+
beat = _detect_celery_beat()
|
|
139
|
+
if beat:
|
|
140
|
+
jobs.extend(beat)
|
|
141
|
+
|
|
142
|
+
if not jobs:
|
|
143
|
+
return {
|
|
144
|
+
"jobs": [],
|
|
145
|
+
"count": 0,
|
|
146
|
+
"message": (
|
|
147
|
+
"No scheduled jobs found. Use register_scheduled_job(name, schedule) "
|
|
148
|
+
"or install APScheduler / configure Celery beat."
|
|
149
|
+
),
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {"count": len(jobs), "jobs": jobs}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@debug_tool(
|
|
156
|
+
"get_job_history",
|
|
157
|
+
"Get execution history for a specific scheduled job",
|
|
158
|
+
)
|
|
159
|
+
def get_job_history(
|
|
160
|
+
job_name: str = ToolParam("Name of the scheduled job"),
|
|
161
|
+
limit: int = ToolParam("Max history entries to return", required=False),
|
|
162
|
+
) -> dict:
|
|
163
|
+
job = _scheduled_jobs.get(job_name)
|
|
164
|
+
if job is None:
|
|
165
|
+
return {
|
|
166
|
+
"error": f"No custom job registered for '{job_name}'",
|
|
167
|
+
"note": "History is only tracked for jobs registered via register_scheduled_job().",
|
|
168
|
+
"available": list(_scheduled_jobs.keys()),
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
history = job.get("history", [])
|
|
172
|
+
if limit:
|
|
173
|
+
history = history[-limit:]
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
"job_name": job_name,
|
|
177
|
+
"schedule": job.get("schedule"),
|
|
178
|
+
"last_run": job.get("last_run"),
|
|
179
|
+
"last_status": job.get("last_status"),
|
|
180
|
+
"total_runs": len(job.get("history", [])),
|
|
181
|
+
"history": list(reversed(history)),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ─── Convenience: execute + record a job on demand ─────────────────────────────
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def run_job(name: str) -> Any:
|
|
189
|
+
"""Execute a registered job by name, record the outcome, and return its result."""
|
|
190
|
+
job = _scheduled_jobs.get(name)
|
|
191
|
+
if job is None:
|
|
192
|
+
raise KeyError(f"No scheduled job registered for '{name}'")
|
|
193
|
+
fn = job.get("job_fn")
|
|
194
|
+
if fn is None:
|
|
195
|
+
raise ValueError(f"Job '{name}' has no callable attached")
|
|
196
|
+
try:
|
|
197
|
+
result = fn()
|
|
198
|
+
record_job_run(name, "success", details=str(result) if result is not None else None)
|
|
199
|
+
return result
|
|
200
|
+
except Exception:
|
|
201
|
+
import traceback
|
|
202
|
+
record_job_run(name, "failed", details=traceback.format_exc())
|
|
203
|
+
raise
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@debug_tool(
|
|
207
|
+
"run_scheduled_job_now",
|
|
208
|
+
"Manually trigger a registered scheduled job and record its result",
|
|
209
|
+
)
|
|
210
|
+
def run_scheduled_job_now(
|
|
211
|
+
job_name: str = ToolParam("Name of the registered scheduled job to trigger"),
|
|
212
|
+
) -> dict:
|
|
213
|
+
job = _scheduled_jobs.get(job_name)
|
|
214
|
+
if job is None:
|
|
215
|
+
return {
|
|
216
|
+
"error": f"No scheduled job registered for '{job_name}'",
|
|
217
|
+
"available": list(_scheduled_jobs.keys()),
|
|
218
|
+
}
|
|
219
|
+
if job.get("job_fn") is None:
|
|
220
|
+
return {
|
|
221
|
+
"error": f"Job '{job_name}' has no callable attached (metadata-only registration)",
|
|
222
|
+
}
|
|
223
|
+
try:
|
|
224
|
+
result = run_job(job_name)
|
|
225
|
+
return {"job_name": job_name, "status": "success", "result": str(result)}
|
|
226
|
+
except Exception as exc:
|
|
227
|
+
return {"job_name": job_name, "status": "failed", "error": str(exc)}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Security inspector: auth configurations, active sessions, and CORS.
|
|
2
|
+
|
|
3
|
+
Register auth configs and session stores at runtime:
|
|
4
|
+
|
|
5
|
+
from debug_agent.inspectors.security_inspector import (
|
|
6
|
+
register_auth_config, register_session_store,
|
|
7
|
+
)
|
|
8
|
+
register_auth_config("api_key", {"scheme": "api_key", ...})
|
|
9
|
+
register_session_store("flask_session", my_session_backend)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import time
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ─── Registration registries ──────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
_auth_configs: dict[str, Any] = {}
|
|
24
|
+
_session_stores: dict[str, Any] = {}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def register_auth_config(name: str, config: Any) -> None:
|
|
28
|
+
"""Register an authentication configuration under *name*."""
|
|
29
|
+
_auth_configs[name] = config
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register_session_store(name: str, store: Any) -> None:
|
|
33
|
+
"""Register a session backend under *name* so the inspector can query it."""
|
|
34
|
+
_session_stores[name] = store
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _detect_scheme_type(config: Any) -> str:
|
|
41
|
+
"""Best-effort label for the auth scheme type."""
|
|
42
|
+
if isinstance(config, dict):
|
|
43
|
+
explicit = config.get("scheme") or config.get("type")
|
|
44
|
+
if explicit:
|
|
45
|
+
return str(explicit)
|
|
46
|
+
cls = type(config).__name__.lower()
|
|
47
|
+
for needle in ("jwt", "login", "basic", "apikey", "oauth", "token", "session"):
|
|
48
|
+
if needle in cls:
|
|
49
|
+
return needle
|
|
50
|
+
return type(config).__name__
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _has_secret(config: Any) -> bool:
|
|
54
|
+
"""Return True if a secret-like key is present (value is never exposed)."""
|
|
55
|
+
_SECRET_KEYS = (
|
|
56
|
+
"secret", "secret_key", "api_key", "token", "password",
|
|
57
|
+
"private_key", "signing_key",
|
|
58
|
+
)
|
|
59
|
+
if isinstance(config, dict):
|
|
60
|
+
return any(
|
|
61
|
+
bool(config.get(k))
|
|
62
|
+
for k in _SECRET_KEYS
|
|
63
|
+
)
|
|
64
|
+
return any(getattr(config, k, None) for k in _SECRET_KEYS)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _extract_token_expiry(config: Any) -> Any:
|
|
68
|
+
for key in ("token_expiry", "expiry", "expires_in", "token_expiration", "exp"):
|
|
69
|
+
if isinstance(config, dict):
|
|
70
|
+
if key in config:
|
|
71
|
+
return config[key]
|
|
72
|
+
else:
|
|
73
|
+
val = getattr(config, key, None)
|
|
74
|
+
if val is not None:
|
|
75
|
+
return val
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _summarise_auth_config(name: str, config: Any) -> dict:
|
|
80
|
+
return {
|
|
81
|
+
"name": name,
|
|
82
|
+
"scheme_type": _detect_scheme_type(config),
|
|
83
|
+
"token_expiry": _extract_token_expiry(config),
|
|
84
|
+
"secret_present": _has_secret(config),
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _query_session_store(name: str, store: Any) -> list[dict] | dict:
|
|
89
|
+
"""Try several common interfaces to extract sessions from *store*."""
|
|
90
|
+
# Callable returning a list of sessions
|
|
91
|
+
if callable(store):
|
|
92
|
+
try:
|
|
93
|
+
result = store()
|
|
94
|
+
if isinstance(result, list):
|
|
95
|
+
return result
|
|
96
|
+
if isinstance(result, dict) and "sessions" in result:
|
|
97
|
+
return result["sessions"]
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
# Objects with an explicit method
|
|
102
|
+
for method in ("active_sessions", "get_sessions", "all_sessions", "list_sessions"):
|
|
103
|
+
fn = getattr(store, method, None)
|
|
104
|
+
if callable(fn):
|
|
105
|
+
try:
|
|
106
|
+
return list(fn())
|
|
107
|
+
except Exception:
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
# Dict-of-sessions store
|
|
111
|
+
if isinstance(store, dict):
|
|
112
|
+
sessions = []
|
|
113
|
+
for sid, data in store.items():
|
|
114
|
+
sessions.append(_normalise_session(sid, data))
|
|
115
|
+
return sessions
|
|
116
|
+
|
|
117
|
+
return {"name": name, "error": "Unsupported session store interface"}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _normalise_session(sid: Any, data: Any) -> dict:
|
|
121
|
+
if isinstance(data, dict):
|
|
122
|
+
return {
|
|
123
|
+
"session_id": str(sid),
|
|
124
|
+
"user": data.get("user") or data.get("username") or data.get("user_id"),
|
|
125
|
+
"created": data.get("created") or data.get("created_at"),
|
|
126
|
+
"last_access": data.get("last_access") or data.get("last_activity") or data.get("updated"),
|
|
127
|
+
"ip": data.get("ip") or data.get("remote_addr") or data.get("ip_address"),
|
|
128
|
+
}
|
|
129
|
+
return {"session_id": str(sid), "data": str(data)}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _detect_cors_from_frameworks() -> dict | None:
|
|
133
|
+
"""Auto-detect CORS configuration from common Flask / FastAPI / Django middleware."""
|
|
134
|
+
# Flask-CORS
|
|
135
|
+
try:
|
|
136
|
+
import flask # type: ignore
|
|
137
|
+
|
|
138
|
+
# Flask-CORS stores its config on the extension object
|
|
139
|
+
for ext_name in ("cors", "CORS"):
|
|
140
|
+
for ref in _iter_flask_extensions():
|
|
141
|
+
if hasattr(ref, "_options") or type(ref).__module__.startswith("flask_cors"):
|
|
142
|
+
opts = getattr(ref, "_options", {}) or {}
|
|
143
|
+
resources = getattr(ref, "resources", {})
|
|
144
|
+
return {
|
|
145
|
+
"source": "Flask-CORS",
|
|
146
|
+
"origins": opts.get("origins", resources.get("origins", [])),
|
|
147
|
+
"methods": opts.get("methods"),
|
|
148
|
+
"allow_headers": opts.get("allow_headers"),
|
|
149
|
+
"expose_headers": opts.get("expose_headers"),
|
|
150
|
+
"supports_credentials": opts.get("supports_credentials"),
|
|
151
|
+
"max_age": opts.get("max_age"),
|
|
152
|
+
}
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
# Django CORS headers
|
|
157
|
+
try:
|
|
158
|
+
from django.conf import settings # type: ignore
|
|
159
|
+
|
|
160
|
+
if getattr(settings, "CONFIGURED", False):
|
|
161
|
+
return {
|
|
162
|
+
"source": "django-cors-headers",
|
|
163
|
+
"origins": list(getattr(settings, "CORS_ALLOWED_ORIGINS", []) or []),
|
|
164
|
+
"allow_all": getattr(settings, "CORS_ALLOW_ALL_ORIGINS", False),
|
|
165
|
+
"methods": list(getattr(settings, "CORS_ALLOW_METHODS", []) or []),
|
|
166
|
+
"allow_headers": list(getattr(settings, "CORS_ALLOW_HEADERS", []) or []),
|
|
167
|
+
"allow_credentials": getattr(settings, "CORS_ALLOW_CREDENTIALS", False),
|
|
168
|
+
}
|
|
169
|
+
except Exception:
|
|
170
|
+
pass
|
|
171
|
+
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _iter_flask_extensions():
|
|
176
|
+
"""Yield Flask extension objects from any Flask app in scope."""
|
|
177
|
+
try:
|
|
178
|
+
import flask # type: ignore
|
|
179
|
+
ctx = flask.current_app
|
|
180
|
+
if ctx is not None:
|
|
181
|
+
yield from getattr(ctx, "extensions", {}).values()
|
|
182
|
+
except Exception:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@debug_tool(
|
|
190
|
+
"get_auth_config",
|
|
191
|
+
"List registered authentication configurations (scheme type, token expiry, secret present)",
|
|
192
|
+
)
|
|
193
|
+
def get_auth_config() -> dict:
|
|
194
|
+
if not _auth_configs:
|
|
195
|
+
return {
|
|
196
|
+
"registered": [],
|
|
197
|
+
"count": 0,
|
|
198
|
+
"message": "No auth configs registered. Use register_auth_config(name, config).",
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
"count": len(_auth_configs),
|
|
202
|
+
"configs": [_summarise_auth_config(name, cfg) for name, cfg in _auth_configs.items()],
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@debug_tool(
|
|
207
|
+
"get_active_sessions",
|
|
208
|
+
"List active user sessions from registered session backends",
|
|
209
|
+
)
|
|
210
|
+
def get_active_sessions() -> dict:
|
|
211
|
+
if not _session_stores:
|
|
212
|
+
return {
|
|
213
|
+
"stores": [],
|
|
214
|
+
"total_sessions": 0,
|
|
215
|
+
"message": "No session stores registered. Use register_session_store(name, store).",
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
all_sessions: list[dict] = []
|
|
219
|
+
stores_summary: list[dict] = []
|
|
220
|
+
for store_name, store in _session_stores.items():
|
|
221
|
+
result = _query_session_store(store_name, store)
|
|
222
|
+
if isinstance(result, list):
|
|
223
|
+
all_sessions.extend(result)
|
|
224
|
+
stores_summary.append({"name": store_name, "sessions": len(result)})
|
|
225
|
+
else:
|
|
226
|
+
stores_summary.append(result)
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
"total_sessions": len(all_sessions),
|
|
230
|
+
"stores": stores_summary,
|
|
231
|
+
"sessions": all_sessions,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@debug_tool(
|
|
236
|
+
"get_cors_config",
|
|
237
|
+
"Show CORS configuration: allowed origins, methods, headers, credentials",
|
|
238
|
+
)
|
|
239
|
+
def get_cors_config() -> dict:
|
|
240
|
+
detected = _detect_cors_from_frameworks()
|
|
241
|
+
if detected:
|
|
242
|
+
return {"detected": True, **detected}
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
"detected": False,
|
|
246
|
+
"message": (
|
|
247
|
+
"No CORS configuration auto-detected. Register one via "
|
|
248
|
+
"register_auth_config('cors', {...}) or install Flask-CORS / "
|
|
249
|
+
"django-cors-headers."
|
|
250
|
+
),
|
|
251
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""WebSocket inspector: active connections, stats, and rooms.
|
|
2
|
+
|
|
3
|
+
Register WebSocket servers at runtime:
|
|
4
|
+
|
|
5
|
+
from debug_agent.inspectors.websocket_inspector import register_ws_server
|
|
6
|
+
register_ws_server("socketio", sio_instance)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from debug_agent.tool_registry import debug_tool, ToolParam
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ─── Registration ─────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
_ws_servers: dict[str, Any] = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_ws_server(name: str, server: Any) -> None:
|
|
23
|
+
"""Register a WebSocket server (Flask-SocketIO, FastAPI WS, Django Channels)."""
|
|
24
|
+
_ws_servers[name] = server
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _get_connections_from_server(name: str, server: Any) -> list[dict]:
|
|
31
|
+
"""Try common interfaces to extract active connections from *server*."""
|
|
32
|
+
connections: list[dict] = []
|
|
33
|
+
|
|
34
|
+
# python-socketio / Flask-SocketIO AsyncServer / Server
|
|
35
|
+
try:
|
|
36
|
+
# Sync Server.eio.sockets → dict of sid → engine
|
|
37
|
+
eio = getattr(server, "eio", None)
|
|
38
|
+
if eio is not None:
|
|
39
|
+
sockets = getattr(eio, "sockets", {})
|
|
40
|
+
if isinstance(sockets, dict):
|
|
41
|
+
for sid, sock in sockets.items():
|
|
42
|
+
connections.append({
|
|
43
|
+
"connection_id": str(sid),
|
|
44
|
+
"remote_address": getattr(sock, "remote_addr", None),
|
|
45
|
+
"connected_since": _iso(getattr(sock, "connected_at", None)),
|
|
46
|
+
"messages_sent": getattr(sock, "upstream_messages", None),
|
|
47
|
+
"messages_received": getattr(sock, "downstream_messages", None),
|
|
48
|
+
})
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
# Callable interface — server returns a list of connection dicts
|
|
53
|
+
if not connections and callable(server):
|
|
54
|
+
try:
|
|
55
|
+
result = server()
|
|
56
|
+
if isinstance(result, list):
|
|
57
|
+
connections = result
|
|
58
|
+
except Exception:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
# Object with explicit method
|
|
62
|
+
if not connections:
|
|
63
|
+
for method_name in ("get_connections", "active_connections", "connections"):
|
|
64
|
+
fn = getattr(server, method_name, None)
|
|
65
|
+
if callable(fn):
|
|
66
|
+
try:
|
|
67
|
+
result = fn()
|
|
68
|
+
if isinstance(result, list):
|
|
69
|
+
connections = result
|
|
70
|
+
elif isinstance(result, dict):
|
|
71
|
+
connections = list(result.values())
|
|
72
|
+
break
|
|
73
|
+
except Exception:
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
# Dict of conn_id → conn_data
|
|
77
|
+
if not connections and isinstance(server, dict):
|
|
78
|
+
for cid, data in server.items():
|
|
79
|
+
if isinstance(data, dict):
|
|
80
|
+
connections.append({"connection_id": str(cid), **data})
|
|
81
|
+
|
|
82
|
+
# Tag each connection with its source server
|
|
83
|
+
for conn in connections:
|
|
84
|
+
conn.setdefault("server", name)
|
|
85
|
+
|
|
86
|
+
return connections
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _get_rooms_from_server(server: Any) -> dict[str, int]:
|
|
90
|
+
"""Try to extract room → member count from a Socket.IO server."""
|
|
91
|
+
rooms: dict[str, int] = {}
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
# python-socketio Server.get_rooms() or _rooms attribute
|
|
95
|
+
if hasattr(server, "get_rooms"):
|
|
96
|
+
for room in server.get_rooms(): # type: ignore[attr-defined]
|
|
97
|
+
rooms[str(room)] = len(server.eio.sockets) # fallback
|
|
98
|
+
elif hasattr(server, "rooms"):
|
|
99
|
+
raw_rooms = server.rooms
|
|
100
|
+
if isinstance(raw_rooms, dict):
|
|
101
|
+
for room_name, members in raw_rooms.items():
|
|
102
|
+
rooms[str(room_name)] = len(members) if hasattr(members, "__len__") else 0
|
|
103
|
+
elif isinstance(raw_rooms, (list, set)):
|
|
104
|
+
for r in raw_rooms:
|
|
105
|
+
rooms[str(r)] = 1
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
return rooms
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _iso(ts: Any) -> str | None:
|
|
113
|
+
"""Best-effort conversion of a timestamp to ISO string."""
|
|
114
|
+
if ts is None:
|
|
115
|
+
return None
|
|
116
|
+
if isinstance(ts, str):
|
|
117
|
+
return ts
|
|
118
|
+
if isinstance(ts, (int, float)):
|
|
119
|
+
return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat()
|
|
120
|
+
if hasattr(ts, "isoformat"):
|
|
121
|
+
return ts.isoformat()
|
|
122
|
+
return str(ts)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# ─── Tools ────────────────────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@debug_tool(
|
|
129
|
+
"get_ws_connections",
|
|
130
|
+
"List active WebSocket connections (Flask-SocketIO, FastAPI WS, Django Channels)",
|
|
131
|
+
)
|
|
132
|
+
def get_ws_connections() -> dict:
|
|
133
|
+
if not _ws_servers:
|
|
134
|
+
return {
|
|
135
|
+
"connections": [],
|
|
136
|
+
"total": 0,
|
|
137
|
+
"message": "No WebSocket servers registered. Use register_ws_server(name, server).",
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
all_conns: list[dict] = []
|
|
141
|
+
server_counts: dict[str, int] = {}
|
|
142
|
+
for name, server in _ws_servers.items():
|
|
143
|
+
conns = _get_connections_from_server(name, server)
|
|
144
|
+
all_conns.extend(conns)
|
|
145
|
+
server_counts[name] = len(conns)
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
"total": len(all_conns),
|
|
149
|
+
"servers": server_counts,
|
|
150
|
+
"connections": all_conns,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@debug_tool(
|
|
155
|
+
"get_ws_stats",
|
|
156
|
+
"Get WebSocket statistics: total connections, per-server counts, uptime",
|
|
157
|
+
)
|
|
158
|
+
def get_ws_stats() -> dict:
|
|
159
|
+
if not _ws_servers:
|
|
160
|
+
return {
|
|
161
|
+
"total_servers": 0,
|
|
162
|
+
"total_connections": 0,
|
|
163
|
+
"message": "No WebSocket servers registered.",
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
all_conns: list[dict] = []
|
|
167
|
+
per_server: dict[str, dict] = {}
|
|
168
|
+
for name, server in _ws_servers.items():
|
|
169
|
+
conns = _get_connections_from_server(name, server)
|
|
170
|
+
all_conns.extend(conns)
|
|
171
|
+
total_sent = sum(c.get("messages_sent") or 0 for c in conns if c.get("messages_sent"))
|
|
172
|
+
total_recv = sum(c.get("messages_received") or 0 for c in conns if c.get("messages_received"))
|
|
173
|
+
per_server[name] = {
|
|
174
|
+
"connections": len(conns),
|
|
175
|
+
"messages_sent": total_sent,
|
|
176
|
+
"messages_received": total_recv,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
# Earliest connection time for uptime estimate
|
|
180
|
+
connect_times = [c.get("connected_since") for c in all_conns if c.get("connected_since")]
|
|
181
|
+
earliest = min(connect_times) if connect_times else None
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
"total_servers": len(_ws_servers),
|
|
185
|
+
"total_connections": len(all_conns),
|
|
186
|
+
"earliest_connection": earliest,
|
|
187
|
+
"per_server": per_server,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@debug_tool(
|
|
192
|
+
"get_ws_rooms",
|
|
193
|
+
"List Socket.IO rooms with member counts",
|
|
194
|
+
)
|
|
195
|
+
def get_ws_rooms() -> dict:
|
|
196
|
+
if not _ws_servers:
|
|
197
|
+
return {
|
|
198
|
+
"rooms": {},
|
|
199
|
+
"total_rooms": 0,
|
|
200
|
+
"message": "No WebSocket servers registered.",
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
all_rooms: dict[str, int] = {}
|
|
204
|
+
server_room_counts: dict[str, int] = {}
|
|
205
|
+
for name, server in _ws_servers.items():
|
|
206
|
+
rooms = _get_rooms_from_server(server)
|
|
207
|
+
server_room_counts[name] = len(rooms)
|
|
208
|
+
all_rooms.update(rooms)
|
|
209
|
+
|
|
210
|
+
if not all_rooms:
|
|
211
|
+
return {
|
|
212
|
+
"rooms": {},
|
|
213
|
+
"total_rooms": 0,
|
|
214
|
+
"message": (
|
|
215
|
+
"No rooms detected. Room tracking is supported for python-socketio / "
|
|
216
|
+
"Flask-SocketIO servers."
|
|
217
|
+
),
|
|
218
|
+
"servers_checked": list(_ws_servers.keys()),
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
"total_rooms": len(all_rooms),
|
|
223
|
+
"rooms": dict(sorted(all_rooms.items(), key=lambda x: -x[1])),
|
|
224
|
+
"per_server": server_room_counts,
|
|
225
|
+
}
|
|
@@ -15,10 +15,12 @@ src/debug_agent/inspectors/cache_inspector.py
|
|
|
15
15
|
src/debug_agent/inspectors/celery.py
|
|
16
16
|
src/debug_agent/inspectors/database.py
|
|
17
17
|
src/debug_agent/inspectors/django.py
|
|
18
|
+
src/debug_agent/inspectors/error_tracking.py
|
|
18
19
|
src/debug_agent/inspectors/fastapi_ext.py
|
|
19
20
|
src/debug_agent/inspectors/fd_inspector.py
|
|
20
21
|
src/debug_agent/inspectors/flask_ext.py
|
|
21
22
|
src/debug_agent/inspectors/framework.py
|
|
23
|
+
src/debug_agent/inspectors/health_inspector.py
|
|
22
24
|
src/debug_agent/inspectors/http_client_inspector.py
|
|
23
25
|
src/debug_agent/inspectors/http_tracker.py
|
|
24
26
|
src/debug_agent/inspectors/jinja2.py
|
|
@@ -28,10 +30,13 @@ src/debug_agent/inspectors/metrics_inspector.py
|
|
|
28
30
|
src/debug_agent/inspectors/modules.py
|
|
29
31
|
src/debug_agent/inspectors/redis.py
|
|
30
32
|
src/debug_agent/inspectors/runtime.py
|
|
33
|
+
src/debug_agent/inspectors/scheduler_inspector.py
|
|
34
|
+
src/debug_agent/inspectors/security_inspector.py
|
|
31
35
|
src/debug_agent/inspectors/signals.py
|
|
32
36
|
src/debug_agent/inspectors/system.py
|
|
33
37
|
src/debug_agent/inspectors/threads.py
|
|
34
38
|
src/debug_agent/inspectors/warnings_inspector.py
|
|
39
|
+
src/debug_agent/inspectors/websocket_inspector.py
|
|
35
40
|
src/debug_agent/web/__init__.py
|
|
36
41
|
src/debug_agent/web/chat_page.py
|
|
37
42
|
src/debug_agent_py.egg-info/PKG-INFO
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/http_client_inspector.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/logging_inspector.py
RENAMED
|
File without changes
|
|
File without changes
|
{debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/metrics_inspector.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent/inspectors/warnings_inspector.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{debug_agent_py-0.4.0 → debug_agent_py-0.5.0}/src/debug_agent_py.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|