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/cli/share.py ADDED
@@ -0,0 +1,443 @@
1
+ """Implementation of the ``devdoor share`` public streaming tunnel CLI command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import importlib
8
+ import signal
9
+ from collections.abc import Awaitable, Callable
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Annotated, Protocol, cast
14
+
15
+ import typer
16
+
17
+ from devdoor.core.config import (
18
+ ConfigError,
19
+ LogMode,
20
+ ProjectConfig,
21
+ ServiceConfig,
22
+ load_project_config,
23
+ parse_duration_seconds,
24
+ resolve_paths,
25
+ )
26
+ from devdoor.core.events import CapturedExchange, TrafficEventBus
27
+ from devdoor.core.protocol import RegistrationResponse
28
+ from devdoor.core.router import Router
29
+ from devdoor.proxy.forwarder import Forwarder
30
+ from devdoor.tunnel.auth_client import resolve_auth_token, resolve_relay_url
31
+ from devdoor.tunnel.client import (
32
+ TunnelClient,
33
+ TunnelConfig,
34
+ TunnelRejectionError,
35
+ TunnelTerminatedError,
36
+ )
37
+ from devdoor.tunnel.relay_api import SubdomainValidationError, validate_subdomain
38
+
39
+ parse_ttl_seconds = parse_duration_seconds
40
+
41
+
42
+ class ShareError(ValueError):
43
+ """Raised when ``devdoor share`` arguments or config cannot be resolved."""
44
+
45
+
46
+ @dataclass(frozen=True, slots=True)
47
+ class ShareTarget:
48
+ """Resolved local service and in-process router for ``devdoor share``."""
49
+
50
+ service: ServiceConfig
51
+ router: Router
52
+ log_mode: LogMode
53
+ config_path: Path | None = None
54
+
55
+
56
+ def _match_project_service(services: list[ServiceConfig], selector: str) -> ServiceConfig:
57
+ needle = selector.strip().lower()
58
+ matches = [
59
+ svc
60
+ for svc in services
61
+ if (svc.name and svc.name.lower() == needle)
62
+ or svc.domain.lower() == needle
63
+ or svc.domain.split(".", 1)[0].lower() == needle
64
+ ]
65
+ if not matches:
66
+ names = ", ".join(svc.name or svc.domain for svc in services)
67
+ raise ShareError(f"Service {selector!r} not found. Available services: {names}")
68
+ if len(matches) > 1:
69
+ names = ", ".join(svc.domain for svc in matches)
70
+ raise ShareError(f"Ambiguous service selector {selector!r}; matched: {names}")
71
+ return matches[0]
72
+
73
+
74
+ def resolve_share_target(
75
+ *,
76
+ service: str | None = None,
77
+ port: int | None = None,
78
+ config_path: Path | None = None,
79
+ cwd: Path | None = None,
80
+ cors: bool = False,
81
+ ) -> ShareTarget:
82
+ """Resolve ``--port`` or ``devdoor.yaml`` service routes into an in-process ``Router``."""
83
+ if service is not None and port is not None:
84
+ raise ShareError("Specify either a service name from devdoor.yaml or --port, not both.")
85
+
86
+ if port is not None:
87
+ if not (1 <= port <= 65535):
88
+ raise ShareError(f"Port must be between 1 and 65535, got {port}.")
89
+ svc = ServiceConfig(domain="local.test", port=port)
90
+ proj = ProjectConfig(services=[svc], cors=cors)
91
+ return ShareTarget(service=svc, router=Router.from_project(proj), log_mode=proj.log_mode)
92
+
93
+ try:
94
+ loaded = load_project_config(start_dir=cwd, config_path=config_path)
95
+ except ConfigError as exc:
96
+ raise ShareError(str(exc)) from exc
97
+
98
+ services = loaded.project.services
99
+ if service is None:
100
+ if len(services) > 1:
101
+ choices = ", ".join(svc.name or svc.domain for svc in services)
102
+ raise ShareError(
103
+ f"Multiple services found in {loaded.config_path.name}; specify one: {choices}"
104
+ )
105
+ chosen = services[0]
106
+ else:
107
+ chosen = _match_project_service(services, service)
108
+
109
+ effective_log = chosen.log_mode or loaded.project.log_mode
110
+ effective_cors = (
111
+ True if cors else (chosen.cors if chosen.cors is not None else loaded.project.cors)
112
+ )
113
+ scoped_project = ProjectConfig(
114
+ services=[chosen],
115
+ log_mode=effective_log,
116
+ cors=effective_cors,
117
+ )
118
+ return ShareTarget(
119
+ service=chosen,
120
+ router=Router.from_project(scoped_project),
121
+ log_mode=effective_log,
122
+ config_path=loaded.config_path,
123
+ )
124
+
125
+
126
+ def _format_share_log_line(exchange: CapturedExchange) -> str | None:
127
+ if exchange.log_mode == "off":
128
+ return None
129
+ stamp = datetime.now().strftime("%H:%M:%S")
130
+ if exchange.log_mode == "minimal":
131
+ return f"{stamp} {exchange.host} {exchange.status} {exchange.duration_ms:.0f}ms"
132
+ return (
133
+ f"{stamp} {exchange.method:<6} {exchange.path} "
134
+ f"{exchange.status} {exchange.duration_ms:.0f}ms"
135
+ )
136
+
137
+
138
+ async def run_share(
139
+ *,
140
+ target: ShareTarget,
141
+ relay_url: str,
142
+ token: str,
143
+ subdomain: str | None = None,
144
+ domain: str | None = None,
145
+ password: str | None = None,
146
+ ttl_seconds: int | None = None,
147
+ preserve_host: bool = False,
148
+ use_tui: bool = False,
149
+ stop_event: asyncio.Event | None = None,
150
+ output_fn: Callable[[str], None] = typer.echo,
151
+ ) -> None:
152
+ """Run an interactive public tunnel session cleanly until stopped."""
153
+ event_bus = TrafficEventBus()
154
+ forwarder = Forwarder(event_bus)
155
+ queue = event_bus.subscribe()
156
+
157
+ client_cfg = TunnelConfig(
158
+ relay_url=relay_url,
159
+ token=token,
160
+ subdomain=subdomain,
161
+ domain=domain,
162
+ password=password,
163
+ ttl_seconds=ttl_seconds,
164
+ target_domain=target.service.domain,
165
+ preserve_host=preserve_host,
166
+ )
167
+
168
+ class _TuiStatus(Protocol):
169
+ url: str
170
+ target: str
171
+ status: str
172
+
173
+ class _TuiBannerApp(Protocol):
174
+ def refresh_tunnel_banner(self) -> None: ...
175
+
176
+ tui_status_holder: list[_TuiStatus] = []
177
+ tui_app_holder: list[_TuiBannerApp] = []
178
+
179
+ if use_tui:
180
+ try:
181
+ tui_mod = importlib.import_module("devdoor.tui.inspector_app")
182
+ status_cls = getattr(tui_mod, "ShareTunnelStatus", None)
183
+ if callable(status_cls):
184
+ status_obj = status_cls(
185
+ url="connecting...",
186
+ target=f"127.0.0.1:{target.service.port}",
187
+ status="connecting",
188
+ )
189
+ tui_status_holder.append(cast(_TuiStatus, status_obj))
190
+ except ModuleNotFoundError:
191
+ pass
192
+
193
+ def _on_connected(resp: RegistrationResponse) -> None:
194
+ target_desc = f"127.0.0.1:{target.service.port}"
195
+ if target.service.routes:
196
+ target_desc += f" (+{len(target.service.routes)} routes)"
197
+ if use_tui and tui_status_holder:
198
+ st = tui_status_holder[0]
199
+ st.url = resp.url
200
+ st.target = target_desc
201
+ st.status = "connected"
202
+ if tui_app_holder:
203
+ tui_app_holder[0].refresh_tunnel_banner()
204
+ return
205
+ if use_tui:
206
+ return
207
+ output_fn(f"Tunnel ready: {resp.url} -> {target_desc}")
208
+ if resp.domain:
209
+ custom_url = f"https://{resp.domain}"
210
+ if custom_url.rstrip("/") != resp.url.rstrip("/"):
211
+ output_fn(f"Custom domain ready: {custom_url} -> {target_desc}")
212
+ if password:
213
+ output_fn("Password protection enabled (passphrase set at startup).")
214
+
215
+ def _on_reconnecting(attempt: int, delay: float, reason: str) -> None:
216
+ if use_tui and tui_status_holder:
217
+ st = tui_status_holder[0]
218
+ st.status = f"reconnecting ({attempt})"
219
+ if tui_app_holder:
220
+ tui_app_holder[0].refresh_tunnel_banner()
221
+ return
222
+ if not use_tui:
223
+ output_fn(
224
+ f"Connection lost ({reason}); reconnecting in {delay:.1f}s (attempt {attempt})..."
225
+ )
226
+
227
+ client = TunnelClient(
228
+ config=client_cfg,
229
+ router=target.router,
230
+ forwarder=forwarder,
231
+ event_bus=event_bus,
232
+ on_connected=_on_connected,
233
+ on_reconnecting=_on_reconnecting,
234
+ )
235
+
236
+ loop = asyncio.get_running_loop()
237
+ for sig in (signal.SIGINT, signal.SIGTERM):
238
+ with contextlib.suppress(NotImplementedError, RuntimeError):
239
+ loop.add_signal_handler(sig, client.request_stop)
240
+
241
+ done_event = asyncio.Event()
242
+
243
+ async def _log_printer() -> None:
244
+ while not done_event.is_set():
245
+ get_task = asyncio.create_task(queue.get())
246
+ done_task = asyncio.create_task(done_event.wait())
247
+ try:
248
+ done, _ = await asyncio.wait(
249
+ {get_task, done_task},
250
+ return_when=asyncio.FIRST_COMPLETED,
251
+ )
252
+ finally:
253
+ for pending in (get_task, done_task):
254
+ if not pending.done():
255
+ pending.cancel()
256
+ with contextlib.suppress(asyncio.CancelledError):
257
+ await pending
258
+ if done_task in done:
259
+ return
260
+ exchange = get_task.result()
261
+ line = _format_share_log_line(exchange)
262
+ if line is not None:
263
+ output_fn(line)
264
+
265
+ async def _watch_external_stop() -> None:
266
+ if stop_event is None:
267
+ return
268
+ stop_task = asyncio.create_task(stop_event.wait())
269
+ done_task = asyncio.create_task(done_event.wait())
270
+ try:
271
+ done, _ = await asyncio.wait(
272
+ {stop_task, done_task},
273
+ return_when=asyncio.FIRST_COMPLETED,
274
+ )
275
+ if stop_task in done:
276
+ client.request_stop()
277
+ finally:
278
+ for pending in (stop_task, done_task):
279
+ if not pending.done():
280
+ pending.cancel()
281
+ with contextlib.suppress(asyncio.CancelledError):
282
+ await pending
283
+
284
+ printer_task: asyncio.Task[None] | None = None
285
+ tui_task: asyncio.Task[None] | None = None
286
+ watch_task = asyncio.create_task(_watch_external_stop())
287
+
288
+ def _register_tui_app(app: object) -> None:
289
+ tui_app_holder.append(cast(_TuiBannerApp, app))
290
+
291
+ if use_tui:
292
+ try:
293
+ tui_mod = importlib.import_module("devdoor.tui.inspector_app")
294
+ runner = getattr(tui_mod, "run_share_tui", None)
295
+ except ModuleNotFoundError:
296
+ runner = None
297
+ if callable(runner):
298
+ coro = cast(Callable[..., Awaitable[None]], runner)(
299
+ event_bus,
300
+ client.request_stop,
301
+ router=target.router,
302
+ forwarder=forwarder,
303
+ tunnel_status=tui_status_holder[0] if tui_status_holder else None,
304
+ on_app_ready=_register_tui_app,
305
+ )
306
+ tui_task = asyncio.create_task(_await_and_stop(coro, client))
307
+ else:
308
+ output_fn("TUI viewer is not available yet; falling back to terminal logs.")
309
+ printer_task = asyncio.create_task(_log_printer())
310
+ else:
311
+ printer_task = asyncio.create_task(_log_printer())
312
+
313
+ try:
314
+ await client.run()
315
+ finally:
316
+ done_event.set()
317
+ for bg in (watch_task, printer_task, tui_task):
318
+ if bg is not None:
319
+ if not bg.done():
320
+ bg.cancel()
321
+ with contextlib.suppress(asyncio.CancelledError):
322
+ await bg
323
+ event_bus.unsubscribe(queue)
324
+ await forwarder.close()
325
+
326
+
327
+ async def _await_and_stop(coro: Awaitable[None], client: TunnelClient) -> None:
328
+ try:
329
+ await coro
330
+ finally:
331
+ client.request_stop()
332
+
333
+
334
+ def share_command(
335
+ service: Annotated[
336
+ str | None,
337
+ typer.Argument(help="Optional service name or domain from devdoor.yaml."),
338
+ ] = None,
339
+ port: Annotated[
340
+ int | None,
341
+ typer.Option("--port", "-p", help="Local port to expose."),
342
+ ] = None,
343
+ config: Annotated[
344
+ Path | None,
345
+ typer.Option("--config", "-c", help="Path to devdoor.yaml / .devdoor.yaml."),
346
+ ] = None,
347
+ subdomain: Annotated[
348
+ str | None,
349
+ typer.Option("--subdomain", "-s", help="Request a vanity subdomain on the relay."),
350
+ ] = None,
351
+ domain: Annotated[
352
+ str | None,
353
+ typer.Option("--domain", "-d", help="Expose via a verified custom domain."),
354
+ ] = None,
355
+ password: Annotated[
356
+ str | None,
357
+ typer.Option("--password", help="Protect public URL with HTTP Basic Auth."),
358
+ ] = None,
359
+ ttl: Annotated[
360
+ str | None,
361
+ typer.Option("--ttl", help="Tunnel lifetime (e.g. 30m, 2h, 1d)."),
362
+ ] = None,
363
+ relay: Annotated[
364
+ str | None,
365
+ typer.Option("--relay", help="Override relay server URL."),
366
+ ] = None,
367
+ preserve_host: Annotated[
368
+ bool,
369
+ typer.Option(
370
+ "--preserve-host",
371
+ help="Forward incoming public Host header instead of rewriting to localhost:<port>.",
372
+ ),
373
+ ] = False,
374
+ cors: Annotated[
375
+ bool,
376
+ typer.Option("--cors", help="Inject permissive development CORS headers."),
377
+ ] = False,
378
+ tui: Annotated[
379
+ bool,
380
+ typer.Option("--tui", help="Launch interactive Textual inspector UI alongside tunnel."),
381
+ ] = False,
382
+ ) -> None:
383
+ """Expose a local service over a secure public HTTPS tunnel."""
384
+ if subdomain is not None and domain is not None:
385
+ typer.secho("Cannot specify both --subdomain and --domain.", fg=typer.colors.RED, err=True)
386
+ raise typer.Exit(code=1)
387
+
388
+ normalized_subdomain: str | None = None
389
+ if subdomain is not None:
390
+ try:
391
+ normalized_subdomain = validate_subdomain(subdomain)
392
+ except SubdomainValidationError as exc:
393
+ typer.secho(f"Invalid subdomain: {exc}", fg=typer.colors.RED, err=True)
394
+ raise typer.Exit(code=1) from exc
395
+
396
+ ttl_seconds: int | None = None
397
+ if ttl is not None:
398
+ try:
399
+ ttl_seconds = parse_ttl_seconds(ttl)
400
+ except ValueError as exc:
401
+ typer.secho(f"Invalid --ttl: {exc}", fg=typer.colors.RED, err=True)
402
+ raise typer.Exit(code=1) from exc
403
+
404
+ try:
405
+ target = resolve_share_target(
406
+ service=service,
407
+ port=port,
408
+ config_path=config,
409
+ cors=cors,
410
+ )
411
+ except ShareError as exc:
412
+ typer.secho(f"Error: {exc}", fg=typer.colors.RED, err=True)
413
+ raise typer.Exit(code=1) from exc
414
+
415
+ paths = resolve_paths()
416
+ token = resolve_auth_token(paths=paths)
417
+ if not token:
418
+ typer.secho("Not logged in. Run 'devdoor login' first.", fg=typer.colors.RED, err=True)
419
+ raise typer.Exit(code=1)
420
+
421
+ try:
422
+ relay_url = resolve_relay_url(cli_relay=relay, paths=paths)
423
+ except ValueError as exc:
424
+ typer.secho(f"Invalid relay URL: {exc}", fg=typer.colors.RED, err=True)
425
+ raise typer.Exit(code=1) from exc
426
+
427
+ try:
428
+ asyncio.run(
429
+ run_share(
430
+ target=target,
431
+ relay_url=relay_url,
432
+ token=token,
433
+ subdomain=normalized_subdomain,
434
+ domain=domain.strip().lower().rstrip(".") if domain else None,
435
+ password=password,
436
+ ttl_seconds=ttl_seconds,
437
+ preserve_host=preserve_host,
438
+ use_tui=tui,
439
+ )
440
+ )
441
+ except (TunnelRejectionError, TunnelTerminatedError) as exc:
442
+ typer.secho(f"Tunnel stopped: {exc}", fg=typer.colors.RED, err=True)
443
+ raise typer.Exit(code=1) from exc
@@ -0,0 +1,40 @@
1
+ """Shared Typer parameter parsers for DevDoor CLI modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from devdoor.core.config import LogMode, parse_duration_seconds, parse_log_mode
8
+
9
+
10
+ def parse_cli_log_mode(raw: str) -> LogMode:
11
+ """Parse ``--log-mode`` or config ``log-mode`` into ``LogMode`` for CLI commands."""
12
+ try:
13
+ return parse_log_mode(raw)
14
+ except ValueError as exc:
15
+ raise typer.BadParameter(str(exc)) from exc
16
+
17
+
18
+ def parse_cli_port(raw: str) -> int:
19
+ """Parse a TCP port string (``1..65535``) raising ``typer.BadParameter`` on error."""
20
+ try:
21
+ port = int(raw.strip())
22
+ except ValueError as exc:
23
+ raise typer.BadParameter(f"Expected integer port, got {raw!r}") from exc
24
+ if not (1 <= port <= 65535):
25
+ raise typer.BadParameter(f"Port must be 1..65535, got {port}")
26
+ return port
27
+
28
+
29
+ def resolve_wait_timeout(wait: bool, timeout: str | None) -> float:
30
+ """Validate paired ``--wait`` / ``--timeout`` options and return timeout seconds."""
31
+ if timeout is not None and not wait:
32
+ typer.secho("--timeout requires --wait.", fg=typer.colors.RED, err=True)
33
+ raise typer.Exit(code=1)
34
+ if timeout is None:
35
+ return 30.0
36
+ try:
37
+ return float(parse_duration_seconds(timeout))
38
+ except ValueError as exc:
39
+ typer.secho(f"Invalid --timeout: {exc}", fg=typer.colors.RED, err=True)
40
+ raise typer.Exit(code=1) from exc
@@ -0,0 +1 @@
1
+ """Core runtime modules for DevDoor."""