nacho-python 0.0.3__tar.gz → 0.1.1__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 (45) hide show
  1. nacho_python-0.1.1/PKG-INFO +859 -0
  2. nacho_python-0.1.1/README.md +812 -0
  3. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/__init__.py +12 -5
  4. nacho_python-0.1.1/nacho/_version.py +3 -0
  5. nacho_python-0.1.1/nacho/cli/__init__.py +9 -0
  6. nacho_python-0.1.1/nacho/cli/main.py +750 -0
  7. nacho_python-0.1.1/nacho/client.py +252 -0
  8. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/config.py +82 -53
  9. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/env.py +58 -31
  10. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/event.py +69 -103
  11. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/schema.py +10 -24
  12. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/server/__init__.py +4 -4
  13. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/server/app.py +216 -120
  14. nacho_python-0.1.1/nacho/server/auth.py +183 -0
  15. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/server/models.py +37 -24
  16. nacho_python-0.1.1/nacho/server/runtime.py +671 -0
  17. nacho_python-0.1.1/nacho/server/ui/index.html +1921 -0
  18. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/storage/__init__.py +14 -3
  19. nacho_python-0.1.1/nacho/storage/base.py +71 -0
  20. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/storage/file.py +6 -5
  21. nacho_python-0.1.1/nacho/storage/remote.py +353 -0
  22. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/utils/__init__.py +1 -2
  23. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/utils/io.py +35 -41
  24. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho/utils/path.py +51 -32
  25. nacho_python-0.1.1/nacho_python.egg-info/PKG-INFO +859 -0
  26. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho_python.egg-info/SOURCES.txt +2 -0
  27. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho_python.egg-info/requires.txt +5 -3
  28. {nacho_python-0.0.3 → nacho_python-0.1.1}/pyproject.toml +21 -12
  29. nacho_python-0.0.3/PKG-INFO +0 -676
  30. nacho_python-0.0.3/README.md +0 -631
  31. nacho_python-0.0.3/nacho/_version.py +0 -4
  32. nacho_python-0.0.3/nacho/cli/__init__.py +0 -11
  33. nacho_python-0.0.3/nacho/cli/main.py +0 -638
  34. nacho_python-0.0.3/nacho/server/auth.py +0 -93
  35. nacho_python-0.0.3/nacho/server/runtime.py +0 -452
  36. nacho_python-0.0.3/nacho/server/ui/index.html +0 -1292
  37. nacho_python-0.0.3/nacho/storage/base.py +0 -33
  38. nacho_python-0.0.3/nacho/storage/remote.py +0 -293
  39. nacho_python-0.0.3/nacho_python.egg-info/PKG-INFO +0 -676
  40. {nacho_python-0.0.3 → nacho_python-0.1.1}/LICENSE +0 -0
  41. {nacho_python-0.0.3 → nacho_python-0.1.1}/MANIFEST.in +0 -0
  42. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho_python.egg-info/dependency_links.txt +0 -0
  43. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho_python.egg-info/entry_points.txt +0 -0
  44. {nacho_python-0.0.3 → nacho_python-0.1.1}/nacho_python.egg-info/top_level.txt +0 -0
  45. {nacho_python-0.0.3 → nacho_python-0.1.1}/setup.cfg +0 -0
@@ -0,0 +1,859 @@
1
+ Metadata-Version: 2.4
2
+ Name: nacho-python
3
+ Version: 0.1.1
4
+ Summary: Nacho - Lightweight, schema-first dynamic configuration service
5
+ Author-email: "Nya Foundation Team (k3scat)" <k3scat@github.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/nya-foundation/nacho
8
+ Project-URL: Bug Tracker, https://github.com/nya-foundation/nacho/issues
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: pyyaml>=6.0
21
+ Requires-Dist: tomli>=2.0.0; python_version < "3.11"
22
+ Requires-Dist: tomli-w>=1.0.0
23
+ Provides-Extra: server
24
+ Requires-Dist: fastapi>=0.100.0; extra == "server"
25
+ Requires-Dist: uvicorn>=0.22.0; extra == "server"
26
+ Requires-Dist: websockets>=10.0; extra == "server"
27
+ Provides-Extra: remote
28
+ Requires-Dist: requests>=2.31.0; extra == "remote"
29
+ Requires-Dist: websocket-client>=1.8.0; extra == "remote"
30
+ Provides-Extra: schema
31
+ Requires-Dist: jsonschema>=4.0.0; extra == "schema"
32
+ Requires-Dist: rfc3987>=1.3.8; extra == "schema"
33
+ Provides-Extra: all
34
+ Requires-Dist: nacho-python[remote,schema,server]; extra == "all"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
37
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
38
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
39
+ Requires-Dist: httpx>=0.27.0; extra == "dev"
40
+ Requires-Dist: nacho-python[all]; extra == "dev"
41
+ Provides-Extra: lint
42
+ Requires-Dist: ruff>=0.5.0; extra == "lint"
43
+ Provides-Extra: uitest
44
+ Requires-Dist: playwright>=1.45; extra == "uitest"
45
+ Requires-Dist: pytest-playwright>=0.5.0; extra == "uitest"
46
+ Dynamic: license-file
47
+
48
+ # Nacho
49
+
50
+ <div align="center">
51
+
52
+ <pre>
53
+ _ _ _ ____ _ _ ___
54
+ | \ | | / \ / ___|| | | | / _ \
55
+ | \| | / _ \ | | | |_| || | | |
56
+ | |\ | / ___ \ | |___ | _ || |_| |
57
+ |_| \_|/_/ \_\ \____||_| |_| \___/
58
+ </pre>
59
+
60
+ <h3>Lightweight, self-hosted dynamic configuration service for Python</h3>
61
+
62
+ <p>
63
+ <a href="README.md">English</a> |
64
+ <a href="README_zh.md">中文</a> |
65
+ <a href="README_ja.md">日本語</a>
66
+ </p>
67
+
68
+ <div>
69
+ <a href="https://pypi.org/project/nacho-python/"><img src="https://img.shields.io/pypi/v/nacho-python.svg" alt="PyPI version"/></a>
70
+ <a href="https://pypi.org/project/nacho-python/"><img src="https://img.shields.io/pypi/pyversions/nacho-python.svg" alt="Python versions"/></a>
71
+ <a href="https://github.com/nya-foundation/nacho/blob/main/LICENSE"><img src="https://img.shields.io/github/license/nya-foundation/nacho.svg" alt="License"/></a>
72
+ <a href="https://pepy.tech/projects/nacho-python"><img src="https://static.pepy.tech/badge/nacho-python" alt="PyPI Downloads"/></a>
73
+ <a href="https://hub.docker.com/r/k3scat/nacho"><img src="https://img.shields.io/docker/pulls/k3scat/nacho" alt="Docker Pulls"/></a>
74
+ <a href="https://deepwiki.com/Nya-Foundation/Nacho"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"/></a>
75
+ </div>
76
+
77
+ <div>
78
+ <a href="https://codecov.io/gh/nya-foundation/nacho"><img src="https://codecov.io/gh/nya-foundation/nacho/branch/main/graph/badge.svg" alt="Code Coverage"/></a>
79
+ <a href="https://github.com/nya-foundation/nacho/actions/workflows/scan.yml"><img src="https://github.com/nya-foundation/nacho/actions/workflows/scan.yml/badge.svg" alt="CodeQL and Dependencies Scan"/></a>
80
+ <a href="https://github.com/nya-foundation/nacho/actions/workflows/publish.yml"><img src="https://github.com/nya-foundation/nacho/actions/workflows/publish.yml/badge.svg" alt="CI/CD Builds"/></a>
81
+ </div>
82
+ </div>
83
+
84
+ ## Overview
85
+
86
+ Nacho is a self-hosted configuration service for Python. Run one Nacho server,
87
+ point your services at it with a few lines of code, and push configuration
88
+ changes that reach them live — no redeploy, no restart, no polling.
89
+
90
+ Every write is validated against a JSON Schema before it is stored, every
91
+ revision is kept in a rollback history, and a built-in single-file web UI
92
+ manages all of it. When you do not need a server, the same library works
93
+ standalone against a local file or an in-memory dict.
94
+
95
+ | Capability | Description |
96
+ |---|---|
97
+ | Centralized configuration | One server manages every service's configuration through a REST API, a CLI, and a web UI. |
98
+ | Live updates | Clients subscribe over WebSocket and receive changes the moment they happen. |
99
+ | Schema-first validation | Writes are checked against a JSON Schema and rejected before they reach storage. |
100
+ | History and rollback | Every revision is snapshotted; any revision can be inspected and restored. |
101
+ | Drop-in Python client | `RemoteStorageBackend` gives a remote application the same API as a local file. |
102
+ | Optimistic concurrency | Revision-checked writes turn lost updates into explicit `409 Conflict` responses. |
103
+ | Multi-format | JSON, YAML, and TOML are interchangeable across API payloads, stored files, and the UI editor. |
104
+ | Standalone mode | Use Nacho as a plain configuration library with no server at all. |
105
+
106
+ ## Installation
107
+
108
+ Nacho keeps its core dependency footprint small through optional extras:
109
+
110
+ ```bash
111
+ pip install nacho-python[server] # run a configuration server
112
+ pip install nacho-python[remote] # connect a service to a server
113
+ pip install nacho-python[schema] # JSON Schema validation for standalone use
114
+ pip install nacho-python # core: standalone local file management
115
+ ```
116
+
117
+ Requires Python 3.9 or later. Docker images are available for containerized
118
+ deployments (see [Docker](#docker)).
119
+
120
+ ## Quick start
121
+
122
+ Start a server:
123
+
124
+ ```bash
125
+ pip install nacho-python[server]
126
+ nacho server --config config.yaml --api-key "secure-key"
127
+ ```
128
+
129
+ The server is now live at `http://127.0.0.1:8000` with a REST API, WebSocket
130
+ push, interactive API docs at `/docs`, and a management UI at `/ui`.
131
+
132
+ Connect a service:
133
+
134
+ ```bash
135
+ pip install nacho-python[remote]
136
+ ```
137
+
138
+ ```python
139
+ from nacho import Nacho, RemoteStorageBackend
140
+
141
+ config = Nacho(
142
+ storage=RemoteStorageBackend(
143
+ url="http://127.0.0.1:8000",
144
+ app_name="my-service",
145
+ api_key="secure-key",
146
+ watch=True, # receive live updates over WebSocket
147
+ ),
148
+ events=True,
149
+ )
150
+
151
+ # Read configuration exactly like a local dict
152
+ port = config.get_int("server.port", default=8000)
153
+
154
+ # React the instant someone changes it on the server
155
+ @config.on_change("features.*")
156
+ def on_flag_change(path, new_value, **kwargs):
157
+ print(f"{path} is now {new_value}")
158
+ ```
159
+
160
+ Change a value from the UI, the CLI, or the API, and every connected client
161
+ sees it immediately.
162
+
163
+ No server needed? Nacho also works as a standalone file-backed library:
164
+ `config = Nacho("config.yaml")`. See
165
+ [Standalone usage](#standalone-usage).
166
+
167
+ ## Running a server
168
+
169
+ The CLI is the usual way to run a server:
170
+
171
+ ```bash
172
+ nacho server \
173
+ --config config.yaml \
174
+ --schema schema.json \
175
+ --port 8000 \
176
+ --api-key "secure-key" \
177
+ --data-dir ".nacho/apps" \
178
+ --history-limit 50
179
+ ```
180
+
181
+ The server binds to `127.0.0.1` by default. Pass `--host 0.0.0.0` to accept
182
+ connections from other machines; the CLI prints a warning if you expose the
183
+ server without `--api-key`, because an unauthenticated server grants full
184
+ write access to anyone who can reach it.
185
+
186
+ Run exactly **one server process** per data directory. App state, revision
187
+ counters, and WebSocket subscriptions live in process memory, so running the
188
+ app behind multiple workers (e.g. `uvicorn --workers 2`) or pointing two
189
+ server processes at the same `--data-dir` produces inconsistent revisions and
190
+ missed live updates.
191
+
192
+ | Flag | Default | Description |
193
+ |---|---|---|
194
+ | `--host` | `127.0.0.1` | Bind address (`0.0.0.0` to listen on all interfaces) |
195
+ | `--port` | `8000` | Bind port |
196
+ | `--config`, `-c` | none | Configuration file to serve as an app |
197
+ | `--schema` | none | JSON Schema enforced for `--config` |
198
+ | `--app-name` | `default` | App name for the `--config` file |
199
+ | `--data-dir` | none | Directory for API-created app state and history |
200
+ | `--api-key` | none | Enable bearer-token authentication |
201
+ | `--read-only-api-key` | none | Additional key granting read access only |
202
+ | `--history-limit` | `50` | Revision snapshots kept per app (`0` disables history) |
203
+ | `--read-only` | off | Reject every write |
204
+ | `--reload` | off | Auto-reload for development |
205
+
206
+ ### Embedding in an existing application
207
+
208
+ `NachoOrchestrator` wraps one or more `Nacho` instances in a FastAPI
209
+ application, so a server can also be constructed in code or mounted into an
210
+ existing app:
211
+
212
+ ```python
213
+ from fastapi import FastAPI
214
+ from nacho import Nacho, NachoOrchestrator
215
+
216
+ app = FastAPI(title="My Application")
217
+
218
+ orchestrator = NachoOrchestrator(
219
+ apps={"config": Nacho("config.yaml", events=True)},
220
+ api_key="secure-key",
221
+ cors_origins=["https://admin.example.com"],
222
+ )
223
+
224
+ app.mount("/config", orchestrator.app) # configuration API under /config
225
+ ```
226
+
227
+ Run it directly with `orchestrator.run(host="127.0.0.1", port=8000)` when it
228
+ is not mounted.
229
+
230
+ ### Management UI
231
+
232
+ The server hosts a single-file web UI at `/ui` — no separate process, no build
233
+ step. It provides:
234
+
235
+ - App management: list, create, rename, describe, and delete apps.
236
+ - Configuration editing: a code editor for JSON, YAML, and TOML with syntax
237
+ highlighting, format switching, on-demand validation, and revision-aware
238
+ saves that surface conflicts instead of clobbering newer data.
239
+ - Schema editing: view, edit, or clear an app's JSON Schema; the current
240
+ configuration is re-checked against the new schema before it is accepted.
241
+ - History: browse revision snapshots and restore any of them with one click.
242
+ - Live updates: changes pushed over WebSocket are reflected in real time, and
243
+ unsaved local edits are preserved when a remote change arrives.
244
+
245
+ When the server runs with `--api-key`, the UI prompts for the key on first
246
+ load. The `/ui` page itself is public so the sign-in screen can load; every
247
+ API call behind it requires authentication.
248
+
249
+ #### Pre-authenticating an embedded UI
250
+
251
+ When the orchestrator is mounted inside a host application that already has
252
+ its own session auth, users should not face a second login. The UI reads its
253
+ credential from two same-origin browser stores, and **these two names are a
254
+ stable contract** — seed them before navigating to `/ui` and the UI comes up
255
+ already signed in:
256
+
257
+ | Store | Name | Used for |
258
+ |---|---|---|
259
+ | `localStorage` | `nacho_api_key` | `Authorization: Bearer` header on REST calls |
260
+ | Cookie | `NACHO_api_key` | The WebSocket handshake, which cannot send headers |
261
+
262
+ The cookie value must be URL-encoded, and its path must match the mount
263
+ point — the UI derives it as `location.pathname` with a trailing `/ui`
264
+ removed (so `/config/ui` yields a cookie path of `/config`, and a top-level
265
+ mount yields `/`):
266
+
267
+ ```js
268
+ // Run on your own login page, same origin as the mounted UI.
269
+ function preauthenticateNacho(key, mountPath = "") {
270
+ localStorage.setItem("nacho_api_key", key);
271
+ const secure = location.protocol === "https:" ? "; Secure" : "";
272
+ document.cookie =
273
+ "NACHO_api_key=" + encodeURIComponent(key) +
274
+ "; path=" + (mountPath || "/") + "; SameSite=Strict" + secure;
275
+ }
276
+ ```
277
+
278
+ Seed only a credential the signed-in user is entitled to. A user who may
279
+ read configuration but not change it should be given the
280
+ `--read-only-api-key`, not the admin key — the UI surfaces the server's
281
+ `403` responses on write attempts.
282
+
283
+ Do not pass the key in the URL (`?token=`): query strings leak through
284
+ browser history, `Referer` headers, and proxy logs.
285
+
286
+ ### Authentication
287
+
288
+ Passing `--api-key` (or `api_key=` to `NachoOrchestrator`) enables bearer
289
+ authentication for the whole API. Clients send the key either as an
290
+ `Authorization: Bearer <key>` header or through the cookie the UI sets for
291
+ its own WebSocket handshake. Requests with a missing or wrong key receive
292
+ `401 Unauthorized`. The comparison is timing-safe.
293
+
294
+ A second key can be added with `--read-only-api-key` (or
295
+ `read_only_api_key=`). It authenticates GETs and WebSocket subscriptions but
296
+ receives `403 Forbidden` on any write — hand it to dashboards, pollers, and
297
+ services that only consume configuration, so the write credential never
298
+ leaves the operators who need it.
299
+
300
+ `/`, `/health`, `/ui`, `/docs`, `/redoc`, and `/openapi.json` stay public: the
301
+ API surface is not a secret, only the data behind it.
302
+
303
+ Cross-origin browser access is disabled unless you opt in with
304
+ `cors_origins=[...]` — the bundled UI is same-origin and the SDK/CLI are not
305
+ browsers, so a drive-by web page cannot reach a default server.
306
+
307
+ ## REST API
308
+
309
+ Interactive documentation is available at `/docs` (Swagger UI) and `/redoc`
310
+ once the server is running.
311
+
312
+ ### Payload format
313
+
314
+ Config and schema payloads are native JSON objects:
315
+
316
+ ```bash
317
+ curl -X POST http://127.0.0.1:8000/api/apps \
318
+ -H "Authorization: Bearer secure-key" \
319
+ -H "Content-Type: application/json" \
320
+ -d '{
321
+ "name": "my-service",
322
+ "data": {"database": {"host": "localhost", "port": 5432}},
323
+ "schema": {"type": "object", "properties": {"database": {"type": "object"}}}
324
+ }'
325
+ ```
326
+
327
+ Payloads may also be sent as encoded strings in any supported format, which
328
+ is how the CLI and UI submit YAML and TOML:
329
+
330
+ ```json
331
+ {"data": "database:\n host: localhost\n", "format": "yaml"}
332
+ ```
333
+
334
+ ### Revisions and optimistic concurrency
335
+
336
+ Every app carries a monotonically increasing revision, bumped on each
337
+ successful write. Reads of `/config` (full or per-path) return the current
338
+ revision in the `ETag` and `X-Nacho-Revision` response headers. Writes may
339
+ include a `revision` field stating the revision the client last saw; if the
340
+ server has moved on, the write fails with `409 Conflict` and the stored
341
+ configuration is left untouched:
342
+
343
+ ```bash
344
+ curl -X PUT http://127.0.0.1:8000/api/apps/my-service/config/cache.ttl \
345
+ -H "Authorization: Bearer secure-key" \
346
+ -H "Content-Type: application/json" \
347
+ -d '{"value": 600, "revision": 3}'
348
+ ```
349
+
350
+ Omitting `revision` performs an unconditional write.
351
+
352
+ The `ETag` also enables cheap polling: send it back as `If-None-Match` and
353
+ the server answers `304 Not Modified` — no body — until the revision moves.
354
+
355
+ ```bash
356
+ curl -H 'If-None-Match: "3"' http://127.0.0.1:8000/api/apps/my-service/config
357
+ ```
358
+
359
+ ### History and rollback
360
+
361
+ The server snapshots every revision (configuration, schema, and metadata)
362
+ into a per-app ring buffer — on disk under `data_dir/history/` when a data
363
+ directory is configured, in memory otherwise. `--history-limit` controls
364
+ retention.
365
+
366
+ Rollback is roll-forward: restoring revision 41 does not rewrite history but
367
+ creates a new revision whose content equals snapshot 41. The revision counter
368
+ stays monotonic, live clients are notified like on any other write, and a
369
+ rollback can itself be rolled back. A snapshot restores configuration and
370
+ schema together, so the result is always self-consistent.
371
+
372
+ ```bash
373
+ curl http://127.0.0.1:8000/api/apps/my-service/history
374
+ curl http://127.0.0.1:8000/api/apps/my-service/history/41
375
+ curl -X POST http://127.0.0.1:8000/api/apps/my-service/rollback \
376
+ -H "Content-Type: application/json" \
377
+ -d '{"revision": 41, "expected_revision": 42}'
378
+ ```
379
+
380
+ ### Endpoint reference
381
+
382
+ System:
383
+
384
+ | Endpoint | Method | Description |
385
+ |---|---|---|
386
+ | `/health` | GET | Health check and instance summary |
387
+ | `/ui` | GET | Built-in web management UI |
388
+ | `/docs`, `/redoc` | GET | Interactive API documentation |
389
+ | `/api/convert` | POST | Convert a payload between JSON, YAML, and TOML |
390
+
391
+ App management:
392
+
393
+ | Endpoint | Method | Description |
394
+ |---|---|---|
395
+ | `/api/apps` | GET | List all apps |
396
+ | `/api/apps` | POST | Create an app |
397
+ | `/api/apps/{app}` | GET | Get app info |
398
+ | `/api/apps/{app}` | PUT | Replace an app's config, schema, and description |
399
+ | `/api/apps/{app}` | DELETE | Delete an app |
400
+ | `/api/apps/{app}/metadata` | PATCH | Rename an app or change its description |
401
+
402
+ Configuration and schema:
403
+
404
+ | Endpoint | Method | Description |
405
+ |---|---|---|
406
+ | `/api/apps/{app}/config` | GET | Get the full configuration |
407
+ | `/api/apps/{app}/config` | PUT | Replace the full configuration |
408
+ | `/api/apps/{app}/config/{path}` | GET | Get the value at a dotted path |
409
+ | `/api/apps/{app}/config/{path}` | PUT | Set the value at a dotted path |
410
+ | `/api/apps/{app}/config/{path}` | DELETE | Delete the key at a dotted path |
411
+ | `/api/apps/{app}/schema` | GET | Get the app's JSON Schema |
412
+ | `/api/apps/{app}/schema` | PUT | Replace or clear the app's JSON Schema |
413
+ | `/api/apps/{app}/validate` | POST | Validate a payload against the app's schema |
414
+
415
+ History:
416
+
417
+ | Endpoint | Method | Description |
418
+ |---|---|---|
419
+ | `/api/apps/{app}/history` | GET | List revision snapshots, newest first |
420
+ | `/api/apps/{app}/history/{revision}` | GET | Get one revision snapshot |
421
+ | `/api/apps/{app}/rollback` | POST | Restore a snapshot as a new revision |
422
+
423
+ Real-time:
424
+
425
+ | Endpoint | Protocol | Description |
426
+ |---|---|---|
427
+ | `/ws/{app}` | WebSocket | Receive the current config on subscribe, then every change |
428
+
429
+ The WebSocket is receive-only: the server sends an `initial_config` message
430
+ on subscribe followed by an `update` message per change, each carrying the
431
+ app name, revision, and full configuration. Writes always go through REST, so
432
+ there is never ambiguity about who owns the state.
433
+
434
+ ## Remote clients
435
+
436
+ A remote client reads and writes through the REST API and receives pushes
437
+ over WebSocket. Once constructed, a remote-backed `Nacho` instance behaves
438
+ exactly like a file-backed one — the same `get`, `set`, `on_change`, and
439
+ schema APIs.
440
+
441
+ Requires `pip install nacho-python[remote]`.
442
+
443
+ ```text
444
+ REST reads/writes
445
+ +-------------+ GET/PUT/PATCH/DELETE +----------------------+
446
+ | Python app | -----------------------> | Nacho server |
447
+ | Nacho | | REST API + Web UI |
448
+ | Remote | <----------------------- | File/dict storage |
449
+ | client | WebSocket pushes | Schema validation |
450
+ +-------------+ /ws/{app} +----------------------+
451
+ | ^
452
+ | on_change handlers |
453
+ +---------------------------------------------+
454
+ live config updates
455
+ ```
456
+
457
+ ```python
458
+ from nacho import Nacho, RemoteStorageBackend
459
+
460
+ storage = RemoteStorageBackend(
461
+ url="https://config-server.example.com",
462
+ app_name="my-service",
463
+ api_key="secure-key",
464
+ watch=True, # opt in to WebSocket updates
465
+ )
466
+
467
+ config = Nacho(storage=storage, events=True)
468
+
469
+ host = config.get("database.host")
470
+
471
+ @config.on_change("features.*")
472
+ def on_feature_change(path, new_value, **kwargs):
473
+ print(f"feature flag updated: {path} = {new_value}")
474
+ ```
475
+
476
+ Connecting never mutates the server: a wrong API key fails loudly at
477
+ construction, reading a nonexistent app raises a clear error (so a typo
478
+ cannot silently return an empty config), and the first `save()` to a
479
+ nonexistent app creates it.
480
+
481
+ The backend is revision-aware. Every load and push records the server
482
+ revision it saw, and `save()` sends it back — if another client wrote in
483
+ between, `save()` raises `ConflictError` (with the server's expected/actual
484
+ revisions) instead of silently overwriting the other write. Call `load()`,
485
+ reapply your change, and save again:
486
+
487
+ ```python
488
+ from nacho import ConflictError
489
+
490
+ try:
491
+ config.save()
492
+ except ConflictError:
493
+ config.load() # pick up the concurrent change
494
+ config.set("my.key", value)
495
+ config.save()
496
+ ```
497
+
498
+ If the WebSocket connection drops, the watcher reconnects automatically with
499
+ a bounded number of consecutive retries (`reconnect=0` retries forever), and
500
+ the counter resets on every successful connection. Keepalive pings detect
501
+ half-open connections, and permanent failures (bad key, deleted app) stop
502
+ the retry loop with a clear log line instead of retrying forever. Stale or
503
+ out-of-order pushes are dropped, so the local snapshot never rolls backwards.
504
+
505
+ The CLI covers the same ground without the SDK — see
506
+ [Command-line interface](#command-line-interface).
507
+
508
+ ## Event system
509
+
510
+ With `events=True`, Nacho dispatches change notifications after every
511
+ successful write, whether the change was made locally or pushed from a
512
+ server. Events carry the changed path, old value, new value, and event type.
513
+
514
+ ```python
515
+ from nacho import Nacho, EventType
516
+
517
+ config = Nacho("config.yaml", events=True)
518
+
519
+ # Fires for any change to a key under "database"
520
+ @config.on_change("database.*")
521
+ def on_db_change(path, old_value, new_value, **kwargs):
522
+ print(f"database key changed: {path}")
523
+
524
+ # Fires once per write operation (aggregate event)
525
+ @config.on_change("@global")
526
+ def on_any_change(**kwargs):
527
+ print("config was modified")
528
+
529
+ # Fires for CREATE or UPDATE events under "cache"
530
+ @config.on_event([EventType.CREATE, EventType.UPDATE], path_pattern="cache.*")
531
+ def on_cache_change(event_type, path, new_value, **kwargs):
532
+ print(f"{event_type.name} {path} = {new_value}")
533
+
534
+ config.set("database.host", "new-host") # on_db_change, on_any_change
535
+ config.set("cache.ttl", 600) # on_cache_change (CREATE)
536
+ config.set("cache.ttl", 300) # on_cache_change (UPDATE)
537
+ ```
538
+
539
+ Path pattern reference:
540
+
541
+ | Pattern | Fires when |
542
+ |---|---|
543
+ | `None` (default) | Any change at any path |
544
+ | `"@global"` | Once per write operation (aggregate) |
545
+ | `"*"` | Any per-key event (not the aggregate) |
546
+ | `"database.*"` | Any key nested under `database` |
547
+
548
+ Handlers may be sync or async. Async handlers are scheduled on the running
549
+ event loop when one exists, and executed with `asyncio.run()` otherwise.
550
+ Registering a handler on an instance created without `events=True` logs a
551
+ warning, because the handler would never fire.
552
+
553
+ ## Schema validation
554
+
555
+ Nacho enforces the schema on every write. An invalid value raises
556
+ `ValidationError` before the change is applied, so the configuration is never
557
+ left in an invalid state. The same guarantee applies to local writes and to
558
+ writes accepted by the server.
559
+
560
+ Standalone usage requires `pip install nacho-python[schema]`.
561
+
562
+ ```json
563
+ {
564
+ "type": "object",
565
+ "required": ["database"],
566
+ "properties": {
567
+ "database": {
568
+ "type": "object",
569
+ "required": ["host", "port"],
570
+ "properties": {
571
+ "host": {"type": "string"},
572
+ "port": {"type": "integer", "minimum": 1024}
573
+ }
574
+ }
575
+ }
576
+ }
577
+ ```
578
+
579
+ ```python
580
+ from nacho import Nacho, ValidationError
581
+
582
+ config = Nacho("config.yaml", schema="schema.json")
583
+
584
+ # An invalid write raises immediately; the config is not modified
585
+ try:
586
+ config.set("database.port", "not-a-number")
587
+ except ValidationError as e:
588
+ print(e.errors) # list of violation strings
589
+
590
+ # Inspect the current config without writing
591
+ errors = config.validate()
592
+
593
+ # Validate an arbitrary dict against the schema
594
+ errors = config.check({"database": {"host": "localhost", "port": 80}})
595
+ ```
596
+
597
+ ## Standalone usage
598
+
599
+ Nacho does not require a server. Point it at a local file, or hand it a plain
600
+ dict, and it works as a self-contained configuration library for scripts,
601
+ tests, and single-process applications. Everything below behaves identically
602
+ with a file, a dict, or a remote server behind it.
603
+
604
+ ### Reading and writing
605
+
606
+ ```python
607
+ from nacho import Nacho
608
+
609
+ config = Nacho({"database": {"host": "127.0.0.1", "port": 5432}}) # in-memory
610
+ config = Nacho("config.yaml") # file-backed
611
+
612
+ # Typed reads with sensible coercion
613
+ host = config.get("database.host")
614
+ port = config.get_int("database.port")
615
+ debug = config.get_bool("app.debug")
616
+ tags = config.get_list("app.tags")
617
+ options = config.get_dict("app.options")
618
+
619
+ config.update({"logging": {"level": "DEBUG"}}) # deep-merge
620
+ config.replace({"database": {"host": "prod-db", "port": 5432}})
621
+ config.delete("legacy.setting")
622
+ config.load() # reload from storage
623
+ config.save() # persist to storage
624
+ print(config.json()) # export as a JSON string
625
+ ```
626
+
627
+ ### Transactions
628
+
629
+ Group multiple writes into one atomic operation. The transaction commits when
630
+ the block exits cleanly and is discarded on any exception. Commit replays the
631
+ transaction's operations onto the *current* configuration, so an unrelated
632
+ write that landed while the transaction was open is preserved, not discarded:
633
+
634
+ ```python
635
+ with config.transaction() as txn:
636
+ txn.set("database.host", "new-host")
637
+ txn.set("database.port", 5433)
638
+ # Handlers fire once here with the aggregated changes
639
+ config.save()
640
+ ```
641
+
642
+ ### Environment variable overrides
643
+
644
+ Pass `env_prefix` to overlay environment variables on the configuration at
645
+ load time. Variable names follow `{PREFIX}_{NESTED_KEY}`, with nesting levels
646
+ separated by the delimiter (default `_`):
647
+
648
+ ```bash
649
+ export MYAPP_DATABASE_HOST=prod-db.example.com
650
+ export MYAPP_DATABASE_PORT=5433
651
+ export MYAPP_FEATURES_ENABLED=true
652
+ ```
653
+
654
+ ```python
655
+ config = Nacho("config.yaml", env_prefix="MYAPP")
656
+
657
+ config.get("database.host") # "prod-db.example.com"
658
+ config.get_int("database.port") # 5433
659
+ config.get_bool("features.enabled") # True
660
+ ```
661
+
662
+ Values are coerced where unambiguous: `true`/`false`/`yes`/`no`/`on`/`off`
663
+ become booleans, numeric strings become numbers (`"1"` is the integer 1, not
664
+ a boolean), and JSON-looking strings are parsed as JSON. Floats are only
665
+ parsed when the text round-trips, so `MYAPP_VERSION=3.10` stays the string
666
+ `"3.10"`, and quoting a value (`MYAPP_PORT='"8080"'`) forces it to stay a
667
+ string. Everything else stays a string.
668
+
669
+ Keys with underscores in their names use a doubled delimiter for nesting:
670
+ `MYAPP_DB__MAX_CONNECTIONS` sets `db.max_connections`. Env overrides are
671
+ runtime-only overlays: `save()` persists the stored configuration, not the
672
+ overlaid view.
673
+
674
+ ## Command-line interface
675
+
676
+ ```bash
677
+ nacho --help
678
+ nacho --version
679
+ ```
680
+
681
+ Every remote command takes `--remote <url>`, `--app-name <name>` (default
682
+ `default`), and `--api-key <key>`. Errors are written to stderr, and exit
683
+ codes distinguish failure classes so scripts can branch without parsing
684
+ messages:
685
+
686
+ | Exit code | Meaning |
687
+ |---|---|
688
+ | 0 | Success |
689
+ | 1 | Generic error (schema violation, transport failure, missing extras) |
690
+ | 2 | Usage error (bad flags or arguments) |
691
+ | 3 | Not found (missing app, key, path, or history revision) |
692
+ | 4 | Revision conflict (a concurrent write won) |
693
+ | 5 | Authentication failure (bad or missing API key, read-only server) |
694
+
695
+ Output is rendered in `--format {json,yaml,toml}` (default `json`), so every
696
+ command's output is machine-parseable; `nacho get missing.key` exits 3 with a
697
+ stderr message instead of printing `None`.
698
+
699
+ ### Values
700
+
701
+ ```bash
702
+ # Read a key, or the whole config, locally or remotely
703
+ nacho get database.host --config config.yaml
704
+ nacho get --format json --remote http://config-server:8000 --app-name my-service
705
+
706
+ # Include the current revision in the output
707
+ nacho get --show-revision --format json --remote http://config-server:8000
708
+
709
+ # Write and delete, with optional conflict-safe revision checks
710
+ nacho set cache.ttl 600 --remote http://config-server:8000 --revision 3
711
+ nacho delete legacy.setting --remote http://config-server:8000 --revision 4
712
+
713
+ # Force a type when auto-detection would guess wrong
714
+ nacho set app.version 3.10 --type str --remote http://config-server:8000
715
+ nacho set app.flags '{"beta": true}' --type json --remote http://config-server:8000
716
+
717
+ # Local file equivalents
718
+ nacho set database.port 5432 --config config.yaml
719
+ nacho delete legacy.setting --config config.yaml
720
+ ```
721
+
722
+ Local writes are read-modify-write on the file with no cross-process lock:
723
+ the file itself is written atomically, but two `nacho set` commands racing on
724
+ the same file can lose one of the updates. Point concurrent writers at a
725
+ server (`--remote`) instead — that is what revision-checked writes are for.
726
+
727
+ ### Apps
728
+
729
+ ```bash
730
+ nacho apps list --remote http://config-server:8000
731
+ nacho apps create my-service \
732
+ --remote http://config-server:8000 \
733
+ --description "Core service" \
734
+ --config config.yaml \
735
+ --schema schema.json
736
+ nacho apps show --remote http://config-server:8000 --app-name my-service
737
+ nacho apps rename my-service-v2 --remote http://config-server:8000 --app-name my-service
738
+ nacho apps describe "Payments service" --remote http://config-server:8000 --app-name my-service
739
+ nacho apps delete my-service --remote http://config-server:8000
740
+ ```
741
+
742
+ ### Schemas and validation
743
+
744
+ ```bash
745
+ # Print or replace the schema the server enforces
746
+ nacho schema get --remote http://config-server:8000 --app-name my-service
747
+ nacho schema push schema.json --remote http://config-server:8000 --app-name my-service
748
+
749
+ # Validate a local file against the server's stored schema
750
+ nacho validate --config config.yaml --remote http://config-server:8000 --app-name my-service
751
+
752
+ # Validate against a local schema file instead
753
+ nacho validate --config config.yaml --schema schema.json
754
+ ```
755
+
756
+ ### History and rollback
757
+
758
+ ```bash
759
+ nacho history list --remote http://config-server:8000 --app-name my-service
760
+ nacho history show 41 --remote http://config-server:8000 --app-name my-service
761
+
762
+ # What changed between two revisions — or between revision 41 and now
763
+ nacho history diff 41 42 --remote http://config-server:8000 --app-name my-service
764
+ nacho history diff 41 --remote http://config-server:8000 --app-name my-service
765
+
766
+ # Restore revision 41 as a new revision; --revision-check makes it conflict-safe
767
+ nacho rollback 41 --remote http://config-server:8000 --app-name my-service --revision-check 42
768
+ ```
769
+
770
+ ### Live updates
771
+
772
+ ```bash
773
+ # Print the current config, then one JSON line per change (Ctrl+C to stop)
774
+ nacho watch --remote http://config-server:8000 --app-name my-service
775
+ ```
776
+
777
+ ### Scaffolding
778
+
779
+ ```bash
780
+ # Create a config file from a built-in template
781
+ nacho init config.yaml --template default
782
+ # Templates: empty, default, web-app, api-service, microservice
783
+ ```
784
+
785
+ ## Docker
786
+
787
+ Nacho ships a multi-stage `Dockerfile` producing a small Alpine-based image
788
+ that runs the configuration server as a non-root user, with a container
789
+ health check against `/health`. Published images are available on Docker Hub
790
+ and GHCR:
791
+
792
+ ```bash
793
+ docker pull k3scat/nacho:latest
794
+ docker pull ghcr.io/nya-foundation/nacho:latest
795
+
796
+ # Run the server (UI at http://localhost:8000/ui)
797
+ docker run -p 8000:8000 k3scat/nacho:latest
798
+
799
+ # Run with authentication enabled
800
+ docker run -p 8000:8000 k3scat/nacho:latest \
801
+ server --host 0.0.0.0 --config config.yaml --api-key "secure-key"
802
+
803
+ # Mount your own config for the default app
804
+ docker run -p 8000:8000 \
805
+ -v "$(pwd)/config.yaml:/app/config.yaml" k3scat/nacho:latest
806
+ ```
807
+
808
+ Or with Compose:
809
+
810
+ ```bash
811
+ docker compose up --build
812
+ ```
813
+
814
+ The image entrypoint is `nacho`; the default command is
815
+ `server --host 0.0.0.0 --config config.yaml`. Append any `nacho server` flags
816
+ to override the defaults. The container exposes port `8000`.
817
+
818
+ ## Operational notes
819
+
820
+ - Dot-notation paths are intentionally simple. Literal dots in key names and
821
+ numeric string keys are ambiguous; prefer nested object keys.
822
+ - The built-in API-key authentication suits local, private, and single-tenant
823
+ deployments. Shared production deployments should add scoped tokens, audit
824
+ logging, and rate limiting in front of the service.
825
+ - Server state is file-backed and single-process. The revision counter is
826
+ authoritative in memory, so run one server process per data directory; the
827
+ storage abstraction is the boundary to implement a stronger backend if you
828
+ need multi-process or high-availability operation.
829
+ - Editing a `--config` file by hand while the server is running is not
830
+ detected; the server's next write wins. Make changes through the API, CLI,
831
+ or UI.
832
+
833
+ ## Development
834
+
835
+ ```bash
836
+ git clone https://github.com/nya-foundation/nacho.git
837
+ cd nacho
838
+ uv sync --all-extras
839
+
840
+ uv run pytest # fast suites (unit + smoke), 95% coverage gate
841
+ uv run pytest -m "integration or e2e" --no-cov # live-server suites
842
+ uv run pytest -m docker --no-cov # builds and exercises the Docker image
843
+ uv run playwright install chromium # one-time browser download
844
+ uv run pytest -m ui --no-cov # browser-driven web UI suite
845
+
846
+ uvx ruff format . && uvx ruff check . # formatting and lint (enforced in CI)
847
+ ```
848
+
849
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the branch model, code style, and
850
+ release process.
851
+
852
+ ## Community
853
+
854
+ Open an issue on [GitHub](https://github.com/nya-foundation/nacho/issues) or
855
+ join the [Nya Foundation Discord](https://discord.gg/jXAxVPSs7K).
856
+
857
+ ## License
858
+
859
+ MIT — see [LICENSE](LICENSE) for details.