Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 84 additions & 32 deletions src/sharpit/engine/capture/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,33 +159,27 @@ def _slowest_route(row: dict[str, Any] | None) -> dict[str, Any]:
return dict(zip(ROUTE_KPI_KEYS, values, strict=True))


def activity_report(
ctx: SharpitContext,
type: str | None,
severity: str | None,
since: int | None,
limit: int | None,
q: str | None,
*,
journal_filters: bool = False,
) -> dict[str, Any]:
"""``LiveActivityReport``, newest first; ``typeCounts`` and KPIs count every entry, before the filters."""
settings = ctx.settings
found, warnings = _sources(ctx)
exchanges: list[dict[str, Any]] = found["requests"].rows() if "requests" in found else []
groups: list[dict[str, Any]] = found["exceptions"].report()["groups"] if "exceptions" in found else []
statements: list[dict[str, Any]] = found["sql"].rows() if "sql" in found else []
request_ids = {r["id"] for r in exchanges}
sql_by_request: dict[str, list[dict[str, Any]]] = {}
for row in statements:
if row["traceId"] is not None:
sql_by_request.setdefault(row["traceId"], []).append(row)
def _request_level(status: int, duration: int, slow_ms: int) -> str:
if status >= 500:
return "ERROR"
if status >= 400:
return "WARN"
return "SLOW" if duration >= slow_ms else "OK"


def _sql_level(row: dict[str, Any]) -> str:
if not row["success"]:
return "ERROR"
return "SLOW" if row["slow"] else "OK"


def _request_entries(
exchanges: list[dict[str, Any]], sql_by_request: dict[str, list[dict[str, Any]]], settings: Any
) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
slow_ms = settings.activity_request_slow_threshold_ms
for r in exchanges:
status, duration = r["status"], r["durationMs"]
level = "ERROR" if status >= 500 else "WARN" if status >= 400 else "SLOW" if duration >= slow_ms else "OK"
n_plus_one = any(
g["potentialNPlusOne"]
for g in _groups(sql_by_request.get(r["id"], ()), settings.activity_n_plus_one_threshold)
Expand All @@ -195,7 +189,7 @@ def activity_report(
id=r["id"],
type="REQUEST",
timestamp=r["startNs"] // 1_000_000,
severity=level,
severity=_request_level(status, duration, slow_ms),
summary=f"{r['method']} {r['path']}",
detail=f"{status} · {duration}ms",
durationMs=duration,
Expand All @@ -208,14 +202,19 @@ def activity_report(
sqlNPlusOneSuspected=n_plus_one,
)
)
return entries


def _sql_entries(statements: list[dict[str, Any]], request_ids: set[str]) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
for s in statements:
rid = s["traceId"]
entries.append(
_entry(
id=f"sql-{s['id']}",
type="SQL",
timestamp=s["timestamp"] // 1_000_000,
severity="ERROR" if not s["success"] else "SLOW" if s["slow"] else "OK",
severity=_sql_level(s),
summary=_summarize_sql(s["category"], s["sql"]),
detail=None if s["success"] else s["errorMessage"],
durationMs=s["durationMillis"],
Expand All @@ -224,6 +223,11 @@ def activity_report(
parentId=rid if rid in request_ids else None,
)
)
return entries


def _exception_entries(groups: list[dict[str, Any]], request_ids: set[str]) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
for g in groups:
rid = g["lastTraceId"]
detail = g["location"]
Expand All @@ -245,12 +249,17 @@ def activity_report(
parentId=rid if rid in request_ids else None,
)
)
entries.sort(key=lambda e: e["timestamp"], reverse=True)
type_counts: dict[str, int] = {}
for entry in entries:
type_counts[entry["type"]] = type_counts.get(entry["type"], 0) + 1
return entries

cap = settings.activity_max_entries if not limit or limit <= 0 else min(limit, settings.activity_max_entries)

def _visible(
entries: list[dict[str, Any]],
cap: int,
type: str | None,
severity: str | None,
since: int | None,
q: str | None,
) -> list[dict[str, Any]]:
wanted_type = (type or "").strip().upper()
wanted_severity = (severity or "").strip().upper()
needle = (q or "").strip().lower()
Expand All @@ -269,11 +278,19 @@ def activity_report(
):
continue
visible.append(entry)
return visible


def _kpis(
ctx: SharpitContext,
exchanges: list[dict[str, Any]],
groups: list[dict[str, Any]],
statements: list[dict[str, Any]],
) -> dict[str, Any]:
durations = sorted(r["durationMs"] for r in exchanges)
slowest = max(exchanges, key=lambda r: r["durationMs"], default=None)
errors = sum(r["status"] >= 400 for r in exchanges)
kpis = {
return {
"requestsPerMinute": round(_per_minute([r["startNs"] // 1_000_000 for r in exchanges]), 2),
"errorRatePercent": round(100 * errors / len(exchanges), 2) if exchanges else 0.0,
"p50LatencyMs": _percentile(durations, 50),
Expand All @@ -293,11 +310,46 @@ def activity_report(
"latencySampleCount": len(durations),
**_slowest_route(slowest),
}


def activity_report(
ctx: SharpitContext,
type: str | None,
severity: str | None,
since: int | None,
limit: int | None,
q: str | None,
*,
journal_filters: bool = False,
) -> dict[str, Any]:
"""``LiveActivityReport``, newest first; ``typeCounts`` and KPIs count every entry, before the filters."""
settings = ctx.settings
found, warnings = _sources(ctx)
exchanges: list[dict[str, Any]] = found["requests"].rows() if "requests" in found else []
groups: list[dict[str, Any]] = found["exceptions"].report()["groups"] if "exceptions" in found else []
statements: list[dict[str, Any]] = found["sql"].rows() if "sql" in found else []
request_ids = {r["id"] for r in exchanges}
sql_by_request: dict[str, list[dict[str, Any]]] = {}
for row in statements:
if row["traceId"] is not None:
sql_by_request.setdefault(row["traceId"], []).append(row)

entries = [
*_request_entries(exchanges, sql_by_request, settings),
*_sql_entries(statements, request_ids),
*_exception_entries(groups, request_ids),
]
entries.sort(key=lambda e: e["timestamp"], reverse=True)
type_counts: dict[str, int] = {}
for entry in entries:
type_counts[entry["type"]] = type_counts.get(entry["type"], 0) + 1

cap = settings.activity_max_entries if not limit or limit <= 0 else min(limit, settings.activity_max_entries)
return {
"available": bool(found),
"entries": visible,
"entries": _visible(entries, cap, type, severity, since, q),
"typeCounts": type_counts,
"kpis": kpis,
"kpis": _kpis(ctx, exchanges, groups, statements),
"sources": list(found),
"warnings": [*warnings, BUFFER_SOURCE_FILTERS] if journal_filters else warnings,
"pageInfo": None,
Expand Down
2 changes: 1 addition & 1 deletion src/sharpit/engine/capture/exchanges.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def trace_id(request_headers: RawHeaders, request_id: str) -> str:
return traceparent_id(request_headers) or request_id


def exchange_row(
def exchange_row( # NOSONAR - keyword-only fields of one flat row, called once per request from the capture hot path
masker: Masker,
*,
request_id: str,
Expand Down
4 changes: 2 additions & 2 deletions src/sharpit/engine/capture/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
import sysconfig

_STDLIB = tuple(
{
dict.fromkeys( # ordered de-duplication: stdlib and platstdlib are often the same directory
os.path.normcase(os.path.abspath(p)) + os.sep
for k in ("stdlib", "platstdlib")
if (p := sysconfig.get_paths().get(k))
}
)
)
_SHARPIT = os.path.normcase(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) + os.sep # sharpit/
_PACKAGE_DIRS = {"site-packages", "dist-packages"}
Expand Down
20 changes: 13 additions & 7 deletions src/sharpit/engine/capture/sqltrace.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ def _truncate(text: str, limit: int) -> str:
return text if len(text) <= limit else text[:limit] + "…"


def _batch_size(parameters: object, batch_size: int | None) -> int:
return batch_size if batch_size is not None else len(cast_sequence(parameters))


def _statement_output(masker: Masker, max_sql_length: int, sql: str, dialect: Dialect) -> tuple[Shape, str, str]:
shape = sqltext.statement_shape(masker, sql, dialect)
return shape, _truncate(shape.text, max_sql_length), category_of(sql)
Expand Down Expand Up @@ -303,6 +307,13 @@ def _parameter(self, name: str, value: object) -> str:
shown, masked = self._masker.mask(name, value)
return _truncate(MASK if masked else repr(shown), self._max_parameter_length)

def _error_message(self, error: BaseException | None, dialect: Dialect) -> str | None:
if error is None:
return None
masker = self._masker
masked = sqltext.error_text(masker, error, dialect, known=True, keep_frames=False) or masker.mask_text("")
return _truncate(masked, self._max_sql_length) if masked is not None else None

def record(
self,
sql: str,
Expand Down Expand Up @@ -331,10 +342,7 @@ def record(
# capture on shows the raw statement, but never one sharpit cannot read (owner, item 7)
raw = masker.capture_parameters and dialect is not Dialect.UNSUPPORTED
stored = _truncate(masker.mask_text(sql) or "", self._max_sql_length) if raw else text
error_message: str | None = None
if error is not None:
masked = sqltext.error_text(masker, error, dialect, known=True, keep_frames=False) or masker.mask_text("")
error_message = _truncate(masked, self._max_sql_length) if masked is not None else None
error_message = self._error_message(error, dialect)
has_parameters = bool(parameters)
millis = duration_ns // 1_000_000
site = call_site if self.capture_call_site else None
Expand All @@ -349,9 +357,7 @@ def record(
"success": success and error is None,
"errorMessage": error_message,
"affectedRows": rowcount if rowcount >= 0 and error is None else None,
"batchSize": (batch_size if batch_size is not None else len(cast_sequence(parameters)))
if executemany and has_parameters
else 0,
"batchSize": _batch_size(parameters, batch_size) if executemany and has_parameters else 0,
"connectionId": connection_id,
"thread": thread,
"slow": self._slow(millis),
Expand Down
2 changes: 1 addition & 1 deletion src/sharpit/engine/daemon_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ def _worker(self) -> None:
if future.set_running_or_notify_cancel():
try:
future.set_result(fn(*args, **kwargs))
except BaseException as exc:
except BaseException as exc: # NOSONAR - the future carries it; the worker must not die
future.set_exception(exc)
Loading