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/server/models.py ADDED
@@ -0,0 +1,165 @@
1
+ """Request models for the Nacho HTTP API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, Optional, Union
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
9
+
10
+ SUPPORTED_FORMATS = {"json", "yaml", "toml"}
11
+ VALUE_TYPES = {"str", "int", "float", "bool", "list", "dict", "raw"}
12
+ APP_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]*$")
13
+
14
+
15
+ def validate_app_name(name: str) -> str:
16
+ if not APP_NAME_RE.match(name):
17
+ raise ValueError(
18
+ "Name must start with alphanumeric and contain only "
19
+ "alphanumeric, underscore, or hyphen characters"
20
+ )
21
+ return name
22
+
23
+
24
+ class ConfigRequest(BaseModel):
25
+ """Full configuration payload."""
26
+
27
+ data: Union[str, Dict[str, Any]] = Field(
28
+ ...,
29
+ description="Configuration data as an object, or as an encoded string",
30
+ )
31
+ format: str = Field(default="json", description="json, yaml, or toml")
32
+ revision: Optional[int] = Field(
33
+ default=None,
34
+ ge=1,
35
+ description="Expected app revision for optimistic concurrency",
36
+ )
37
+
38
+ @field_validator("format")
39
+ @classmethod
40
+ def validate_format(cls, value: str) -> str:
41
+ value = value.lower()
42
+ if value not in SUPPORTED_FORMATS:
43
+ raise ValueError(f"Format must be one of: {', '.join(sorted(SUPPORTED_FORMATS))}")
44
+ return value
45
+
46
+ model_config = ConfigDict(
47
+ json_schema_extra={
48
+ "examples": [
49
+ {"data": {"feature": True}},
50
+ {"data": '{"feature": true}', "format": "json"},
51
+ ]
52
+ }
53
+ )
54
+
55
+
56
+ class AppCreateRequest(ConfigRequest):
57
+ """Create or replace an app."""
58
+
59
+ name: str = Field(..., min_length=1, max_length=64)
60
+ description: Optional[str] = Field(default=None, max_length=256)
61
+ schema_: Optional[Union[str, Dict[str, Any]]] = Field(
62
+ default=None,
63
+ alias="schema",
64
+ description="Optional JSON Schema as an object, or as an encoded string",
65
+ )
66
+ schema_format: str = Field(default="json", description="json, yaml, or toml")
67
+ model_config = ConfigDict(populate_by_name=True)
68
+
69
+ @field_validator("name")
70
+ @classmethod
71
+ def validate_name(cls, value: str) -> str:
72
+ return validate_app_name(value)
73
+
74
+ @field_validator("schema_format")
75
+ @classmethod
76
+ def validate_schema_format(cls, value: str) -> str:
77
+ value = value.lower()
78
+ if value not in SUPPORTED_FORMATS:
79
+ allowed = ", ".join(sorted(SUPPORTED_FORMATS))
80
+ raise ValueError(f"Schema format must be one of: {allowed}")
81
+ return value
82
+
83
+
84
+ class ConvertRequest(BaseModel):
85
+ """Convert a config or schema payload between json, yaml, and toml."""
86
+
87
+ data: Union[str, Dict[str, Any]] = Field(
88
+ ...,
89
+ description="Payload as an object, or as an encoded string in the source format",
90
+ )
91
+ from_: str = Field(default="json", alias="from", description="Source format")
92
+ to: str = Field(default="json", description="Target format")
93
+ model_config = ConfigDict(populate_by_name=True)
94
+
95
+ @field_validator("from_", "to")
96
+ @classmethod
97
+ def validate_fmt(cls, value: str) -> str:
98
+ value = value.lower()
99
+ if value not in SUPPORTED_FORMATS:
100
+ raise ValueError(f"Format must be one of: {', '.join(sorted(SUPPORTED_FORMATS))}")
101
+ return value
102
+
103
+
104
+ class SchemaUpdateRequest(BaseModel):
105
+ """Replace (or clear) an app's JSON Schema after creation."""
106
+
107
+ schema_: Optional[Union[str, Dict[str, Any]]] = Field(
108
+ default=None,
109
+ alias="schema",
110
+ description="JSON Schema as an object or encoded string; null clears the schema",
111
+ )
112
+ schema_format: str = Field(default="json", description="json, yaml, or toml")
113
+ revision: Optional[int] = Field(
114
+ default=None,
115
+ ge=1,
116
+ description="Expected app revision for optimistic concurrency",
117
+ )
118
+ model_config = ConfigDict(populate_by_name=True)
119
+
120
+ @field_validator("schema_format")
121
+ @classmethod
122
+ def validate_schema_format(cls, value: str) -> str:
123
+ value = value.lower()
124
+ if value not in SUPPORTED_FORMATS:
125
+ raise ValueError(f"Schema format must be one of: {', '.join(sorted(SUPPORTED_FORMATS))}")
126
+ return value
127
+
128
+
129
+ class AppMetadataRequest(BaseModel):
130
+ """Rename an app or change its description."""
131
+
132
+ name: Optional[str] = Field(default=None, min_length=1, max_length=64)
133
+ description: Optional[str] = Field(default=None, max_length=256)
134
+ revision: Optional[int] = Field(
135
+ default=None,
136
+ ge=1,
137
+ description="Expected app revision for optimistic concurrency",
138
+ )
139
+
140
+ @field_validator("name")
141
+ @classmethod
142
+ def validate_name(cls, value: Optional[str]) -> Optional[str]:
143
+ if value is None:
144
+ return value
145
+ return validate_app_name(value)
146
+
147
+
148
+ class PathUpdateRequest(BaseModel):
149
+ """Set a single config path."""
150
+
151
+ value: Any
152
+ type: str = Field(default="raw", description="raw, str, int, float, bool, list, or dict")
153
+ revision: Optional[int] = Field(
154
+ default=None,
155
+ ge=1,
156
+ description="Expected app revision for optimistic concurrency",
157
+ )
158
+
159
+ @field_validator("type")
160
+ @classmethod
161
+ def validate_type(cls, value: str) -> str:
162
+ value = value.lower()
163
+ if value not in VALUE_TYPES:
164
+ raise ValueError(f"Type must be one of: {', '.join(sorted(VALUE_TYPES))}")
165
+ return value
@@ -0,0 +1,452 @@
1
+ """Runtime state for the Nacho API server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import copy
7
+ import logging
8
+ import threading
9
+ from dataclasses import dataclass, field
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any, Awaitable, Callable, Dict, Iterable, List, Optional
13
+
14
+ from fastapi import WebSocket
15
+
16
+ from nacho.config import Nacho
17
+ from nacho.utils.io import load_file, save_file
18
+
19
+ from .models import validate_app_name
20
+
21
+
22
+ def utc_now() -> str:
23
+ return datetime.now(timezone.utc).isoformat()
24
+
25
+
26
+ class RevisionConflictError(RuntimeError):
27
+ """Raised when a write targets an older app revision."""
28
+
29
+ def __init__(self, expected: int, actual: int) -> None:
30
+ self.expected = expected
31
+ self.actual = actual
32
+ super().__init__(f"Revision conflict: expected {expected}, current revision is {actual}")
33
+
34
+
35
+ class WebSocketHub:
36
+ """Tracks WebSocket subscribers for one app."""
37
+
38
+ def __init__(self, app_name: str, logger: logging.Logger) -> None:
39
+ self.app_name = app_name
40
+ self.logger = logger
41
+ self._connections: List[WebSocket] = []
42
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
43
+ self._lock = threading.RLock()
44
+
45
+ @property
46
+ def count(self) -> int:
47
+ with self._lock:
48
+ return len(self._connections)
49
+
50
+ async def connect(self, websocket: WebSocket) -> None:
51
+ await websocket.accept()
52
+ with self._lock:
53
+ self._loop = asyncio.get_running_loop()
54
+ self._connections.append(websocket)
55
+
56
+ def disconnect(self, websocket: WebSocket) -> None:
57
+ with self._lock:
58
+ if websocket in self._connections:
59
+ self._connections.remove(websocket)
60
+ if not self._connections:
61
+ self._loop = None
62
+
63
+ async def broadcast(self, message: Dict[str, Any]) -> None:
64
+ stale: List[WebSocket] = []
65
+ with self._lock:
66
+ connections = list(self._connections)
67
+
68
+ for websocket in connections:
69
+ try:
70
+ await websocket.send_json(message)
71
+ except Exception as exc:
72
+ self.logger.warning("WebSocket send failed for %s: %s", self.app_name, exc)
73
+ stale.append(websocket)
74
+ for websocket in stale:
75
+ self.disconnect(websocket)
76
+
77
+ def schedule(self, callback: Callable[[], Awaitable[None]]) -> None:
78
+ """Schedule async WebSocket work on the connection loop when clients exist."""
79
+ with self._lock:
80
+ loop = self._loop
81
+ has_connections = bool(self._connections)
82
+ if loop is None or not has_connections:
83
+ return
84
+ if loop.is_closed():
85
+ return
86
+ try:
87
+ asyncio.run_coroutine_threadsafe(callback(), loop)
88
+ except RuntimeError as exc:
89
+ self.logger.warning(
90
+ "WebSocket broadcast scheduling failed for %s: %s", self.app_name, exc
91
+ )
92
+
93
+ def close_all(self) -> None:
94
+ with self._lock:
95
+ loop = self._loop
96
+ connections = list(self._connections)
97
+ self._connections.clear()
98
+ self._loop = None
99
+
100
+ if loop is None or loop.is_closed():
101
+ return
102
+ for websocket in connections:
103
+ try:
104
+ asyncio.run_coroutine_threadsafe(websocket.close(), loop)
105
+ except RuntimeError:
106
+ pass
107
+
108
+
109
+ @dataclass
110
+ class ConfigApp:
111
+ """A managed app plus API metadata."""
112
+
113
+ name: str
114
+ config: Nacho
115
+ description: Optional[str] = None
116
+ schema: Optional[Dict[str, Any]] = None
117
+ logger: logging.Logger = field(default_factory=lambda: logging.getLogger(__name__))
118
+ revision: int = 1
119
+ created_at: str = field(default_factory=utc_now)
120
+ updated_at: str = field(default_factory=utc_now)
121
+
122
+ def __post_init__(self) -> None:
123
+ self.hub = WebSocketHub(self.name, self.logger)
124
+
125
+ def broadcast_update(self) -> None:
126
+ self.hub.schedule(self._broadcast_update)
127
+
128
+ async def _broadcast_update(self) -> None:
129
+ await self.hub.broadcast(
130
+ {
131
+ "type": "update",
132
+ "app": self.name,
133
+ "revision": self.revision,
134
+ "data": self.config.get_all(),
135
+ }
136
+ )
137
+
138
+ @property
139
+ def info(self) -> Dict[str, Any]:
140
+ return {
141
+ "name": self.name,
142
+ "description": self.description,
143
+ "revision": self.revision,
144
+ "created_at": self.created_at,
145
+ "updated_at": self.updated_at,
146
+ "config_count": len(self.config.get_all()),
147
+ "connections": self.hub.count,
148
+ "schema": self.schema is not None,
149
+ }
150
+
151
+ def touch(self) -> None:
152
+ self.revision += 1
153
+ self.updated_at = utc_now()
154
+
155
+ def snapshot(self) -> Dict[str, Any]:
156
+ return {
157
+ "name": self.name,
158
+ "description": self.description,
159
+ "revision": self.revision,
160
+ "created_at": self.created_at,
161
+ "updated_at": self.updated_at,
162
+ "schema": copy.deepcopy(self.schema),
163
+ "config": self.config.get_all(),
164
+ }
165
+
166
+ def cleanup(self) -> None:
167
+ self.config.cleanup()
168
+ self.hub.close_all()
169
+
170
+
171
+ class AppStore:
172
+ """Simple durable app store backed by one JSON file per app."""
173
+
174
+ def __init__(self, data_dir: Optional[Path]) -> None:
175
+ self.data_dir = Path(data_dir) if data_dir else None
176
+ if self.data_dir:
177
+ self.data_dir.mkdir(parents=True, exist_ok=True)
178
+
179
+ def _path(self, name: str) -> Path:
180
+ if self.data_dir is None:
181
+ raise RuntimeError("AppStore has no data directory")
182
+ validate_app_name(name)
183
+ return self.data_dir / f"{name}.json"
184
+
185
+ def load(self) -> Iterable[Dict[str, Any]]:
186
+ if self.data_dir is None:
187
+ return []
188
+ apps = []
189
+ for path in sorted(self.data_dir.glob("*.json")):
190
+ data = load_file(path)
191
+ if data:
192
+ apps.append(data)
193
+ return apps
194
+
195
+ def save(self, app: ConfigApp) -> None:
196
+ if self.data_dir is None:
197
+ return
198
+ save_file(self._path(app.name), app.snapshot())
199
+
200
+ def delete(self, name: str) -> None:
201
+ if self.data_dir is None:
202
+ return
203
+ self._path(name).unlink(missing_ok=True)
204
+
205
+
206
+ class AppManager:
207
+ """Owns managed apps and persistence."""
208
+
209
+ def __init__(
210
+ self,
211
+ *,
212
+ data_dir: Optional[Path] = None,
213
+ logger: Optional[logging.Logger] = None,
214
+ ) -> None:
215
+ self.logger = logger or logging.getLogger(__name__)
216
+ self.store = AppStore(data_dir)
217
+ self._apps: Dict[str, ConfigApp] = {}
218
+ self._lock = threading.RLock()
219
+
220
+ @property
221
+ def apps(self) -> Dict[str, ConfigApp]:
222
+ with self._lock:
223
+ return dict(self._apps)
224
+
225
+ def load_persisted(self) -> None:
226
+ for raw in self.store.load():
227
+ name = raw.get("name")
228
+ if not isinstance(name, str):
229
+ continue
230
+ config_data = raw.get("config") or {}
231
+ schema = raw.get("schema")
232
+ app = ConfigApp(
233
+ name=name,
234
+ config=Nacho(config_data, schema=schema, events=True),
235
+ description=raw.get("description"),
236
+ schema=schema,
237
+ logger=self.logger,
238
+ revision=int(raw.get("revision") or 1),
239
+ created_at=raw.get("created_at") or utc_now(),
240
+ updated_at=raw.get("updated_at") or utc_now(),
241
+ )
242
+ self._apps[name] = app
243
+
244
+ def create(
245
+ self,
246
+ name: str,
247
+ *,
248
+ config_data: Optional[Dict[str, Any]] = None,
249
+ config: Optional[Nacho] = None,
250
+ description: Optional[str] = None,
251
+ schema: Optional[Dict[str, Any]] = None,
252
+ replace: bool = False,
253
+ ) -> ConfigApp:
254
+ validate_app_name(name)
255
+ with self._lock:
256
+ if name in self._apps and not replace:
257
+ raise ValueError(f"App {name!r} already exists")
258
+ if name in self._apps:
259
+ self._apps[name].cleanup()
260
+
261
+ app_config = config or Nacho(config_data or {}, schema=schema, events=True)
262
+ app = ConfigApp(
263
+ name=name,
264
+ config=app_config,
265
+ description=description,
266
+ schema=schema,
267
+ logger=self.logger,
268
+ )
269
+ self._apps[name] = app
270
+ self.store.save(app)
271
+ return app
272
+
273
+ def replace(
274
+ self,
275
+ current_name: str,
276
+ *,
277
+ new_name: str,
278
+ config_data: Dict[str, Any],
279
+ description: Optional[str] = None,
280
+ schema: Optional[Dict[str, Any]] = None,
281
+ expected_revision: Optional[int] = None,
282
+ ) -> ConfigApp:
283
+ validate_app_name(new_name)
284
+ with self._lock:
285
+ current = self._require_app(current_name)
286
+ self._check_revision(current, expected_revision)
287
+ if new_name != current_name and new_name in self._apps:
288
+ raise ValueError(f"App {new_name!r} already exists")
289
+
290
+ target_schema = schema if schema is not None else current.schema
291
+ config_changed = current.config.replace(config_data, schema=target_schema)
292
+ metadata_changed = (
293
+ new_name != current_name
294
+ or description != current.description
295
+ or target_schema != current.schema
296
+ )
297
+
298
+ if new_name != current_name:
299
+ del self._apps[current_name]
300
+ current.name = new_name
301
+ current.hub.app_name = new_name
302
+ self._apps[new_name] = current
303
+
304
+ current.description = description
305
+ current.schema = copy.deepcopy(target_schema)
306
+ if config_changed or metadata_changed:
307
+ current.touch()
308
+ self.store.save(current)
309
+ if new_name != current_name:
310
+ self.store.delete(current_name)
311
+ return current
312
+
313
+ def get(self, name: str) -> Optional[ConfigApp]:
314
+ with self._lock:
315
+ return self._apps.get(name)
316
+
317
+ def list_info(self) -> Dict[str, Dict[str, Any]]:
318
+ with self._lock:
319
+ return {name: app.info for name, app in self._apps.items()}
320
+
321
+ def rename(
322
+ self,
323
+ current_name: str,
324
+ *,
325
+ new_name: Optional[str] = None,
326
+ description: Optional[str] = None,
327
+ expected_revision: Optional[int] = None,
328
+ ) -> ConfigApp:
329
+ with self._lock:
330
+ app = self._apps.get(current_name)
331
+ if app is None:
332
+ raise KeyError(current_name)
333
+ self._check_revision(app, expected_revision)
334
+ if description is not None:
335
+ app.description = description
336
+
337
+ if new_name and new_name != current_name:
338
+ validate_app_name(new_name)
339
+ if new_name in self._apps:
340
+ raise ValueError(f"App {new_name!r} already exists")
341
+ del self._apps[current_name]
342
+ self.store.delete(current_name)
343
+ app.name = new_name
344
+ app.hub.app_name = new_name
345
+ self._apps[new_name] = app
346
+
347
+ app.touch()
348
+ self.store.save(app)
349
+ return app
350
+
351
+ def persist(self, app: ConfigApp, *, changed: bool = True, notify: bool = False) -> None:
352
+ should_notify = False
353
+ with self._lock:
354
+ if changed:
355
+ app.config.save()
356
+ app.touch()
357
+ should_notify = notify
358
+ self.store.save(app)
359
+ if should_notify:
360
+ app.broadcast_update()
361
+
362
+ def replace_config(
363
+ self,
364
+ name: str,
365
+ data: Dict[str, Any],
366
+ *,
367
+ expected_revision: Optional[int] = None,
368
+ ) -> ConfigApp:
369
+ with self._lock:
370
+ app = self._require_app(name)
371
+ self._check_revision(app, expected_revision)
372
+ changed = app.config.replace(data)
373
+ self.persist(app, changed=changed, notify=True)
374
+ return app
375
+
376
+ def update_schema(
377
+ self,
378
+ name: str,
379
+ schema: Optional[Dict[str, Any]],
380
+ *,
381
+ expected_revision: Optional[int] = None,
382
+ ) -> ConfigApp:
383
+ """Replace an app's schema; *schema* of ``None`` clears it.
384
+
385
+ Re-validates the current configuration against the new schema —
386
+ ``replace()`` raises ValidationError if the config would become invalid.
387
+ """
388
+ with self._lock:
389
+ app = self._require_app(name)
390
+ self._check_revision(app, expected_revision)
391
+ app.config.replace(app.config.get_all(), schema=schema)
392
+ app.schema = copy.deepcopy(schema)
393
+ self.persist(app, changed=True, notify=True)
394
+ return app
395
+
396
+ def set_config_path(
397
+ self,
398
+ name: str,
399
+ path: str,
400
+ value: Any,
401
+ *,
402
+ expected_revision: Optional[int] = None,
403
+ ) -> bool:
404
+ with self._lock:
405
+ app = self._require_app(name)
406
+ self._check_revision(app, expected_revision)
407
+ changed = app.config.set(path, value)
408
+ self.persist(app, changed=changed, notify=True)
409
+ return changed
410
+
411
+ def delete_config_path(
412
+ self,
413
+ name: str,
414
+ path: str,
415
+ *,
416
+ expected_revision: Optional[int] = None,
417
+ ) -> bool:
418
+ with self._lock:
419
+ app = self._require_app(name)
420
+ self._check_revision(app, expected_revision)
421
+ deleted = app.config.delete(path)
422
+ if deleted:
423
+ self.persist(app, changed=True, notify=True)
424
+ return deleted
425
+
426
+ def delete(self, name: str) -> bool:
427
+ with self._lock:
428
+ app = self._apps.pop(name, None)
429
+ if app is None:
430
+ return False
431
+ app.cleanup()
432
+ self.store.delete(name)
433
+ return True
434
+
435
+ def cleanup(self) -> None:
436
+ with self._lock:
437
+ apps = list(self._apps.values())
438
+ self._apps.clear()
439
+ for app in apps:
440
+ app.cleanup()
441
+
442
+ def _require_app(self, name: str) -> ConfigApp:
443
+ app = self._apps.get(name)
444
+ if app is None:
445
+ raise KeyError(name)
446
+ return app
447
+
448
+ def _check_revision(self, app: ConfigApp, expected_revision: Optional[int]) -> None:
449
+ if expected_revision is None:
450
+ return
451
+ if expected_revision != app.revision:
452
+ raise RevisionConflictError(expected_revision, app.revision)