okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-023-int into f-023-tui267a48427b

main
13.5 KiB248 linesraw
1"""Shared status/monitor grammar for the source launcher and portable client.
2
3This module and the one-shot status path use only Python's standard library.
4Textual is imported only when an interactive monitor actually starts.
5"""
6
7from __future__ import annotations
8
9import argparse
10import contextlib
11import io
12import json
13import os
14import sys
15
16from strata_cli.client import ClientError, Endpoint
17from strata_cli import connections
18
19
20def _connection(p: argparse.ArgumentParser) -> None:
21    p.add_argument("--url", help="Strata server root; remote connections require HTTPS")
22    p.add_argument("--connection", metavar="NAME", help="saved read-only connection")
23    p.add_argument("--credential-env", metavar="NAME",
24                   help="environment variable containing the server credential")
25    p.add_argument("--timeout", type=float, help="bounded request timeout in seconds (default 3)")
26
27
28def add_status(sp: argparse._SubParsersAction) -> None:
29    status = sp.add_parser("status", help="one read-only telemetry snapshot")
30    _connection(status)
31    status.add_argument("--output", choices=("human", "json"), default="human")
32    status.add_argument("--json", action="store_true", help="alias for --output json")
33    status.add_argument("--quiet", action="store_true", help="suppress human informational output")
34
35
36def running_launch() -> dict | None:
37    """The server a `strata launch` has running (address and its key), when no address was given: so `strata monitor` needs no --url.
38    Nothing is read when a connection, STRATA_URL or STRATA_CONNECTION names the server, and a thin monitor bundle has no launch code."""
39    if os.environ.get("STRATA_URL") or os.environ.get("STRATA_CONNECTION"):
40        return None
41    try:
42        from strata_cli.launch.cmd import launch_info
43        info = launch_info()
44    except Exception:                                    # noqa: BLE001 - no launch code, no profiles: use the default address
45        return None
46    return info if info and info.get("running") and info.get("url") else None
47
48
49def add_monitor(sp: argparse._SubParsersAction) -> None:
50    monitor = sp.add_parser("monitor", help="read-only terminal monitor: seven views (Overview ... Logs, Connect), the same as the one strata launch opens")
51    _connection(monitor)
52    monitor.add_argument("--once", action="store_true", help="print one snapshot without starting the TUI")
53    monitor.add_argument("--output", choices=("human", "json"), default="human")
54    monitor.add_argument("--json", action="store_true", help="alias for --output json with --once")
55    monitor.add_argument("--quiet", action="store_true", help="suppress one-shot human output")
56    monitor.add_argument("--theme", choices=("auto", "dark", "light", "terminal"), default="auto")
57    monitor.add_argument("--color", choices=("auto", "always", "never"), default="auto")
58    monitor.add_argument("--glyphs", choices=("auto", "unicode", "braille", "ascii"), default="auto")
59    monitor.add_argument("--interval", type=float, default=1.0)
60    monitor.add_argument("--requests", type=int, default=12)
61
62
63def add_logs(sp: argparse._SubParsersAction) -> None:
64    logs = sp.add_parser("logs", help="bounded redacted request activity (read only)")
65    _connection(logs)
66    logs.add_argument("--source", choices=("runtime", "harness"), default="runtime")
67    logs.add_argument("--follow", action="store_true", help="poll for new transitions until Ctrl+C")
68    logs.add_argument("--interval", type=float, default=2.0,
69                      help="follow poll interval in seconds (0.5–30; default 2)")
70    logs.add_argument("--output", choices=("human", "json", "jsonl"), default="human")
71    logs.add_argument("--json", action="store_true", help="alias for --output json without --follow")
72    logs.add_argument("--quiet", action="store_true", help="suppress human progress text")
73
74
75def add_connections(sp: argparse._SubParsersAction) -> None:
76    connection = sp.add_parser("connection", help="save monitor endpoints without storing credential values")
77    actions = connection.add_subparsers(dest="connection_command", required=True)
78    create = actions.add_parser("create", help="save a named server endpoint")
79    create.add_argument("name")
80    create.add_argument("--url", required=True)
81    create.add_argument("--prefix", default="", help="reverse-proxy path prefix, e.g. /strata")
82    create.add_argument("--credential-env", default="STRATA_TELEMETRY_KEY")
83    show = actions.add_parser("show", help="show a saved connection without its credential")
84    show.add_argument("name")
85    actions.add_parser("list", help="list saved connections")
86    set_command = actions.add_parser("set", help="edit one URL, prefix or credential reference")
87    set_command.add_argument("name")
88    set_command.add_argument("assignment", metavar="KEY=VALUE")
89    set_command.add_argument("--plan", action="store_true")
90    set_command.add_argument("--if-revision", metavar="REVISION")
91    for command in (create, show, actions.choices["list"], set_command):
92        command.add_argument("--output", choices=("human", "json"), default="human")
93        command.add_argument("--json", action="store_true", help="alias for --output json")
94        command.add_argument("--quiet", action="store_true", help="suppress human informational output")
95
96    config = sp.add_parser("config", help="inspect effective client connection settings")
97    config_actions = config.add_subparsers(dest="config_command", required=True)
98    effective = config_actions.add_parser("show", help="show connection and credential origins")
99    effective.add_argument("--effective", action="store_true", help="show resolved settings (default)")
100    _connection(effective)
101    effective.add_argument("--output", choices=("human", "json"), default="human")
102    effective.add_argument("--json", action="store_true", help="alias for --output json")
103    effective.add_argument("--quiet", action="store_true", help="suppress human informational output")
104
105
106def parser() -> argparse.ArgumentParser:
107    ap = argparse.ArgumentParser(prog="strata-monitor", description="Read-only Strata serving client")
108    sp = ap.add_subparsers(dest="command", required=True)
109    add_status(sp)
110    add_monitor(sp)
111    add_logs(sp)
112    add_connections(sp)
113    return ap
114
115
116def _file_words(exc: BaseException) -> str:
117    try:
118        from strata_control import longpath
119    except ImportError:                                 # the standalone monitor bundle does not carry strata_control
120        return f"local file operation failed ({type(exc).__name__})"
121    return longpath.file_words(exc)
122
123
124def _error(message: str, code: int, machine: bool) -> int:
125    if machine:
126        print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))
127    else:
128        print(f"strata: {message}", file=sys.stderr)
129    return code
130
131
132def _local_command(a: argparse.Namespace, machine: bool) -> int:
133    if a.command == "config":
134        resolved = connections.resolve(url=a.url, connection=a.connection,
135                                       credential_env=a.credential_env, timeout=a.timeout)
136        payload = {"schema_version": 1, "ok": True, "effective": resolved}
137        print(json.dumps(payload if machine else resolved, indent=None if machine else 2,
138                         ensure_ascii=False))
139        return 0
140    action = a.connection_command
141    if action == "list":
142        rows = connections.list_connections()
143        payload = {"schema_version": 1, "ok": True, "connections": rows}
144    elif action == "show":
145        value, revision = connections.load(a.name)
146        payload = {"schema_version": 1, "ok": True, "connection": value, "revision": revision}
147    elif action == "create":
148        value, revision = connections.create(a.name, a.url, prefix=a.prefix,
149                                             credential_env=a.credential_env)
150        payload = {"schema_version": 1, "ok": True, "connection": value, "revision": revision}
151    else:
152        value, revision = connections.propose(a.name, a.assignment)
153        if a.if_revision is not None and a.if_revision != revision:
154            raise connections.ConnectionError("connection changed since preview; inspect it again", 6)
155        if a.plan:
156            payload = {"schema_version": 1, "ok": True, "connection": value,
157                       "revision": revision, "would_save": value != connections.load(a.name)[0]}
158        else:
159            saved, new_revision = connections.save(a.name, value, expected_revision=revision)
160            payload = {"schema_version": 1, "ok": True, "connection": saved,
161                       "previous_revision": revision, "revision": new_revision}
162    print(json.dumps(payload if machine else {k: v for k, v in payload.items() if k not in ("schema_version", "ok")},
163                     indent=None if machine else 2, ensure_ascii=False))
164    return 0
165
166
167def run(a: argparse.Namespace) -> int:
168    machine = a.output in ("json", "jsonl") or getattr(a, "json", False)
169    quiet = bool(getattr(a, "quiet", False) and not machine)
170    try:
171        if a.command in ("connection", "config"):
172            if quiet:
173                with contextlib.redirect_stdout(io.StringIO()):
174                    return _local_command(a, machine)
175            return _local_command(a, machine)
176        if a.command == "logs":
177            if not 0.5 <= a.interval <= 30:
178                return _error("--interval must be 0.5–30 seconds", 2, machine)
179            if a.json:
180                if a.follow or a.output == "jsonl":
181                    return _error("--json is one-shot only; use --follow --output jsonl", 2, machine)
182                a.output = "json"
183            if a.follow and a.output == "json":
184                return _error("--follow requires human or jsonl output", 2, machine)
185            if not a.follow and a.output == "jsonl":
186                return _error("jsonl output requires --follow", 2, machine)
187            if a.source == "harness":
188                return _error("shared local harness activity is unavailable; use --source runtime", 5, machine)
189        if a.command == "monitor" and (a.interval < 0.5 or a.interval > 30 or not 1 <= a.requests <= 50):
190            return _error("--interval must be 0.5–30 seconds and --requests must be 1–50", 2, machine)
191        if a.command == "monitor" and (a.json or a.output == "json") and not a.once:
192            return _error("JSON monitor output requires --once; interactive monitor uses a terminal", 2, machine)
193        if a.command == "monitor" and not a.once and not sys.stdout.isatty():
194            return _error("interactive monitor needs a terminal; use --once or strata status --json", 2, machine)
195        found = running_launch() if a.command in ("monitor", "status", "logs") and not (a.url or a.connection) else None
196        resolved = connections.resolve(url=found["url"] if found else a.url, connection=a.connection,
197                                       credential_env=a.credential_env, timeout=a.timeout)
198        endpoint = Endpoint(resolved["url"], os.environ.get(resolved["credential_env"]) or (found or {}).get("key"),
199                            resolved["timeout_s"], resolved["prefix"])
200        if a.command == "logs":
201            from strata_cli.logs import run as run_logs
202            return run_logs(endpoint, follow=a.follow, output=a.output, interval=a.interval, quiet=quiet)
203        if machine or a.command == "status" or a.once:
204            snapshot = endpoint.snapshot()
205        if machine:
206            print(json.dumps({"schema_version": 1, "ok": True, "snapshot": snapshot},
207                             ensure_ascii=False, allow_nan=False))
208            return 0
209        if a.command == "status" or a.once:
210            from strata_cli.render import render_view
211            if not quiet:
212                print(render_view(snapshot, "overview", width=80, height=24))
213            return 0
214        try:
215            from strata_cli.launch.monitor_ext import LaunchMonitor
216        except ImportError:
217            # the portable monitor bundle carries the read-only client only (no launch/Connect view): run the plain Monitor
218            try:
219                from strata_cli.monitor import MonitorApp
220            except ImportError:
221                return _error("monitor component missing; install the optional terminal UI dependency", 5, machine)
222            MonitorApp(endpoint, None, interval=a.interval, requests=a.requests,
223                       theme=a.theme, color=a.color, glyphs=a.glyphs).run()
224            return 0
225        # the one monitor, with the same seven views as the one `strata launch` opens (Connect is key 7 and works against this --url
226        # server); q just detaches here: nothing was started by this command, so there is nothing to stop
227        LaunchMonitor(endpoint, None, info={"url": endpoint.base_url, "urls": [endpoint.base_url], "key": endpoint.credential or "", "model": "",
228                                            "profile": None, "name": None}, ask_quit=False, interval=a.interval, requests=a.requests,
229                      theme=a.theme, color=a.color, glyphs=a.glyphs).run()
230        return 0
231    except ClientError as e:
232        return _error(str(e), e.exit_code, machine)
233    except connections.ConnectionError as e:
234        return _error(str(e), e.exit_code, machine)
235    except ValueError as e:
236        return _error(str(e), 2, machine)
237    except BrokenPipeError:
238        return 0
239    except OSError as e:
240        return _error(_file_words(e), 6, machine)
241    except KeyboardInterrupt:
242        if a.command == "logs" and a.follow:
243            return 0
244        return _error("interrupted; operation completion may be unknown", 130, machine)
245
246
247def main(argv: list[str] | None = None) -> int:
248    return run(parser().parse_args(argv))