orbital-client 0.2.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,3 @@
1
+ """Command-line interface for Orbital."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,3 @@
1
+ from .main import run
2
+
3
+ run()
orbital_cli/client.py ADDED
@@ -0,0 +1,138 @@
1
+ """Thin HTTP client over the control-plane REST API.
2
+
3
+ Every non-2xx response becomes a CliError carrying the exit code that
4
+ matches its status (see errors.py), with the server's `detail` message.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from collections.abc import Callable, Iterator
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ from . import __version__
16
+ from .errors import CliError, ExitCode, code_for_status
17
+
18
+ API_PREFIX = "/api/v1"
19
+ DEFAULT_TIMEOUT = 30.0
20
+
21
+ HttpFactory = Callable[..., httpx.Client]
22
+
23
+
24
+ def default_http_factory(*, base_url: str, headers: dict[str, str], timeout: float) -> httpx.Client:
25
+ return httpx.Client(base_url=base_url, headers=headers, timeout=timeout)
26
+
27
+
28
+ # Swapped out by tests to point the CLI at an in-process control plane.
29
+ http_factory: HttpFactory = default_http_factory
30
+
31
+
32
+ def _detail(response: httpx.Response) -> str:
33
+ try:
34
+ body = response.json()
35
+ except ValueError:
36
+ return response.text.strip() or response.reason_phrase
37
+ detail = body.get("detail", body) if isinstance(body, dict) else body
38
+ if isinstance(detail, list): # FastAPI/pydantic validation errors
39
+ parts = []
40
+ for err in detail:
41
+ if isinstance(err, dict):
42
+ loc = ".".join(str(x) for x in err.get("loc", []) if x != "body")
43
+ parts.append(f"{loc}: {err.get('msg')}" if loc else str(err.get("msg")))
44
+ else:
45
+ parts.append(str(err))
46
+ return "; ".join(parts)
47
+ return str(detail)
48
+
49
+
50
+ class Client:
51
+ def __init__(self, base_url: str, token: str | None, *, verbose: bool = False):
52
+ self.base_url = base_url.rstrip("/")
53
+ self.verbose = verbose
54
+ headers = {"User-Agent": f"orbital-client/{__version__}", "Accept": "application/json"}
55
+ if token:
56
+ headers["Authorization"] = f"Bearer {token}"
57
+ self._http = http_factory(base_url=self.base_url, headers=headers, timeout=DEFAULT_TIMEOUT)
58
+
59
+ def close(self) -> None:
60
+ self._http.close()
61
+
62
+ # -- core ----------------------------------------------------------------
63
+
64
+ def _url(self, path: str) -> str:
65
+ return path if path.startswith(("/healthz", "/api/")) else API_PREFIX + path
66
+
67
+ def _log(self, method: str, url: str, status: int | None = None) -> None:
68
+ if self.verbose:
69
+ suffix = f" -> {status}" if status is not None else ""
70
+ # the Authorization header is never printed
71
+ print(f"> {method} {self.base_url}{url}{suffix}", file=sys.stderr)
72
+
73
+ def _check(self, response: httpx.Response) -> httpx.Response:
74
+ if response.is_success:
75
+ return response
76
+ status = response.status_code
77
+ message = _detail(response)
78
+ if status == 401:
79
+ message = f"not authenticated ({message}); set ORBITAL_TOKEN or run `orbital login`"
80
+ elif status == 403:
81
+ message = f"permission denied: {message}"
82
+ raise CliError(message, code_for_status(status), http_status=status)
83
+
84
+ def request(
85
+ self,
86
+ method: str,
87
+ path: str,
88
+ *,
89
+ json: Any = None,
90
+ params: dict[str, Any] | None = None,
91
+ timeout: float | None = None,
92
+ ) -> httpx.Response:
93
+ url = self._url(path)
94
+ kwargs: dict[str, Any] = {"json": json, "params": params}
95
+ if timeout is not None:
96
+ kwargs["timeout"] = timeout
97
+ try:
98
+ response = self._http.request(method, url, **kwargs)
99
+ except httpx.TimeoutException as e:
100
+ raise CliError(f"request to {self.base_url} timed out: {e}", ExitCode.ERROR) from e
101
+ except httpx.TransportError as e:
102
+ raise CliError(f"cannot reach {self.base_url}: {e}", ExitCode.ERROR) from e
103
+ self._log(method, url, response.status_code)
104
+ return self._check(response)
105
+
106
+ def get(self, path: str, **params: Any) -> Any:
107
+ clean = {k: v for k, v in params.items() if v is not None}
108
+ return self.request("GET", path, params=clean or None).json()
109
+
110
+ def get_text(self, path: str, **params: Any) -> str:
111
+ clean = {k: v for k, v in params.items() if v is not None}
112
+ return self.request("GET", path, params=clean or None).text
113
+
114
+ def post(self, path: str, json: Any = None) -> Any:
115
+ return self.request("POST", path, json=json).json()
116
+
117
+ def patch(self, path: str, json: Any) -> Any:
118
+ return self.request("PATCH", path, json=json).json()
119
+
120
+ def put(self, path: str, json: Any) -> Any:
121
+ return self.request("PUT", path, json=json).json()
122
+
123
+ def delete(self, path: str) -> Any:
124
+ return self.request("DELETE", path).json()
125
+
126
+ def stream_text(self, path: str, **params: Any) -> Iterator[str]:
127
+ """Yield decoded text chunks of a streaming (chunked) response."""
128
+ url = self._url(path)
129
+ clean = {k: v for k, v in params.items() if v is not None}
130
+ try:
131
+ with self._http.stream("GET", url, params=clean, timeout=None) as response:
132
+ self._log("GET", url, response.status_code)
133
+ if not response.is_success:
134
+ response.read()
135
+ self._check(response)
136
+ yield from response.iter_text()
137
+ except httpx.TransportError as e:
138
+ raise CliError(f"connection to {self.base_url} lost: {e}", ExitCode.ERROR) from e
@@ -0,0 +1 @@
1
+ """Command groups; each module exposes `register(app)`."""
@@ -0,0 +1,84 @@
1
+ """`orbital admin ...` (admin role only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from ..output import Column, ago, col, emit, info, write_text
8
+ from ..state import get_state
9
+ from .observe import SCAN_COLUMNS
10
+
11
+ admin_app = typer.Typer(help="Platform-wide views (admin role only).", no_args_is_help=True)
12
+
13
+
14
+ @admin_app.command("overview")
15
+ def overview() -> None:
16
+ """Fleet summary: app count, running apps, resource usage per app."""
17
+ s = get_state()
18
+ data = s.client.get("/admin/overview")
19
+ if s.fmt != "table":
20
+ emit(data["apps"] if s.fmt == "name" else data, s.fmt, name_key="slug")
21
+ return
22
+ t = data["totals"]
23
+ info(
24
+ f"{t['app_count']} apps, {t['running_count']} running, "
25
+ f"{t['cpu']:.2f} cores, {t['mem'] / 1024 / 1024:.0f} MiB in use"
26
+ )
27
+ emit(
28
+ data["apps"],
29
+ "table",
30
+ columns=[
31
+ col("SLUG", "slug"),
32
+ col("STATE", "state"),
33
+ Column("CPU", lambda a: None if a.get("cpu") is None else f"{a['cpu']:.3f}"),
34
+ Column(
35
+ "MEM MIB", lambda a: None if a.get("mem") is None else f"{a['mem'] / 2**20:.0f}"
36
+ ),
37
+ col("RESTARTS", "restarts"),
38
+ col("OWNERS", "owner_groups"),
39
+ ],
40
+ empty="No apps.",
41
+ )
42
+
43
+
44
+ @admin_app.command("activity")
45
+ def activity(
46
+ limit: int = typer.Option(20, "--limit", min=1, max=100, help="Number of events"),
47
+ ) -> None:
48
+ """Recent platform-wide events, newest first."""
49
+ s = get_state()
50
+ emit(
51
+ s.client.get("/admin/activity", limit=limit),
52
+ s.fmt,
53
+ columns=[
54
+ Column("WHEN", lambda e: ago(e.get("created_at"))),
55
+ col("LEVEL", "level"),
56
+ col("APP", "slug"),
57
+ col("EVENT", "text"),
58
+ col("ACTOR", "actor"),
59
+ ],
60
+ empty="No activity.",
61
+ )
62
+
63
+
64
+ @admin_app.command("logs")
65
+ def logs(tail: int = typer.Option(500, "--tail", min=1, help="Number of recent lines")) -> None:
66
+ """Control-plane logs (always raw text)."""
67
+ write_text(get_state().client.get_text("/admin/logs", tail=tail))
68
+
69
+
70
+ @admin_app.command("scans")
71
+ def scans() -> None:
72
+ """Latest vulnerability scan of every app."""
73
+ s = get_state()
74
+ emit(
75
+ s.client.get("/admin/scans"),
76
+ s.fmt,
77
+ columns=[col("APP", "slug"), *SCAN_COLUMNS],
78
+ name_key="slug",
79
+ empty="No scans.",
80
+ )
81
+
82
+
83
+ def register(app: typer.Typer) -> None:
84
+ app.add_typer(admin_app, name="admin")
@@ -0,0 +1,87 @@
1
+ """`orbital apply -f orbital.toml`: create or update an app declaratively."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import typer
8
+
9
+ from .. import manifest
10
+ from .. import wait as waiting
11
+ from ..output import emit, emit_json, info
12
+ from ..resolve import find_app
13
+ from ..state import get_state
14
+ from .apps import show_app
15
+ from .common import timeout_option
16
+
17
+
18
+ def apply(
19
+ file: Path = typer.Option(
20
+ Path("orbital.toml"), "-f", "--file", help="Manifest to apply", show_default=True
21
+ ),
22
+ redeploy: bool = typer.Option(
23
+ True,
24
+ "--redeploy/--no-redeploy",
25
+ help="Redeploy after applying, even if no setting needs a rebuild",
26
+ ),
27
+ dry_run: bool = typer.Option(False, "--dry-run", help="Print the plan and change nothing"),
28
+ wait: bool = typer.Option(
29
+ False, "--wait", help="Block until the resulting deploy succeeds (exit 0) or fails (exit 8)"
30
+ ),
31
+ follow: bool = typer.Option(
32
+ False, "--follow", help="Stream build logs to stderr while waiting (implies --wait)"
33
+ ),
34
+ timeout: float = timeout_option(),
35
+ ) -> None:
36
+ """Create the app described by the manifest, or update the settings that
37
+ differ and redeploy. Secrets are never read from the manifest."""
38
+ s = get_state()
39
+ spec = manifest.load(file)
40
+ app = find_app(s.client, spec["slug"])
41
+ plan = manifest.plan(spec, app, redeploy=redeploy)
42
+
43
+ if dry_run:
44
+ if s.fmt == "json":
45
+ emit_json(plan.to_dict())
46
+ else:
47
+ print(plan.describe())
48
+ return
49
+ if not s.quiet:
50
+ info(plan.describe())
51
+
52
+ if plan.action == "create":
53
+ result = s.client.post("/apps", json=spec)
54
+ before = {**result, "current_build_id": None}
55
+ else:
56
+ assert app is not None
57
+ before = app
58
+ result = app
59
+ if plan.action == "update":
60
+ payload = {k: c["to"] for k, c in plan.changes.items()}
61
+ result = s.client.patch(f"/apps/{app['id']}", json=payload)
62
+ if plan.redeploy and not plan.rebuild_by_patch:
63
+ s.client.post(f"/apps/{app['id']}/deploy")
64
+
65
+ building_already = "already in progress" in plan.reason
66
+ if (wait or follow) and (plan.redeploy or building_already):
67
+ if building_already:
68
+ # follow the build that's already running rather than a new one
69
+ result = waiting.wait_for_state(
70
+ s.client, before, target="running", timeout=timeout, progress=not s.quiet
71
+ )
72
+ else:
73
+ result = waiting.wait_for_rollout(
74
+ s.client, before, timeout=timeout, follow=follow, progress=not s.quiet
75
+ )
76
+ elif plan.redeploy and not s.quiet:
77
+ info(f"{spec['slug']}: deploy scheduled")
78
+ if s.fmt == "name":
79
+ print(result["slug"])
80
+ elif s.fmt == "json":
81
+ emit(result, "json")
82
+ else:
83
+ show_app(result)
84
+
85
+
86
+ def register(app: typer.Typer) -> None:
87
+ app.command("apply")(apply)