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.
@@ -0,0 +1,209 @@
1
+ """CLI commands for inspecting stored traffic logs (``devdoor logs``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ from collections.abc import Callable
9
+ from typing import Annotated, cast
10
+
11
+ import aiohttp
12
+ import typer
13
+
14
+ from devdoor.core.config import DevDoorPaths, resolve_paths
15
+ from devdoor.core.engine import is_process_alive, load_daemon_state
16
+ from devdoor.core.events import CapturedExchange, format_access_log
17
+ from devdoor.core.router import normalize_host
18
+ from devdoor.inspector.store import InspectorStore
19
+ from devdoor.tui.inspector_app import run_inspect_tui
20
+
21
+
22
+ async def _follow_via_daemon_ws(
23
+ *,
24
+ ws_url: str,
25
+ token: str,
26
+ normalized_domain: str | None,
27
+ stop_event: asyncio.Event | None,
28
+ output_fn: Callable[[str], None],
29
+ ) -> None:
30
+ timeout = aiohttp.ClientTimeout(total=None, connect=5.0, sock_read=None)
31
+ async with (
32
+ aiohttp.ClientSession(timeout=timeout) as session,
33
+ session.ws_connect(
34
+ ws_url,
35
+ headers={"Authorization": f"Bearer {token}"},
36
+ ) as ws,
37
+ ):
38
+ while stop_event is None or not stop_event.is_set():
39
+ recv_task = asyncio.create_task(ws.receive())
40
+ waiters: set[asyncio.Task[object]] = {cast(asyncio.Task[object], recv_task)}
41
+ stop_task: asyncio.Task[bool] | None = None
42
+ if stop_event is not None:
43
+ stop_task = asyncio.create_task(stop_event.wait())
44
+ waiters.add(cast(asyncio.Task[object], stop_task))
45
+
46
+ try:
47
+ done, _ = await asyncio.wait(waiters, return_when=asyncio.FIRST_COMPLETED)
48
+ finally:
49
+ for pending in waiters:
50
+ if not pending.done():
51
+ pending.cancel()
52
+ with contextlib.suppress(asyncio.CancelledError):
53
+ await pending
54
+ if stop_task is not None and stop_task in done:
55
+ return
56
+
57
+ msg = recv_task.result()
58
+ if msg.type == aiohttp.WSMsgType.TEXT:
59
+ raw: object = json.loads(msg.data)
60
+ if isinstance(raw, dict):
61
+ mapping = {str(k): v for k, v in cast(dict[object, object], raw).items()}
62
+ exchange = CapturedExchange.from_event_dict(mapping)
63
+ if normalized_domain and normalize_host(exchange.host) != normalized_domain:
64
+ continue
65
+ line = format_access_log(exchange)
66
+ if line is not None:
67
+ output_fn(line)
68
+ elif msg.type in {
69
+ aiohttp.WSMsgType.CLOSE,
70
+ aiohttp.WSMsgType.CLOSING,
71
+ aiohttp.WSMsgType.CLOSED,
72
+ }:
73
+ return
74
+
75
+
76
+ async def follow_logs(
77
+ *,
78
+ domain: str | None = None,
79
+ paths: DevDoorPaths | None = None,
80
+ stop_event: asyncio.Event | None = None,
81
+ output_fn: Callable[[str], None] = typer.echo,
82
+ poll_interval: float = 0.25,
83
+ ) -> None:
84
+ """Stream live formatted access logs from daemon WS events or SQLite WAL polling."""
85
+ resolved = paths or resolve_paths()
86
+ normalized_domain = normalize_host(domain) if domain else None
87
+
88
+ state = load_daemon_state(resolved)
89
+ if state is not None and is_process_alive(state.pid):
90
+ ws_url = state.control_url.replace("http://", "ws://") + "/_control/events"
91
+ try:
92
+ await _follow_via_daemon_ws(
93
+ ws_url=ws_url,
94
+ token=state.token,
95
+ normalized_domain=normalized_domain,
96
+ stop_event=stop_event,
97
+ output_fn=output_fn,
98
+ )
99
+ return
100
+ except aiohttp.ClientError, TimeoutError, OSError:
101
+ pass
102
+
103
+ seen_ids: set[str] = set()
104
+ async with InspectorStore(paths=resolved) as store:
105
+ for initial in await store.list_exchanges(limit=50, host=normalized_domain):
106
+ seen_ids.add(initial.id)
107
+ while stop_event is None or not stop_event.is_set():
108
+ rows = await store.list_exchanges(limit=50, host=normalized_domain)
109
+ for item in reversed(rows):
110
+ if item.id not in seen_ids:
111
+ seen_ids.add(item.id)
112
+ line = format_access_log(item)
113
+ if line is not None:
114
+ output_fn(line)
115
+ if stop_event is not None:
116
+ try:
117
+ await asyncio.wait_for(stop_event.wait(), timeout=poll_interval)
118
+ return
119
+ except TimeoutError:
120
+ continue
121
+ await asyncio.sleep(poll_interval)
122
+
123
+
124
+ def logs_command(
125
+ domain: Annotated[
126
+ str | None,
127
+ typer.Argument(help="Optional domain filter."),
128
+ ] = None,
129
+ follow: Annotated[
130
+ bool,
131
+ typer.Option("--follow", "-f", help="Follow live traffic events as they arrive."),
132
+ ] = False,
133
+ flush: Annotated[
134
+ bool,
135
+ typer.Option("--flush", help="Delete all stored traffic logs from inspector.db."),
136
+ ] = False,
137
+ yes: Annotated[
138
+ bool,
139
+ typer.Option("--yes", "-y", help="Skip confirmation prompt for --flush."),
140
+ ] = False,
141
+ limit: Annotated[
142
+ int,
143
+ typer.Option("--limit", "-n", help="Maximum recent exchanges to display."),
144
+ ] = 50,
145
+ ) -> None:
146
+ """View, tail, or clear stored HTTP and tunnel request logs."""
147
+ if flush and (follow or domain is not None):
148
+ typer.secho(
149
+ "Cannot combine --flush with --follow or a [domain] filter.",
150
+ fg=typer.colors.RED,
151
+ err=True,
152
+ )
153
+ raise typer.Exit(code=1)
154
+
155
+ paths = resolve_paths()
156
+
157
+ if flush:
158
+ if not yes and not typer.confirm("Clear all stored DevDoor traffic logs?"):
159
+ raise typer.Exit(code=1)
160
+
161
+ async def _clear() -> int:
162
+ async with InspectorStore(paths=paths) as store:
163
+ return await store.clear_exchanges()
164
+
165
+ deleted = asyncio.run(_clear())
166
+ typer.echo(f"Cleared {deleted} stored exchange(s).")
167
+ return
168
+
169
+ normalized_domain = normalize_host(domain) if domain else None
170
+
171
+ async def _fetch_recent() -> list[CapturedExchange]:
172
+ async with InspectorStore(paths=paths) as store:
173
+ return await store.list_exchanges(limit=limit, host=normalized_domain)
174
+
175
+ rows = asyncio.run(_fetch_recent())
176
+ printed = 0
177
+ for item in reversed(rows):
178
+ line = format_access_log(item)
179
+ if line is not None:
180
+ typer.echo(line)
181
+ printed += 1
182
+
183
+ if not follow and printed == 0:
184
+ typer.echo("No logs recorded yet.")
185
+ return
186
+
187
+ if follow:
188
+ with contextlib.suppress(KeyboardInterrupt):
189
+ asyncio.run(follow_logs(domain=normalized_domain, paths=paths))
190
+
191
+
192
+ def launch_inspect_tui(*, domain: str | None = None, limit: int = 200) -> None:
193
+ """Open the interactive Textual inspector UI."""
194
+ asyncio.run(run_inspect_tui(domain=domain, limit=limit, paths=resolve_paths()))
195
+
196
+
197
+ def inspect_command(
198
+ domain: Annotated[
199
+ str | None,
200
+ typer.Option("--domain", "-d", help="Filter captured traffic to a single host."),
201
+ ] = None,
202
+ limit: Annotated[
203
+ int,
204
+ typer.Option("--limit", "-n", help="Maximum recent exchanges to load."),
205
+ ] = 200,
206
+ ) -> None:
207
+ """Launch the interactive split-pane TUI traffic inspector."""
208
+ with contextlib.suppress(KeyboardInterrupt):
209
+ launch_inspect_tui(domain=domain, limit=limit)