|
| 1 | +"""Where the backend is, and what credential to reach it with. |
| 2 | +
|
| 3 | +Every native client (tray, vault sync, wearable client, havpe relay) needs the |
| 4 | +same four facts and used to derive them independently — four copies of the |
| 5 | +repo-root ``.env`` load, four copies of the discovery fallback, four readings of |
| 6 | +``CHRONICLE_API_KEY``. This is the single source. |
| 7 | +""" |
| 8 | + |
| 9 | +import logging |
| 10 | +import os |
| 11 | +import socket |
| 12 | +import sys |
| 13 | +from dataclasses import dataclass |
| 14 | +from pathlib import Path |
| 15 | +from typing import Optional |
| 16 | + |
| 17 | +from dotenv import load_dotenv |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +# Files that only exist together at the repository root. Used as the marker |
| 22 | +# rather than a fixed number of parent hops, because that only holds when the |
| 23 | +# package is installed editable — a regular install puts this module in |
| 24 | +# site-packages, where counting parents silently yields the wrong directory |
| 25 | +# (and a silently-empty API key). |
| 26 | +_ROOT_MARKERS = ("discovery.py", "setup_utils.py") |
| 27 | + |
| 28 | + |
| 29 | +def _looks_like_repo_root(path: Path) -> bool: |
| 30 | + return all((path / marker).is_file() for marker in _ROOT_MARKERS) |
| 31 | + |
| 32 | + |
| 33 | +def _find_repo_root() -> Path: |
| 34 | + """Locate the Chronicle checkout, or fall back to the source-tree layout.""" |
| 35 | + override = os.getenv("CHRONICLE_REPO_ROOT") |
| 36 | + if override: |
| 37 | + candidate = Path(override).expanduser().resolve() |
| 38 | + if _looks_like_repo_root(candidate): |
| 39 | + return candidate |
| 40 | + logger.warning("CHRONICLE_REPO_ROOT=%s does not look like a checkout", candidate) |
| 41 | + |
| 42 | + here = Path(__file__).resolve() |
| 43 | + cwd = Path.cwd().resolve() |
| 44 | + # `Path.parents` excludes the path itself, so include each start directory |
| 45 | + # explicitly — the common case is being run from the checkout root. |
| 46 | + for start in (here, cwd): |
| 47 | + for candidate in (start, *start.parents): |
| 48 | + if _looks_like_repo_root(candidate): |
| 49 | + return candidate |
| 50 | + |
| 51 | + # extras/chronicle-client/chronicle_client/config.py -> repo root |
| 52 | + return here.parents[3] |
| 53 | + |
| 54 | + |
| 55 | +REPO_ROOT = _find_repo_root() |
| 56 | + |
| 57 | +_env_loaded = False |
| 58 | + |
| 59 | + |
| 60 | +def load_client_env() -> None: |
| 61 | + """Load the repository-root ``.env`` shared by all native client components. |
| 62 | +
|
| 63 | + Idempotent: several sections of the tray call this during startup, and |
| 64 | + python-dotenv does not override already-set variables, so repeated calls are |
| 65 | + harmless — but skipping the re-read keeps startup logs clean. |
| 66 | + """ |
| 67 | + global _env_loaded |
| 68 | + if _env_loaded: |
| 69 | + return |
| 70 | + load_dotenv(REPO_ROOT / ".env") |
| 71 | + _env_loaded = True |
| 72 | + |
| 73 | + |
| 74 | +def resolve_backend_url(explicit: Optional[str] = None) -> str: |
| 75 | + """Resolve the backend base URL: explicit value > Tailnet discovery > localhost. |
| 76 | +
|
| 77 | + ``discovery`` lives at the repository root and is not yet a package, so this |
| 78 | + is the one place in client code that has to put the repo root on ``sys.path``. |
| 79 | + Keeping it here means no other client module needs to know that. |
| 80 | + """ |
| 81 | + if explicit is None: |
| 82 | + explicit = os.getenv("BACKEND_URL") |
| 83 | + |
| 84 | + root = str(REPO_ROOT) |
| 85 | + if root not in sys.path: |
| 86 | + sys.path.append(root) |
| 87 | + try: |
| 88 | + from discovery import resolve_backend_url as _resolve |
| 89 | + except ImportError: |
| 90 | + logger.warning("discovery module unavailable; set BACKEND_URL in .env") |
| 91 | + return explicit or "http://localhost:8000" |
| 92 | + return _resolve(explicit, logger=logger) |
| 93 | + |
| 94 | + |
| 95 | +def websocket_url(backend_url: str) -> str: |
| 96 | + """Derive the WebSocket base URL from an http(s) backend URL.""" |
| 97 | + return backend_url.replace("https://", "wss://").replace("http://", "ws://") |
| 98 | + |
| 99 | + |
| 100 | +@dataclass |
| 101 | +class ClientConfig: |
| 102 | + """Connection settings shared by every native client.""" |
| 103 | + |
| 104 | + backend_url: str |
| 105 | + backend_ws_url: str |
| 106 | + # Long-lived Chronicle API key (webui → Settings → API Keys). A JWT expires |
| 107 | + # after 24h and these clients have no way to log in again, so a key is the |
| 108 | + # only credential that survives a long-running session. |
| 109 | + api_key: str |
| 110 | + device_name: str |
| 111 | + verify_ssl: bool = True |
| 112 | + |
| 113 | + @classmethod |
| 114 | + def from_env(cls, *, default_device_name: Optional[str] = None) -> "ClientConfig": |
| 115 | + load_client_env() |
| 116 | + backend_url = resolve_backend_url() |
| 117 | + return cls( |
| 118 | + backend_url=backend_url, |
| 119 | + backend_ws_url=os.getenv("BACKEND_WS_URL") or websocket_url(backend_url), |
| 120 | + api_key=os.getenv("CHRONICLE_API_KEY", ""), |
| 121 | + device_name=( |
| 122 | + os.getenv("DEVICE_NAME") |
| 123 | + or default_device_name |
| 124 | + or socket.gethostname() |
| 125 | + ), |
| 126 | + verify_ssl=os.getenv("VERIFY_SSL", "true").lower() == "true", |
| 127 | + ) |
0 commit comments