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,68 @@
1
+ """Safe shell-quoted cURL snippet generation with default secret redaction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ from typing import Literal
7
+
8
+ from devdoor.core.events import CapturedExchange, redact_headers
9
+
10
+ ShellKind = Literal["posix", "powershell"]
11
+
12
+ _OMIT_CURL_HEADERS: frozenset[str] = frozenset(
13
+ {
14
+ "host",
15
+ "content-length",
16
+ "connection",
17
+ "accept-encoding",
18
+ }
19
+ )
20
+
21
+
22
+ def _quote_arg(value: str, *, shell: ShellKind) -> str:
23
+ if shell == "powershell":
24
+ escaped = value.replace("'", "''")
25
+ return f"'{escaped}'"
26
+ return shlex.quote(value)
27
+
28
+
29
+ def build_curl_command(
30
+ exchange: CapturedExchange,
31
+ *,
32
+ scheme: str = "https",
33
+ reveal_secrets: bool = False,
34
+ shell: ShellKind = "posix",
35
+ ) -> str:
36
+ """Format ``exchange`` into a copyable POSIX or PowerShell ``cURL`` command."""
37
+ cmd_name = "curl.exe" if shell == "powershell" else "curl"
38
+ parts: list[str] = [cmd_name]
39
+
40
+ method = exchange.method.upper()
41
+ if method != "GET":
42
+ parts.extend(["-X", _quote_arg(method, shell=shell)])
43
+
44
+ path = exchange.path if exchange.path.startswith("/") else f"/{exchange.path}"
45
+ url = f"{scheme}://{exchange.host}{path}"
46
+ parts.append(_quote_arg(url, shell=shell))
47
+
48
+ headers = redact_headers(exchange.req_headers, include_secrets=reveal_secrets)
49
+ for name, value in headers:
50
+ if name.lower() in _OMIT_CURL_HEADERS:
51
+ continue
52
+ parts.extend(["-H", _quote_arg(f"{name}: {value}", shell=shell)])
53
+
54
+ if exchange.req_body_preview:
55
+ try:
56
+ body_text = exchange.req_body_preview.decode("utf-8")
57
+ if "\x00" in body_text:
58
+ raise ValueError("NUL byte in body")
59
+ parts.extend(["--data-raw", _quote_arg(body_text, shell=shell)])
60
+ except UnicodeDecodeError, ValueError:
61
+ parts.extend(
62
+ [
63
+ "--data-binary",
64
+ _quote_arg(f"<binary {len(exchange.req_body_preview)} bytes>", shell=shell),
65
+ ]
66
+ )
67
+
68
+ return " ".join(parts)
@@ -0,0 +1,147 @@
1
+ """Control-plane HTTP extensions exposing inspector history and local replay."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ from collections.abc import Awaitable, Callable
8
+ from typing import cast
9
+
10
+ from aiohttp import web
11
+
12
+ from devdoor.core.config import DevDoorPaths
13
+ from devdoor.core.engine import ControlExtender
14
+ from devdoor.core.events import TrafficEventBus
15
+ from devdoor.core.router import Router
16
+ from devdoor.inspector.replay import (
17
+ ExchangeNotFoundError,
18
+ ReplayService,
19
+ TruncatedBodyError,
20
+ )
21
+ from devdoor.inspector.store import InspectorStore
22
+ from devdoor.proxy.forwarder import Forwarder
23
+
24
+
25
+ def create_inspector_control_extender(
26
+ store: InspectorStore,
27
+ replay_service: ReplayService,
28
+ ) -> ControlExtender:
29
+ """Return a callback mounting ``/_control/exchanges*`` and ``/_control/replay/*``."""
30
+
31
+ def _extend(app: web.Application) -> None:
32
+ async def list_exchanges(request: web.Request) -> web.Response:
33
+ raw_limit = request.query.get("limit", "100")
34
+ try:
35
+ limit = int(raw_limit)
36
+ except ValueError:
37
+ return web.json_response({"error": "invalid_limit"}, status=400)
38
+ items = await store.list_exchanges(
39
+ limit=limit,
40
+ host=request.query.get("host"),
41
+ source=request.query.get("source"),
42
+ query=request.query.get("q"),
43
+ )
44
+ return web.json_response({"exchanges": [item.to_event_dict() for item in items]})
45
+
46
+ async def get_exchange(request: web.Request) -> web.Response:
47
+ exchange_id = request.match_info["exchange_id"]
48
+ item = await store.get_exchange(exchange_id)
49
+ if item is None:
50
+ return web.json_response({"error": "not_found"}, status=404)
51
+ return web.json_response(item.to_event_dict())
52
+
53
+ async def replay_exchange(request: web.Request) -> web.Response:
54
+ exchange_id = request.match_info["exchange_id"]
55
+ raw_text = await request.text()
56
+ headers_override: tuple[tuple[str, str], ...] | None = None
57
+ body_override: bytes | None = None
58
+ target_port_override: int | None = None
59
+
60
+ if raw_text.strip():
61
+ try:
62
+ parsed: object = json.loads(raw_text)
63
+ except ValueError:
64
+ return web.json_response({"error": "invalid_json"}, status=400)
65
+ if not isinstance(parsed, dict):
66
+ return web.json_response({"error": "expected_json_object"}, status=400)
67
+ data = cast(dict[object, object], parsed)
68
+
69
+ raw_headers = data.get("headers")
70
+ if isinstance(raw_headers, list):
71
+ pairs: list[tuple[str, str]] = []
72
+ for entry in cast(list[object], raw_headers):
73
+ if isinstance(entry, (list, tuple)):
74
+ seq = cast(list[object] | tuple[object, ...], entry)
75
+ if len(seq) == 2:
76
+ pairs.append((str(seq[0]), str(seq[1])))
77
+ headers_override = tuple(pairs)
78
+
79
+ if isinstance(data.get("body_b64"), str):
80
+ body_override = base64.b64decode(cast(str, data["body_b64"]).encode("ascii"))
81
+ elif isinstance(data.get("body"), str):
82
+ body_override = cast(str, data["body"]).encode("utf-8")
83
+
84
+ raw_port = data.get("target_port")
85
+ if isinstance(raw_port, int) and not isinstance(raw_port, bool):
86
+ target_port_override = raw_port
87
+
88
+ try:
89
+ child = await replay_service.replay(
90
+ exchange_id,
91
+ headers_override=headers_override,
92
+ body_override=body_override,
93
+ target_port_override=target_port_override,
94
+ )
95
+ except ExchangeNotFoundError as exc:
96
+ return web.json_response({"error": "not_found", "message": str(exc)}, status=404)
97
+ except TruncatedBodyError as exc:
98
+ return web.json_response(
99
+ {"error": "body_truncated", "message": str(exc)},
100
+ status=409,
101
+ )
102
+ return web.json_response(child.to_event_dict())
103
+
104
+ async def clear_exchanges(_request: web.Request) -> web.Response:
105
+ deleted = await store.clear_exchanges()
106
+ return web.json_response({"deleted": deleted})
107
+
108
+ app.router.add_get("/_control/exchanges", list_exchanges)
109
+ app.router.add_get("/_control/exchanges/{exchange_id}", get_exchange)
110
+ app.router.add_post("/_control/replay/{exchange_id}", replay_exchange)
111
+ app.router.add_delete("/_control/exchanges", clear_exchanges)
112
+
113
+ return _extend
114
+
115
+
116
+ def attach_inspector_to_engine(
117
+ paths: DevDoorPaths,
118
+ event_bus: TrafficEventBus,
119
+ router: Router,
120
+ forwarder: Forwarder,
121
+ ) -> tuple[ControlExtender, Callable[[], Awaitable[None]]]:
122
+ """Wire WAL ``InspectorStore`` and ``ReplayService`` into the local proxy daemon."""
123
+ store = InspectorStore(paths=paths)
124
+ replay_service = ReplayService(
125
+ store=store,
126
+ forwarder=forwarder,
127
+ event_bus=event_bus,
128
+ router=router,
129
+ )
130
+ base_extender = create_inspector_control_extender(store, replay_service)
131
+ stop_writer_holder: list[Callable[[], Awaitable[None]]] = []
132
+
133
+ def _extend_with_lifecycle(app: web.Application) -> None:
134
+ base_extender(app)
135
+
136
+ async def _on_startup(_app: web.Application) -> None:
137
+ await store.open()
138
+ stop_writer_holder.append(store.start_bus_writer(event_bus))
139
+
140
+ app.on_startup.append(_on_startup)
141
+
142
+ async def _cleanup() -> None:
143
+ for stop_writer in stop_writer_holder:
144
+ await stop_writer()
145
+ await store.close()
146
+
147
+ return _extend_with_lifecycle, _cleanup
@@ -0,0 +1,122 @@
1
+ """Deterministic local replay service for captured inspector exchanges."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from collections.abc import Sequence
7
+
8
+ from devdoor.core.events import BodyTapBuffer, CapturedExchange, TrafficEventBus
9
+ from devdoor.core.router import Router
10
+ from devdoor.inspector.store import InspectorStore
11
+ from devdoor.proxy.forwarder import Forwarder, build_upstream_headers
12
+
13
+
14
+ class ExchangeNotFoundError(LookupError):
15
+ """Raised when the requested exchange ID does not exist in ``InspectorStore``."""
16
+
17
+
18
+ class TruncatedBodyError(ValueError):
19
+ """Raised when attempting to replay a truncated request body without an override."""
20
+
21
+
22
+ class ReplayService:
23
+ """Re-dispatches captured requests against local upstream services via ``Forwarder``."""
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ store: InspectorStore,
29
+ forwarder: Forwarder,
30
+ event_bus: TrafficEventBus,
31
+ router: Router | None = None,
32
+ ) -> None:
33
+ self._store = store
34
+ self._forwarder = forwarder
35
+ self._event_bus = event_bus
36
+ self._router = router
37
+
38
+ async def replay(
39
+ self,
40
+ exchange_id: str,
41
+ *,
42
+ headers_override: Sequence[tuple[str, str]] | None = None,
43
+ body_override: bytes | None = None,
44
+ target_port_override: int | None = None,
45
+ ) -> CapturedExchange:
46
+ """Replay ``exchange_id`` locally and persist + emit the resulting child exchange."""
47
+ original = await self._store.get_exchange(exchange_id)
48
+ if original is None:
49
+ raise ExchangeNotFoundError(f"Captured exchange {exchange_id!r} was not found.")
50
+
51
+ if original.req_body_truncated and body_override is None:
52
+ raise TruncatedBodyError(
53
+ "Original request body exceeded 1 MiB and was truncated; "
54
+ "provide an explicit body override before replaying."
55
+ )
56
+
57
+ target_port = target_port_override or original.target_port
58
+ target_path = original.path or "/"
59
+ if target_port_override is None and self._router is not None:
60
+ match = self._router.match(original.host, target_path)
61
+ if match is not None:
62
+ target_port = match.port
63
+ target_path = match.target_path
64
+
65
+ raw_headers = tuple(
66
+ headers_override if headers_override is not None else original.req_headers
67
+ )
68
+ body_bytes = body_override if body_override is not None else original.req_body_preview
69
+ send_body = body_bytes if body_bytes else None
70
+
71
+ upstream_headers = build_upstream_headers(
72
+ raw_headers,
73
+ client_ip="127.0.0.1",
74
+ proto="http",
75
+ original_host=original.host,
76
+ host_override=None,
77
+ drop_content_length=True,
78
+ )
79
+ if send_body is not None:
80
+ upstream_headers["Content-Length"] = str(len(send_body))
81
+
82
+ req_tap = BodyTapBuffer()
83
+ if send_body is not None:
84
+ req_tap.write(send_body)
85
+ resp_tap = BodyTapBuffer()
86
+ started = time.perf_counter()
87
+
88
+ url = f"http://127.0.0.1:{target_port}{target_path}"
89
+ async with self._forwarder.get_session().request(
90
+ original.method,
91
+ url,
92
+ headers=upstream_headers,
93
+ data=send_body,
94
+ allow_redirects=False,
95
+ ) as resp:
96
+ resp_headers = tuple(resp.headers.items())
97
+ async for chunk in resp.content.iter_any():
98
+ if chunk:
99
+ resp_tap.write(chunk)
100
+ status = resp.status
101
+
102
+ req_preview, req_truncated = req_tap.snapshot()
103
+ resp_preview, resp_truncated = resp_tap.snapshot()
104
+ child = self._event_bus.emit_exchange(
105
+ source="local",
106
+ host=original.host,
107
+ method=original.method,
108
+ path=original.path,
109
+ target_port=target_port,
110
+ status=status,
111
+ duration_ms=(time.perf_counter() - started) * 1000.0,
112
+ req_headers=tuple(upstream_headers.items()),
113
+ resp_headers=resp_headers,
114
+ req_body_preview=req_preview,
115
+ resp_body_preview=resp_preview,
116
+ req_body_truncated=req_truncated,
117
+ resp_body_truncated=resp_truncated,
118
+ log_mode=original.log_mode,
119
+ replayed_from_id=original.id,
120
+ )
121
+ await self._store.save_exchange(child)
122
+ return child
@@ -0,0 +1,291 @@
1
+ """Async WAL-backed SQLite persistence for captured HTTP and WebSocket exchanges."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import json
8
+ import os
9
+ import sys
10
+ from collections.abc import Awaitable, Callable
11
+ from typing import Self, cast
12
+
13
+ import aiosqlite
14
+
15
+ from devdoor.core.config import DevDoorPaths, resolve_paths
16
+ from devdoor.core.events import (
17
+ MAX_BODY_CAPTURE_BYTES,
18
+ CapturedExchange,
19
+ TrafficEventBus,
20
+ coerce_header_pairs,
21
+ coerce_log_mode,
22
+ coerce_traffic_source,
23
+ )
24
+
25
+ MAX_STORED_EXCHANGES = 1000
26
+
27
+ _SCHEMA_SQL = """
28
+ CREATE TABLE IF NOT EXISTS exchanges (
29
+ id TEXT PRIMARY KEY,
30
+ created_at_ms INTEGER NOT NULL,
31
+ source TEXT NOT NULL,
32
+ host TEXT NOT NULL,
33
+ method TEXT NOT NULL,
34
+ path TEXT NOT NULL,
35
+ target_port INTEGER NOT NULL,
36
+ status INTEGER NOT NULL,
37
+ duration_ms REAL NOT NULL,
38
+ req_headers_json TEXT NOT NULL,
39
+ resp_headers_json TEXT NOT NULL,
40
+ req_body BLOB NOT NULL,
41
+ resp_body BLOB NOT NULL,
42
+ req_body_truncated INTEGER NOT NULL,
43
+ resp_body_truncated INTEGER NOT NULL,
44
+ log_mode TEXT NOT NULL DEFAULT 'full',
45
+ replayed_from_id TEXT
46
+ );
47
+ CREATE INDEX IF NOT EXISTS idx_exchanges_created_at_ms
48
+ ON exchanges(created_at_ms DESC, id DESC);
49
+ """
50
+
51
+ _SELECT_COLUMNS = (
52
+ "id, created_at_ms, source, host, method, path, target_port, status, duration_ms, "
53
+ "req_headers_json, resp_headers_json, req_body, resp_body, "
54
+ "req_body_truncated, resp_body_truncated, log_mode, replayed_from_id"
55
+ )
56
+
57
+ _LIST_SQL = (
58
+ "SELECT "
59
+ + _SELECT_COLUMNS
60
+ + " FROM exchanges "
61
+ + "WHERE (? IS NULL OR source = ?) "
62
+ + "AND (? IS NULL OR LOWER(host) = LOWER(?)) "
63
+ + "AND (? IS NULL OR path LIKE ? ESCAPE '\\' OR host LIKE ? ESCAPE '\\' "
64
+ + "OR method LIKE ? ESCAPE '\\' OR CAST(status AS TEXT) LIKE ? ESCAPE '\\') "
65
+ + "ORDER BY created_at_ms DESC, id DESC LIMIT ?"
66
+ )
67
+
68
+
69
+ def _escape_like(raw: str) -> str:
70
+ return raw.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
71
+
72
+
73
+ def _encode_headers_json(headers: tuple[tuple[str, str], ...]) -> str:
74
+ return json.dumps([[name, value] for name, value in headers], separators=(",", ":"))
75
+
76
+
77
+ def _decode_headers_json(raw: str) -> tuple[tuple[str, str], ...]:
78
+ parsed: object = json.loads(raw) if raw else []
79
+ return coerce_header_pairs(parsed)
80
+
81
+
82
+ def _row_to_exchange(row: tuple[object, ...]) -> CapturedExchange:
83
+ replayed = str(row[16]) if row[16] is not None else None
84
+ return CapturedExchange(
85
+ id=str(row[0]),
86
+ created_at_ms=int(cast(int, row[1])),
87
+ source=coerce_traffic_source(row[2]),
88
+ host=str(row[3]),
89
+ method=str(row[4]),
90
+ path=str(row[5]),
91
+ target_port=int(cast(int, row[6])),
92
+ status=int(cast(int, row[7])),
93
+ duration_ms=float(cast(float, row[8])),
94
+ req_headers=_decode_headers_json(str(row[9])),
95
+ resp_headers=_decode_headers_json(str(row[10])),
96
+ req_body_preview=bytes(cast(bytes, row[11])),
97
+ resp_body_preview=bytes(cast(bytes, row[12])),
98
+ req_body_truncated=bool(row[13]),
99
+ resp_body_truncated=bool(row[14]),
100
+ log_mode=coerce_log_mode(row[15]),
101
+ replayed_from_id=replayed,
102
+ )
103
+
104
+
105
+ class InspectorStore:
106
+ """Async SQLite store managing bounded traffic captures under WAL concurrency."""
107
+
108
+ def __init__(
109
+ self,
110
+ *,
111
+ paths: DevDoorPaths | None = None,
112
+ max_exchanges: int = MAX_STORED_EXCHANGES,
113
+ ) -> None:
114
+ self._paths = paths or resolve_paths()
115
+ self._max_exchanges = max(1, max_exchanges)
116
+ self._db: aiosqlite.Connection | None = None
117
+ self._write_lock = asyncio.Lock()
118
+
119
+ async def __aenter__(self) -> Self:
120
+ await self.open()
121
+ return self
122
+
123
+ async def __aexit__(self, *_exc: object) -> None:
124
+ await self.close()
125
+
126
+ async def open(self) -> None:
127
+ """Open ``inspector.db`` in WAL mode with ``0600`` POSIX permissions."""
128
+ if self._db is not None:
129
+ return
130
+ self._paths.home.mkdir(parents=True, exist_ok=True)
131
+ if sys.platform != "win32":
132
+ os.chmod(self._paths.home, 0o700)
133
+
134
+ db = await aiosqlite.connect(str(self._paths.inspector_db))
135
+ await db.execute("PRAGMA journal_mode=WAL;")
136
+ await db.execute("PRAGMA synchronous=NORMAL;")
137
+ await db.execute("PRAGMA busy_timeout=3000;")
138
+ await db.executescript(_SCHEMA_SQL)
139
+ await db.commit()
140
+ if sys.platform != "win32" and self._paths.inspector_db.exists():
141
+ os.chmod(self._paths.inspector_db, 0o600)
142
+ self._db = db
143
+
144
+ async def close(self) -> None:
145
+ """Close the SQLite connection."""
146
+ if self._db is not None:
147
+ await self._db.close()
148
+ self._db = None
149
+
150
+ def _require_db(self) -> aiosqlite.Connection:
151
+ if self._db is None:
152
+ raise RuntimeError("InspectorStore is not open; call open() or use async with.")
153
+ return self._db
154
+
155
+ async def journal_mode(self) -> str:
156
+ """Return active SQLite journal mode (e.g. ``'wal'``)."""
157
+ db = self._require_db()
158
+ async with db.execute("PRAGMA journal_mode;") as cursor:
159
+ row = await cursor.fetchone()
160
+ return str(row[0]).lower() if row is not None else ""
161
+
162
+ async def save_exchange(self, exchange: CapturedExchange) -> None:
163
+ """Persist ``exchange`` capped at ``1 MiB`` per body and prune excess history."""
164
+ db = self._require_db()
165
+ req_blob = exchange.req_body_preview[:MAX_BODY_CAPTURE_BYTES]
166
+ resp_blob = exchange.resp_body_preview[:MAX_BODY_CAPTURE_BYTES]
167
+
168
+ async with self._write_lock:
169
+ await db.execute(
170
+ """
171
+ INSERT OR REPLACE INTO exchanges (
172
+ id, created_at_ms, source, host, method, path, target_port,
173
+ status, duration_ms, req_headers_json, resp_headers_json,
174
+ req_body, resp_body, req_body_truncated, resp_body_truncated,
175
+ log_mode, replayed_from_id
176
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
177
+ """,
178
+ (
179
+ exchange.id,
180
+ exchange.created_at_ms,
181
+ exchange.source,
182
+ exchange.host,
183
+ exchange.method,
184
+ exchange.path,
185
+ exchange.target_port,
186
+ exchange.status,
187
+ exchange.duration_ms,
188
+ _encode_headers_json(exchange.req_headers),
189
+ _encode_headers_json(exchange.resp_headers),
190
+ req_blob,
191
+ resp_blob,
192
+ 1 if exchange.req_body_truncated else 0,
193
+ 1 if exchange.resp_body_truncated else 0,
194
+ exchange.log_mode,
195
+ exchange.replayed_from_id,
196
+ ),
197
+ )
198
+ await db.execute(
199
+ """
200
+ DELETE FROM exchanges WHERE id IN (
201
+ SELECT id FROM exchanges
202
+ ORDER BY created_at_ms DESC, id DESC
203
+ LIMIT -1 OFFSET ?
204
+ )
205
+ """,
206
+ (self._max_exchanges,),
207
+ )
208
+ await db.commit()
209
+
210
+ async def list_exchanges(
211
+ self,
212
+ *,
213
+ limit: int = 100,
214
+ host: str | None = None,
215
+ source: str | None = None,
216
+ query: str | None = None,
217
+ ) -> list[CapturedExchange]:
218
+ """List stored exchanges ordered newest-first with optional filters."""
219
+ db = self._require_db()
220
+ clean_source = source.strip().lower() if source and source.strip() else None
221
+ clean_host = host.strip().lower() if host and host.strip() else None
222
+ pattern = f"%{_escape_like(query.strip())}%" if query and query.strip() else None
223
+ capped_limit = max(1, min(limit, self._max_exchanges))
224
+
225
+ params = (
226
+ clean_source,
227
+ clean_source,
228
+ clean_host,
229
+ clean_host,
230
+ pattern,
231
+ pattern,
232
+ pattern,
233
+ pattern,
234
+ pattern,
235
+ capped_limit,
236
+ )
237
+ async with db.execute(_LIST_SQL, params) as cursor:
238
+ rows = await cursor.fetchall()
239
+ return [_row_to_exchange(tuple(row)) for row in rows]
240
+
241
+ async def get_exchange(self, exchange_id: str) -> CapturedExchange | None:
242
+ """Fetch a single stored exchange by ``exchange_id``."""
243
+ db = self._require_db()
244
+ sql = "SELECT " + _SELECT_COLUMNS + " FROM exchanges WHERE id = ?"
245
+ async with db.execute(sql, (exchange_id,)) as cursor:
246
+ row = await cursor.fetchone()
247
+ return _row_to_exchange(tuple(row)) if row is not None else None
248
+
249
+ async def clear_exchanges(self) -> int:
250
+ """Delete all stored exchanges and return deleted row count."""
251
+ db = self._require_db()
252
+ async with self._write_lock:
253
+ cursor = await db.execute("DELETE FROM exchanges")
254
+ await db.commit()
255
+ return int(cursor.rowcount)
256
+
257
+ def start_bus_writer(self, event_bus: TrafficEventBus) -> Callable[[], Awaitable[None]]:
258
+ """Subscribe asynchronously to ``event_bus`` and persist events without blocking proxy."""
259
+ queue = event_bus.subscribe()
260
+ stop_event = asyncio.Event()
261
+
262
+ async def _worker() -> None:
263
+ try:
264
+ while not stop_event.is_set() or not queue.empty():
265
+ if not queue.empty():
266
+ item = queue.get_nowait()
267
+ await self.save_exchange(item)
268
+ continue
269
+ get_task = asyncio.create_task(queue.get())
270
+ stop_task = asyncio.create_task(stop_event.wait())
271
+ done, _ = await asyncio.wait(
272
+ {get_task, stop_task},
273
+ return_when=asyncio.FIRST_COMPLETED,
274
+ )
275
+ for pending in (get_task, stop_task):
276
+ if not pending.done():
277
+ pending.cancel()
278
+ with contextlib.suppress(asyncio.CancelledError):
279
+ await pending
280
+ if get_task in done and not get_task.cancelled():
281
+ await self.save_exchange(get_task.result())
282
+ finally:
283
+ event_bus.unsubscribe(queue)
284
+
285
+ task = asyncio.create_task(_worker())
286
+
287
+ async def _stop() -> None:
288
+ stop_event.set()
289
+ await task
290
+
291
+ return _stop
@@ -0,0 +1,36 @@
1
+ """Cross-platform OS trust, hosts, and port-forwarding adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from devdoor.platform.base import OSPlatformAdapter, PlatformAdapterError
8
+ from devdoor.platform.darwin import DarwinAdapter
9
+ from devdoor.platform.linux import LinuxAdapter
10
+ from devdoor.platform.windows import WindowsAdapter
11
+
12
+
13
+ def get_platform_adapter(
14
+ *,
15
+ platform_name: str | None = None,
16
+ elevated_windows: bool = False,
17
+ ) -> OSPlatformAdapter:
18
+ """Return the active OS platform adapter."""
19
+ target = (platform_name or sys.platform).lower()
20
+ if target == "darwin":
21
+ return DarwinAdapter()
22
+ if target.startswith("linux"):
23
+ return LinuxAdapter()
24
+ if target.startswith("win"):
25
+ return WindowsAdapter(elevated=elevated_windows)
26
+ raise PlatformAdapterError(f"Unsupported operating system platform: {target!r}")
27
+
28
+
29
+ __all__ = [
30
+ "DarwinAdapter",
31
+ "LinuxAdapter",
32
+ "OSPlatformAdapter",
33
+ "PlatformAdapterError",
34
+ "WindowsAdapter",
35
+ "get_platform_adapter",
36
+ ]