From 34f477e620a3c993ad86724dd877e32567f02022 Mon Sep 17 00:00:00 2001 From: Flavio Oliva Date: Mon, 23 Nov 2026 21:47:44 +0000 Subject: [PATCH] refactor: clear Sonar code smells in capture, probe and the FastAPI adapter Extract helpers from the cognitive-complexity hot spots (activity report, SQL record, probe validation and run, provider discovery), replace nested conditional expressions with explicit statements, and annotate the deliberate patterns (worker catch-all, snapshot copies, probe timeout parameter, flat exchange row signature) with their reason. Pinned C901 counts are lowered. Signed-off-by: Flavio Oliva --- src/sharpit/engine/capture/activity.py | 116 ++++++++++----- src/sharpit/engine/capture/exchanges.py | 2 +- src/sharpit/engine/capture/frames.py | 4 +- src/sharpit/engine/capture/sqltrace.py | 20 ++- src/sharpit/engine/daemon_executor.py | 2 +- src/sharpit/engine/probe.py | 181 ++++++++++++++---------- src/sharpit/fastapi/adapter.py | 4 +- src/sharpit/fastapi/capture.py | 2 +- src/sharpit/fastapi/introspector.py | 93 +++++++----- tests/complexity_baseline.json | 6 +- 10 files changed, 269 insertions(+), 161 deletions(-) diff --git a/src/sharpit/engine/capture/activity.py b/src/sharpit/engine/capture/activity.py index 930aa7da8..efca86392 100644 --- a/src/sharpit/engine/capture/activity.py +++ b/src/sharpit/engine/capture/activity.py @@ -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) @@ -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, @@ -208,6 +202,11 @@ 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( @@ -215,7 +214,7 @@ def activity_report( 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"], @@ -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"] @@ -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() @@ -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), @@ -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, diff --git a/src/sharpit/engine/capture/exchanges.py b/src/sharpit/engine/capture/exchanges.py index d132ed414..be0caed75 100644 --- a/src/sharpit/engine/capture/exchanges.py +++ b/src/sharpit/engine/capture/exchanges.py @@ -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, diff --git a/src/sharpit/engine/capture/frames.py b/src/sharpit/engine/capture/frames.py index 5122080b5..6d8a7d095 100644 --- a/src/sharpit/engine/capture/frames.py +++ b/src/sharpit/engine/capture/frames.py @@ -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"} diff --git a/src/sharpit/engine/capture/sqltrace.py b/src/sharpit/engine/capture/sqltrace.py index d1d8042bc..5db0e3035 100644 --- a/src/sharpit/engine/capture/sqltrace.py +++ b/src/sharpit/engine/capture/sqltrace.py @@ -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) @@ -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, @@ -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 @@ -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), diff --git a/src/sharpit/engine/daemon_executor.py b/src/sharpit/engine/daemon_executor.py index 1c55f5065..deb0b6a79 100644 --- a/src/sharpit/engine/daemon_executor.py +++ b/src/sharpit/engine/daemon_executor.py @@ -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) diff --git a/src/sharpit/engine/probe.py b/src/sharpit/engine/probe.py index faeccef70..22afb937a 100644 --- a/src/sharpit/engine/probe.py +++ b/src/sharpit/engine/probe.py @@ -68,7 +68,7 @@ def _normal_path(path: str) -> str: return ("/" + normalized.lstrip("/")) if leading else normalized -def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str = "") -> ProbeRequest: +def _validated_method(body: dict[str, Any]) -> str: method = body.get("method") if method is None or not str(method).strip(): method = "GET" @@ -79,7 +79,10 @@ def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str method = method.strip().upper() if method not in _METHODS.split(", "): raise BadRequest(f"HTTP Probe request method must be one of {_METHODS}") + return method + +def _validated_path(body: dict[str, Any], settings_path: str, host_root_path: str) -> str: path = body.get("path") if path is None or not str(path).strip(): path = "/" @@ -100,7 +103,10 @@ def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str host_mount = host_root_path.rstrip("/") + settings_path if under(normalized, settings_path) or under(normalized, host_mount): raise BadRequest("HTTP Probe cannot target sharpit itself") + return path + +def _validated_payload(body: dict[str, Any]) -> str: payload = body.get("body") if payload is None: payload = "" @@ -108,7 +114,31 @@ def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str raise BadRequest("HTTP Probe request body must be a string") if _utf8_size(payload) > MAX_REQUEST_BODY_BYTES: raise BadRequest(f"HTTP Probe request body exceeds the maximum of {MAX_REQUEST_BODY_BYTES} bytes") - + return payload + + +def _validated_header(name: object, value: object, total: int) -> tuple[str, str, int] | None: + """``(lowercase name, value, new running total)``, or ``None`` for a null value.""" + if not isinstance(name, str) or _utf8_size(name) > MAX_HEADER_NAME_BYTES: + raise BadRequest(f"HTTP Probe request header name exceeds the maximum of {MAX_HEADER_NAME_BYTES} bytes") + if not _HEADER_TOKEN.fullmatch(name): + raise BadRequest("HTTP Probe request header name is invalid") + if value is None: + return None + if not isinstance(value, str): + raise BadRequest("HTTP Probe request header value is invalid") + value_size = _utf8_size(value) + if value_size > MAX_HEADER_VALUE_BYTES: + raise BadRequest(f"HTTP Probe request header value exceeds the maximum of {MAX_HEADER_VALUE_BYTES} bytes") + if any(char in value for char in "\r\n\x00"): + raise BadRequest("HTTP Probe request header value contains a forbidden character") + total += _utf8_size(name) + value_size + if total > MAX_TOTAL_HEADER_BYTES: + raise BadRequest(f"HTTP Probe request headers exceed the maximum total of {MAX_TOTAL_HEADER_BYTES} bytes") + return name.lower(), value, total + + +def _validated_headers(body: dict[str, Any]) -> dict[str, str]: raw_headers = body.get("headers") if raw_headers is None: raw_headers = {} @@ -120,26 +150,20 @@ def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str headers: dict[str, str] = {} total = 0 for name, value in raw_headers.items(): - if not isinstance(name, str) or _utf8_size(name) > MAX_HEADER_NAME_BYTES: - raise BadRequest(f"HTTP Probe request header name exceeds the maximum of {MAX_HEADER_NAME_BYTES} bytes") - if not _HEADER_TOKEN.fullmatch(name): - raise BadRequest("HTTP Probe request header name is invalid") - if value is None: + checked = _validated_header(name, value, total) + if checked is None: continue - if not isinstance(value, str): - raise BadRequest("HTTP Probe request header value is invalid") - value_size = _utf8_size(value) - if value_size > MAX_HEADER_VALUE_BYTES: - raise BadRequest(f"HTTP Probe request header value exceeds the maximum of {MAX_HEADER_VALUE_BYTES} bytes") - if any(char in value for char in "\r\n\x00"): - raise BadRequest("HTTP Probe request header value contains a forbidden character") - total += _utf8_size(name) + value_size - if total > MAX_TOTAL_HEADER_BYTES: - raise BadRequest(f"HTTP Probe request headers exceed the maximum total of {MAX_TOTAL_HEADER_BYTES} bytes") - lowered = name.lower() + lowered, value, total = checked if lowered not in RESTRICTED_HEADERS: headers[lowered] = value - return ProbeRequest(method, path, payload, headers) + return headers + + +def validate_probe(body: dict[str, Any], settings_path: str, host_root_path: str = "") -> ProbeRequest: + method = _validated_method(body) + path = _validated_path(body, settings_path, host_root_path) + payload = _validated_payload(body) + return ProbeRequest(method, path, payload, _validated_headers(body)) class ProbeSlots: @@ -218,23 +242,10 @@ def _task_done(task: asyncio.Task[Any], on_complete: Callable[[], None]) -> None _PENDING_TASKS: set[asyncio.Task[Any]] = set() -async def run_probe( - host_app: Any, - request: ProbeRequest, - caller_scope: Mapping[str, Any], - host_root_path: str, - masker: Masker, - *, - application: Callable[[], Dialect | None], - timeout: float = PROBE_TIMEOUT, - max_body: int = MAX_RESPONSE_BODY_BYTES, - on_complete: Callable[[], None] | None = None, - host_runner: Callable[..., Awaitable[None]] | None = None, -) -> dict[str, Any]: +def _probe_scope(request: ProbeRequest, caller_scope: Mapping[str, Any], host_root_path: str) -> dict[str, Any]: parsed = urlsplit(request.path) path_prefix = host_root_path.rstrip("/") raw_path = quote(path_prefix + parsed.path, safe="/%:@!$&'()*+,;=-._~").encode("ascii") - request_body = request.body.encode("utf-8") if request.method in {"POST", "PUT", "PATCH"} else b"" incoming = [ (name.encode("latin-1"), value.encode("latin-1", errors="replace")) for name, value in request.headers.items() ] @@ -243,7 +254,7 @@ async def run_probe( incoming.append((b"host", value)) break incoming.append((b"x-sharpit-probe", b"1")) - scope: dict[str, Any] = { + return { "type": "http", "asgi": {"version": "3.0", "spec_version": "2.4"}, "http_version": "1.1", @@ -259,6 +270,57 @@ async def run_probe( "state": dict(caller_scope.get("state", {})), "extensions": {"sharpit.probe": True}, } + + +def _probe_result( + status: int, + headers: dict[str, str], + body: str | None, + started: float, + error: str | None, + truncated: bool, +) -> dict[str, Any]: + return { + "status": status, + "statusText": _status_text(status) if status else "Error", + "headers": headers, + "body": body, + "durationMs": round((time.monotonic() - started) * 1000), + "error": error, + "truncated": truncated, + } + + +def _exception_message(masker: Masker, exc: Exception, application: Callable[[], Dialect | None]) -> str: + dialect = exception_dialect(exc, application) + if is_database_exception(exc): + return error_text(masker, exc, dialect) or type(exc).__name__ + # as a7a6ff2f: an unclassified error keeps its "Name: " diagnostics, masked + return error_text(masker, f"{type(exc).__name__}: {exc}", dialect) or type(exc).__name__ + + +def _cancel_host(cancel_host: list[Callable[[], None]], task: asyncio.Task[Any]) -> None: + if cancel_host: + cancel_host[0]() + else: + task.cancel() + + +async def run_probe( + host_app: Any, + request: ProbeRequest, + caller_scope: Mapping[str, Any], + host_root_path: str, + masker: Masker, + *, + application: Callable[[], Dialect | None], + timeout: float = PROBE_TIMEOUT, # NOSONAR - asyncio.timeout() would cancel the task + max_body: int = MAX_RESPONSE_BODY_BYTES, + on_complete: Callable[[], None] | None = None, + host_runner: Callable[..., Awaitable[None]] | None = None, +) -> dict[str, Any]: + request_body = request.body.encode("utf-8") if request.method in {"POST", "PUT", "PATCH"} else b"" + scope = _probe_scope(request, caller_scope, host_root_path) sent_body = bytearray() response_headers: list[tuple[bytes, bytes]] = [] status = 0 @@ -302,10 +364,7 @@ async def invoke_host() -> None: done, _ = await asyncio.wait({task}, timeout=timeout) if not done: finished.set() - if cancel_host: - cancel_host[0]() - else: - task.cancel() + _cancel_host(cancel_host, task) _PENDING_TASKS.add(task) if on_complete is not None: @@ -317,54 +376,26 @@ def finish(completed: asyncio.Task[Any]) -> None: transferred_slot = True else: task.add_done_callback(lambda completed: _PENDING_TASKS.discard(completed)) - return { - "status": status, - "statusText": _status_text(status) if status else "Error", - "headers": {}, - "body": _body(bytes(sent_body), None, masker), - "durationMs": round((time.monotonic() - started) * 1000), - "error": f"HTTP Probe timed out after {timeout:g}s", - "truncated": False, - } + return _probe_result( + status, {}, _body(bytes(sent_body), None, masker), started, + f"HTTP Probe timed out after {timeout:g}s", False, + ) # fmt: skip await task except asyncio.CancelledError: if not truncated: - if cancel_host: - cancel_host[0]() - else: - task.cancel() + _cancel_host(cancel_host, task) if on_complete is not None and not transferred_slot: task.add_done_callback(lambda completed: _task_done(completed, on_complete)) transferred_slot = True raise except Exception as exc: # noqa: BLE001 - app exceptions become a stable masked probe response - dialect = exception_dialect(exc, application) - if is_database_exception(exc): - message = error_text(masker, exc, dialect) or type(exc).__name__ - else: # as a7a6ff2f: an unclassified error keeps its "Name: " diagnostics, masked - message = error_text(masker, f"{type(exc).__name__}: {exc}", dialect) or type(exc).__name__ - status = 500 - return { - "status": status, - "statusText": _status_text(status), - "headers": {}, - "body": _body(bytes(sent_body), None, masker), - "durationMs": round((time.monotonic() - started) * 1000), - "error": message, - "truncated": False, - } + message = _exception_message(masker, exc, application) + return _probe_result(500, {}, _body(bytes(sent_body), None, masker), started, message, False) finally: finished.set() if on_complete is not None and not transferred_slot: on_complete() headers = _headers(response_headers, masker) body = _body(bytes(sent_body), headers.get("content-type"), masker) - return { - "status": status, - "statusText": _status_text(status) if status else "Error", - "headers": headers, - "body": body, - "durationMs": round((time.monotonic() - started) * 1000), - "error": "HTTP Probe target returned no response" if status == 0 else None, - "truncated": truncated, - } + error = "HTTP Probe target returned no response" if status == 0 else None + return _probe_result(status, headers, body, started, error, truncated) diff --git a/src/sharpit/fastapi/adapter.py b/src/sharpit/fastapi/adapter.py index 26bfc7062..0cf584aee 100644 --- a/src/sharpit/fastapi/adapter.py +++ b/src/sharpit/fastapi/adapter.py @@ -190,7 +190,9 @@ def _toggle_value(raw: bytes) -> object: body: object = json.loads(raw) if raw.strip() else None except (ValueError, RecursionError): return 0 - return None if body is None else cast("dict[str, Any]", body).get("enabled") if isinstance(body, dict) else 0 + if body is None: + return None + return cast("dict[str, Any]", body).get("enabled") if isinstance(body, dict) else 0 async def _read_capped(request: Request, cap: int) -> bytes | None: diff --git a/src/sharpit/fastapi/capture.py b/src/sharpit/fastapi/capture.py index 9ecb25329..070204040 100644 --- a/src/sharpit/fastapi/capture.py +++ b/src/sharpit/fastapi/capture.py @@ -462,7 +462,7 @@ def _attach(self, target: logging.Logger) -> None: def _attach_non_propagating(self) -> None: """Loggers that never reach root but print somewhere (uvicorn's ``uvicorn`` and ``uvicorn.access``).""" - for name, candidate in list(logging.root.manager.loggerDict.items()): + for name, candidate in list(logging.root.manager.loggerDict.items()): # NOSONAR - snapshot copy own = name == "sharpit" or name.startswith("sharpit.") if isinstance(candidate, logging.Logger) and not candidate.propagate and candidate.handlers and not own: self._attach(candidate) diff --git a/src/sharpit/fastapi/introspector.py b/src/sharpit/fastapi/introspector.py index 154deaebc..ccfd1f394 100644 --- a/src/sharpit/fastapi/introspector.py +++ b/src/sharpit/fastapi/introspector.py @@ -156,7 +156,7 @@ def _resource(obj: object) -> str | None: return None line = _first_line(target) return f"{source}:{line}" if line is not None else source - except Exception: # noqa: BLE001 - no source (built-in, C extension, exec'd): the bean stays, without a resource + except Exception: # noqa: BLE001 # no source (built-in, C extension, exec'd): the bean stays, without a resource return None @@ -229,7 +229,9 @@ def _return_annotation(endpoint: object) -> object | None: raw = inspect.signature(endpoint).return_annotation # pyright: ignore[reportArgumentType] except (TypeError, ValueError): return None - return None if raw is inspect.Signature.empty else type(None) if raw is None else raw + if raw is inspect.Signature.empty: + return None + return type(None) if raw is None else raw def _query_params(dependant: object, depth: int = 0) -> tuple[str, ...]: @@ -428,6 +430,34 @@ def _secured_route( ) +class _ProviderGraph: + """The dependency providers found so far (identity -> object, discovery order) and their direct sub-providers.""" + + def __init__(self) -> None: + self.found: dict[int, tuple[object, Literal["request", "singleton"]]] = {} + self.edges: dict[int, dict[int, None]] = {} # identity -> ordered direct sub-provider identities + + def add(self, obj: object, scope: Literal["request", "singleton"]) -> tuple[int, bool]: + key = id(obj) + new = key not in self.found + if new: + self.found[key] = (obj, scope) + self.edges[key] = {} + return key, new + + def visit(self, dependant: object, owner: int | None, depth: int) -> None: + subs: Any = getattr(dependant, "dependencies", None) or () + for sub in list(subs): # NOSONAR - snapshot: a host thread may add routes while the panel reads + call = getattr(sub, "call", None) + if call is None: + continue + key, new = self.add(call, "request") # registered before the edge, so an edge never dangles + if owner is not None: + self.edges[owner][key] = None + if new and depth < MAX_DEPTH: + self.visit(sub, key, depth + 1) + + class FastApiIntrospector: def __init__(self, app: object, exclude_mount: str | None = None, lifespan: object | None = None) -> None: self.app = app @@ -773,65 +803,52 @@ def _opaque_route(info: RouteInfo, chain: int, limitations: list[str], served: b (), info.path, info.handler, opaque=True, path_regex=_path_regex(info.path, True), chain=chain ) - def providers(self) -> list[ProviderInfo]: - # Read attributes only: no dependency is called, the middleware stack is never built, no OpenAPI schema. - # Beans are dependency providers; route endpoints are mappings, not beans. - found: dict[int, tuple[object, Literal["request", "singleton"]]] = {} # identity -> object, discovery order - edges: dict[int, dict[int, None]] = {} # identity -> ordered direct sub-provider identities - - def add(obj: object, scope: Literal["request", "singleton"]) -> tuple[int, bool]: - key = id(obj) - new = key not in found - if new: - found[key] = (obj, scope) - edges[key] = {} - return key, new - - def visit(dependant: object, owner: int | None, depth: int) -> None: - subs: Any = getattr(dependant, "dependencies", None) or () - for sub in list(subs): - call = getattr(sub, "call", None) - if call is None: - continue - key, new = add(call, "request") # registered before the edge, so an edge never dangles - if owner is not None: - edges[owner][key] = None - if new and depth < MAX_DEPTH: - visit(sub, key, depth + 1) - + def _collect_route_providers(self, graph: _ProviderGraph) -> None: for _, route in self._entries(): try: - visit(_attrs(route).get("dependant") if route is not None else None, None, 0) + graph.visit(_attrs(route).get("dependant") if route is not None else None, None, 0) for dependency in self._included_dependencies_by_route.get(id(route), ()): call = getattr(dependency, "dependency", None) if call is not None: - key, new = add(call, "request") + key, new = graph.add(call, "request") if new: - visit(_dependant_of(call), key, 1) + graph.visit(_dependant_of(call), key, 1) except Exception: # noqa: BLE001,S112 - one odd route must not empty the panel continue + def _collect_override_providers(self, graph: _ProviderGraph) -> dict[int, int]: overridden_by: dict[int, int] = {} overrides: Any = _attrs(self.app).get("dependency_overrides") or {} - for original, override in list(overrides.items()): + for original, override in list(overrides.items()): # NOSONAR - snapshot: a host thread may edit the overrides try: - add(original, "request") - key, new = add(override, "request") + graph.add(original, "request") + key, new = graph.add(override, "request") overridden_by[id(original)] = key if new: - visit(_dependant_of(override), key, 1) + graph.visit(_dependant_of(override), key, 1) except Exception: # noqa: BLE001,S112 continue + return overridden_by + def _collect_singletons(self, graph: _ProviderGraph) -> None: middleware: Any = _attrs(self.app).get("user_middleware") or () - for entry in list(middleware): + for entry in list(middleware): # NOSONAR - snapshot: the middleware list can change while the panel reads cls = getattr(entry, "cls", None) # only the class: args/kwargs (secret keys) are never read if cls is not None and not getattr(cls, "__module__", "").startswith( _OWN_MODULE_PREFIX ): # not sharpit's own - add(cls, "singleton") + graph.add(cls, "singleton") if self.lifespan is not None: - add(self.lifespan, "singleton") + graph.add(self.lifespan, "singleton") + + def providers(self) -> list[ProviderInfo]: + # Read attributes only: no dependency is called, the middleware stack is never built, no OpenAPI schema. + # Beans are dependency providers; route endpoints are mappings, not beans. + graph = _ProviderGraph() + self._collect_route_providers(graph) + overridden_by = self._collect_override_providers(graph) + self._collect_singletons(graph) + found, edges = graph.found, graph.edges names: dict[int, str] = {} seen: dict[str, int] = {} diff --git a/tests/complexity_baseline.json b/tests/complexity_baseline.json index 835e19d91..53412397d 100644 --- a/tests/complexity_baseline.json +++ b/tests/complexity_baseline.json @@ -1,16 +1,16 @@ { "examples/fastapi_sqla/app.py": 1, "src/sharpit/engine/activation.py": 1, - "src/sharpit/engine/capture/activity.py": 1, + "src/sharpit/engine/capture/activity.py": 0, "src/sharpit/engine/collectors/alembic.py": 2, "src/sharpit/engine/collectors/config/settings_source.py": 1, "src/sharpit/engine/mcp.py": 0, - "src/sharpit/engine/probe.py": 2, + "src/sharpit/engine/probe.py": 1, "src/sharpit/engine/tools.py": 0, "src/sharpit/fastapi/adapter.py": 0, "src/sharpit/fastapi/capture.py": 1, "src/sharpit/fastapi/capture_exceptions.py": 0, - "src/sharpit/fastapi/introspector.py": 1, + "src/sharpit/fastapi/introspector.py": 0, "src/sharpit/settings.py": 2, "tests/test_masking_corpus.py": 1 }