nacho-python 0.1.1__py3-none-any.whl → 1.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.
nacho/__init__.py CHANGED
@@ -4,6 +4,7 @@ from ._version import __version__
4
4
  from .config import Nacho
5
5
  from .event import EventType
6
6
  from .schema import HAS_SCHEMA_DEPS, ValidationError
7
+ from .server import HAS_SERVER_DEPS, NachoOrchestrator
7
8
  from .storage import (
8
9
  HAS_REMOTE_DEPS,
9
10
  AuthError,
@@ -16,13 +17,6 @@ from .storage import (
16
17
  StorageError,
17
18
  )
18
19
 
19
- try:
20
- from .server.app import NachoOrchestrator
21
-
22
- HAS_SERVER_DEPS = True
23
- except ImportError: # pragma: no cover - optional 'server' extra not installed
24
- HAS_SERVER_DEPS = False
25
-
26
20
  __all__ = [
27
21
  "__version__",
28
22
  "Nacho",
@@ -41,6 +35,3 @@ __all__ = [
41
35
  "HAS_REMOTE_DEPS",
42
36
  "HAS_SERVER_DEPS",
43
37
  ]
44
- if not HAS_SERVER_DEPS:
45
- # Keep __all__ truthful so `from nacho import *` never hits an undefined name.
46
- __all__.remove("NachoOrchestrator")
nacho/_version.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Version information for Nacho."""
2
2
 
3
- __version__ = "0.1.1"
3
+ __version__ = "1.1.0"
nacho/cli/main.py CHANGED
@@ -8,8 +8,9 @@ import ipaddress
8
8
  import json
9
9
  import logging
10
10
  import sys
11
+ from collections.abc import Callable
11
12
  from pathlib import Path
12
- from typing import TYPE_CHECKING, Any, Callable, List, Optional
13
+ from typing import TYPE_CHECKING, Any
13
14
 
14
15
  from nacho import HAS_REMOTE_DEPS, HAS_SCHEMA_DEPS, HAS_SERVER_DEPS
15
16
  from nacho._version import __version__
@@ -26,11 +27,9 @@ if TYPE_CHECKING: # pragma: no cover - typing only
26
27
 
27
28
  LOGGER = logging.getLogger("nacho.cli")
28
29
 
29
- # Exit codes. EXIT_USAGE is argparse's own code for bad arguments; the rest
30
- # are produced by the @cli_command wrapper from the typed client errors.
30
+ # Exit codes produced by the @cli_command wrapper from typed client errors.
31
31
  EXIT_OK = 0
32
32
  EXIT_ERROR = 1
33
- EXIT_USAGE = 2
34
33
  EXIT_NOT_FOUND = 3
35
34
  EXIT_CONFLICT = 4
36
35
  EXIT_AUTH = 5
@@ -49,7 +48,7 @@ def banner() -> str:
49
48
  return f"{BANNER} Lightweight, self-hosted dynamic configuration · v{__version__}\n"
50
49
 
51
50
 
52
- BUILT_IN_TEMPLATES = {
51
+ BUILT_IN_TEMPLATES: dict[str, dict[str, Any]] = {
53
52
  "empty": {},
54
53
  "web-app": {
55
54
  "app": {"name": "web-app", "version": "1.0.0", "port": 3000},
@@ -110,21 +109,21 @@ def require_remote_deps() -> None:
110
109
  raise ImportError("Remote features require: pip install nacho-python[remote]")
111
110
 
112
111
 
113
- def build_client(args: argparse.Namespace, app_name: Optional[str] = None) -> "NachoClient":
112
+ def build_client(args: argparse.Namespace, app_name: str | None = None) -> "NachoClient":
114
113
  """Build the one NachoClient a command uses from --remote/--app-name/--api-key."""
115
114
  require_remote_deps()
116
115
  from nacho.client import NachoClient
117
116
 
118
117
  return NachoClient(
119
118
  args.remote,
120
- app_name=app_name or getattr(args, "app_name", "default"),
119
+ app_name=app_name or getattr(args, "app_name", None) or "default",
121
120
  api_key=args.api_key,
122
121
  )
123
122
 
124
123
 
125
124
  def create_config(
126
- config_path: Optional[str] = None,
127
- schema: Optional[str] = None,
125
+ config_path: str | None = None,
126
+ schema: str | None = None,
128
127
  read_only: bool = False,
129
128
  ) -> Nacho:
130
129
  """Create a Nacho instance for a local config file."""
@@ -245,10 +244,6 @@ def create_parser() -> argparse.ArgumentParser:
245
244
  server.add_argument("--schema", help="Schema file path")
246
245
  server.add_argument("--data-dir", help="Directory for API-created app state")
247
246
  server.add_argument("--api-key", help="API key for authentication")
248
- server.add_argument(
249
- "--read-only-api-key",
250
- help="Additional API key granting read access only (GETs and WebSocket watch)",
251
- )
252
247
  server.add_argument("--app-name", help="Application name for config server")
253
248
  server.add_argument(
254
249
  "--history-limit",
@@ -256,7 +251,11 @@ def create_parser() -> argparse.ArgumentParser:
256
251
  default=50,
257
252
  help="Revision snapshots to keep per app for rollback (0 disables history)",
258
253
  )
259
- server.add_argument("--read-only", action="store_true", help="Read-only mode")
254
+ server.add_argument(
255
+ "--read-only",
256
+ action="store_true",
257
+ help="Serve reads only — every write is refused, whoever the caller is",
258
+ )
260
259
  server.add_argument("--reload", action="store_true", help="Auto-reload for development")
261
260
  server.set_defaults(func=cmd_server)
262
261
 
@@ -443,9 +442,7 @@ def cmd_server(args: argparse.Namespace) -> int:
443
442
 
444
443
  print(banner())
445
444
 
446
- # With only a read-only key configured, nobody can write at all, so the
447
- # exposure warning only applies when NO key protects the server.
448
- if not args.api_key and not args.read_only_api_key and not is_loopback_host(args.host):
445
+ if not args.api_key and not is_loopback_host(args.host):
449
446
  print(
450
447
  "WARNING: serving on a non-loopback interface without --api-key — "
451
448
  "anyone who can reach this host has full write access.",
@@ -460,7 +457,6 @@ def cmd_server(args: argparse.Namespace) -> int:
460
457
  orchestrator = NachoOrchestrator(
461
458
  apps=apps,
462
459
  api_key=args.api_key,
463
- read_only_api_key=args.read_only_api_key,
464
460
  read_only=args.read_only,
465
461
  data_dir=args.data_dir,
466
462
  history_limit=args.history_limit,
@@ -675,7 +671,7 @@ def cmd_history_diff(args: argparse.Namespace) -> int:
675
671
  schema_b = client.get_schema()
676
672
  label_b = f"current (revision {revision})"
677
673
 
678
- def as_lines(config: dict) -> List[str]:
674
+ def as_lines(config: dict) -> list[str]:
679
675
  return json.dumps(config, indent=2, sort_keys=True, ensure_ascii=False).splitlines()
680
676
 
681
677
  diff = list(
@@ -734,7 +730,7 @@ def cmd_watch(args: argparse.Namespace) -> int:
734
730
  # ---------------------------------------------------------------------------
735
731
  # Entry point
736
732
  # ---------------------------------------------------------------------------
737
- def main_cli(argv: Optional[List[str]] = None) -> int:
733
+ def main_cli(argv: list[str] | None = None) -> int:
738
734
  """Main CLI entry point."""
739
735
  parser = create_parser()
740
736
  args = parser.parse_args(argv)
nacho/client.py CHANGED
@@ -11,7 +11,8 @@ Requires the ``remote`` extra (``pip install nacho-python[remote]``).
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
- from typing import Any, Dict, List, Optional, Tuple
14
+ from typing import Any
15
+ from urllib.parse import quote
15
16
 
16
17
  import requests
17
18
 
@@ -33,19 +34,20 @@ class NachoClient:
33
34
  self,
34
35
  url: str,
35
36
  app_name: str = "default",
36
- api_key: Optional[str] = None,
37
+ api_key: str | None = None,
37
38
  timeout: float = _DEFAULT_TIMEOUT,
38
39
  ) -> None:
39
40
  self.base = url.rstrip("/")
40
41
  self.app_name = app_name
41
42
  self.api_key = api_key
42
43
  self.timeout = timeout
44
+ self.last_generation: str | None = None
43
45
 
44
46
  # ------------------------------------------------------------------
45
47
  # Low-level request plumbing
46
48
  # ------------------------------------------------------------------
47
49
 
48
- def headers(self) -> Dict[str, str]:
50
+ def headers(self) -> dict[str, str]:
49
51
  if self.api_key:
50
52
  return {"Authorization": f"Bearer {self.api_key}"}
51
53
  return {}
@@ -55,9 +57,9 @@ class NachoClient:
55
57
  method: str,
56
58
  path: str,
57
59
  *,
58
- json_body: Optional[Dict[str, Any]] = None,
59
- params: Optional[Dict[str, Any]] = None,
60
- allowed: Tuple[int, ...] = (),
60
+ json_body: dict[str, Any] | None = None,
61
+ params: dict[str, Any] | None = None,
62
+ allowed: tuple[int, ...] = (),
61
63
  ) -> requests.Response:
62
64
  """Perform a request; raise a typed error for any non-2xx status
63
65
  not listed in *allowed*."""
@@ -109,10 +111,15 @@ class NachoClient:
109
111
  raise RemoteError(message, status=status_code, detail=detail)
110
112
 
111
113
  def _app(self, suffix: str = "") -> str:
112
- return f"/api/apps/{self.app_name}{suffix}"
114
+ return f"/api/apps/{quote(self.app_name, safe='')}{suffix}"
115
+
116
+ def _record_generation(self, resp: requests.Response) -> None:
117
+ generation = resp.headers.get("X-Nacho-Generation")
118
+ if generation:
119
+ self.last_generation = generation
113
120
 
114
121
  @staticmethod
115
- def _revision_from(resp: requests.Response) -> Optional[int]:
122
+ def _revision_from(resp: requests.Response) -> int | None:
116
123
  raw = resp.headers.get("X-Nacho-Revision")
117
124
  return int(raw) if raw and raw.isdigit() else None
118
125
 
@@ -120,10 +127,10 @@ class NachoClient:
120
127
  # System
121
128
  # ------------------------------------------------------------------
122
129
 
123
- def health(self) -> Dict[str, Any]:
130
+ def health(self) -> dict[str, Any]:
124
131
  return self.request("GET", "/health").json()
125
132
 
126
- def convert(self, data: Any, *, from_fmt: str, to_fmt: str) -> Dict[str, Any]:
133
+ def convert(self, data: Any, *, from_fmt: str, to_fmt: str) -> dict[str, Any]:
127
134
  payload = {"data": data, "from": from_fmt, "to": to_fmt}
128
135
  return self.request("POST", "/api/convert", json_body=payload).json()
129
136
 
@@ -131,19 +138,19 @@ class NachoClient:
131
138
  # Apps
132
139
  # ------------------------------------------------------------------
133
140
 
134
- def list_apps(self) -> Dict[str, Dict[str, Any]]:
141
+ def list_apps(self) -> dict[str, dict[str, Any]]:
135
142
  return self.request("GET", "/api/apps").json()["data"]
136
143
 
137
144
  def create_app(
138
145
  self,
139
146
  *,
140
- data: Optional[Any] = None,
147
+ data: Any | None = None,
141
148
  fmt: str = "json",
142
- schema: Optional[Any] = None,
149
+ schema: Any | None = None,
143
150
  schema_format: str = "json",
144
- description: Optional[str] = None,
145
- ) -> Dict[str, Any]:
146
- payload: Dict[str, Any] = {
151
+ description: str | None = None,
152
+ ) -> dict[str, Any]:
153
+ payload: dict[str, Any] = {
147
154
  "name": self.app_name,
148
155
  "data": data if data is not None else {},
149
156
  "format": fmt,
@@ -155,19 +162,19 @@ class NachoClient:
155
162
  payload["description"] = description
156
163
  return self.request("POST", "/api/apps", json_body=payload).json()
157
164
 
158
- def get_app_info(self) -> Dict[str, Any]:
165
+ def get_app_info(self) -> dict[str, Any]:
159
166
  return self.request("GET", self._app()).json()["data"]
160
167
 
161
- def delete_app(self) -> Dict[str, Any]:
168
+ def delete_app(self) -> dict[str, Any]:
162
169
  return self.request("DELETE", self._app()).json()
163
170
 
164
171
  def update_metadata(
165
172
  self,
166
173
  *,
167
- name: Optional[str] = None,
168
- description: Optional[str] = None,
169
- revision: Optional[int] = None,
170
- ) -> Dict[str, Any]:
174
+ name: str | None = None,
175
+ description: str | None = None,
176
+ revision: int | None = None,
177
+ ) -> dict[str, Any]:
171
178
  payload = {
172
179
  k: v
173
180
  for k, v in (("name", name), ("description", description), ("revision", revision))
@@ -179,20 +186,22 @@ class NachoClient:
179
186
  # Config
180
187
  # ------------------------------------------------------------------
181
188
 
182
- def get_config(self) -> Tuple[Dict[str, Any], Optional[int]]:
189
+ def get_config(self) -> tuple[dict[str, Any], int | None]:
183
190
  resp = self.request("GET", self._app("/config"))
191
+ self._record_generation(resp)
184
192
  return resp.json(), self._revision_from(resp)
185
193
 
186
194
  def put_config(
187
- self, data: Any, *, fmt: str = "json", revision: Optional[int] = None
188
- ) -> Dict[str, Any]:
189
- payload: Dict[str, Any] = {"data": data, "format": fmt}
195
+ self, data: Any, *, fmt: str = "json", revision: int | None = None
196
+ ) -> dict[str, Any]:
197
+ payload: dict[str, Any] = {"data": data, "format": fmt}
190
198
  if revision is not None:
191
199
  payload["revision"] = revision
192
200
  return self.request("PUT", self._app("/config"), json_body=payload).json()
193
201
 
194
- def get_path(self, path: str) -> Tuple[Any, Optional[int]]:
195
- resp = self.request("GET", self._app(f"/config/{path}"))
202
+ def get_path(self, path: str) -> tuple[Any, int | None]:
203
+ resp = self.request("GET", self._app(f"/config/{quote(path, safe='')}"))
204
+ self._record_generation(resp)
196
205
  return resp.json()["value"], self._revision_from(resp)
197
206
 
198
207
  def set_path(
@@ -200,38 +209,42 @@ class NachoClient:
200
209
  path: str,
201
210
  value: Any,
202
211
  *,
203
- revision: Optional[int] = None,
212
+ revision: int | None = None,
204
213
  value_type: str = "raw",
205
- ) -> Dict[str, Any]:
206
- payload: Dict[str, Any] = {"value": value, "type": value_type}
214
+ ) -> dict[str, Any]:
215
+ payload: dict[str, Any] = {"value": value, "type": value_type}
207
216
  if revision is not None:
208
217
  payload["revision"] = revision
209
- return self.request("PUT", self._app(f"/config/{path}"), json_body=payload).json()
218
+ return self.request(
219
+ "PUT", self._app(f"/config/{quote(path, safe='')}"), json_body=payload
220
+ ).json()
210
221
 
211
- def delete_path(self, path: str, *, revision: Optional[int] = None) -> Dict[str, Any]:
222
+ def delete_path(self, path: str, *, revision: int | None = None) -> dict[str, Any]:
212
223
  params = {"revision": revision} if revision is not None else None
213
- return self.request("DELETE", self._app(f"/config/{path}"), params=params).json()
224
+ return self.request(
225
+ "DELETE", self._app(f"/config/{quote(path, safe='')}"), params=params
226
+ ).json()
214
227
 
215
228
  # ------------------------------------------------------------------
216
229
  # Schema
217
230
  # ------------------------------------------------------------------
218
231
 
219
- def get_schema(self) -> Optional[Dict[str, Any]]:
232
+ def get_schema(self) -> dict[str, Any] | None:
220
233
  return self.request("GET", self._app("/schema")).json()["data"]
221
234
 
222
235
  def put_schema(
223
236
  self,
224
- schema: Optional[Any],
237
+ schema: Any | None,
225
238
  *,
226
239
  fmt: str = "json",
227
- revision: Optional[int] = None,
228
- ) -> Dict[str, Any]:
229
- payload: Dict[str, Any] = {"schema": schema, "schema_format": fmt}
240
+ revision: int | None = None,
241
+ ) -> dict[str, Any]:
242
+ payload: dict[str, Any] = {"schema": schema, "schema_format": fmt}
230
243
  if revision is not None:
231
244
  payload["revision"] = revision
232
245
  return self.request("PUT", self._app("/schema"), json_body=payload).json()
233
246
 
234
- def validate(self, data: Any, *, fmt: str = "json") -> Dict[str, Any]:
247
+ def validate(self, data: Any, *, fmt: str = "json") -> dict[str, Any]:
235
248
  payload = {"data": data, "format": fmt}
236
249
  return self.request("POST", self._app("/validate"), json_body=payload).json()
237
250
 
@@ -239,14 +252,14 @@ class NachoClient:
239
252
  # History
240
253
  # ------------------------------------------------------------------
241
254
 
242
- def list_history(self) -> List[Dict[str, Any]]:
255
+ def list_history(self) -> list[dict[str, Any]]:
243
256
  return self.request("GET", self._app("/history")).json()["data"]
244
257
 
245
- def get_history_snapshot(self, revision: int) -> Dict[str, Any]:
258
+ def get_history_snapshot(self, revision: int) -> dict[str, Any]:
246
259
  return self.request("GET", self._app(f"/history/{revision}")).json()["data"]
247
260
 
248
- def rollback(self, revision: int, *, expected_revision: Optional[int] = None) -> Dict[str, Any]:
249
- payload: Dict[str, Any] = {"revision": revision}
261
+ def rollback(self, revision: int, *, expected_revision: int | None = None) -> dict[str, Any]:
262
+ payload: dict[str, Any] = {"revision": revision}
250
263
  if expected_revision is not None:
251
264
  payload["expected_revision"] = expected_revision
252
265
  return self.request("POST", self._app("/rollback"), json_body=payload).json()