fastapi-radar 0.1.6__py3-none-any.whl → 0.3.1__py3-none-any.whl

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.
@@ -4,8 +4,8 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>FastAPI Radar - Debugging Dashboard</title>
7
- <script type="module" crossorigin src="/__radar/assets/index-BJa0l2JD.js"></script>
8
- <link rel="stylesheet" crossorigin href="/__radar/assets/index-DCxkDBhr.css">
7
+ <script type="module" crossorigin src="/__radar/assets/index-8Om0PGu6.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/__radar/assets/index-XlGcZj49.css">
9
9
  </head>
10
10
  <body>
11
11
  <div id="root"></div>
@@ -0,0 +1,149 @@
1
+ # ISC License
2
+ #
3
+ # Copyright (c) 2018-2025, Andrea Giammarchi, @WebReflection
4
+ #
5
+ # Permission to use, copy, modify, and/or distribute this software for any
6
+ # purpose with or without fee is hereby granted, provided that the above
7
+ # copyright notice and this permission notice appear in all copies.
8
+ #
9
+ # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ # AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14
+ # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ # PERFORMANCE OF THIS SOFTWARE.
16
+
17
+ import json as _json
18
+
19
+ class _Known:
20
+ def __init__(self):
21
+ self.key = []
22
+ self.value = []
23
+
24
+ class _String:
25
+ def __init__(self, value):
26
+ self.value = value
27
+
28
+
29
+ def _array_keys(value):
30
+ keys = []
31
+ i = 0
32
+ for _ in value:
33
+ keys.append(i)
34
+ i += 1
35
+ return keys
36
+
37
+ def _object_keys(value):
38
+ keys = []
39
+ for key in value:
40
+ keys.append(key)
41
+ return keys
42
+
43
+ def _is_array(value):
44
+ return isinstance(value, (list, tuple))
45
+
46
+ def _is_object(value):
47
+ return isinstance(value, dict)
48
+
49
+ def _is_string(value):
50
+ return isinstance(value, str)
51
+
52
+ def _index(known, input, value):
53
+ input.append(value)
54
+ index = str(len(input) - 1)
55
+ known.key.append(value)
56
+ known.value.append(index)
57
+ return index
58
+
59
+ def _loop(keys, input, known, output):
60
+ for key in keys:
61
+ value = output[key]
62
+ if isinstance(value, _String):
63
+ _ref(key, input[int(value.value)], input, known, output)
64
+
65
+ return output
66
+
67
+ def _ref(key, value, input, known, output):
68
+ if _is_array(value) and value not in known:
69
+ known.append(value)
70
+ value = _loop(_array_keys(value), input, known, value)
71
+ elif _is_object(value) and value not in known:
72
+ known.append(value)
73
+ value = _loop(_object_keys(value), input, known, value)
74
+
75
+ output[key] = value
76
+
77
+ def _relate(known, input, value):
78
+ if _is_string(value) or _is_array(value) or _is_object(value):
79
+ try:
80
+ return known.value[known.key.index(value)]
81
+ except:
82
+ return _index(known, input, value)
83
+
84
+ return value
85
+
86
+ def _transform(known, input, value):
87
+ if _is_array(value):
88
+ output = []
89
+ for val in value:
90
+ output.append(_relate(known, input, val))
91
+ return output
92
+
93
+ if _is_object(value):
94
+ obj = {}
95
+ for key in value:
96
+ obj[key] = _relate(known, input, value[key])
97
+ return obj
98
+
99
+ return value
100
+
101
+ def _wrap(value):
102
+ if _is_string(value):
103
+ return _String(value)
104
+
105
+ if _is_array(value):
106
+ i = 0
107
+ for val in value:
108
+ value[i] = _wrap(val)
109
+ i += 1
110
+
111
+ elif _is_object(value):
112
+ for key in value:
113
+ value[key] = _wrap(value[key])
114
+
115
+ return value
116
+
117
+ def parse(value, *args, **kwargs):
118
+ json = _json.loads(value, *args, **kwargs)
119
+ wrapped = []
120
+ for value in json:
121
+ wrapped.append(_wrap(value))
122
+
123
+ input = []
124
+ for value in wrapped:
125
+ if isinstance(value, _String):
126
+ input.append(value.value)
127
+ else:
128
+ input.append(value)
129
+
130
+ value = input[0]
131
+
132
+ if _is_array(value):
133
+ return _loop(_array_keys(value), input, [value], value)
134
+
135
+ if _is_object(value):
136
+ return _loop(_object_keys(value), input, [value], value)
137
+
138
+ return value
139
+
140
+
141
+ def stringify(value, *args, **kwargs):
142
+ known = _Known()
143
+ input = []
144
+ output = []
145
+ i = int(_index(known, input, value))
146
+ while i < len(input):
147
+ output.append(_transform(known, input, input[i]))
148
+ i += 1
149
+ return _json.dumps(output, *args, **kwargs)
@@ -4,13 +4,27 @@ import json
4
4
  import time
5
5
  import traceback
6
6
  import uuid
7
- from typing import Optional, Callable
8
7
  from contextvars import ContextVar
8
+ from typing import Callable, Optional
9
+
10
+ from sqlalchemy.exc import SQLAlchemyError
9
11
  from starlette.middleware.base import BaseHTTPMiddleware
10
12
  from starlette.requests import Request
11
13
  from starlette.responses import Response, StreamingResponse
14
+
12
15
  from .models import CapturedRequest, CapturedException
13
- from .utils import serialize_headers, get_client_ip, truncate_body
16
+ from .utils import (
17
+ serialize_headers,
18
+ get_client_ip,
19
+ truncate_body,
20
+ redact_sensitive_data,
21
+ )
22
+ from .tracing import (
23
+ TraceContext,
24
+ TracingManager,
25
+ create_trace_context,
26
+ set_trace_context,
27
+ )
14
28
 
15
29
  request_context: ContextVar[Optional[str]] = ContextVar("request_id", default=None)
16
30
 
@@ -23,12 +37,17 @@ class RadarMiddleware(BaseHTTPMiddleware):
23
37
  exclude_paths: list[str] = None,
24
38
  max_body_size: int = 10000,
25
39
  capture_response_body: bool = True,
40
+ enable_tracing: bool = True,
41
+ service_name: str = "fastapi-app",
26
42
  ):
27
43
  super().__init__(app)
28
44
  self.get_session = get_session
29
45
  self.exclude_paths = exclude_paths or []
30
46
  self.max_body_size = max_body_size
31
47
  self.capture_response_body = capture_response_body
48
+ self.enable_tracing = enable_tracing
49
+ self.service_name = service_name
50
+ self.tracing_manager = TracingManager(get_session) if enable_tracing else None
32
51
 
33
52
  async def dispatch(self, request: Request, call_next) -> Response:
34
53
  if self._should_skip(request):
@@ -38,6 +57,43 @@ class RadarMiddleware(BaseHTTPMiddleware):
38
57
  request_context.set(request_id)
39
58
  start_time = time.time()
40
59
 
60
+ # Create tracing context for this request
61
+ trace_ctx = None
62
+ root_span_id = None
63
+
64
+ if self.enable_tracing and self.tracing_manager:
65
+ existing_trace_id = request.headers.get("x-trace-id")
66
+ parent_span_id = request.headers.get("x-parent-span-id")
67
+
68
+ if existing_trace_id:
69
+ # Child span for existing trace
70
+ trace_ctx = TraceContext(existing_trace_id, self.service_name)
71
+ else:
72
+ # Create a new trace
73
+ trace_ctx = create_trace_context(self.service_name)
74
+
75
+ # Set tracing context
76
+ set_trace_context(trace_ctx)
77
+
78
+ # Create root span
79
+ root_span_id = trace_ctx.create_span(
80
+ operation_name=f"{request.method} {request.url.path}",
81
+ parent_span_id=parent_span_id,
82
+ span_kind="server",
83
+ tags={
84
+ "http.method": request.method,
85
+ "http.url": str(request.url),
86
+ "http.path": request.url.path,
87
+ "http.query": (
88
+ str(request.query_params) if request.query_params else None
89
+ ),
90
+ "user_agent": request.headers.get("user-agent"),
91
+ "request_id": request_id,
92
+ },
93
+ )
94
+
95
+ trace_ctx.set_current_span(root_span_id)
96
+
41
97
  request_body = await self._get_request_body(request)
42
98
 
43
99
  captured_request = CapturedRequest(
@@ -48,7 +104,7 @@ class RadarMiddleware(BaseHTTPMiddleware):
48
104
  query_params=dict(request.query_params) if request.query_params else None,
49
105
  headers=serialize_headers(request.headers),
50
106
  body=(
51
- truncate_body(request_body, self.max_body_size)
107
+ redact_sensitive_data(truncate_body(request_body, self.max_body_size))
52
108
  if request_body
53
109
  else None
54
110
  ),
@@ -59,24 +115,39 @@ class RadarMiddleware(BaseHTTPMiddleware):
59
115
  exception_occurred = False
60
116
 
61
117
  try:
62
- response = await call_next(request)
118
+ response = original_response = await call_next(request)
63
119
 
64
120
  captured_request.status_code = response.status_code
65
121
  captured_request.response_headers = serialize_headers(response.headers)
66
122
 
67
- if self.capture_response_body and not isinstance(
68
- response, StreamingResponse
69
- ):
70
- response_body = b""
71
- async for chunk in response.body_iterator:
72
- response_body += chunk
73
-
74
- captured_request.response_body = truncate_body(
75
- response_body.decode("utf-8", errors="ignore"), self.max_body_size
76
- )
77
-
78
- response = Response(
79
- content=response_body,
123
+ if self.capture_response_body:
124
+
125
+ async def capture_response():
126
+ response_body = ""
127
+ capturing = True
128
+ async for chunk in original_response.body_iterator:
129
+ yield chunk
130
+ if capturing:
131
+ response_body += chunk.decode("utf-8", errors="ignore")
132
+ try:
133
+ with self.get_session() as session:
134
+ captured_request.response_body = (
135
+ redact_sensitive_data(
136
+ truncate_body(
137
+ response_body, self.max_body_size
138
+ )
139
+ )
140
+ )
141
+ session.add(captured_request)
142
+ session.commit()
143
+ except SQLAlchemyError:
144
+ # CapturedRequest record has been deleted.
145
+ capturing = False
146
+ else:
147
+ capturing = len(response_body) < self.max_body_size
148
+
149
+ response = StreamingResponse(
150
+ content=capture_response(),
80
151
  status_code=response.status_code,
81
152
  headers=dict(response.headers),
82
153
  media_type=response.media_type,
@@ -85,18 +156,45 @@ class RadarMiddleware(BaseHTTPMiddleware):
85
156
  except Exception as e:
86
157
  exception_occurred = True
87
158
  self._capture_exception(request_id, e)
159
+
160
+ # Record exception in span
161
+ if trace_ctx and root_span_id:
162
+ trace_ctx.add_span_log(
163
+ root_span_id,
164
+ f"Exception occurred: {str(e)}",
165
+ level="error",
166
+ exception_type=type(e).__name__,
167
+ )
168
+
88
169
  raise
89
170
 
90
171
  finally:
91
172
  duration = round((time.time() - start_time) * 1000, 2)
92
173
  captured_request.duration_ms = duration
93
174
 
175
+ # Finish span tracking
176
+ if trace_ctx and root_span_id:
177
+ status = "error" if exception_occurred else "ok"
178
+ trace_ctx.finish_span(
179
+ root_span_id,
180
+ status=status,
181
+ tags={
182
+ "http.status_code": response.status_code if response else None,
183
+ "duration_ms": duration,
184
+ },
185
+ )
186
+
94
187
  with self.get_session() as session:
95
188
  session.add(captured_request)
96
189
  if exception_occurred:
97
190
  exception_data = self._get_exception_data(request_id)
98
191
  if exception_data:
99
192
  session.add(exception_data)
193
+
194
+ # Persist trace data
195
+ if trace_ctx and self.tracing_manager:
196
+ self.tracing_manager.save_trace_context(trace_ctx)
197
+
100
198
  session.commit()
101
199
 
102
200
  request_context.set(None)
fastapi_radar/models.py CHANGED
@@ -1,9 +1,23 @@
1
1
  """Storage models for FastAPI Radar."""
2
2
 
3
- from datetime import datetime
4
- from sqlalchemy import Column, String, Integer, Float, Text, DateTime, ForeignKey, JSON
5
- from sqlalchemy.ext.declarative import declarative_base
6
- from sqlalchemy.orm import relationship
3
+ from datetime import datetime, timezone
4
+
5
+ from sqlalchemy import (
6
+ Column,
7
+ String,
8
+ Integer,
9
+ Float,
10
+ Text,
11
+ DateTime,
12
+ JSON,
13
+ Sequence,
14
+ )
15
+
16
+ try:
17
+ from sqlalchemy.orm import declarative_base
18
+ except ImportError:
19
+ from sqlalchemy.ext.declarative import declarative_base
20
+ from sqlalchemy.orm import relationship, foreign # noqa: F401
7
21
 
8
22
  Base = declarative_base()
9
23
 
@@ -11,7 +25,9 @@ Base = declarative_base()
11
25
  class CapturedRequest(Base):
12
26
  __tablename__ = "radar_requests"
13
27
 
14
- id = Column(Integer, primary_key=True, index=True)
28
+ id = Column(
29
+ Integer, Sequence("radar_requests_id_seq"), primary_key=True, index=True
30
+ )
15
31
  request_id = Column(String(36), unique=True, index=True, nullable=False)
16
32
  method = Column(String(10), nullable=False)
17
33
  url = Column(String(500), nullable=False)
@@ -24,43 +40,151 @@ class CapturedRequest(Base):
24
40
  response_headers = Column(JSON)
25
41
  duration_ms = Column(Float)
26
42
  client_ip = Column(String(50))
27
- created_at = Column(DateTime, default=datetime.utcnow, index=True)
43
+ created_at = Column(
44
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
45
+ )
28
46
 
29
47
  queries = relationship(
30
- "CapturedQuery", back_populates="request", cascade="all, delete-orphan"
48
+ "CapturedQuery",
49
+ back_populates="request",
50
+ primaryjoin="CapturedRequest.request_id == foreign(CapturedQuery.request_id)",
51
+ cascade="all, delete-orphan",
31
52
  )
32
53
  exceptions = relationship(
33
- "CapturedException", back_populates="request", cascade="all, delete-orphan"
54
+ "CapturedException",
55
+ back_populates="request",
56
+ primaryjoin=(
57
+ "CapturedRequest.request_id == foreign(CapturedException.request_id)"
58
+ ),
59
+ cascade="all, delete-orphan",
34
60
  )
35
61
 
36
62
 
37
63
  class CapturedQuery(Base):
38
64
  __tablename__ = "radar_queries"
39
65
 
40
- id = Column(Integer, primary_key=True, index=True)
41
- request_id = Column(
42
- String(36), ForeignKey("radar_requests.request_id", ondelete="CASCADE")
43
- )
66
+ id = Column(Integer, Sequence("radar_queries_id_seq"), primary_key=True, index=True)
67
+ request_id = Column(String(36), index=True)
44
68
  sql = Column(Text, nullable=False)
45
69
  parameters = Column(JSON)
46
70
  duration_ms = Column(Float)
47
71
  rows_affected = Column(Integer)
48
72
  connection_name = Column(String(100))
49
- created_at = Column(DateTime, default=datetime.utcnow, index=True)
73
+ created_at = Column(
74
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
75
+ )
50
76
 
51
- request = relationship("CapturedRequest", back_populates="queries")
77
+ request = relationship(
78
+ "CapturedRequest",
79
+ back_populates="queries",
80
+ primaryjoin="foreign(CapturedQuery.request_id) == CapturedRequest.request_id",
81
+ )
52
82
 
53
83
 
54
84
  class CapturedException(Base):
55
85
  __tablename__ = "radar_exceptions"
56
86
 
57
- id = Column(Integer, primary_key=True, index=True)
58
- request_id = Column(
59
- String(36), ForeignKey("radar_requests.request_id", ondelete="CASCADE")
87
+ id = Column(
88
+ Integer, Sequence("radar_exceptions_id_seq"), primary_key=True, index=True
60
89
  )
90
+ request_id = Column(String(36), index=True)
61
91
  exception_type = Column(String(100), nullable=False)
62
92
  exception_value = Column(Text)
63
93
  traceback = Column(Text, nullable=False)
64
- created_at = Column(DateTime, default=datetime.utcnow, index=True)
94
+ created_at = Column(
95
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
96
+ )
97
+
98
+ request = relationship(
99
+ "CapturedRequest",
100
+ back_populates="exceptions",
101
+ primaryjoin=(
102
+ "foreign(CapturedException.request_id) == CapturedRequest.request_id"
103
+ ),
104
+ )
105
+
106
+
107
+ class Trace(Base):
108
+ __tablename__ = "radar_traces"
109
+
110
+ trace_id = Column(String(32), primary_key=True, index=True)
111
+ service_name = Column(String(100), index=True)
112
+ operation_name = Column(String(200))
113
+ start_time = Column(
114
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
115
+ )
116
+ end_time = Column(DateTime)
117
+ duration_ms = Column(Float)
118
+ span_count = Column(Integer, default=0)
119
+ status = Column(String(20), default="ok")
120
+ tags = Column(JSON)
121
+ created_at = Column(
122
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
123
+ )
124
+
125
+ spans = relationship(
126
+ "Span",
127
+ back_populates="trace",
128
+ primaryjoin="Trace.trace_id == foreign(Span.trace_id)",
129
+ cascade="all, delete-orphan",
130
+ )
131
+
132
+
133
+ class Span(Base):
134
+ __tablename__ = "radar_spans"
135
+
136
+ span_id = Column(String(16), primary_key=True, index=True)
137
+ trace_id = Column(String(32), index=True)
138
+ parent_span_id = Column(String(16), index=True, nullable=True)
139
+ operation_name = Column(String(200), nullable=False)
140
+ service_name = Column(String(100), index=True)
141
+ span_kind = Column(String(20), default="server")
142
+ start_time = Column(DateTime, nullable=False, index=True)
143
+ end_time = Column(DateTime)
144
+ duration_ms = Column(Float)
145
+ status = Column(String(20), default="ok")
146
+ tags = Column(JSON)
147
+ logs = Column(JSON)
148
+ created_at = Column(
149
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
150
+ )
151
+
152
+ trace = relationship(
153
+ "Trace",
154
+ back_populates="spans",
155
+ primaryjoin="foreign(Span.trace_id) == Trace.trace_id",
156
+ )
157
+
65
158
 
66
- request = relationship("CapturedRequest", back_populates="exceptions")
159
+ class SpanRelation(Base):
160
+ __tablename__ = "radar_span_relations"
161
+
162
+ id = Column(
163
+ Integer, Sequence("radar_span_relations_id_seq"), primary_key=True, index=True
164
+ )
165
+ trace_id = Column(String(32), index=True)
166
+ parent_span_id = Column(String(16), index=True)
167
+ child_span_id = Column(String(16), index=True)
168
+ depth = Column(Integer, default=0)
169
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
170
+
171
+
172
+ class BackgroundTask(Base):
173
+ __tablename__ = "radar_background_tasks"
174
+
175
+ id = Column(
176
+ Integer, Sequence("radar_background_tasks_id_seq"), primary_key=True, index=True
177
+ )
178
+ task_id = Column(String(36), unique=True, index=True, nullable=False)
179
+ request_id = Column(String(36), index=True, nullable=True)
180
+ name = Column(String(200), nullable=False)
181
+ status = Column(
182
+ String(20), default="pending", index=True
183
+ ) # pending, running, completed, failed
184
+ start_time = Column(DateTime, index=True)
185
+ end_time = Column(DateTime)
186
+ duration_ms = Column(Float)
187
+ error = Column(Text)
188
+ created_at = Column(
189
+ DateTime, default=lambda: datetime.now(timezone.utc), index=True
190
+ )