nacho-python 0.0.1__py3-none-any.whl → 0.0.3__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
@@ -13,14 +13,14 @@ from .storage import (
13
13
 
14
14
  try:
15
15
  from .storage import RemoteStorageBackend
16
- except ImportError:
16
+ except ImportError: # pragma: no cover - optional 'remote' extra not installed
17
17
  pass
18
18
 
19
19
  try:
20
20
  from .server.app import NachoOrchestrator
21
21
 
22
22
  HAS_SERVER_DEPS = True
23
- except ImportError:
23
+ except ImportError: # pragma: no cover - optional 'server' extra not installed
24
24
  HAS_SERVER_DEPS = False
25
25
 
26
26
  __all__ = [
nacho/_version.py CHANGED
@@ -1,4 +1,4 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """Version information for Nacho."""
3
3
 
4
- __version__ = "0.0.1"
4
+ __version__ = "0.0.3"
nacho/cli/main.py CHANGED
@@ -22,11 +22,11 @@ from nacho.utils.io import save_file
22
22
  LOGGER = logging.getLogger("nacho.cli")
23
23
 
24
24
  BANNER = r"""
25
- _ _ _ ____ _ _ ___
26
- | \ | | / \ / ___|| | | | / _ \
27
- | \| | / _ \ | | | |_| || | | |
28
- | |\ | / ___ \ | |___ | _ || |_| |
29
- |_| \_|/_/ \_\ \____||_| |_| \___/
25
+ _ _ _ ____ _ _ ___
26
+ | \ | | / \ / ___|| | | | / _ \
27
+ | \| | / _ \ | | | |_| || | | |
28
+ | |\ | / ___ \ | |___ | _ || |_| |
29
+ |_| \_|/_/ \_\ \____||_| |_| \___/
30
30
  """
31
31
 
32
32
 
@@ -34,7 +34,7 @@ def banner() -> str:
34
34
  """Return the ASCII banner with a version tagline."""
35
35
  return (
36
36
  f"{BANNER}"
37
- f" Lightweight, schema-first dynamic configuration · v{__version__}\n"
37
+ f" Lightweight, self-hosted dynamic configuration · v{__version__}\n"
38
38
  )
39
39
 
40
40
 
nacho/schema.py CHANGED
@@ -19,7 +19,7 @@ try:
19
19
  from jsonschema import validators as _jv
20
20
 
21
21
  HAS_SCHEMA_DEPS = True
22
- except ImportError:
22
+ except ImportError: # pragma: no cover - optional 'schema' extra not installed
23
23
  HAS_SCHEMA_DEPS = False
24
24
 
25
25
 
@@ -108,13 +108,13 @@ class SchemaValidator:
108
108
  import yaml
109
109
 
110
110
  return yaml.safe_load(path.read_text(encoding="utf-8")) or {}
111
- except ImportError:
111
+ except ImportError: # pragma: no cover - pyyaml is a core dependency
112
112
  raise ImportError("YAML schema files require 'pyyaml'.")
113
113
 
114
114
  if suffix == ".toml":
115
115
  try:
116
116
  import tomllib # type: ignore
117
- except ImportError:
117
+ except ImportError: # pragma: no cover - Python < 3.11 fallback
118
118
  import tomli as tomllib # type: ignore
119
119
  return tomllib.loads(path.read_text(encoding="utf-8")) or {}
120
120
 
nacho/server/__init__.py CHANGED
@@ -10,13 +10,13 @@ try:
10
10
  import uvicorn
11
11
 
12
12
  HAS_SERVER_DEPS = True
13
- except ImportError:
13
+ except ImportError: # pragma: no cover - optional 'server' extra not installed
14
14
  HAS_SERVER_DEPS = False
15
15
 
16
16
  # Only import if dependencies are available
17
17
  if HAS_SERVER_DEPS:
18
18
  from .app import NachoOrchestrator
19
- else:
19
+ else: # pragma: no cover - optional 'server' extra not installed
20
20
  # Define a placeholder class that raises ImportError when instantiated
21
21
  class NachoOrchestrator:
22
22
  """Placeholder class for NachoOrchestrator.
nacho/server/app.py CHANGED
@@ -18,6 +18,7 @@ from nacho.config import Nacho
18
18
  from nacho.schema import ValidationError
19
19
  from nacho.server.auth import AuthGuard, AuthMiddleware
20
20
  from nacho.utils.io import dump_string, load_string
21
+ from nacho.utils.path import get_nested_value
21
22
 
22
23
  from .models import (
23
24
  AppCreateRequest,
@@ -283,8 +284,11 @@ class NachoOrchestrator:
283
284
  @self.app.get("/api/apps/{app_name}/config/{path:path}")
284
285
  async def get_path(app_name: str, path: str) -> Dict[str, Any]:
285
286
  app = self._get_app(app_name)
287
+ # Resolve against the snapshot directly: Nacho.get() deep-copies its
288
+ # result, so an identity-sentinel passed to it would never compare
289
+ # equal — get_nested_value preserves the sentinel by identity.
286
290
  missing = object()
287
- value = app.config.get(path, missing)
291
+ value = get_nested_value(app.config.get_all(), path, missing)
288
292
  if value is missing:
289
293
  raise HTTPException(
290
294
  status_code=status.HTTP_404_NOT_FOUND,
@@ -510,6 +514,8 @@ class NachoOrchestrator:
510
514
  detail="Server is in read-only mode",
511
515
  )
512
516
 
513
- def run(self, host: str = "0.0.0.0", port: int = 8000, reload: bool = False) -> None:
517
+ def run( # pragma: no cover - thin uvicorn wrapper, exercised via the CLI
518
+ self, host: str = "0.0.0.0", port: int = 8000, reload: bool = False
519
+ ) -> None:
514
520
  config = uvicorn.Config(app=self.app, host=host, port=port, reload=reload)
515
521
  uvicorn.Server(config).run()
@@ -374,6 +374,14 @@ textarea.code {
374
374
 
375
375
  <script>
376
376
  "use strict";
377
+ /* ===================================================================== */
378
+ /* Mount base — derived from where the UI was served, so the same bundle */
379
+ /* works whether the orchestrator is mounted at "/" or under a subpath */
380
+ /* such as "/config". At "/ui" → BASE = ""; at "/config/ui" → "/config". */
381
+ /* ===================================================================== */
382
+ const BASE = location.pathname.replace(/\/ui\/?$/, "");
383
+ const COOKIE_PATH = BASE || "/";
384
+
377
385
  /* ===================================================================== */
378
386
  /* State */
379
387
  /* ===================================================================== */
@@ -412,7 +420,7 @@ async function api(method, path, body) {
412
420
  const headers = {};
413
421
  if (body !== undefined) headers["Content-Type"] = "application/json";
414
422
  if (state.apiKey) headers["Authorization"] = "Bearer " + state.apiKey;
415
- const resp = await fetch(path, {
423
+ const resp = await fetch(BASE + path, {
416
424
  method,
417
425
  headers,
418
426
  body: body !== undefined ? JSON.stringify(body) : undefined,
@@ -461,10 +469,10 @@ async function serializeSafe(obj, fmt, label) {
461
469
  /* Cookie (needed so the WebSocket handshake can authenticate) */
462
470
  /* ===================================================================== */
463
471
  function setAuthCookie(key) {
464
- document.cookie = "NACHO_api_key=" + key + "; path=/; SameSite=Strict";
472
+ document.cookie = "NACHO_api_key=" + key + "; path=" + COOKIE_PATH + "; SameSite=Strict";
465
473
  }
466
474
  function clearAuthCookie() {
467
- document.cookie = "NACHO_api_key=; path=/; Max-Age=0; SameSite=Strict";
475
+ document.cookie = "NACHO_api_key=; path=" + COOKIE_PATH + "; Max-Age=0; SameSite=Strict";
468
476
  }
469
477
 
470
478
  /* ===================================================================== */
@@ -599,7 +607,7 @@ function mountCodeEditor(host, opts) {
599
607
  async function boot() {
600
608
  let health = {};
601
609
  try {
602
- const r = await fetch("/health");
610
+ const r = await fetch(BASE + "/health");
603
611
  health = await r.json();
604
612
  } catch (_) { /* server may still be coming up */ }
605
613
  state.authRequired = health.auth_required !== false;
@@ -1036,7 +1044,9 @@ function openWs(name, attempt) {
1036
1044
  closeWs();
1037
1045
  attempt = attempt || 0;
1038
1046
  const proto = location.protocol === "https:" ? "wss" : "ws";
1039
- const ws = new WebSocket(proto + "://" + location.host + "/ws/" + encodeURIComponent(name));
1047
+ const ws = new WebSocket(
1048
+ proto + "://" + location.host + BASE + "/ws/" + encodeURIComponent(name)
1049
+ );
1040
1050
  state.ws = ws;
1041
1051
  ws.onopen = () => { setLive(true); attempt = 0; };
1042
1052
  ws.onclose = () => {
nacho/storage/__init__.py CHANGED
@@ -7,7 +7,7 @@ try:
7
7
 
8
8
  HAS_REMOTE_DEPS = True
9
9
  from .remote import RemoteStorageBackend
10
- except ImportError:
10
+ except ImportError: # pragma: no cover - optional 'remote' extra not installed
11
11
  HAS_REMOTE_DEPS = False
12
12
 
13
13
  class RemoteStorageBackend: # type: ignore[no-redef]
nacho/utils/io.py CHANGED
@@ -13,12 +13,12 @@ import yaml
13
13
 
14
14
  try:
15
15
  import tomllib # Python ≥ 3.11
16
- except ImportError:
16
+ except ImportError: # pragma: no cover - Python < 3.11 fallback
17
17
  import tomli as tomllib # type: ignore[no-redef]
18
18
 
19
19
  try:
20
20
  import tomli_w
21
- except ImportError:
21
+ except ImportError: # pragma: no cover - optional TOML-write dependency
22
22
  tomli_w = None # type: ignore[assignment]
23
23
 
24
24
  logger = logging.getLogger(__name__)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nacho-python
3
- Version: 0.0.1
3
+ Version: 0.0.3
4
4
  Summary: Nacho - Lightweight, schema-first dynamic configuration service
5
5
  Author-email: "Nya Foundation Team (k3scat)" <k3scat@github.com>
6
6
  License-Expression: MIT
@@ -45,17 +45,17 @@ Dynamic: license-file
45
45
 
46
46
  # Nacho
47
47
 
48
- ```text
48
+ <div align="center">
49
+
50
+ <pre>
49
51
  _ _ _ ____ _ _ ___
50
52
  | \ | | / \ / ___|| | | | / _ \
51
53
  | \| | / _ \ | | | |_| || | | |
52
54
  | |\ | / ___ \ | |___ | _ || |_| |
53
55
  |_| \_|/_/ \_\ \____||_| |_| \___/
54
- ```
56
+ </pre>
55
57
 
56
- <div align="center">
57
-
58
- <h3>Lightweight, schema-first dynamic configuration service for Python.</h3>
58
+ <h3>Lightweight, self-hosted dynamic configuration service for Python.</h3>
59
59
 
60
60
  <p>
61
61
  <a href="README.md">English</a> |
@@ -83,18 +83,23 @@ Dynamic: license-file
83
83
 
84
84
  ## What is Nacho?
85
85
 
86
- Nacho is a schema-first dynamic configuration service for Python applications.
87
- It handles YAML, JSON, and TOML configuration files and provides a consistent API across local files, in-memory dicts, and remote configuration servers.
86
+ Nacho is a lightweight, self-hosted configuration **service** for Python.
87
+
88
+ Run a Nacho server, point your services at it with a few lines of code, and push
89
+ configuration changes that reach them **live** — no redeploy, no restart. Every
90
+ change is validated against a JSON Schema before it is stored, and a built-in
91
+ web UI lets you manage it all. When you don't need a server, the same library
92
+ also works standalone against a local file.
88
93
 
89
94
  | Feature | Description |
90
95
  |---|---|
91
- | **Multi-format support** | Read and write YAML, JSON, and TOML with a unified API. |
92
- | **Schema-first validation** | Validate every write against a JSON Schema — invalid data is rejected before it reaches storage. |
93
- | **Event system** | Register handlers that fire on specific configuration changes, keyed by dot-notation path patterns. |
94
- | **Environment overrides** | Overlay environment variables at runtime without writing them back to storage. |
95
- | **Remote configuration** | Connect to a Nacho API server for centralized configuration and optional WebSocket push. |
96
- | **Thread safe** | All read/write operations are protected by a reentrant lock. |
97
- | **Pluggable storage** | Swap in file, in-memory, or remote backends without changing application code. |
96
+ | **Centralized config server** | Run one Nacho server and manage every service's configuration from a REST API, CLI, or web UI. |
97
+ | **Live updates** | Clients subscribe over WebSocket and see changes the moment they happen — no polling, no restart. |
98
+ | **Schema-first validation** | Every write is checked against a JSON Schema; invalid data is rejected before it reaches storage. |
99
+ | **Drop-in Python client** | `RemoteStorageBackend` gives a remote app the same API as a local file — swap the storage, change nothing else. |
100
+ | **Built-in management UI** | Create apps and edit configuration or schema — in JSON, YAML, or TOML — from a single-file web UI the server hosts itself. |
101
+ | **Multi-format** | JSON, YAML, and TOML everywhere: API payloads, stored files, and the UI editor. |
102
+ | **Standalone mode** | No server required — point Nacho at a local file or an in-memory dict and use it as a plain config library. |
98
103
 
99
104
  ## Prerequisites
100
105
 
@@ -106,18 +111,18 @@ It handles YAML, JSON, and TOML configuration files and provides a consistent AP
106
111
  Nacho uses optional extras to keep the core dependency footprint small.
107
112
 
108
113
  ```bash
109
- # Core — local file management only
110
- pip install nacho-python
111
-
112
- # With web server and REST API
114
+ # Run a configuration server
113
115
  pip install nacho-python[server]
114
116
 
117
+ # Connect a service to a server (remote client)
118
+ pip install nacho-python[remote]
119
+
120
+ # Core — standalone local file management only
121
+ pip install nacho-python
122
+
115
123
  # With JSON Schema validation
116
124
  pip install nacho-python[schema]
117
125
 
118
- # With remote client
119
- pip install nacho-python[remote]
120
-
121
126
  # Everything
122
127
  pip install nacho-python[all]
123
128
 
@@ -127,225 +132,64 @@ pip install nacho-python[dev]
127
132
 
128
133
  | Extra | Dependencies | Purpose |
129
134
  |---|---|---|
130
- | *(none)* | pyyaml, tomli-w | Local file read/write (YAML, JSON, TOML) |
131
- | `server` | fastapi, uvicorn, websockets | REST API and WebSocket watch server |
132
- | `schema` | jsonschema, rfc3987 | JSON Schema validation on writes |
135
+ | `server` | fastapi, uvicorn, websockets | REST API and WebSocket configuration server |
133
136
  | `remote` | requests, websocket-client | Remote configuration client |
137
+ | `schema` | jsonschema, rfc3987 | JSON Schema validation on writes |
138
+ | *(none)* | pyyaml, tomli-w | Standalone local file read/write (YAML, JSON, TOML) |
134
139
  | `all` | All of the above | Complete installation |
135
140
  | `dev` | pytest, httpx, coverage | Development and testing |
136
141
 
137
142
  ## Quick Start
138
143
 
139
- ```python
140
- from nacho import Nacho
141
-
142
- # File-backed configuration (file is created if it does not exist)
143
- config = Nacho("config.yaml", events=True)
144
-
145
- # Register a handler that fires when any key under "database" changes
146
- @config.on_change("database.*")
147
- def on_db_change(path, old_value, new_value, **kwargs):
148
- print(f"{path}: {old_value} -> {new_value}")
149
-
150
- # Read values with dot-notation keys
151
- host = config.get("database.host", default="localhost")
152
- port = config.get_int("database.port", default=5432)
153
-
154
- # Write values — triggers registered handlers
155
- config.set("database.pool_size", 10)
156
-
157
- # Persist to disk
158
- config.save()
159
- ```
160
-
161
- ## Configuration Management
162
-
163
- Nacho accepts a file path, a dict, or an explicit storage backend.
164
-
165
- ```python
166
- from nacho import Nacho
167
-
168
- # In-memory with initial data
169
- config = Nacho({"database": {"host": "127.0.0.1", "port": 5432}})
170
-
171
- # File-backed
172
- config = Nacho("config.yaml")
173
-
174
- # Read with type coercion
175
- host = config.get("database.host") # str
176
- port = config.get_int("database.port") # int
177
- debug = config.get_bool("app.debug") # bool
178
- tags = config.get_list("app.tags") # list
179
- options = config.get_dict("app.options") # dict
180
-
181
- # Deep-merge additional keys (does not remove existing keys)
182
- config.update({"logging": {"level": "DEBUG"}})
183
-
184
- # Replace the entire config
185
- config.replace({"database": {"host": "prod-db", "port": 5432}})
186
-
187
- # Delete a key
188
- config.delete("legacy.setting")
189
-
190
- # Reload from storage and re-apply env overrides
191
- config.reload()
192
-
193
- # Export current config as a JSON string
194
- print(config.json())
195
- ```
196
-
197
- ### Atomic transactions
198
-
199
- Group multiple writes into a single atomic operation. The transaction commits when the block exits cleanly; it is discarded on any exception.
200
-
201
- ```python
202
- with config.transaction() as txn:
203
- txn.set("database.host", "new-host")
204
- txn.set("database.port", 5433)
205
- # Handlers fire once here with the aggregated changes
206
- config.save()
207
- ```
208
-
209
- ## Environment Variable Overrides
210
-
211
- Pass `env_prefix` to apply environment variables on top of the configuration at load time. Variable names follow the pattern `{PREFIX}_{NESTED_KEY}`, with nested levels separated by the delimiter (default: `_`).
144
+ **1. Run a Nacho server**
212
145
 
213
146
  ```bash
214
- export MYAPP_DATABASE_HOST=prod-db.example.com
215
- export MYAPP_DATABASE_PORT=5433
216
- export MYAPP_FEATURES_ENABLED=true
217
- ```
218
-
219
- ```python
220
- config = Nacho(
221
- "config.yaml",
222
- env_prefix="MYAPP",
223
- env_delimiter="_",
224
- )
225
-
226
- config.get("database.host") # "prod-db.example.com"
227
- config.get_int("database.port") # 5433
228
- config.get_bool("features.enabled") # True
229
- ```
230
-
231
- Environment values are coerced to bool, int, float, or JSON objects where possible, and fall back to string otherwise. Env overrides are runtime-only overlays: `save()` persists the stored config, not the effective env-overlaid values.
232
-
233
- ## Event System
234
-
235
- The event system dispatches change notifications after every successful write. Events carry the changed path, old value, new value, and event type.
236
-
237
- ```python
238
- from nacho import Nacho, EventType
239
-
240
- config = Nacho("config.yaml", events=True)
241
-
242
- # Fires for any change to a key under "database"
243
- @config.on_change("database.*")
244
- def on_db_change(path, old_value, new_value, **kwargs):
245
- print(f"database key changed: {path}")
246
-
247
- # Fires once per write operation (aggregate event), regardless of which key changed
248
- @config.on_change("@global")
249
- def on_any_change(**kwargs):
250
- print("config was modified")
251
-
252
- # Fires for CREATE or UPDATE events under "cache"
253
- @config.on_event([EventType.CREATE, EventType.UPDATE], path_pattern="cache.*")
254
- def on_cache_change(event_type, path, new_value, **kwargs):
255
- print(f"{event_type.name} {path} = {new_value}")
256
-
257
- config.set("database.host", "new-host") # triggers on_db_change, on_any_change
258
- config.set("cache.ttl", 600) # triggers on_cache_change (CREATE)
259
- config.set("cache.ttl", 300) # triggers on_cache_change (UPDATE)
260
- ```
261
-
262
- **Path pattern reference:**
263
-
264
- | Pattern | Fires when |
265
- |---|---|
266
- | `None` (default) | Any change at any path |
267
- | `"@global"` | Once per write operation (aggregate) |
268
- | `"*"` | Any per-key event (not aggregate) |
269
- | `"database.*"` | Any key nested under `database` |
270
-
271
- Handlers may be sync or async. Async handlers are scheduled on the running event loop when one exists, or run via `asyncio.run()` otherwise.
272
-
273
- ## Schema Validation
274
-
275
- Nacho enforces schema on every write. An invalid value raises `ValidationError` before the change is applied — the configuration is never left in an invalid state.
276
-
277
- Requires `pip install nacho-python[schema]`.
278
-
279
- ```json
280
- // schema.json
281
- {
282
- "type": "object",
283
- "properties": {
284
- "database": {
285
- "type": "object",
286
- "required": ["host", "port"],
287
- "properties": {
288
- "host": {"type": "string"},
289
- "port": {"type": "integer", "minimum": 1024}
290
- }
291
- }
292
- },
293
- "required": ["database"]
294
- }
147
+ pip install nacho-python[server]
148
+ nacho server --config config.yaml --api-key "secure-key"
295
149
  ```
296
150
 
297
- ```python
298
- from nacho import Nacho, ValidationError
299
-
300
- config = Nacho("config.yaml", schema="schema.json")
301
-
302
- # Invalid write raises immediately — config is not modified
303
- try:
304
- config.set("database.port", "not-a-number")
305
- except ValidationError as e:
306
- print(e.errors) # list of violation strings
151
+ The server is now live at `http://localhost:8000` — REST API, WebSocket push,
152
+ and a built-in management UI at `/ui`.
307
153
 
308
- # Inspect the current config against the schema without writing
309
- errors = config.validate()
310
- if errors:
311
- print("Current config has violations:", errors)
154
+ **2. Point your service at it**
312
155
 
313
- # Validate an arbitrary dict against the schema
314
- errors = config.check({"database": {"host": "localhost", "port": 80}})
315
- print(errors) # ["port must be >= 1024"]
156
+ ```bash
157
+ pip install nacho-python[remote]
316
158
  ```
317
159
 
318
- ## Remote Configuration
319
-
320
- Connect to a Nacho server and optionally receive real-time updates over WebSocket. The client writes through the REST API; the server can push changes back over WebSocket.
321
-
322
- Requires `pip install nacho-python[remote]`.
323
-
324
160
  ```python
325
161
  from nacho import Nacho, RemoteStorageBackend
326
162
 
327
- storage = RemoteStorageBackend(
328
- url="https://config-server.example.com",
329
- app_name="my-service",
330
- api_key="secure-key",
331
- watch=True, # opt in to WebSocket updates
163
+ config = Nacho(
164
+ storage=RemoteStorageBackend(
165
+ url="http://localhost:8000",
166
+ app_name="my-service",
167
+ api_key="secure-key",
168
+ watch=True, # receive live updates over WebSocket
169
+ ),
170
+ events=True,
332
171
  )
333
172
 
334
- config = Nacho(storage=storage, events=True)
335
-
336
- # The API is identical to file-backed usage
337
- host = config.get("database.host")
173
+ # Read configuration exactly like a local dict
174
+ port = config.get_int("server.port", default=8000)
338
175
 
339
- # Handlers fire on changes pushed from the server
176
+ # React the instant someone changes it on the server
340
177
  @config.on_change("features.*")
341
- def on_feature_change(path, new_value, **kwargs):
342
- print(f"feature flag updated: {path} = {new_value}")
178
+ def on_flag_change(path, new_value, **kwargs):
179
+ print(f"{path} is now {new_value}")
343
180
  ```
344
181
 
345
- ## REST API Server
182
+ Change a value from the UI, the CLI, or the API — every connected client sees it
183
+ immediately.
184
+
185
+ > **No server needed?** Nacho also works as a standalone file-backed library:
186
+ > `config = Nacho("config.yaml")`. See [Standalone file-backed usage](#standalone-file-backed-usage).
187
+
188
+ ## Running a Nacho Server
346
189
 
347
190
  `NachoOrchestrator` wraps one or more `Nacho` instances in a FastAPI application.
348
- The server is API-first: use `/docs` for interactive OpenAPI documentation, `/ws/{app}` for live config updates, and `/ui` for the built-in management UI.
191
+ The server is API-first: use `/docs` for interactive OpenAPI documentation,
192
+ `/ws/{app}` for live config updates, and `/ui` for the built-in management UI.
349
193
 
350
194
  Requires `pip install nacho-python[server]`.
351
195
 
@@ -364,6 +208,8 @@ server = NachoOrchestrator(
364
208
  server.run(host="0.0.0.0", port=8000)
365
209
  ```
366
210
 
211
+ The simplest way to start a server is the CLI — see [Command-Line Interface](#command-line-interface).
212
+
367
213
  ### Management UI
368
214
 
369
215
  Nacho ships a built-in web UI for managing apps, configurations, and schemas.
@@ -485,6 +331,224 @@ curl -X PUT http://localhost:8000/api/apps/my-service/config/cache.ttl \
485
331
  |---|---|---|
486
332
  | `/ws/{app}` | WebSocket | Receive configuration change events |
487
333
 
334
+ ## Remote Clients
335
+
336
+ A remote client connects to a Nacho server and optionally receives real-time
337
+ updates over WebSocket. The client writes through the REST API; the server
338
+ pushes changes back over WebSocket. Once constructed, a remote-backed `Nacho`
339
+ instance behaves **exactly** like a file-backed one — the same `get`, `set`,
340
+ `on_change`, and schema APIs.
341
+
342
+ Requires `pip install nacho-python[remote]`.
343
+
344
+ ```text
345
+ REST reads/writes
346
+ +-------------+ GET/PUT/PATCH/DELETE +----------------------+
347
+ | Python app | -----------------------> | Nacho server |
348
+ | Nacho | | REST API + Web UI |
349
+ | Remote | <----------------------- | File/dict storage |
350
+ | client | WebSocket pushes | Schema validation |
351
+ +-------------+ /ws/{app} +----------------------+
352
+ | ^
353
+ | on_change handlers |
354
+ +---------------------------------------------+
355
+ live config updates
356
+ ```
357
+
358
+ ```python
359
+ from nacho import Nacho, RemoteStorageBackend
360
+
361
+ storage = RemoteStorageBackend(
362
+ url="https://config-server.example.com",
363
+ app_name="my-service",
364
+ api_key="secure-key",
365
+ watch=True, # opt in to WebSocket updates
366
+ )
367
+
368
+ config = Nacho(storage=storage, events=True)
369
+
370
+ # The API is identical to file-backed usage
371
+ host = config.get("database.host")
372
+
373
+ # Handlers fire on changes pushed from the server
374
+ @config.on_change("features.*")
375
+ def on_feature_change(path, new_value, **kwargs):
376
+ print(f"feature flag updated: {path} = {new_value}")
377
+ ```
378
+
379
+ You can also reach a server without the SDK at all — straight from the
380
+ [command line](#remote):
381
+
382
+ ```bash
383
+ nacho get database.host --remote http://config-server:8000 --app-name my-service
384
+ ```
385
+
386
+ ## Event System
387
+
388
+ The event system dispatches change notifications after every successful write —
389
+ whether the change was made locally or **pushed from a Nacho server**. Events
390
+ carry the changed path, old value, new value, and event type.
391
+
392
+ ```python
393
+ from nacho import Nacho, EventType
394
+
395
+ config = Nacho("config.yaml", events=True)
396
+
397
+ # Fires for any change to a key under "database"
398
+ @config.on_change("database.*")
399
+ def on_db_change(path, old_value, new_value, **kwargs):
400
+ print(f"database key changed: {path}")
401
+
402
+ # Fires once per write operation (aggregate event), regardless of which key changed
403
+ @config.on_change("@global")
404
+ def on_any_change(**kwargs):
405
+ print("config was modified")
406
+
407
+ # Fires for CREATE or UPDATE events under "cache"
408
+ @config.on_event([EventType.CREATE, EventType.UPDATE], path_pattern="cache.*")
409
+ def on_cache_change(event_type, path, new_value, **kwargs):
410
+ print(f"{event_type.name} {path} = {new_value}")
411
+
412
+ config.set("database.host", "new-host") # triggers on_db_change, on_any_change
413
+ config.set("cache.ttl", 600) # triggers on_cache_change (CREATE)
414
+ config.set("cache.ttl", 300) # triggers on_cache_change (UPDATE)
415
+ ```
416
+
417
+ **Path pattern reference:**
418
+
419
+ | Pattern | Fires when |
420
+ |---|---|
421
+ | `None` (default) | Any change at any path |
422
+ | `"@global"` | Once per write operation (aggregate) |
423
+ | `"*"` | Any per-key event (not aggregate) |
424
+ | `"database.*"` | Any key nested under `database` |
425
+
426
+ Handlers may be sync or async. Async handlers are scheduled on the running event loop when one exists, or run via `asyncio.run()` otherwise.
427
+
428
+ ## Schema Validation
429
+
430
+ Nacho enforces schema on every write. An invalid value raises `ValidationError` before the change is applied — the configuration is never left in an invalid state. This applies to local writes and to data accepted by the server alike.
431
+
432
+ Requires `pip install nacho-python[schema]`.
433
+
434
+ ```json
435
+ // schema.json
436
+ {
437
+ "type": "object",
438
+ "properties": {
439
+ "database": {
440
+ "type": "object",
441
+ "required": ["host", "port"],
442
+ "properties": {
443
+ "host": {"type": "string"},
444
+ "port": {"type": "integer", "minimum": 1024}
445
+ }
446
+ }
447
+ },
448
+ "required": ["database"]
449
+ }
450
+ ```
451
+
452
+ ```python
453
+ from nacho import Nacho, ValidationError
454
+
455
+ config = Nacho("config.yaml", schema="schema.json")
456
+
457
+ # Invalid write raises immediately — config is not modified
458
+ try:
459
+ config.set("database.port", "not-a-number")
460
+ except ValidationError as e:
461
+ print(e.errors) # list of violation strings
462
+
463
+ # Inspect the current config against the schema without writing
464
+ errors = config.validate()
465
+ if errors:
466
+ print("Current config has violations:", errors)
467
+
468
+ # Validate an arbitrary dict against the schema
469
+ errors = config.check({"database": {"host": "localhost", "port": 80}})
470
+ print(errors) # ["port must be >= 1024"]
471
+ ```
472
+
473
+ ## Standalone file-backed usage
474
+
475
+ Nacho doesn't require a server. Point it at a local file (or hand it a plain
476
+ dict) and it works as a self-contained configuration library — handy for
477
+ scripts, tests, and single-process apps. Everything below works identically
478
+ whether Nacho is backed by a file, a dict, or a remote server.
479
+
480
+ ### Configuration management
481
+
482
+ Nacho accepts a file path, a dict, or an explicit storage backend.
483
+
484
+ ```python
485
+ from nacho import Nacho
486
+
487
+ # In-memory with initial data
488
+ config = Nacho({"database": {"host": "127.0.0.1", "port": 5432}})
489
+
490
+ # File-backed
491
+ config = Nacho("config.yaml")
492
+
493
+ # Read with type coercion
494
+ host = config.get("database.host") # str
495
+ port = config.get_int("database.port") # int
496
+ debug = config.get_bool("app.debug") # bool
497
+ tags = config.get_list("app.tags") # list
498
+ options = config.get_dict("app.options") # dict
499
+
500
+ # Deep-merge additional keys (does not remove existing keys)
501
+ config.update({"logging": {"level": "DEBUG"}})
502
+
503
+ # Replace the entire config
504
+ config.replace({"database": {"host": "prod-db", "port": 5432}})
505
+
506
+ # Delete a key
507
+ config.delete("legacy.setting")
508
+
509
+ # Reload from storage and re-apply env overrides
510
+ config.reload()
511
+
512
+ # Export current config as a JSON string
513
+ print(config.json())
514
+ ```
515
+
516
+ ### Atomic transactions
517
+
518
+ Group multiple writes into a single atomic operation. The transaction commits when the block exits cleanly; it is discarded on any exception.
519
+
520
+ ```python
521
+ with config.transaction() as txn:
522
+ txn.set("database.host", "new-host")
523
+ txn.set("database.port", 5433)
524
+ # Handlers fire once here with the aggregated changes
525
+ config.save()
526
+ ```
527
+
528
+ ### Environment variable overrides
529
+
530
+ Pass `env_prefix` to apply environment variables on top of the configuration at load time. Variable names follow the pattern `{PREFIX}_{NESTED_KEY}`, with nested levels separated by the delimiter (default: `_`).
531
+
532
+ ```bash
533
+ export MYAPP_DATABASE_HOST=prod-db.example.com
534
+ export MYAPP_DATABASE_PORT=5433
535
+ export MYAPP_FEATURES_ENABLED=true
536
+ ```
537
+
538
+ ```python
539
+ config = Nacho(
540
+ "config.yaml",
541
+ env_prefix="MYAPP",
542
+ env_delimiter="_",
543
+ )
544
+
545
+ config.get("database.host") # "prod-db.example.com"
546
+ config.get_int("database.port") # 5433
547
+ config.get_bool("features.enabled") # True
548
+ ```
549
+
550
+ Environment values are coerced to bool, int, float, or JSON objects where possible, and fall back to string otherwise. Env overrides are runtime-only overlays: `save()` persists the stored config, not the effective env-overlaid values.
551
+
488
552
  ## Command-Line Interface
489
553
 
490
554
  ```bash
@@ -507,28 +571,6 @@ nacho server \
507
571
  --read-only false
508
572
  ```
509
573
 
510
- ### Local configuration
511
-
512
- ```bash
513
- # Create a new config from a template
514
- nacho init config.yaml --template default
515
-
516
- # Available templates: empty, default, web-app, api-service, microservice
517
-
518
- # Read
519
- nacho get database.host --config config.yaml
520
- nacho get --config config.yaml --format json
521
-
522
- # Write
523
- nacho set database.port 5432 --config config.yaml
524
-
525
- # Delete
526
- nacho delete legacy.setting --config config.yaml
527
-
528
- # Validate against schema
529
- nacho validate --config config.yaml --schema schema.json
530
- ```
531
-
532
574
  ### Remote
533
575
 
534
576
  ```bash
@@ -558,25 +600,54 @@ nacho delete legacy.setting \
558
600
  --revision 4
559
601
  ```
560
602
 
603
+ ### Local configuration
604
+
605
+ ```bash
606
+ # Create a new config from a template
607
+ nacho init config.yaml --template default
608
+
609
+ # Available templates: empty, default, web-app, api-service, microservice
610
+
611
+ # Read
612
+ nacho get database.host --config config.yaml
613
+ nacho get --config config.yaml --format json
614
+
615
+ # Write
616
+ nacho set database.port 5432 --config config.yaml
617
+
618
+ # Delete
619
+ nacho delete legacy.setting --config config.yaml
620
+
621
+ # Validate against schema
622
+ nacho validate --config config.yaml --schema schema.json
623
+ ```
624
+
561
625
  ## Docker
562
626
 
563
627
  Nacho ships a multi-stage `Dockerfile` that builds a small Alpine-based image
564
- running the REST API server.
628
+ running the configuration server. Published images are available from Docker Hub
629
+ and GHCR:
565
630
 
566
631
  ```bash
632
+ # Pull from Docker Hub
633
+ docker pull k3scat/nacho:latest
634
+
635
+ # Pull from GitHub Container Registry
636
+ docker pull ghcr.io/nya-foundation/nacho:latest
637
+
567
638
  # Build the image
568
639
  docker build -t nacho .
569
640
 
570
641
  # Run the server (UI at http://localhost:8000/ui)
571
- docker run -p 8000:8000 nacho
642
+ docker run -p 8000:8000 k3scat/nacho:latest
572
643
 
573
644
  # Run with authentication enabled
574
- docker run -p 8000:8000 nacho \
575
- nacho server --config config.yaml --api-key "secure-key"
645
+ docker run -p 8000:8000 ghcr.io/nya-foundation/nacho:latest \
646
+ server --config config.yaml --api-key "secure-key"
576
647
 
577
648
  # Mount your own config for the default app
578
649
  docker run -p 8000:8000 \
579
- -v "$(pwd)/config.yaml:/app/config.yaml" nacho
650
+ -v "$(pwd)/config.yaml:/app/config.yaml" k3scat/nacho:latest
580
651
  ```
581
652
 
582
653
  Or use `docker-compose`:
@@ -0,0 +1,27 @@
1
+ nacho/__init__.py,sha256=VubNTGhBDrESwXhOXwDHJXrYpx0KKIwwHp3pm_A-Akg,917
2
+ nacho/_version.py,sha256=AYIYOKF7eBIxVga351EuFL22-eAWZJNbJ8jdSpBK82E,84
3
+ nacho/config.py,sha256=UdD6uK9aW6GgVJmTN-BFkLWCkZssnmoSwm4VQJW7nRM,20052
4
+ nacho/env.py,sha256=FHGWw4Ek6UUcHyDCKRH49080p4smhNp-cX8di2TkrR0,3947
5
+ nacho/event.py,sha256=oOoAesD-mKWQ1bqve5JwJWg05MDcAZDPt2KJLgqbbUU,13578
6
+ nacho/schema.py,sha256=QlmiPZH0lK-oi0KA_q1fjIRemNeojbJ5roTJrDHDjHU,4300
7
+ nacho/cli/__init__.py,sha256=1GG7V0_6VkMeMTBl40iQSywUBcTyPDmGYLvKLUwwU0I,226
8
+ nacho/cli/main.py,sha256=ump_AdQpAceS6yJAptfqI07zZ88TCrepc4LcmIuw6NE,19326
9
+ nacho/server/__init__.py,sha256=yhxR_qaV5JDKj_X-GawIx-G7KyG9GfSckLMpgCaWUr4,1126
10
+ nacho/server/app.py,sha256=h7Aj8VXkRA6dO2TNAV0EHhSLfuq-SM6I5DveiNDkjNM,20945
11
+ nacho/server/auth.py,sha256=fGdpiEo1IqZfKueaXDurJyopPB9GoYNxP438OH-F5pw,3179
12
+ nacho/server/models.py,sha256=JyJsor5O3ap06_YiYaQwQzxK7FcBiasU1uDqlq2CnXk,5448
13
+ nacho/server/runtime.py,sha256=YdyGCwo6MJGu_Q_gjfp6hh_5v5Ked5wSffR7P15D2Fc,14656
14
+ nacho/server/ui/index.html,sha256=URsxcnAlsaWRQy8P4B1wknqnd_FnpgchBnTIaXvOm5s,46603
15
+ nacho/storage/__init__.py,sha256=EfGT4LSIrb4XsgK0s2OeInryj93dBBXZqxyyC0je-n8,737
16
+ nacho/storage/base.py,sha256=U-cxcgfalJuTD4lmb9Sohycs-HsRccTkpoVsogWo1YM,1003
17
+ nacho/storage/file.py,sha256=5YBXEIO-ohj5csKk205V58xbq-IG_mi0dLQFagoiYyc,1233
18
+ nacho/storage/remote.py,sha256=Q_XYs6reqcuCLwuetoYmZe4UUe6uufCUAmyDqc79bcM,10536
19
+ nacho/utils/__init__.py,sha256=CHe4gnig4m44sjSkvK4c1u_sA55HIAFBl2D-Q8E5Y0w,387
20
+ nacho/utils/io.py,sha256=7V66ceHUa56I61MYwoBTXBwOBW1EFAFs21kMQyQg86Y,4848
21
+ nacho/utils/path.py,sha256=4dp3U5deUxloyo9O7IvTxS5nnhCQHHEinNvG5H9qOrc,4430
22
+ nacho_python-0.0.3.dist-info/licenses/LICENSE,sha256=bhOMRTFZk4E0cuMGzforv8O2iAhZXSEWqrVUFCerj30,1070
23
+ nacho_python-0.0.3.dist-info/METADATA,sha256=giA9as4sZE3OrItjwvsKrY5UyYTeyUQze8lzmWHKo-0,22864
24
+ nacho_python-0.0.3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
25
+ nacho_python-0.0.3.dist-info/entry_points.txt,sha256=r9ZAxNAvzab7f7CJ7ZwrcO4EPJ7SxFWV9-VC7hZs9iE,50
26
+ nacho_python-0.0.3.dist-info/top_level.txt,sha256=yFdawvydh3Coi3CzlPR5sp7KFmVE7IEAOcm_wlMtIBY,6
27
+ nacho_python-0.0.3.dist-info/RECORD,,
@@ -1,27 +0,0 @@
1
- nacho/__init__.py,sha256=ANshpjs6K4YYkUP6NlAoKg2a9aj_q1wlqXixRuozt8A,797
2
- nacho/_version.py,sha256=CWbYIcoXfBdBpY9gmklDmPnvLfCq72q551r3guC5qyk,84
3
- nacho/config.py,sha256=UdD6uK9aW6GgVJmTN-BFkLWCkZssnmoSwm4VQJW7nRM,20052
4
- nacho/env.py,sha256=FHGWw4Ek6UUcHyDCKRH49080p4smhNp-cX8di2TkrR0,3947
5
- nacho/event.py,sha256=oOoAesD-mKWQ1bqve5JwJWg05MDcAZDPt2KJLgqbbUU,13578
6
- nacho/schema.py,sha256=saI_jvEOAEGG--xwAid7RJitHjhaDBRTXnswxKnT3pk,4145
7
- nacho/cli/__init__.py,sha256=1GG7V0_6VkMeMTBl40iQSywUBcTyPDmGYLvKLUwwU0I,226
8
- nacho/cli/main.py,sha256=XLW0x7c6zZgt1Xu6HbG6WmI9kR-42ktL5u2TeJL-YGs,19272
9
- nacho/server/__init__.py,sha256=bl0-dzlYaT9QnLbdsrHiHZADDBgYy15EwaR2PLx-z1Y,1006
10
- nacho/server/app.py,sha256=D9Q8srW6uSqwenxzl91otUKniD6hQsa1hLw-1T4uDj4,20558
11
- nacho/server/auth.py,sha256=fGdpiEo1IqZfKueaXDurJyopPB9GoYNxP438OH-F5pw,3179
12
- nacho/server/models.py,sha256=JyJsor5O3ap06_YiYaQwQzxK7FcBiasU1uDqlq2CnXk,5448
13
- nacho/server/runtime.py,sha256=YdyGCwo6MJGu_Q_gjfp6hh_5v5Ked5wSffR7P15D2Fc,14656
14
- nacho/server/ui/index.html,sha256=YyEsDpYFWqwJWf9zNYFirpR2k8ykeCZGes-Oo9Cvdy0,46059
15
- nacho/storage/__init__.py,sha256=gmkFZgRkmQauMubZQJvJal7rVJir5C-SxpclKSL2SUA,677
16
- nacho/storage/base.py,sha256=U-cxcgfalJuTD4lmb9Sohycs-HsRccTkpoVsogWo1YM,1003
17
- nacho/storage/file.py,sha256=5YBXEIO-ohj5csKk205V58xbq-IG_mi0dLQFagoiYyc,1233
18
- nacho/storage/remote.py,sha256=Q_XYs6reqcuCLwuetoYmZe4UUe6uufCUAmyDqc79bcM,10536
19
- nacho/utils/__init__.py,sha256=CHe4gnig4m44sjSkvK4c1u_sA55HIAFBl2D-Q8E5Y0w,387
20
- nacho/utils/io.py,sha256=Pexhhp8B4bt9GgDsMpKw_eiytjlgOEADxDmIDrkK9tg,4750
21
- nacho/utils/path.py,sha256=4dp3U5deUxloyo9O7IvTxS5nnhCQHHEinNvG5H9qOrc,4430
22
- nacho_python-0.0.1.dist-info/licenses/LICENSE,sha256=bhOMRTFZk4E0cuMGzforv8O2iAhZXSEWqrVUFCerj30,1070
23
- nacho_python-0.0.1.dist-info/METADATA,sha256=L1e_QisWELV9qQtQEFDLDKyGFGSpfYiD4S1_JA7-f70,20015
24
- nacho_python-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
25
- nacho_python-0.0.1.dist-info/entry_points.txt,sha256=r9ZAxNAvzab7f7CJ7ZwrcO4EPJ7SxFWV9-VC7hZs9iE,50
26
- nacho_python-0.0.1.dist-info/top_level.txt,sha256=yFdawvydh3Coi3CzlPR5sp7KFmVE7IEAOcm_wlMtIBY,6
27
- nacho_python-0.0.1.dist-info/RECORD,,