nacho-python 0.1.1__tar.gz → 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {nacho_python-0.1.1/nacho_python.egg-info → nacho_python-1.0.0}/PKG-INFO +30 -14
- {nacho_python-0.1.1 → nacho_python-1.0.0}/README.md +28 -13
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/__init__.py +1 -10
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/_version.py +1 -1
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/cli/main.py +7 -12
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/client.py +17 -4
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/config.py +7 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/schema.py +6 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/app.py +41 -35
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/auth.py +29 -76
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/runtime.py +194 -55
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/ui/index.html +1161 -227
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/storage/__init__.py +6 -4
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/storage/remote.py +51 -1
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/utils/io.py +2 -2
- {nacho_python-0.1.1 → nacho_python-1.0.0/nacho_python.egg-info}/PKG-INFO +30 -14
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho_python.egg-info/SOURCES.txt +0 -22
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho_python.egg-info/requires.txt +1 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/pyproject.toml +3 -3
- {nacho_python-0.1.1 → nacho_python-1.0.0}/LICENSE +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/MANIFEST.in +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/cli/__init__.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/env.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/event.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/__init__.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/server/models.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/storage/base.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/storage/file.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/utils/__init__.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho/utils/path.py +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho_python.egg-info/dependency_links.txt +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho_python.egg-info/entry_points.txt +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/nacho_python.egg-info/top_level.txt +0 -0
- {nacho_python-0.1.1 → nacho_python-1.0.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: nacho-python
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 1.0.0
|
|
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
|
|
@@ -22,6 +22,7 @@ Requires-Dist: tomli>=2.0.0; python_version < "3.11"
|
|
|
22
22
|
Requires-Dist: tomli-w>=1.0.0
|
|
23
23
|
Provides-Extra: server
|
|
24
24
|
Requires-Dist: fastapi>=0.100.0; extra == "server"
|
|
25
|
+
Requires-Dist: pydantic>=2.0.0; extra == "server"
|
|
25
26
|
Requires-Dist: uvicorn>=0.22.0; extra == "server"
|
|
26
27
|
Requires-Dist: websockets>=10.0; extra == "server"
|
|
27
28
|
Provides-Extra: remote
|
|
@@ -198,7 +199,6 @@ missed live updates.
|
|
|
198
199
|
| `--app-name` | `default` | App name for the `--config` file |
|
|
199
200
|
| `--data-dir` | none | Directory for API-created app state and history |
|
|
200
201
|
| `--api-key` | none | Enable bearer-token authentication |
|
|
201
|
-
| `--read-only-api-key` | none | Additional key granting read access only |
|
|
202
202
|
| `--history-limit` | `50` | Revision snapshots kept per app (`0` disables history) |
|
|
203
203
|
| `--read-only` | off | Reject every write |
|
|
204
204
|
| `--reload` | off | Auto-reload for development |
|
|
@@ -275,10 +275,10 @@ function preauthenticateNacho(key, mountPath = "") {
|
|
|
275
275
|
}
|
|
276
276
|
```
|
|
277
277
|
|
|
278
|
-
Seed
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
278
|
+
Seed the key only for users your own application has already authorised to
|
|
279
|
+
manage configuration. The key grants full access, so a host application that
|
|
280
|
+
wants some users to look without touching must enforce that itself — by not
|
|
281
|
+
seeding the key, or by mounting the UI only for the users it trusts.
|
|
282
282
|
|
|
283
283
|
Do not pass the key in the URL (`?token=`): query strings leak through
|
|
284
284
|
browser history, `Referer` headers, and proxy logs.
|
|
@@ -291,11 +291,14 @@ authentication for the whole API. Clients send the key either as an
|
|
|
291
291
|
its own WebSocket handshake. Requests with a missing or wrong key receive
|
|
292
292
|
`401 Unauthorized`. The comparison is timing-safe.
|
|
293
293
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
294
|
+
There is one key and access is all-or-nothing — no roles, no second key.
|
|
295
|
+
Two separate controls cover the read-only cases:
|
|
296
|
+
|
|
297
|
+
- A **client** that should never write constructs its instance with
|
|
298
|
+
`read_only=True`; every mutating call then raises `PermissionError`
|
|
299
|
+
locally, without a round trip.
|
|
300
|
+
- A **server** that should refuse every write runs with `--read-only`, which
|
|
301
|
+
answers `403 Forbidden` to any mutation regardless of the caller.
|
|
299
302
|
|
|
300
303
|
`/`, `/health`, `/ui`, `/docs`, `/redoc`, and `/openapi.json` stay public: the
|
|
301
304
|
API surface is not a secret, only the data behind it.
|
|
@@ -335,7 +338,8 @@ is how the CLI and UI submit YAML and TOML:
|
|
|
335
338
|
|
|
336
339
|
Every app carries a monotonically increasing revision, bumped on each
|
|
337
340
|
successful write. Reads of `/config` (full or per-path) return the current
|
|
338
|
-
revision in
|
|
341
|
+
revision in `X-Nacho-Revision`; `X-Nacho-Generation` identifies the current
|
|
342
|
+
server process, and `ETag` combines both values. Writes may
|
|
339
343
|
include a `revision` field stating the revision the client last saw; if the
|
|
340
344
|
server has moved on, the write fails with `409 Conflict` and the stored
|
|
341
345
|
configuration is left untouched:
|
|
@@ -353,7 +357,8 @@ The `ETag` also enables cheap polling: send it back as `If-None-Match` and
|
|
|
353
357
|
the server answers `304 Not Modified` — no body — until the revision moves.
|
|
354
358
|
|
|
355
359
|
```bash
|
|
356
|
-
curl -H 'If-None-Match: "3"'
|
|
360
|
+
curl -H 'If-None-Match: "<generation>:3"' \
|
|
361
|
+
http://127.0.0.1:8000/api/apps/my-service/config
|
|
357
362
|
```
|
|
358
363
|
|
|
359
364
|
### History and rollback
|
|
@@ -428,7 +433,9 @@ Real-time:
|
|
|
428
433
|
|
|
429
434
|
The WebSocket is receive-only: the server sends an `initial_config` message
|
|
430
435
|
on subscribe followed by an `update` message per change, each carrying the
|
|
431
|
-
app name, revision,
|
|
436
|
+
server generation, app name, revision, full configuration, schema, and current
|
|
437
|
+
metadata. The generation lets clients recover safely when an ephemeral server
|
|
438
|
+
restarts its revision counter. Writes always go through REST, so
|
|
432
439
|
there is never ambiguity about who owns the state.
|
|
433
440
|
|
|
434
441
|
## Remote clients
|
|
@@ -501,6 +508,9 @@ the counter resets on every successful connection. Keepalive pings detect
|
|
|
501
508
|
half-open connections, and permanent failures (bad key, deleted app) stop
|
|
502
509
|
the retry loop with a clear log line instead of retrying forever. Stale or
|
|
503
510
|
out-of-order pushes are dropped, so the local snapshot never rolls backwards.
|
|
511
|
+
Applications can expose `storage.watching`, `storage.last_watch_error`, and
|
|
512
|
+
`storage.generation` in their own health checks instead of relying on logs to
|
|
513
|
+
detect a stale subscription.
|
|
504
514
|
|
|
505
515
|
The CLI covers the same ground without the SDK — see
|
|
506
516
|
[Command-line interface](#command-line-interface).
|
|
@@ -811,6 +821,10 @@ Or with Compose:
|
|
|
811
821
|
docker compose up --build
|
|
812
822
|
```
|
|
813
823
|
|
|
824
|
+
Compose binds to loopback by default and persists server state in the
|
|
825
|
+
`nacho-data` volume. Add `--api-key` before exposing the port beyond the local
|
|
826
|
+
machine.
|
|
827
|
+
|
|
814
828
|
The image entrypoint is `nacho`; the default command is
|
|
815
829
|
`server --host 0.0.0.0 --config config.yaml`. Append any `nacho server` flags
|
|
816
830
|
to override the defaults. The container exposes port `8000`.
|
|
@@ -829,6 +843,8 @@ to override the defaults. The container exposes port `8000`.
|
|
|
829
843
|
- Editing a `--config` file by hand while the server is running is not
|
|
830
844
|
detected; the server's next write wins. Make changes through the API, CLI,
|
|
831
845
|
or UI.
|
|
846
|
+
- Newly created server state and history directories use mode `0700`, and
|
|
847
|
+
their JSON files use mode `0600`. Existing permissions are preserved.
|
|
832
848
|
|
|
833
849
|
## Development
|
|
834
850
|
|
|
@@ -151,7 +151,6 @@ missed live updates.
|
|
|
151
151
|
| `--app-name` | `default` | App name for the `--config` file |
|
|
152
152
|
| `--data-dir` | none | Directory for API-created app state and history |
|
|
153
153
|
| `--api-key` | none | Enable bearer-token authentication |
|
|
154
|
-
| `--read-only-api-key` | none | Additional key granting read access only |
|
|
155
154
|
| `--history-limit` | `50` | Revision snapshots kept per app (`0` disables history) |
|
|
156
155
|
| `--read-only` | off | Reject every write |
|
|
157
156
|
| `--reload` | off | Auto-reload for development |
|
|
@@ -228,10 +227,10 @@ function preauthenticateNacho(key, mountPath = "") {
|
|
|
228
227
|
}
|
|
229
228
|
```
|
|
230
229
|
|
|
231
|
-
Seed
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
230
|
+
Seed the key only for users your own application has already authorised to
|
|
231
|
+
manage configuration. The key grants full access, so a host application that
|
|
232
|
+
wants some users to look without touching must enforce that itself — by not
|
|
233
|
+
seeding the key, or by mounting the UI only for the users it trusts.
|
|
235
234
|
|
|
236
235
|
Do not pass the key in the URL (`?token=`): query strings leak through
|
|
237
236
|
browser history, `Referer` headers, and proxy logs.
|
|
@@ -244,11 +243,14 @@ authentication for the whole API. Clients send the key either as an
|
|
|
244
243
|
its own WebSocket handshake. Requests with a missing or wrong key receive
|
|
245
244
|
`401 Unauthorized`. The comparison is timing-safe.
|
|
246
245
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
246
|
+
There is one key and access is all-or-nothing — no roles, no second key.
|
|
247
|
+
Two separate controls cover the read-only cases:
|
|
248
|
+
|
|
249
|
+
- A **client** that should never write constructs its instance with
|
|
250
|
+
`read_only=True`; every mutating call then raises `PermissionError`
|
|
251
|
+
locally, without a round trip.
|
|
252
|
+
- A **server** that should refuse every write runs with `--read-only`, which
|
|
253
|
+
answers `403 Forbidden` to any mutation regardless of the caller.
|
|
252
254
|
|
|
253
255
|
`/`, `/health`, `/ui`, `/docs`, `/redoc`, and `/openapi.json` stay public: the
|
|
254
256
|
API surface is not a secret, only the data behind it.
|
|
@@ -288,7 +290,8 @@ is how the CLI and UI submit YAML and TOML:
|
|
|
288
290
|
|
|
289
291
|
Every app carries a monotonically increasing revision, bumped on each
|
|
290
292
|
successful write. Reads of `/config` (full or per-path) return the current
|
|
291
|
-
revision in
|
|
293
|
+
revision in `X-Nacho-Revision`; `X-Nacho-Generation` identifies the current
|
|
294
|
+
server process, and `ETag` combines both values. Writes may
|
|
292
295
|
include a `revision` field stating the revision the client last saw; if the
|
|
293
296
|
server has moved on, the write fails with `409 Conflict` and the stored
|
|
294
297
|
configuration is left untouched:
|
|
@@ -306,7 +309,8 @@ The `ETag` also enables cheap polling: send it back as `If-None-Match` and
|
|
|
306
309
|
the server answers `304 Not Modified` — no body — until the revision moves.
|
|
307
310
|
|
|
308
311
|
```bash
|
|
309
|
-
curl -H 'If-None-Match: "3"'
|
|
312
|
+
curl -H 'If-None-Match: "<generation>:3"' \
|
|
313
|
+
http://127.0.0.1:8000/api/apps/my-service/config
|
|
310
314
|
```
|
|
311
315
|
|
|
312
316
|
### History and rollback
|
|
@@ -381,7 +385,9 @@ Real-time:
|
|
|
381
385
|
|
|
382
386
|
The WebSocket is receive-only: the server sends an `initial_config` message
|
|
383
387
|
on subscribe followed by an `update` message per change, each carrying the
|
|
384
|
-
app name, revision,
|
|
388
|
+
server generation, app name, revision, full configuration, schema, and current
|
|
389
|
+
metadata. The generation lets clients recover safely when an ephemeral server
|
|
390
|
+
restarts its revision counter. Writes always go through REST, so
|
|
385
391
|
there is never ambiguity about who owns the state.
|
|
386
392
|
|
|
387
393
|
## Remote clients
|
|
@@ -454,6 +460,9 @@ the counter resets on every successful connection. Keepalive pings detect
|
|
|
454
460
|
half-open connections, and permanent failures (bad key, deleted app) stop
|
|
455
461
|
the retry loop with a clear log line instead of retrying forever. Stale or
|
|
456
462
|
out-of-order pushes are dropped, so the local snapshot never rolls backwards.
|
|
463
|
+
Applications can expose `storage.watching`, `storage.last_watch_error`, and
|
|
464
|
+
`storage.generation` in their own health checks instead of relying on logs to
|
|
465
|
+
detect a stale subscription.
|
|
457
466
|
|
|
458
467
|
The CLI covers the same ground without the SDK — see
|
|
459
468
|
[Command-line interface](#command-line-interface).
|
|
@@ -764,6 +773,10 @@ Or with Compose:
|
|
|
764
773
|
docker compose up --build
|
|
765
774
|
```
|
|
766
775
|
|
|
776
|
+
Compose binds to loopback by default and persists server state in the
|
|
777
|
+
`nacho-data` volume. Add `--api-key` before exposing the port beyond the local
|
|
778
|
+
machine.
|
|
779
|
+
|
|
767
780
|
The image entrypoint is `nacho`; the default command is
|
|
768
781
|
`server --host 0.0.0.0 --config config.yaml`. Append any `nacho server` flags
|
|
769
782
|
to override the defaults. The container exposes port `8000`.
|
|
@@ -782,6 +795,8 @@ to override the defaults. The container exposes port `8000`.
|
|
|
782
795
|
- Editing a `--config` file by hand while the server is running is not
|
|
783
796
|
detected; the server's next write wins. Make changes through the API, CLI,
|
|
784
797
|
or UI.
|
|
798
|
+
- Newly created server state and history directories use mode `0700`, and
|
|
799
|
+
their JSON files use mode `0600`. Existing permissions are preserved.
|
|
785
800
|
|
|
786
801
|
## Development
|
|
787
802
|
|
|
@@ -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")
|
|
@@ -26,11 +26,9 @@ if TYPE_CHECKING: # pragma: no cover - typing only
|
|
|
26
26
|
|
|
27
27
|
LOGGER = logging.getLogger("nacho.cli")
|
|
28
28
|
|
|
29
|
-
# Exit codes
|
|
30
|
-
# are produced by the @cli_command wrapper from the typed client errors.
|
|
29
|
+
# Exit codes produced by the @cli_command wrapper from typed client errors.
|
|
31
30
|
EXIT_OK = 0
|
|
32
31
|
EXIT_ERROR = 1
|
|
33
|
-
EXIT_USAGE = 2
|
|
34
32
|
EXIT_NOT_FOUND = 3
|
|
35
33
|
EXIT_CONFLICT = 4
|
|
36
34
|
EXIT_AUTH = 5
|
|
@@ -245,10 +243,6 @@ def create_parser() -> argparse.ArgumentParser:
|
|
|
245
243
|
server.add_argument("--schema", help="Schema file path")
|
|
246
244
|
server.add_argument("--data-dir", help="Directory for API-created app state")
|
|
247
245
|
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
246
|
server.add_argument("--app-name", help="Application name for config server")
|
|
253
247
|
server.add_argument(
|
|
254
248
|
"--history-limit",
|
|
@@ -256,7 +250,11 @@ def create_parser() -> argparse.ArgumentParser:
|
|
|
256
250
|
default=50,
|
|
257
251
|
help="Revision snapshots to keep per app for rollback (0 disables history)",
|
|
258
252
|
)
|
|
259
|
-
server.add_argument(
|
|
253
|
+
server.add_argument(
|
|
254
|
+
"--read-only",
|
|
255
|
+
action="store_true",
|
|
256
|
+
help="Serve reads only — every write is refused, whoever the caller is",
|
|
257
|
+
)
|
|
260
258
|
server.add_argument("--reload", action="store_true", help="Auto-reload for development")
|
|
261
259
|
server.set_defaults(func=cmd_server)
|
|
262
260
|
|
|
@@ -443,9 +441,7 @@ def cmd_server(args: argparse.Namespace) -> int:
|
|
|
443
441
|
|
|
444
442
|
print(banner())
|
|
445
443
|
|
|
446
|
-
|
|
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):
|
|
444
|
+
if not args.api_key and not is_loopback_host(args.host):
|
|
449
445
|
print(
|
|
450
446
|
"WARNING: serving on a non-loopback interface without --api-key — "
|
|
451
447
|
"anyone who can reach this host has full write access.",
|
|
@@ -460,7 +456,6 @@ def cmd_server(args: argparse.Namespace) -> int:
|
|
|
460
456
|
orchestrator = NachoOrchestrator(
|
|
461
457
|
apps=apps,
|
|
462
458
|
api_key=args.api_key,
|
|
463
|
-
read_only_api_key=args.read_only_api_key,
|
|
464
459
|
read_only=args.read_only,
|
|
465
460
|
data_dir=args.data_dir,
|
|
466
461
|
history_limit=args.history_limit,
|
|
@@ -12,6 +12,7 @@ Requires the ``remote`` extra (``pip install nacho-python[remote]``).
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
14
|
from typing import Any, Dict, List, Optional, Tuple
|
|
15
|
+
from urllib.parse import quote
|
|
15
16
|
|
|
16
17
|
import requests
|
|
17
18
|
|
|
@@ -40,6 +41,7 @@ class NachoClient:
|
|
|
40
41
|
self.app_name = app_name
|
|
41
42
|
self.api_key = api_key
|
|
42
43
|
self.timeout = timeout
|
|
44
|
+
self.last_generation: Optional[str] = None
|
|
43
45
|
|
|
44
46
|
# ------------------------------------------------------------------
|
|
45
47
|
# Low-level request plumbing
|
|
@@ -109,7 +111,12 @@ 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
122
|
def _revision_from(resp: requests.Response) -> Optional[int]:
|
|
@@ -181,6 +188,7 @@ class NachoClient:
|
|
|
181
188
|
|
|
182
189
|
def get_config(self) -> Tuple[Dict[str, Any], Optional[int]]:
|
|
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(
|
|
@@ -192,7 +200,8 @@ class NachoClient:
|
|
|
192
200
|
return self.request("PUT", self._app("/config"), json_body=payload).json()
|
|
193
201
|
|
|
194
202
|
def get_path(self, path: str) -> Tuple[Any, Optional[int]]:
|
|
195
|
-
resp = self.request("GET", self._app(f"/config/{path}"))
|
|
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(
|
|
@@ -206,11 +215,15 @@ class NachoClient:
|
|
|
206
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(
|
|
218
|
+
return self.request(
|
|
219
|
+
"PUT", self._app(f"/config/{quote(path, safe='')}"), json_body=payload
|
|
220
|
+
).json()
|
|
210
221
|
|
|
211
222
|
def delete_path(self, path: str, *, revision: Optional[int] = None) -> Dict[str, Any]:
|
|
212
223
|
params = {"revision": revision} if revision is not None else None
|
|
213
|
-
return self.request(
|
|
224
|
+
return self.request(
|
|
225
|
+
"DELETE", self._app(f"/config/{quote(path, safe='')}"), params=params
|
|
226
|
+
).json()
|
|
214
227
|
|
|
215
228
|
# ------------------------------------------------------------------
|
|
216
229
|
# Schema
|
|
@@ -451,6 +451,13 @@ class Nacho:
|
|
|
451
451
|
data = copy.deepcopy(self._data)
|
|
452
452
|
return self._validator.check(data)
|
|
453
453
|
|
|
454
|
+
@property
|
|
455
|
+
def schema(self) -> Optional[Dict[str, Any]]:
|
|
456
|
+
"""The currently enforced JSON Schema, or ``None`` when validation is off."""
|
|
457
|
+
if self._validator is None:
|
|
458
|
+
return None
|
|
459
|
+
return self._validator.schema
|
|
460
|
+
|
|
454
461
|
# ------------------------------------------------------------------
|
|
455
462
|
# Transactions
|
|
456
463
|
# ------------------------------------------------------------------
|
|
@@ -7,6 +7,7 @@ has to check a return value — invalid writes are refused immediately.
|
|
|
7
7
|
|
|
8
8
|
from __future__ import annotations
|
|
9
9
|
|
|
10
|
+
import copy
|
|
10
11
|
import logging
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
from typing import Any, Dict, List, Union
|
|
@@ -60,6 +61,11 @@ class SchemaValidator:
|
|
|
60
61
|
format_checker=jsonschema.FormatChecker(),
|
|
61
62
|
)
|
|
62
63
|
|
|
64
|
+
@property
|
|
65
|
+
def schema(self) -> Dict[str, Any]:
|
|
66
|
+
"""Return an isolated copy of the schema enforced by this validator."""
|
|
67
|
+
return copy.deepcopy(self._schema)
|
|
68
|
+
|
|
63
69
|
# ------------------------------------------------------------------
|
|
64
70
|
# Public API
|
|
65
71
|
# ------------------------------------------------------------------
|
|
@@ -67,7 +67,6 @@ class NachoOrchestrator:
|
|
|
67
67
|
data_dir: Optional[Union[str, Path]] = None,
|
|
68
68
|
logger: Optional[logging.Logger] = None,
|
|
69
69
|
history_limit: int = 50,
|
|
70
|
-
read_only_api_key: Optional[str] = None,
|
|
71
70
|
) -> None:
|
|
72
71
|
self.read_only = read_only
|
|
73
72
|
# No CORS by default: the bundled UI is same-origin and SDK/CLI
|
|
@@ -78,12 +77,7 @@ class NachoOrchestrator:
|
|
|
78
77
|
# (e.g. an empty list from a caller's own config) would otherwise
|
|
79
78
|
# skip AuthGuard entirely and leave the server unauthenticated.
|
|
80
79
|
api_key = validate_api_key("api_key", api_key)
|
|
81
|
-
|
|
82
|
-
self.auth = (
|
|
83
|
-
AuthGuard(api_key=api_key, read_only_api_key=read_only_api_key)
|
|
84
|
-
if (api_key or read_only_api_key)
|
|
85
|
-
else None
|
|
86
|
-
)
|
|
80
|
+
self.auth = AuthGuard(api_key=api_key) if api_key else None
|
|
87
81
|
self.manager = AppManager(
|
|
88
82
|
data_dir=Path(data_dir) if data_dir else None,
|
|
89
83
|
logger=self.logger,
|
|
@@ -128,12 +122,20 @@ class NachoOrchestrator:
|
|
|
128
122
|
async def cap_body_size(request: Request, call_next):
|
|
129
123
|
length = request.headers.get("content-length")
|
|
130
124
|
if length and length.isdigit() and int(length) > _MAX_BODY_BYTES:
|
|
131
|
-
return
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
125
|
+
return self._body_too_large()
|
|
126
|
+
if request.method in {"POST", "PUT", "PATCH"} and not (length and length.isdigit()):
|
|
127
|
+
# Transfer-Encoding: chunked has no Content-Length. Consume only
|
|
128
|
+
# up to the limit, then let Starlette replay the cached body to
|
|
129
|
+
# the endpoint. This closes the header-bypass without buffering
|
|
130
|
+
# an unbounded request.
|
|
131
|
+
chunks = []
|
|
132
|
+
size = 0
|
|
133
|
+
async for chunk in request.stream():
|
|
134
|
+
size += len(chunk)
|
|
135
|
+
if size > _MAX_BODY_BYTES:
|
|
136
|
+
return self._body_too_large()
|
|
137
|
+
chunks.append(chunk)
|
|
138
|
+
request._body = b"".join(chunks)
|
|
137
139
|
return await call_next(request)
|
|
138
140
|
|
|
139
141
|
if self.cors_origins:
|
|
@@ -165,6 +167,8 @@ class NachoOrchestrator:
|
|
|
165
167
|
"apps": len(self.manager.apps),
|
|
166
168
|
"read_only": self.read_only,
|
|
167
169
|
"auth_required": self.auth is not None,
|
|
170
|
+
"generation": self.manager.generation,
|
|
171
|
+
"load_errors": len(self.manager.store.load_errors),
|
|
168
172
|
}
|
|
169
173
|
|
|
170
174
|
@self.app.get("/ui", include_in_schema=False)
|
|
@@ -273,11 +277,12 @@ class NachoOrchestrator:
|
|
|
273
277
|
@self.app.get("/api/apps/{app_name}/config")
|
|
274
278
|
def get_config(app_name: str, request: Request, response: Response) -> Any:
|
|
275
279
|
app = self._get_app(app_name)
|
|
276
|
-
|
|
280
|
+
snapshot = app.snapshot()
|
|
281
|
+
not_modified = self._not_modified(request, snapshot["revision"])
|
|
277
282
|
if not_modified is not None:
|
|
278
283
|
return not_modified
|
|
279
|
-
self._set_revision_headers(response,
|
|
280
|
-
return
|
|
284
|
+
self._set_revision_headers(response, snapshot["revision"])
|
|
285
|
+
return snapshot["config"]
|
|
281
286
|
|
|
282
287
|
@self.app.put("/api/apps/{app_name}/config")
|
|
283
288
|
def replace_config(
|
|
@@ -308,8 +313,7 @@ class NachoOrchestrator:
|
|
|
308
313
|
|
|
309
314
|
@self.app.get("/api/apps/{app_name}/schema")
|
|
310
315
|
def get_schema(app_name: str) -> Dict[str, Any]:
|
|
311
|
-
|
|
312
|
-
return {"data": app.schema}
|
|
316
|
+
return {"data": self._get_app(app_name).snapshot()["schema"]}
|
|
313
317
|
|
|
314
318
|
@self.app.put("/api/apps/{app_name}/schema")
|
|
315
319
|
def replace_schema(
|
|
@@ -337,15 +341,16 @@ class NachoOrchestrator:
|
|
|
337
341
|
@self.app.get("/api/apps/{app_name}/config/{path:path}")
|
|
338
342
|
def get_path(app_name: str, path: str, request: Request, response: Response) -> Any:
|
|
339
343
|
app = self._get_app(app_name)
|
|
340
|
-
|
|
344
|
+
snapshot = app.snapshot()
|
|
345
|
+
not_modified = self._not_modified(request, snapshot["revision"])
|
|
341
346
|
if not_modified is not None:
|
|
342
347
|
return not_modified
|
|
343
|
-
self._set_revision_headers(response,
|
|
348
|
+
self._set_revision_headers(response, snapshot["revision"])
|
|
344
349
|
# Resolve against the snapshot directly: Nacho.get() deep-copies its
|
|
345
350
|
# result, so an identity-sentinel passed to it would never compare
|
|
346
351
|
# equal — get_nested_value preserves the sentinel by identity.
|
|
347
352
|
missing = object()
|
|
348
|
-
value = get_nested_value(
|
|
353
|
+
value = get_nested_value(snapshot["config"], path, missing)
|
|
349
354
|
if value is missing:
|
|
350
355
|
raise HTTPException(
|
|
351
356
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
@@ -487,14 +492,7 @@ class NachoOrchestrator:
|
|
|
487
492
|
|
|
488
493
|
await app.hub.connect(websocket)
|
|
489
494
|
try:
|
|
490
|
-
await websocket.send_json(
|
|
491
|
-
{
|
|
492
|
-
"type": "initial_config",
|
|
493
|
-
"app": app.name,
|
|
494
|
-
"revision": app.revision,
|
|
495
|
-
"data": app.config.get_all(),
|
|
496
|
-
}
|
|
497
|
-
)
|
|
495
|
+
await websocket.send_json(app.event_payload("initial_config"))
|
|
498
496
|
while True:
|
|
499
497
|
# receive() (not receive_text) so a binary frame is
|
|
500
498
|
# ignored instead of killing the connection.
|
|
@@ -557,6 +555,12 @@ class NachoOrchestrator:
|
|
|
557
555
|
def _allow_cors_credentials(self) -> bool:
|
|
558
556
|
return "*" not in self.cors_origins
|
|
559
557
|
|
|
558
|
+
def _body_too_large(self) -> JSONResponse:
|
|
559
|
+
return JSONResponse(
|
|
560
|
+
status_code=413,
|
|
561
|
+
content={"detail": f"Request body exceeds {_MAX_BODY_BYTES // (1024 * 1024)} MiB"},
|
|
562
|
+
)
|
|
563
|
+
|
|
560
564
|
def _get_app(self, name: str) -> ConfigApp:
|
|
561
565
|
app = self.manager.get(name)
|
|
562
566
|
if app is None:
|
|
@@ -579,12 +583,13 @@ class NachoOrchestrator:
|
|
|
579
583
|
},
|
|
580
584
|
)
|
|
581
585
|
|
|
582
|
-
def _set_revision_headers(self, response: Response,
|
|
583
|
-
revision = str(
|
|
584
|
-
response.headers["ETag"] = f'"{revision}"'
|
|
586
|
+
def _set_revision_headers(self, response: Response, revision_value: int) -> None:
|
|
587
|
+
revision = str(revision_value)
|
|
588
|
+
response.headers["ETag"] = f'"{self.manager.generation}:{revision}"'
|
|
585
589
|
response.headers["X-Nacho-Revision"] = revision
|
|
590
|
+
response.headers["X-Nacho-Generation"] = self.manager.generation
|
|
586
591
|
|
|
587
|
-
def _not_modified(self, request: Request,
|
|
592
|
+
def _not_modified(self, request: Request, revision: int) -> Optional[Response]:
|
|
588
593
|
"""304 response when If-None-Match already names the current revision.
|
|
589
594
|
|
|
590
595
|
Lets pollers re-check cheaply: the config body is only sent when the
|
|
@@ -595,10 +600,11 @@ class NachoOrchestrator:
|
|
|
595
600
|
return None
|
|
596
601
|
tags = {tag.strip() for tag in header.split(",")}
|
|
597
602
|
tags |= {tag[2:] for tag in tags if tag.startswith("W/")}
|
|
598
|
-
|
|
603
|
+
current = f'"{self.manager.generation}:{revision}"'
|
|
604
|
+
if "*" not in tags and current not in tags:
|
|
599
605
|
return None
|
|
600
606
|
response = Response(status_code=status.HTTP_304_NOT_MODIFIED)
|
|
601
|
-
self._set_revision_headers(response,
|
|
607
|
+
self._set_revision_headers(response, revision)
|
|
602
608
|
return response
|
|
603
609
|
|
|
604
610
|
def _check_writable(self) -> None:
|