devdoor 0.1.0__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.
devdoor/core/events.py ADDED
@@ -0,0 +1,287 @@
1
+ """Non-blocking traffic capture event bus with bounded body previews and redaction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import base64
7
+ import itertools
8
+ import time
9
+ import uuid
10
+ from collections.abc import Sequence
11
+ from typing import Literal, cast
12
+
13
+ from pydantic import BaseModel, ConfigDict, computed_field
14
+
15
+ from devdoor.core.config import LogMode
16
+
17
+ MAX_BODY_CAPTURE_BYTES = 1_048_576
18
+ DEFAULT_SUBSCRIBER_QUEUE_SIZE = 256
19
+
20
+ TrafficSource = Literal["local", "tunnel"]
21
+
22
+ SENSITIVE_HEADER_NAMES: frozenset[str] = frozenset(
23
+ {
24
+ "authorization",
25
+ "proxy-authorization",
26
+ "cookie",
27
+ "set-cookie",
28
+ "x-api-key",
29
+ }
30
+ )
31
+
32
+
33
+ class BodyTapBuffer:
34
+ """Bounded in-memory byte tap that caps captured body previews at ``max_bytes``."""
35
+
36
+ def __init__(self, *, max_bytes: int = MAX_BODY_CAPTURE_BYTES) -> None:
37
+ self._max_bytes = max_bytes
38
+ self._buffer = bytearray()
39
+ self._truncated = False
40
+
41
+ def write(self, chunk: bytes) -> None:
42
+ """Tee ``chunk`` into the bounded preview without buffering excess bytes."""
43
+ if not chunk or self._truncated:
44
+ if chunk:
45
+ self._truncated = True
46
+ return
47
+
48
+ remaining = self._max_bytes - len(self._buffer)
49
+ if remaining <= 0:
50
+ self._truncated = True
51
+ return
52
+
53
+ if len(chunk) > remaining:
54
+ self._buffer.extend(chunk[:remaining])
55
+ self._truncated = True
56
+ else:
57
+ self._buffer.extend(chunk)
58
+
59
+ def snapshot(self) -> tuple[bytes, bool]:
60
+ """Return ``(preview_bytes, truncated)``."""
61
+ return bytes(self._buffer), self._truncated
62
+
63
+
64
+ def redact_headers(
65
+ headers: Sequence[tuple[str, str]],
66
+ *,
67
+ include_secrets: bool = False,
68
+ ) -> tuple[tuple[str, str], ...]:
69
+ """Mask sensitive authentication and cookie headers unless ``include_secrets`` is set."""
70
+ if include_secrets:
71
+ return tuple((name, value) for name, value in headers)
72
+ return tuple(
73
+ (name, "[REDACTED]" if name.lower() in SENSITIVE_HEADER_NAMES else value)
74
+ for name, value in headers
75
+ )
76
+
77
+
78
+ _EXCHANGE_COUNTER = itertools.count(1)
79
+
80
+
81
+ def coerce_traffic_source(raw: object) -> TrafficSource:
82
+ """Coerce serialized source strings to a valid ``TrafficSource``."""
83
+ return "tunnel" if str(raw) == "tunnel" else "local"
84
+
85
+
86
+ def coerce_log_mode(raw: object) -> LogMode:
87
+ """Coerce serialized log-mode strings to a valid ``LogMode``."""
88
+ mode = str(raw)
89
+ if mode == "minimal":
90
+ return "minimal"
91
+ if mode == "off":
92
+ return "off"
93
+ return "full"
94
+
95
+
96
+ def coerce_header_pairs(raw: object) -> tuple[tuple[str, str], ...]:
97
+ """Decode JSON-serialized ``[[name, value], ...]`` header lists into immutable tuples."""
98
+ if not isinstance(raw, list):
99
+ return ()
100
+ out: list[tuple[str, str]] = []
101
+ for entry in cast(list[object], raw):
102
+ if isinstance(entry, (list, tuple)):
103
+ seq = cast(list[object] | tuple[object, ...], entry)
104
+ if len(seq) == 2:
105
+ out.append((str(seq[0]), str(seq[1])))
106
+ return tuple(out)
107
+
108
+
109
+ def _new_exchange_id(created_at_ms: int) -> str:
110
+ return f"{created_at_ms:013x}-{next(_EXCHANGE_COUNTER):08x}-{uuid.uuid4().hex[:6]}"
111
+
112
+
113
+ class CapturedExchange(BaseModel):
114
+ """Immutable snapshot of a single proxied HTTP or WebSocket exchange."""
115
+
116
+ model_config = ConfigDict(frozen=True)
117
+
118
+ id: str
119
+ created_at_ms: int
120
+ source: TrafficSource
121
+ host: str
122
+ method: str
123
+ path: str
124
+ target_port: int
125
+ status: int
126
+ duration_ms: float
127
+ req_headers: tuple[tuple[str, str], ...] = ()
128
+ resp_headers: tuple[tuple[str, str], ...] = ()
129
+ req_body_preview: bytes = b""
130
+ resp_body_preview: bytes = b""
131
+ req_body_truncated: bool = False
132
+ resp_body_truncated: bool = False
133
+ log_mode: LogMode = "full"
134
+ replayed_from_id: str | None = None
135
+
136
+ @computed_field
137
+ @property
138
+ def body_truncated(self) -> bool:
139
+ """Return whether either captured request or response preview was truncated."""
140
+ return self.req_body_truncated or self.resp_body_truncated
141
+
142
+ def to_event_dict(self) -> dict[str, object]:
143
+ """Serialize exchange metadata cleanly for control-plane WebSocket events."""
144
+ return {
145
+ "id": self.id,
146
+ "created_at_ms": self.created_at_ms,
147
+ "source": self.source,
148
+ "host": self.host,
149
+ "method": self.method,
150
+ "path": self.path,
151
+ "target_port": self.target_port,
152
+ "status": self.status,
153
+ "duration_ms": round(self.duration_ms, 2),
154
+ "req_headers": [[k, v] for k, v in self.req_headers],
155
+ "resp_headers": [[k, v] for k, v in self.resp_headers],
156
+ "req_body_b64": base64.b64encode(self.req_body_preview).decode("ascii"),
157
+ "resp_body_b64": base64.b64encode(self.resp_body_preview).decode("ascii"),
158
+ "req_body_truncated": self.req_body_truncated,
159
+ "resp_body_truncated": self.resp_body_truncated,
160
+ "body_truncated": self.body_truncated,
161
+ "log_mode": self.log_mode,
162
+ "replayed_from_id": self.replayed_from_id,
163
+ }
164
+
165
+ @classmethod
166
+ def from_event_dict(cls, raw: dict[str, object]) -> CapturedExchange:
167
+ """Deserialize a control-plane JSON dict back into ``CapturedExchange``."""
168
+
169
+ def _b64(val: object) -> bytes:
170
+ if not isinstance(val, str) or not val:
171
+ return b""
172
+ return base64.b64decode(val.encode("ascii"))
173
+
174
+ rep = raw.get("replayed_from_id")
175
+ return cls(
176
+ id=str(raw.get("id", "")),
177
+ created_at_ms=int(cast(int, raw.get("created_at_ms", 0))),
178
+ source=coerce_traffic_source(raw.get("source", "local")),
179
+ host=str(raw.get("host", "")),
180
+ method=str(raw.get("method", "GET")),
181
+ path=str(raw.get("path", "/")),
182
+ target_port=int(cast(int, raw.get("target_port", 0))),
183
+ status=int(cast(int, raw.get("status", 0))),
184
+ duration_ms=float(cast(float, raw.get("duration_ms", 0.0))),
185
+ req_headers=coerce_header_pairs(raw.get("req_headers")),
186
+ resp_headers=coerce_header_pairs(raw.get("resp_headers")),
187
+ req_body_preview=_b64(raw.get("req_body_b64")),
188
+ resp_body_preview=_b64(raw.get("resp_body_b64")),
189
+ req_body_truncated=bool(raw.get("req_body_truncated", False)),
190
+ resp_body_truncated=bool(raw.get("resp_body_truncated", False)),
191
+ log_mode=coerce_log_mode(raw.get("log_mode", "full")),
192
+ replayed_from_id=str(rep) if rep is not None else None,
193
+ )
194
+
195
+
196
+ def format_access_log(exchange: CapturedExchange) -> str | None:
197
+ """Format an access log line obeying ``exchange.log_mode``."""
198
+ if exchange.log_mode == "off":
199
+ return None
200
+ if exchange.log_mode == "minimal":
201
+ return (
202
+ f"[{exchange.source}] {exchange.host} "
203
+ f"-> {exchange.status} ({exchange.duration_ms:.1f}ms)"
204
+ )
205
+ return (
206
+ f"[{exchange.source}] {exchange.method} {exchange.host}{exchange.path} "
207
+ f"-> 127.0.0.1:{exchange.target_port} [{exchange.status}] ({exchange.duration_ms:.1f}ms)"
208
+ )
209
+
210
+
211
+ class TrafficEventBus:
212
+ """Non-blocking fan-out bus dropping oldest events on slow subscribers."""
213
+
214
+ def __init__(self) -> None:
215
+ self._subscribers: set[asyncio.Queue[CapturedExchange]] = set()
216
+ self.dropped_count = 0
217
+
218
+ def subscribe(
219
+ self,
220
+ *,
221
+ maxsize: int = DEFAULT_SUBSCRIBER_QUEUE_SIZE,
222
+ ) -> asyncio.Queue[CapturedExchange]:
223
+ """Register a bounded subscriber queue and return it."""
224
+ queue: asyncio.Queue[CapturedExchange] = asyncio.Queue(maxsize=maxsize)
225
+ self._subscribers.add(queue)
226
+ return queue
227
+
228
+ def unsubscribe(self, queue: asyncio.Queue[CapturedExchange]) -> None:
229
+ """Detach a subscriber queue."""
230
+ self._subscribers.discard(queue)
231
+
232
+ def publish(self, exchange: CapturedExchange) -> None:
233
+ """Broadcast ``exchange`` to all active subscribers without blocking callers."""
234
+ for queue in tuple(self._subscribers):
235
+ if queue.full():
236
+ try:
237
+ queue.get_nowait()
238
+ self.dropped_count += 1
239
+ except asyncio.QueueEmpty:
240
+ pass
241
+ try:
242
+ queue.put_nowait(exchange)
243
+ except asyncio.QueueFull:
244
+ self.dropped_count += 1
245
+
246
+ def emit_exchange(
247
+ self,
248
+ *,
249
+ source: TrafficSource,
250
+ host: str,
251
+ method: str,
252
+ path: str,
253
+ target_port: int,
254
+ status: int,
255
+ duration_ms: float,
256
+ req_headers: Sequence[tuple[str, str]] = (),
257
+ resp_headers: Sequence[tuple[str, str]] = (),
258
+ req_body_preview: bytes = b"",
259
+ resp_body_preview: bytes = b"",
260
+ req_body_truncated: bool = False,
261
+ resp_body_truncated: bool = False,
262
+ log_mode: LogMode = "full",
263
+ replayed_from_id: str | None = None,
264
+ ) -> CapturedExchange:
265
+ """Construct, publish, and return a ``CapturedExchange``."""
266
+ created_at_ms = int(time.time() * 1000)
267
+ exchange = CapturedExchange(
268
+ id=_new_exchange_id(created_at_ms),
269
+ created_at_ms=created_at_ms,
270
+ source=source,
271
+ host=host,
272
+ method=method,
273
+ path=path,
274
+ target_port=target_port,
275
+ status=status,
276
+ duration_ms=duration_ms,
277
+ req_headers=tuple(req_headers),
278
+ resp_headers=tuple(resp_headers),
279
+ req_body_preview=req_body_preview,
280
+ resp_body_preview=resp_body_preview,
281
+ req_body_truncated=req_body_truncated,
282
+ resp_body_truncated=resp_body_truncated,
283
+ log_mode=log_mode,
284
+ replayed_from_id=replayed_from_id,
285
+ )
286
+ self.publish(exchange)
287
+ return exchange