nacho-python 0.0.1__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/config.py ADDED
@@ -0,0 +1,544 @@
1
+ """Nacho — schema-first dynamic configuration manager."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import logging
7
+ import threading
8
+ from pathlib import Path
9
+ from typing import Any, Callable, Dict, List, Optional, Union
10
+
11
+ from .env import EnvOverrideHandler
12
+ from .event import (
13
+ Change,
14
+ EventPipeline,
15
+ EventType,
16
+ Transaction,
17
+ detect_changes,
18
+ on_change,
19
+ on_event,
20
+ )
21
+ from .schema import SchemaValidator
22
+ from .storage.base import StorageBackend, StorageError
23
+ from .storage.file import FileStorageBackend
24
+ from .utils.path import deep_merge, delete_nested_value, get_nested_value, set_nested_value
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ _UNCHANGED = object()
29
+
30
+
31
+ class Nacho:
32
+ """Dynamic configuration manager with optional schema enforcement.
33
+
34
+ Construction shortcuts::
35
+
36
+ Nacho() # in-memory only
37
+ Nacho({"key": "value"}) # in-memory with initial data
38
+ Nacho("config.yaml") # file-backed
39
+ Nacho(storage=FileStorageBackend("config.yaml")) # explicit backend
40
+ Nacho(storage=RemoteStorageBackend("http://…")) # remote
41
+
42
+ Schema-first (raises ValidationError on invalid writes)::
43
+
44
+ Nacho("config.yaml", schema="schema.json")
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ storage: Optional[Union[StorageBackend, str, Path, Dict[str, Any]]] = None,
50
+ *,
51
+ schema: Optional[Union[str, Path, Dict[str, Any]]] = None,
52
+ env_prefix: Optional[str] = None,
53
+ env_delimiter: str = "_",
54
+ env_include: Optional[List[str]] = None,
55
+ env_exclude: Optional[List[str]] = None,
56
+ read_only: bool = False,
57
+ events: bool = False,
58
+ allow_empty_on_load_error: bool = False,
59
+ ) -> None:
60
+ self._lock = threading.RLock()
61
+ self._read_only = read_only
62
+ self._events_disabled = not events
63
+ self._allow_empty_on_load_error = allow_empty_on_load_error
64
+ self._pipeline = EventPipeline()
65
+
66
+ self._validator: Optional[SchemaValidator] = self._init_validator(schema)
67
+ self._env: Optional[EnvOverrideHandler] = self._init_env(
68
+ env_prefix, env_delimiter, env_include, env_exclude
69
+ )
70
+
71
+ # _stored_data is the persistable config. _data is the effective view
72
+ # after runtime overlays such as environment variables are applied.
73
+ self._stored_data: Dict[str, Any] = {}
74
+ self._data: Dict[str, Any] = {}
75
+ self._storage: Optional[StorageBackend] = self._init_storage(storage)
76
+
77
+ if self._storage is not None:
78
+ self._storage.on_remote_change = self._on_remote_push
79
+
80
+ self._load_initial()
81
+
82
+ # ------------------------------------------------------------------
83
+ # Construction helpers (private)
84
+ # ------------------------------------------------------------------
85
+
86
+ def _init_storage(
87
+ self, raw: Optional[Union[StorageBackend, str, Path, Dict[str, Any]]]
88
+ ) -> Optional[StorageBackend]:
89
+ if raw is None:
90
+ return None
91
+ if isinstance(raw, StorageBackend):
92
+ return raw
93
+ if isinstance(raw, (str, Path)):
94
+ return FileStorageBackend(raw)
95
+ if isinstance(raw, dict):
96
+ self._stored_data = copy.deepcopy(raw)
97
+ return None
98
+ raise TypeError(
99
+ f"storage must be a StorageBackend, file path, or dict — got {type(raw).__name__!r}"
100
+ )
101
+
102
+ def _init_validator(
103
+ self, schema: Optional[Union[str, Path, Dict[str, Any]]]
104
+ ) -> Optional[SchemaValidator]:
105
+ if schema is None:
106
+ return None
107
+ return SchemaValidator(schema)
108
+
109
+ def _init_env(
110
+ self,
111
+ prefix: Optional[str],
112
+ delimiter: str,
113
+ include: Optional[List[str]],
114
+ exclude: Optional[List[str]],
115
+ ) -> Optional[EnvOverrideHandler]:
116
+ if prefix is None:
117
+ return None
118
+ return EnvOverrideHandler(
119
+ prefix=prefix,
120
+ nested_delimiter=delimiter,
121
+ include_paths=include,
122
+ exclude_paths=exclude,
123
+ )
124
+
125
+ def _load_initial(self) -> None:
126
+ if self._storage is None:
127
+ # In-memory seed: still apply env overrides if configured.
128
+ self._data = self._effective_from_stored(self._stored_data)
129
+ self._validate(self._data)
130
+ return
131
+ try:
132
+ raw = self._storage.load()
133
+ except StorageError as exc:
134
+ if not self._allow_empty_on_load_error:
135
+ raise
136
+ logger.error("Failed to load initial config; starting empty: %s", exc)
137
+ raw = {}
138
+ if not isinstance(raw, dict):
139
+ raise StorageError(f"Storage backend returned {type(raw).__name__}, expected dict")
140
+ self._stored_data = copy.deepcopy(raw)
141
+ self._data = self._effective_from_stored(self._stored_data)
142
+ self._validate(self._data)
143
+
144
+ def _apply_env(self, raw: Dict[str, Any]) -> Dict[str, Any]:
145
+ if self._env is None:
146
+ return copy.deepcopy(raw)
147
+ return self._env.apply(raw)
148
+
149
+ def _effective_from_stored(self, stored: Dict[str, Any]) -> Dict[str, Any]:
150
+ return self._apply_env(stored)
151
+
152
+ # ------------------------------------------------------------------
153
+ # Remote push handler
154
+ # ------------------------------------------------------------------
155
+
156
+ def _on_remote_push(self, incoming: Dict[str, Any]) -> None:
157
+ """Called by the remote storage backend when the server pushes a change."""
158
+ self._force_replace(incoming)
159
+
160
+ # ------------------------------------------------------------------
161
+ # Context manager
162
+ # ------------------------------------------------------------------
163
+
164
+ def __enter__(self) -> "Nacho":
165
+ return self
166
+
167
+ def __exit__(self, *_: Any) -> None:
168
+ self.cleanup()
169
+
170
+ def cleanup(self) -> None:
171
+ if self._storage:
172
+ self._storage.cleanup()
173
+
174
+ # ------------------------------------------------------------------
175
+ # Read API
176
+ # ------------------------------------------------------------------
177
+
178
+ def get(self, key: Optional[str] = None, default: Any = None) -> Any:
179
+ """Return the value at dot-notation *key*, or *default* if absent."""
180
+ with self._lock:
181
+ if key is None:
182
+ return copy.deepcopy(self._data)
183
+ return copy.deepcopy(get_nested_value(self._data, key, default))
184
+
185
+ def get_all(self) -> Dict[str, Any]:
186
+ with self._lock:
187
+ return copy.deepcopy(self._data)
188
+
189
+ def get_int(self, key: str, default: Optional[int] = None) -> Optional[int]:
190
+ value = self.get(key, default)
191
+ if value is None:
192
+ return default
193
+ try:
194
+ return int(value)
195
+ except (ValueError, TypeError):
196
+ logger.warning("Cannot coerce %r to int for key %r", value, key)
197
+ return default
198
+
199
+ def get_float(self, key: str, default: Optional[float] = None) -> Optional[float]:
200
+ value = self.get(key, default)
201
+ if value is None:
202
+ return default
203
+ try:
204
+ return float(value)
205
+ except (ValueError, TypeError):
206
+ logger.warning("Cannot coerce %r to float for key %r", value, key)
207
+ return default
208
+
209
+ def get_bool(self, key: str, default: Optional[bool] = None) -> Optional[bool]:
210
+ value = self.get(key, default)
211
+ if value is None:
212
+ return default
213
+ if isinstance(value, bool):
214
+ return value
215
+ if isinstance(value, str):
216
+ if value.lower() in ("true", "yes", "1", "on"):
217
+ return True
218
+ if value.lower() in ("false", "no", "0", "off"):
219
+ return False
220
+ try:
221
+ return bool(int(value))
222
+ except (ValueError, TypeError):
223
+ logger.warning("Cannot coerce %r to bool for key %r", value, key)
224
+ return default
225
+
226
+ def get_str(self, key: str, default: Optional[str] = None) -> Optional[str]:
227
+ value = self.get(key, default)
228
+ return str(value) if value is not None else default
229
+
230
+ def get_list(self, key: str, default: Optional[List] = None) -> Optional[List]:
231
+ value = self.get(key, default)
232
+ if value is None:
233
+ return default
234
+ if isinstance(value, list):
235
+ return value
236
+ logger.warning("Value for %r is not a list", key)
237
+ return default
238
+
239
+ def get_dict(self, key: str, default: Optional[Dict] = None) -> Optional[Dict]:
240
+ value = self.get(key, default)
241
+ if value is None:
242
+ return default
243
+ if isinstance(value, dict):
244
+ return value
245
+ logger.warning("Value for %r is not a dict", key)
246
+ return default
247
+
248
+ # ------------------------------------------------------------------
249
+ # Write API
250
+ # ------------------------------------------------------------------
251
+
252
+ def set(self, key: str, value: Any) -> bool:
253
+ """Set *key* to *value*.
254
+
255
+ Returns True when something actually changed.
256
+ Validates against schema before applying when a schema is configured.
257
+ Raises ValidationError if the resulting config would be invalid.
258
+ Raises PermissionError when the instance is read-only.
259
+ """
260
+ self._check_writable()
261
+ with self._lock:
262
+ candidate_stored = copy.deepcopy(self._stored_data)
263
+ if not set_nested_value(candidate_stored, key, value):
264
+ return False
265
+ candidate = self._effective_from_stored(candidate_stored)
266
+ self._validate(candidate)
267
+ old = copy.deepcopy(self._data)
268
+ self._stored_data = candidate_stored
269
+ self._data = candidate
270
+ self._emit(detect_changes(old, self._data))
271
+ return True
272
+
273
+ def delete(self, key: str) -> bool:
274
+ """Remove *key* from the config. Returns True if the key existed."""
275
+ self._check_writable()
276
+ with self._lock:
277
+ _MISSING = object()
278
+ if get_nested_value(self._stored_data, key, _MISSING) is _MISSING:
279
+ return False
280
+ old = copy.deepcopy(self._data)
281
+ candidate_stored = copy.deepcopy(self._stored_data)
282
+ delete_nested_value(candidate_stored, key)
283
+ candidate = self._effective_from_stored(candidate_stored)
284
+ self._validate(candidate)
285
+ self._stored_data = candidate_stored
286
+ self._data = candidate
287
+ self._emit(detect_changes(old, self._data))
288
+ return True
289
+
290
+ def update(self, data: Dict[str, Any]) -> bool:
291
+ """Deep-merge *data* into the current config.
292
+
293
+ Returns True when something actually changed.
294
+ """
295
+ self._check_writable()
296
+ if not data:
297
+ return False
298
+ with self._lock:
299
+ candidate_stored = deep_merge(data, self._stored_data)
300
+ candidate = self._effective_from_stored(candidate_stored)
301
+ if candidate_stored == self._stored_data and candidate == self._data:
302
+ return False
303
+ self._validate(candidate)
304
+ old = copy.deepcopy(self._data)
305
+ self._stored_data = candidate_stored
306
+ self._data = candidate
307
+ self._emit(detect_changes(old, self._data))
308
+ return True
309
+
310
+ def replace(
311
+ self,
312
+ data: Dict[str, Any],
313
+ *,
314
+ schema: object = _UNCHANGED,
315
+ ) -> bool:
316
+ """Replace the entire config with *data*.
317
+
318
+ Returns True when something actually changed.
319
+ Raises PermissionError for read-only instances.
320
+ """
321
+ self._check_writable()
322
+ return self._force_replace(data, schema=schema)
323
+
324
+ def _force_replace(self, data: Dict[str, Any], *, schema: object = _UNCHANGED) -> bool:
325
+ """Replace without the read-only check (used by remote push)."""
326
+ if not isinstance(data, dict):
327
+ raise TypeError(f"replace() expects a dict, got {type(data).__name__!r}")
328
+ if schema is _UNCHANGED:
329
+ validator = self._validator
330
+ else:
331
+ validator = self._init_validator(schema) # type: ignore[arg-type]
332
+
333
+ with self._lock:
334
+ candidate_stored = copy.deepcopy(data)
335
+ candidate = self._effective_from_stored(candidate_stored)
336
+ self._validate_with(candidate, validator)
337
+ schema_changed = schema is not _UNCHANGED
338
+ if (
339
+ candidate_stored == self._stored_data
340
+ and candidate == self._data
341
+ and not schema_changed
342
+ ):
343
+ return False
344
+ old = copy.deepcopy(self._data)
345
+ self._validator = validator
346
+ self._stored_data = candidate_stored
347
+ self._data = candidate
348
+ self._emit(detect_changes(old, self._data))
349
+ return True
350
+
351
+ # ------------------------------------------------------------------
352
+ # Persistence
353
+ # ------------------------------------------------------------------
354
+
355
+ def load(self) -> Dict[str, Any]:
356
+ """Reload from storage and apply env overrides. Emits RELOAD event."""
357
+ if self._storage is None:
358
+ with self._lock:
359
+ return copy.deepcopy(self._data)
360
+ try:
361
+ raw = self._storage.load()
362
+ except StorageError as exc:
363
+ if not self._allow_empty_on_load_error:
364
+ raise
365
+ logger.error("Reload failed; keeping current config: %s", exc)
366
+ with self._lock:
367
+ return copy.deepcopy(self._data)
368
+
369
+ with self._lock:
370
+ old = copy.deepcopy(self._data)
371
+ if not isinstance(raw, dict):
372
+ raise StorageError(f"Storage backend returned {type(raw).__name__}, expected dict")
373
+ candidate_stored = copy.deepcopy(raw)
374
+ candidate = self._effective_from_stored(candidate_stored)
375
+ self._validate(candidate)
376
+ self._stored_data = candidate_stored
377
+ self._data = candidate
378
+
379
+ changes = detect_changes(old, self._data)
380
+ if not self._events_disabled:
381
+ snapshot = copy.deepcopy(self._data)
382
+ reload_change = Change(EventType.RELOAD, None, old, snapshot)
383
+ self._pipeline.dispatch([reload_change], snapshot)
384
+ if changes:
385
+ self._pipeline.dispatch(changes, snapshot)
386
+ return copy.deepcopy(self._data)
387
+
388
+ reload = load # alias
389
+
390
+ def save(self) -> None:
391
+ """Persist current in-memory config to storage.
392
+
393
+ Raises PermissionError for read-only instances.
394
+ Raises StorageError on backend failure.
395
+ """
396
+ self._check_writable()
397
+ if self._storage is None:
398
+ return
399
+ with self._lock:
400
+ data = copy.deepcopy(self._stored_data)
401
+ self._storage.save(data)
402
+ logger.debug("Config saved via %s", self._storage)
403
+
404
+ # ------------------------------------------------------------------
405
+ # Schema
406
+ # ------------------------------------------------------------------
407
+
408
+ def validate(self) -> List[str]:
409
+ """Return a list of schema violation strings (empty = valid).
410
+
411
+ Does not raise — use this when you want to inspect errors without
412
+ catching an exception.
413
+ """
414
+ if self._validator is None:
415
+ return []
416
+ with self._lock:
417
+ data = copy.deepcopy(self._data)
418
+ return self._validator.check(data)
419
+
420
+ # ------------------------------------------------------------------
421
+ # Transactions
422
+ # ------------------------------------------------------------------
423
+
424
+ def transaction(self) -> "_TransactionContext":
425
+ """Return a context manager for atomic multi-key updates.
426
+
427
+ Example::
428
+ with config.transaction() as txn:
429
+ txn.set("db.host", "localhost")
430
+ txn.set("db.port", 5432)
431
+ config.save()
432
+ """
433
+ return _TransactionContext(self)
434
+
435
+ # ------------------------------------------------------------------
436
+ # Event decorators
437
+ # ------------------------------------------------------------------
438
+
439
+ def on_change(self, path_pattern: Optional[str] = None, priority: int = 100) -> Callable:
440
+ """Decorator: register a handler for CHANGE events matching *path_pattern*.
441
+
442
+ ``path_pattern=None`` (default) — fires for any CHANGE at any path.
443
+ ``path_pattern="@global"`` — fires exactly once per mutation (aggregate event).
444
+ ``path_pattern="*"`` — fires for every per-path CHANGE (not aggregate).
445
+ ``path_pattern="database.*"`` — fires for any key under ``database``.
446
+ """
447
+ return on_change(self._pipeline, path_pattern, priority)
448
+
449
+ def on_event(
450
+ self,
451
+ event_type: Union[EventType, List[EventType]],
452
+ path_pattern: Optional[str] = None,
453
+ priority: int = 100,
454
+ ) -> Callable:
455
+ """Decorator: register a handler for specific *event_type*(s)."""
456
+ return on_event(self._pipeline, event_type, path_pattern, priority)
457
+
458
+ # ------------------------------------------------------------------
459
+ # Schema helpers
460
+ # ------------------------------------------------------------------
461
+
462
+ def check(self, data: Dict[str, Any]) -> List[str]:
463
+ """Return schema violation strings for *data* without applying it."""
464
+ if self._validator is None:
465
+ return []
466
+ return self._validator.check(data)
467
+
468
+ # ------------------------------------------------------------------
469
+ # Backward-compat properties (used by server layer)
470
+ # ------------------------------------------------------------------
471
+
472
+ @property
473
+ def data(self) -> Dict[str, Any]:
474
+ """Return a defensive copy of the effective configuration.
475
+
476
+ ``data`` is kept as a read-only compatibility property. Mutating the
477
+ returned dict never changes the live configuration; use ``set()``,
478
+ ``update()``, ``replace()``, or ``delete()`` for writes.
479
+ """
480
+ return self.get_all()
481
+
482
+ @property
483
+ def event_pipeline(self) -> EventPipeline:
484
+ return self._pipeline
485
+
486
+ @property
487
+ def event_disabled(self) -> bool:
488
+ return self._events_disabled
489
+
490
+ # ------------------------------------------------------------------
491
+ # json helper
492
+ # ------------------------------------------------------------------
493
+
494
+ def json(self) -> str:
495
+ import json as _json
496
+
497
+ with self._lock:
498
+ return _json.dumps(self._data, indent=2, ensure_ascii=False)
499
+
500
+ # ------------------------------------------------------------------
501
+ # Internals
502
+ # ------------------------------------------------------------------
503
+
504
+ def _check_writable(self) -> None:
505
+ if self._read_only:
506
+ raise PermissionError("This Nacho instance is read-only.")
507
+
508
+ def _validate(self, data: Dict[str, Any]) -> None:
509
+ self._validate_with(data, self._validator)
510
+
511
+ def _validate_with(
512
+ self,
513
+ data: Dict[str, Any],
514
+ validator: Optional[SchemaValidator],
515
+ ) -> None:
516
+ if validator is not None:
517
+ validator.validate(data) # raises ValidationError
518
+
519
+ def _emit(self, changes: List[Change]) -> None:
520
+ if self._events_disabled or not changes:
521
+ return
522
+ with self._lock:
523
+ snapshot = copy.deepcopy(self._data)
524
+ self._pipeline.dispatch(changes, snapshot)
525
+
526
+
527
+ # ---------------------------------------------------------------------------
528
+ # Transaction context manager
529
+ # ---------------------------------------------------------------------------
530
+
531
+
532
+ class _TransactionContext:
533
+ def __init__(self, config: Nacho) -> None:
534
+ self._config = config
535
+
536
+ def __enter__(self) -> Transaction:
537
+ self._config._check_writable()
538
+ self._txn = Transaction(self._config)
539
+ return self._txn
540
+
541
+ def __exit__(self, exc_type: Any, *_: Any) -> bool:
542
+ if exc_type is None:
543
+ self._txn.commit()
544
+ return False # never suppress exceptions
nacho/env.py ADDED
@@ -0,0 +1,117 @@
1
+ """Environment variable override support.
2
+
3
+ Maps NACHO_DATABASE_HOST → database.host (or a user-configured prefix/delimiter).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ import json
10
+ import logging
11
+ import os
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from .utils.path import get_nested_value, set_nested_value
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # System variables to skip when operating prefix-free.
19
+ _SYSTEM_VARS = frozenset({"_", "PATH", "HOME", "USER", "SHELL", "TERM", "LANG", "PWD"})
20
+
21
+
22
+ def _parse_value(raw: str) -> Any:
23
+ """Best-effort parse of an env var string to a Python type."""
24
+ if not raw:
25
+ return ""
26
+ low = raw.lower()
27
+ if low in ("true", "yes", "1", "on"):
28
+ return True
29
+ if low in ("false", "no", "0", "off"):
30
+ return False
31
+ if low in ("null", "none", "~"):
32
+ return None
33
+ try:
34
+ return ast.literal_eval(raw)
35
+ except (ValueError, SyntaxError):
36
+ pass
37
+ if raw.startswith(("{", "[")):
38
+ try:
39
+ return json.loads(raw)
40
+ except json.JSONDecodeError:
41
+ pass
42
+ return raw
43
+
44
+
45
+ class EnvOverrideHandler:
46
+ """Applies matching environment variables on top of a config dict."""
47
+
48
+ def __init__(
49
+ self,
50
+ prefix: str = "NACHO",
51
+ nested_delimiter: str = "_",
52
+ include_paths: Optional[List[str]] = None,
53
+ exclude_paths: Optional[List[str]] = None,
54
+ create_missing: bool = True,
55
+ ) -> None:
56
+ self.prefix = prefix.rstrip("_") if prefix else ""
57
+ self.delimiter = nested_delimiter
58
+ self.include = list(include_paths or [])
59
+ self.exclude = list(exclude_paths or [])
60
+ self.create_missing = create_missing
61
+ self._prefix_with_sep = f"{self.prefix}{self.delimiter}" if self.prefix else ""
62
+
63
+ if not self.prefix:
64
+ logger.warning(
65
+ "EnvOverrideHandler has no prefix — collisions with system variables are possible."
66
+ )
67
+
68
+ def apply(self, data: Dict[str, Any]) -> Dict[str, Any]:
69
+ """Return *data* with matching env vars overlaid (non-destructive copy)."""
70
+ import copy
71
+
72
+ result = copy.deepcopy(data)
73
+ applied = 0
74
+ for name, raw in os.environ.items():
75
+ key = self._to_key(name)
76
+ if key is None:
77
+ continue
78
+ if not self._allowed(key):
79
+ continue
80
+ _MISSING = object()
81
+ if not self.create_missing and get_nested_value(result, key, _MISSING) is _MISSING:
82
+ continue
83
+ if set_nested_value(result, key, _parse_value(raw)):
84
+ logger.debug("Env override: %s → %s = %r", name, key, raw)
85
+ applied += 1
86
+ if applied:
87
+ logger.debug("Applied %d env override(s)", applied)
88
+ return result
89
+
90
+ # ------------------------------------------------------------------
91
+ # Internals
92
+ # ------------------------------------------------------------------
93
+
94
+ def _to_key(self, name: str) -> Optional[str]:
95
+ """Convert an env var name to a dot-notation config key, or None to skip."""
96
+ if self.prefix:
97
+ if not name.startswith(self._prefix_with_sep):
98
+ return None
99
+ tail = name[len(self._prefix_with_sep) :]
100
+ else:
101
+ if name in _SYSTEM_VARS or name.upper().startswith(("UV_", "PYTEST_", "PYTHON")):
102
+ return None
103
+ tail = name
104
+
105
+ if not tail or tail.startswith(self.delimiter) or tail.endswith(self.delimiter):
106
+ return None
107
+ if self.delimiter * 2 in tail:
108
+ return None
109
+
110
+ return tail.replace(self.delimiter, ".").lower()
111
+
112
+ def _allowed(self, key: str) -> bool:
113
+ if any(key == p or key.startswith(f"{p}.") for p in self.exclude):
114
+ return False
115
+ if self.include:
116
+ return any(key == p or key.startswith(f"{p}.") for p in self.include)
117
+ return True