orbital-client 0.2.0__tar.gz

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.
Files changed (40) hide show
  1. orbital_client-0.2.0/PKG-INFO +40 -0
  2. orbital_client-0.2.0/README.md +23 -0
  3. orbital_client-0.2.0/pyproject.toml +69 -0
  4. orbital_client-0.2.0/setup.cfg +4 -0
  5. orbital_client-0.2.0/src/orbital_cli/__init__.py +3 -0
  6. orbital_client-0.2.0/src/orbital_cli/__main__.py +3 -0
  7. orbital_client-0.2.0/src/orbital_cli/client.py +138 -0
  8. orbital_client-0.2.0/src/orbital_cli/commands/__init__.py +1 -0
  9. orbital_client-0.2.0/src/orbital_cli/commands/admin.py +84 -0
  10. orbital_client-0.2.0/src/orbital_cli/commands/apply.py +87 -0
  11. orbital_client-0.2.0/src/orbital_cli/commands/apps.py +413 -0
  12. orbital_client-0.2.0/src/orbital_cli/commands/auth.py +89 -0
  13. orbital_client-0.2.0/src/orbital_cli/commands/common.py +36 -0
  14. orbital_client-0.2.0/src/orbital_cli/commands/misc.py +67 -0
  15. orbital_client-0.2.0/src/orbital_cli/commands/observe.py +279 -0
  16. orbital_client-0.2.0/src/orbital_cli/commands/secrets.py +67 -0
  17. orbital_client-0.2.0/src/orbital_cli/commands/tokens.py +70 -0
  18. orbital_client-0.2.0/src/orbital_cli/config.py +169 -0
  19. orbital_client-0.2.0/src/orbital_cli/errors.py +56 -0
  20. orbital_client-0.2.0/src/orbital_cli/main.py +191 -0
  21. orbital_client-0.2.0/src/orbital_cli/manifest.py +221 -0
  22. orbital_client-0.2.0/src/orbital_cli/output.py +141 -0
  23. orbital_client-0.2.0/src/orbital_cli/py.typed +0 -0
  24. orbital_client-0.2.0/src/orbital_cli/resolve.py +29 -0
  25. orbital_client-0.2.0/src/orbital_cli/state.py +82 -0
  26. orbital_client-0.2.0/src/orbital_cli/wait.py +256 -0
  27. orbital_client-0.2.0/src/orbital_client.egg-info/PKG-INFO +40 -0
  28. orbital_client-0.2.0/src/orbital_client.egg-info/SOURCES.txt +38 -0
  29. orbital_client-0.2.0/src/orbital_client.egg-info/dependency_links.txt +1 -0
  30. orbital_client-0.2.0/src/orbital_client.egg-info/entry_points.txt +3 -0
  31. orbital_client-0.2.0/src/orbital_client.egg-info/requires.txt +8 -0
  32. orbital_client-0.2.0/src/orbital_client.egg-info/top_level.txt +1 -0
  33. orbital_client-0.2.0/tests/test_apply.py +147 -0
  34. orbital_client-0.2.0/tests/test_client.py +102 -0
  35. orbital_client-0.2.0/tests/test_commands.py +716 -0
  36. orbital_client-0.2.0/tests/test_config.py +100 -0
  37. orbital_client-0.2.0/tests/test_contract.py +150 -0
  38. orbital_client-0.2.0/tests/test_manifest.py +148 -0
  39. orbital_client-0.2.0/tests/test_output.py +57 -0
  40. orbital_client-0.2.0/tests/test_wait.py +233 -0
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: orbital-client
3
+ Version: 0.2.0
4
+ Summary: Command-line interface for Orbital, for terminals, CI pipelines and agents
5
+ License-Expression: GPL-3.0-or-later
6
+ Project-URL: Documentation, https://gggard.github.io/orbital/CLI/
7
+ Project-URL: Source, https://github.com/gggard/orbital
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: httpx>=0.28.1
11
+ Requires-Dist: typer>=0.29.3
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=9.2.0; extra == "dev"
14
+ Requires-Dist: pytest-cov>=7.1.0; extra == "dev"
15
+ Requires-Dist: ruff>=0.17.4; extra == "dev"
16
+ Requires-Dist: mypy>=2.4.1; extra == "dev"
17
+
18
+ # orbital-client
19
+
20
+ Command-line interface for [Orbital](https://github.com/gggard/orbital):
21
+ deploy and manage apps from a terminal, a CI pipeline or an AI agent.
22
+
23
+ ```bash
24
+ uvx orbital-client --help
25
+ ```
26
+
27
+ See the [CLI guide](https://gggard.github.io/orbital/CLI/) (source:
28
+ [docs/CLI.md](../docs/CLI.md)) for installation, authentication, CI
29
+ recipes and the full command reference.
30
+
31
+ ## Development
32
+
33
+ ```bash
34
+ make cli-install # from the repo root: installs the CLI and the control plane in .venv
35
+ make cli-test cli-lint cli-typecheck
36
+ ```
37
+
38
+ The contract tests in `tests/test_contract.py` run CLI commands against the
39
+ real control-plane API in-process, so they need the `orbital` package
40
+ installed too (`make cli-install` does both); they're skipped otherwise.
@@ -0,0 +1,23 @@
1
+ # orbital-client
2
+
3
+ Command-line interface for [Orbital](https://github.com/gggard/orbital):
4
+ deploy and manage apps from a terminal, a CI pipeline or an AI agent.
5
+
6
+ ```bash
7
+ uvx orbital-client --help
8
+ ```
9
+
10
+ See the [CLI guide](https://gggard.github.io/orbital/CLI/) (source:
11
+ [docs/CLI.md](../docs/CLI.md)) for installation, authentication, CI
12
+ recipes and the full command reference.
13
+
14
+ ## Development
15
+
16
+ ```bash
17
+ make cli-install # from the repo root: installs the CLI and the control plane in .venv
18
+ make cli-test cli-lint cli-typecheck
19
+ ```
20
+
21
+ The contract tests in `tests/test_contract.py` run CLI commands against the
22
+ real control-plane API in-process, so they need the `orbital` package
23
+ installed too (`make cli-install` does both); they're skipped otherwise.
@@ -0,0 +1,69 @@
1
+ [project]
2
+ name = "orbital-client"
3
+ dynamic = ["version"]
4
+ description = "Command-line interface for Orbital, for terminals, CI pipelines and agents"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "GPL-3.0-or-later"
8
+ dependencies = [
9
+ "httpx>=0.28.1",
10
+ "typer>=0.29.3",
11
+ ]
12
+
13
+ [project.optional-dependencies]
14
+ dev = [
15
+ "pytest>=9.2.0",
16
+ "pytest-cov>=7.1.0",
17
+ "ruff>=0.17.4",
18
+ "mypy>=2.4.1",
19
+ ]
20
+
21
+ [project.scripts]
22
+ orbital = "orbital_cli.main:run"
23
+ # same entry point under the package name, so `uvx orbital-client ...` works
24
+ orbital-client = "orbital_cli.main:run"
25
+
26
+ [project.urls]
27
+ Documentation = "https://gggard.github.io/orbital/CLI/"
28
+ Source = "https://github.com/gggard/orbital"
29
+
30
+ [build-system]
31
+ requires = ["setuptools>=84.2.1"]
32
+ build-backend = "setuptools.build_meta"
33
+
34
+ [tool.setuptools.dynamic]
35
+ version = { attr = "orbital_cli.__version__" }
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+
43
+ [tool.coverage.run]
44
+ source = ["src/orbital_cli"]
45
+ branch = true
46
+
47
+ [tool.coverage.report]
48
+ show_missing = true
49
+
50
+ [tool.ruff]
51
+ line-length = 100
52
+ target-version = "py312"
53
+
54
+ [tool.ruff.lint]
55
+ select = ["E", "W", "F", "I", "B", "UP", "C4", "SIM"]
56
+ ignore = [
57
+ "B008", # Typer's `typer.Option(...)` idiom relies on call-in-default-argument
58
+ ]
59
+
60
+ [tool.ruff.lint.isort]
61
+ known-first-party = ["orbital_cli"]
62
+
63
+ [tool.mypy]
64
+ python_version = "3.12"
65
+ packages = ["orbital_cli"]
66
+ mypy_path = "src"
67
+ ignore_missing_imports = true
68
+ warn_unused_ignores = true
69
+ warn_redundant_casts = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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()
@@ -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)