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/event.py ADDED
@@ -0,0 +1,409 @@
1
+ """Event system for Nacho.
2
+
3
+ Single file replacing six tightly-coupled modules. The design follows three rules:
4
+ 1. Detect changes as a pure function (no side effects).
5
+ 2. Dispatch events through a simple priority queue of handlers.
6
+ 3. Async handlers are supported: they are scheduled on the running loop when
7
+ called from an async context, or run on a shared background loop otherwise.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import copy
14
+ import inspect
15
+ import logging
16
+ import threading
17
+ from dataclasses import dataclass
18
+ from enum import Enum
19
+ from typing import Any, Callable, Dict, List, Optional, Set, Union
20
+
21
+ from .utils.path import (
22
+ deep_merge,
23
+ delete_nested_value,
24
+ get_nested_value,
25
+ parse_path,
26
+ set_nested_value,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _log_task_result(task: asyncio.Task) -> None:
33
+ try:
34
+ task.result()
35
+ except asyncio.CancelledError:
36
+ pass
37
+ except Exception as exc:
38
+ logger.error("Async event handler raised: %s", exc)
39
+
40
+
41
+ class _AsyncEventRunner:
42
+ """Runs async handlers for synchronous callers on one background loop."""
43
+
44
+ def __init__(self) -> None:
45
+ self._lock = threading.Lock()
46
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
47
+ self._thread: Optional[threading.Thread] = None
48
+ self._ready: Optional[threading.Event] = None
49
+
50
+ def run(self, coro: Any) -> None:
51
+ loop = self._ensure_loop()
52
+ future = asyncio.run_coroutine_threadsafe(coro, loop)
53
+ future.result()
54
+
55
+ def _ensure_loop(self) -> asyncio.AbstractEventLoop:
56
+ with self._lock:
57
+ if self._loop is not None and self._loop.is_running():
58
+ return self._loop
59
+
60
+ if self._ready is not None and self._thread is not None and self._thread.is_alive():
61
+ ready = self._ready
62
+ else:
63
+ ready = threading.Event()
64
+ self._ready = ready
65
+
66
+ def run_loop() -> None:
67
+ loop = asyncio.new_event_loop()
68
+ asyncio.set_event_loop(loop)
69
+ with self._lock:
70
+ self._loop = loop
71
+ ready.set()
72
+ loop.run_forever()
73
+
74
+ self._thread = threading.Thread(
75
+ target=run_loop,
76
+ name="nacho-events",
77
+ daemon=True,
78
+ )
79
+ self._thread.start()
80
+
81
+ ready.wait()
82
+ with self._lock:
83
+ return self._loop # type: ignore[return-value]
84
+
85
+
86
+ _async_runner = _AsyncEventRunner()
87
+
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # Event types
91
+ # ---------------------------------------------------------------------------
92
+
93
+
94
+ class EventType(Enum):
95
+ CHANGE = "change" # always emitted alongside CREATE / UPDATE / DELETE
96
+ CREATE = "create"
97
+ UPDATE = "update"
98
+ DELETE = "delete"
99
+ RELOAD = "reload" # full config reload from storage
100
+
101
+
102
+ # ---------------------------------------------------------------------------
103
+ # Change detection
104
+ # ---------------------------------------------------------------------------
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class Change:
109
+ type: EventType
110
+ path: Optional[str] # None → global (aggregate) event
111
+ old_value: Any
112
+ new_value: Any
113
+
114
+
115
+ def detect_changes(old: Dict[str, Any], new: Dict[str, Any]) -> List[Change]:
116
+ """Return a flat list of Changes between two config snapshots.
117
+
118
+ Always starts with one aggregate CHANGE (path=None) so that listeners
119
+ can react to *any* mutation without enumerating every leaf.
120
+ """
121
+ if old == new:
122
+ return []
123
+
124
+ changes: List[Change] = [Change(EventType.CHANGE, None, old, new)]
125
+ _walk(old, new, "", changes)
126
+ return changes
127
+
128
+
129
+ def _walk(
130
+ old: Any,
131
+ new: Any,
132
+ prefix: str,
133
+ out: List[Change],
134
+ ) -> None:
135
+ old_keys: Set[str] = set(old) if isinstance(old, dict) else set()
136
+ new_keys: Set[str] = set(new) if isinstance(new, dict) else set()
137
+
138
+ for key in old_keys - new_keys:
139
+ path = f"{prefix}.{key}" if prefix else key
140
+ out.append(Change(EventType.DELETE, path, old[key], None))
141
+ out.append(Change(EventType.CHANGE, path, old[key], None))
142
+
143
+ for key in new_keys - old_keys:
144
+ path = f"{prefix}.{key}" if prefix else key
145
+ out.append(Change(EventType.CREATE, path, None, new[key]))
146
+ out.append(Change(EventType.CHANGE, path, None, new[key]))
147
+
148
+ for key in old_keys & new_keys:
149
+ path = f"{prefix}.{key}" if prefix else key
150
+ ov, nv = old[key], new[key]
151
+ if ov == nv:
152
+ continue
153
+ if isinstance(ov, dict) and isinstance(nv, dict):
154
+ _walk(ov, nv, path, out)
155
+ else:
156
+ out.append(Change(EventType.UPDATE, path, ov, nv))
157
+ out.append(Change(EventType.CHANGE, path, ov, nv))
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Path matching
162
+ # ---------------------------------------------------------------------------
163
+
164
+
165
+ def _match_path(pattern: Optional[str], path: Optional[str]) -> bool:
166
+ """Return True when *path* matches *pattern*.
167
+
168
+ Patterns:
169
+ None → match any event regardless of path (no filter)
170
+ "@global" → match only the aggregate event (path=None), fires once per operation
171
+ "*" → match every per-path event (not the aggregate)
172
+ "database.*" → match any path whose first segment is "database"
173
+ "database.host" → exact match only
174
+ """
175
+ if pattern is None:
176
+ return True # no filter — match everything
177
+ if pattern == "@global":
178
+ return path is None
179
+ if path is None:
180
+ return False # path-specific patterns never match aggregate events
181
+ if pattern == "*":
182
+ return True
183
+ if pattern == path:
184
+ return True
185
+
186
+ p_segs = parse_path(pattern)
187
+ r_segs = parse_path(path)
188
+
189
+ if pattern.endswith(".*"):
190
+ prefix = p_segs[:-1]
191
+ # Must have MORE segments than the prefix — "db.*" matches "db.host" not "db"
192
+ return len(r_segs) > len(prefix) and _segs_match(prefix, r_segs[: len(prefix)])
193
+
194
+ if len(p_segs) != len(r_segs):
195
+ return False
196
+ return _segs_match(p_segs, r_segs)
197
+
198
+
199
+ def _segs_match(pattern_segs: List[str], path_segs: List[str]) -> bool:
200
+ return all(ps == "*" or ps == rs for ps, rs in zip(pattern_segs, path_segs))
201
+
202
+
203
+ # ---------------------------------------------------------------------------
204
+ # Handler
205
+ # ---------------------------------------------------------------------------
206
+
207
+
208
+ class EventHandler:
209
+ """Wraps a user callback with its matching criteria."""
210
+
211
+ def __init__(
212
+ self,
213
+ callback: Callable,
214
+ event_types: Set[EventType],
215
+ path_pattern: Optional[str],
216
+ priority: int,
217
+ ) -> None:
218
+ if not callable(callback):
219
+ raise TypeError(f"callback must be callable, got {type(callback).__name__!r}")
220
+ self.callback = callback
221
+ self.event_types = event_types
222
+ self.path_pattern = path_pattern
223
+ self.priority = priority
224
+ self.is_async = inspect.iscoroutinefunction(callback) or (
225
+ hasattr(callback, "__call__") and inspect.iscoroutinefunction(callback.__call__)
226
+ )
227
+
228
+ def matches(self, change: Change) -> bool:
229
+ if change.type not in self.event_types:
230
+ return False
231
+ return _match_path(self.path_pattern, change.path)
232
+
233
+ def invoke(self, change: Change, config_data: Dict[str, Any]) -> None:
234
+ kwargs = {
235
+ "event_type": change.type,
236
+ "path": change.path,
237
+ "old_value": copy.deepcopy(change.old_value),
238
+ "new_value": copy.deepcopy(change.new_value),
239
+ "config_data": copy.deepcopy(config_data),
240
+ }
241
+ try:
242
+ if self.is_async:
243
+ coro = self.callback(**kwargs)
244
+ try:
245
+ loop = asyncio.get_running_loop()
246
+ task = loop.create_task(coro)
247
+ task.add_done_callback(_log_task_result)
248
+ except RuntimeError:
249
+ _async_runner.run(coro)
250
+ else:
251
+ self.callback(**kwargs)
252
+ except Exception as exc:
253
+ logger.error("Handler %r raised: %s", self.callback.__name__, exc)
254
+
255
+
256
+ # ---------------------------------------------------------------------------
257
+ # Pipeline
258
+ # ---------------------------------------------------------------------------
259
+
260
+
261
+ class EventPipeline:
262
+ """Ordered collection of EventHandlers with priority-based dispatch."""
263
+
264
+ def __init__(self) -> None:
265
+ self._handlers: List[EventHandler] = []
266
+ self._lock = threading.RLock()
267
+
268
+ def register(
269
+ self,
270
+ callback: Callable,
271
+ event_types: Union[EventType, List[EventType]],
272
+ path_pattern: Optional[str] = None,
273
+ priority: int = 100,
274
+ ) -> EventHandler:
275
+ if isinstance(event_types, EventType):
276
+ event_types = {event_types}
277
+ else:
278
+ event_types = set(event_types)
279
+
280
+ handler = EventHandler(callback, event_types, path_pattern, priority)
281
+ with self._lock:
282
+ self._handlers.append(handler)
283
+ self._handlers.sort(key=lambda h: h.priority)
284
+ logger.debug(
285
+ "Registered handler %r for %s%s",
286
+ callback.__name__,
287
+ [e.value for e in event_types],
288
+ f" on {path_pattern!r}" if path_pattern is not None else "",
289
+ )
290
+ return handler
291
+
292
+ # Kept for backward compat with server code that calls register_handler
293
+ def register_handler(
294
+ self,
295
+ callback: Callable,
296
+ event_types: Union[EventType, List[EventType]],
297
+ path_pattern: Optional[str] = None,
298
+ priority: int = 100,
299
+ ) -> EventHandler:
300
+ return self.register(callback, event_types, path_pattern, priority)
301
+
302
+ def unregister(self, handler: EventHandler) -> bool:
303
+ with self._lock:
304
+ try:
305
+ self._handlers.remove(handler)
306
+ return True
307
+ except ValueError:
308
+ return False
309
+
310
+ def dispatch(self, changes: List[Change], config_data: Dict[str, Any]) -> None:
311
+ """Invoke matching handlers for each change in *changes*."""
312
+ with self._lock:
313
+ handlers = list(self._handlers)
314
+ for change in changes:
315
+ for handler in handlers:
316
+ if handler.matches(change):
317
+ handler.invoke(change, config_data)
318
+
319
+ # Kept for backward compat with server code that calls pipeline.emit()
320
+ def emit(
321
+ self,
322
+ event_type: EventType,
323
+ path: Optional[str] = None,
324
+ old_value: Any = None,
325
+ new_value: Any = None,
326
+ config_data: Optional[Dict[str, Any]] = None,
327
+ ignore: bool = False,
328
+ ) -> int:
329
+ if ignore:
330
+ return 0
331
+ change = Change(event_type, path, old_value, new_value)
332
+ count = 0
333
+ with self._lock:
334
+ handlers = list(self._handlers)
335
+ for handler in handlers:
336
+ if handler.matches(change):
337
+ handler.invoke(change, config_data or {})
338
+ count += 1
339
+ return count
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Decorator helpers
344
+ # ---------------------------------------------------------------------------
345
+
346
+
347
+ def on_event(
348
+ pipeline: EventPipeline,
349
+ event_type: Union[EventType, List[EventType]],
350
+ path_pattern: Optional[str] = None,
351
+ priority: int = 100,
352
+ ) -> Callable:
353
+ def decorator(func: Callable) -> Callable:
354
+ pipeline.register(func, event_type, path_pattern, priority)
355
+ return func
356
+
357
+ return decorator
358
+
359
+
360
+ def on_change(
361
+ pipeline: EventPipeline,
362
+ path_pattern: Optional[str] = None,
363
+ priority: int = 100,
364
+ ) -> Callable:
365
+ return on_event(pipeline, EventType.CHANGE, path_pattern, priority)
366
+
367
+
368
+ # ---------------------------------------------------------------------------
369
+ # Transaction
370
+ # ---------------------------------------------------------------------------
371
+
372
+
373
+ class Transaction:
374
+ """Accumulates mutations in a scratch copy; commits atomically."""
375
+
376
+ def __init__(self, config: "Any") -> None:
377
+ self._config = config
378
+ self._data: Dict[str, Any] = copy.deepcopy(config._stored_data)
379
+
380
+ def get(self, key: Optional[str] = None, default: Any = None) -> Any:
381
+ if key is None:
382
+ return self._data
383
+ return get_nested_value(self._data, key, default)
384
+
385
+ def set(self, key: str, value: Any) -> None:
386
+ set_nested_value(self._data, key, value)
387
+
388
+ def delete(self, key: str) -> bool:
389
+ ok, _ = delete_nested_value(self._data, key)
390
+ return ok
391
+
392
+ def update(self, data: Dict[str, Any]) -> None:
393
+ self._data = deep_merge(data, self._data)
394
+
395
+ def replace(self, data: Dict[str, Any]) -> None:
396
+ self._data = copy.deepcopy(data)
397
+
398
+ def commit(self) -> List[Change]:
399
+ with self._config._lock:
400
+ old = copy.deepcopy(self._config._data)
401
+ candidate_stored = copy.deepcopy(self._data)
402
+ candidate = self._config._effective_from_stored(candidate_stored)
403
+ self._config._validate(candidate)
404
+ changes = detect_changes(old, candidate)
405
+ self._config._stored_data = candidate_stored
406
+ self._config._data = candidate
407
+ if not self._config._events_disabled and changes:
408
+ self._config._pipeline.dispatch(changes, copy.deepcopy(self._config._data))
409
+ return changes
nacho/schema.py ADDED
@@ -0,0 +1,121 @@
1
+ """Schema validation for Nacho.
2
+
3
+ Optional dependency: install with `pip install nacho[schema]`.
4
+ SchemaValidator raises ValidationError on invalid data so the caller never
5
+ has to check a return value — invalid writes are refused immediately.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import logging
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Union
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ try:
18
+ import jsonschema
19
+ from jsonschema import validators as _jv
20
+
21
+ HAS_SCHEMA_DEPS = True
22
+ except ImportError:
23
+ HAS_SCHEMA_DEPS = False
24
+
25
+
26
+ class ValidationError(Exception):
27
+ """Raised when config data fails schema validation."""
28
+
29
+ def __init__(self, errors: List[str]) -> None:
30
+ self.errors = errors
31
+ super().__init__("\n".join(errors))
32
+
33
+
34
+ class SchemaValidator:
35
+ """Validates configuration dicts against a JSON Schema.
36
+
37
+ Raises ImportError at construction time when jsonschema is absent so
38
+ the error surfaces early, not on the first validate() call.
39
+ """
40
+
41
+ def __init__(self, schema: Union[Dict[str, Any], str, Path]) -> None:
42
+ if not HAS_SCHEMA_DEPS:
43
+ raise ImportError(
44
+ "Schema validation requires 'jsonschema'. "
45
+ "Install with: pip install nacho[schema]"
46
+ )
47
+ if isinstance(schema, (str, Path)):
48
+ self._schema = self._load(Path(schema))
49
+ elif isinstance(schema, dict):
50
+ self._schema = schema
51
+ else:
52
+ raise TypeError(f"schema must be a dict, str, or Path — got {type(schema).__name__!r}")
53
+
54
+ # Build validator once; reused on every validate() call.
55
+ validator_cls = _jv.validator_for(self._schema)
56
+ validator_cls.check_schema(self._schema)
57
+ self._validator = validator_cls(
58
+ self._schema,
59
+ format_checker=jsonschema.FormatChecker(),
60
+ )
61
+
62
+ # ------------------------------------------------------------------
63
+ # Public API
64
+ # ------------------------------------------------------------------
65
+
66
+ def validate(self, data: Dict[str, Any]) -> None:
67
+ """Validate *data* against the schema.
68
+
69
+ Raises ValidationError listing every violation found.
70
+ Does nothing when data is valid.
71
+ """
72
+ errors = self._collect_errors(data)
73
+ if errors:
74
+ raise ValidationError(errors)
75
+
76
+ def check(self, data: Dict[str, Any]) -> List[str]:
77
+ """Return a list of error strings (empty when data is valid).
78
+
79
+ Use this when you want errors without an exception.
80
+ """
81
+ return self._collect_errors(data)
82
+
83
+ # ------------------------------------------------------------------
84
+ # Internals
85
+ # ------------------------------------------------------------------
86
+
87
+ def _collect_errors(self, data: Dict[str, Any]) -> List[str]:
88
+ errors: List[str] = []
89
+ for error in self._validator.iter_errors(data):
90
+ path = ".".join(str(p) for p in error.path) or "root"
91
+ errors.append(f"{path}: {error.message}")
92
+ for sub in getattr(error, "context", []):
93
+ sub_path = ".".join(str(p) for p in sub.path) or "root"
94
+ errors.append(f" {sub_path}: {sub.message}")
95
+ return errors
96
+
97
+ @staticmethod
98
+ def _load(path: Path) -> Dict[str, Any]:
99
+ if not path.exists():
100
+ raise FileNotFoundError(f"Schema file not found: {path}")
101
+
102
+ suffix = path.suffix.lower()
103
+ if suffix == ".json":
104
+ return json.loads(path.read_text(encoding="utf-8"))
105
+
106
+ if suffix in (".yaml", ".yml"):
107
+ try:
108
+ import yaml
109
+
110
+ return yaml.safe_load(path.read_text(encoding="utf-8")) or {}
111
+ except ImportError:
112
+ raise ImportError("YAML schema files require 'pyyaml'.")
113
+
114
+ if suffix == ".toml":
115
+ try:
116
+ import tomllib # type: ignore
117
+ except ImportError:
118
+ import tomli as tomllib # type: ignore
119
+ return tomllib.loads(path.read_text(encoding="utf-8")) or {}
120
+
121
+ raise ValueError(f"Unsupported schema file format: {suffix!r}")
@@ -0,0 +1,35 @@
1
+ """REST API server module for Nacho configuration management.
2
+
3
+ This module provides the FastAPI application used by the Nacho server.
4
+ Install with: pip install nacho[server]
5
+ """
6
+
7
+ # Check for server dependencies
8
+ try:
9
+ import fastapi
10
+ import uvicorn
11
+
12
+ HAS_SERVER_DEPS = True
13
+ except ImportError:
14
+ HAS_SERVER_DEPS = False
15
+
16
+ # Only import if dependencies are available
17
+ if HAS_SERVER_DEPS:
18
+ from .app import NachoOrchestrator
19
+ else:
20
+ # Define a placeholder class that raises ImportError when instantiated
21
+ class NachoOrchestrator:
22
+ """Placeholder class for NachoOrchestrator.
23
+
24
+ This raises an informative error when server features are used without
25
+ server dependencies installed.
26
+ """
27
+
28
+ def __init__(self, *args, **kwargs):
29
+ raise ImportError(
30
+ "Web server features require additional dependencies. "
31
+ "Install them with: pip install nacho[server]"
32
+ )
33
+
34
+
35
+ __all__ = ["NachoOrchestrator", "HAS_SERVER_DEPS"]