vgraph 0.1.0__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.
vgraph/server/state.py ADDED
@@ -0,0 +1,96 @@
1
+ """In-memory run history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib
7
+ import importlib.util
8
+ import sys
9
+ from collections import defaultdict, deque
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from uuid import UUID
15
+
16
+ from vgraph.engine import Execution, RunStatus
17
+ from vgraph.registry import ImportIssue, discover, is_user_code
18
+
19
+
20
+ @dataclass
21
+ class RunRecord:
22
+ run_id: UUID
23
+ graph: str
24
+ status: RunStatus
25
+ started_at: datetime
26
+ executions: dict[str, list[Execution]]
27
+ stop: asyncio.Event
28
+
29
+
30
+ class RunHistory:
31
+ def __init__(self, max_per_graph: int = 20):
32
+ self._max = max_per_graph
33
+ self._by_graph: dict[str, deque[RunRecord]] = defaultdict(deque)
34
+ self._by_id: dict[UUID, RunRecord] = {}
35
+
36
+ def add(self, graph: str, run: RunRecord) -> None:
37
+ runs = self._by_graph[graph]
38
+ runs.append(run)
39
+ self._by_id[run.run_id] = run
40
+ while len(runs) > self._max:
41
+ del self._by_id[runs.popleft().run_id]
42
+
43
+ def list(self, graph: str) -> list[RunRecord]:
44
+ return list(reversed(self._by_graph.get(graph, ())))
45
+
46
+ def get(self, run_id: UUID) -> RunRecord | None:
47
+ return self._by_id.get(run_id)
48
+
49
+
50
+ class AppState:
51
+ """Everything the HTTP app shares: registry, run history, subscribers and running tasks."""
52
+
53
+ def __init__(self, target: str | Path, graphs_dir: Path):
54
+ self.target = target
55
+ self.graphs_dir = graphs_dir
56
+ self.history = RunHistory()
57
+ self.subscribers: set[asyncio.Queue[dict[str, Any]]] = set()
58
+ self.running: dict[asyncio.Task[Any], asyncio.Event] = {} # task -> its stop event
59
+ self.registry = discover(target)
60
+ self.registry_errors: list[ImportIssue] = self.registry.issues
61
+
62
+ def publish(self, message: dict[str, Any]) -> None:
63
+ for q in self.subscribers:
64
+ q.put_nowait(message)
65
+
66
+ def _target_modules(self) -> set[str]:
67
+ path = Path(self.target)
68
+ if path.is_dir(): # every module living under the directory, helpers included
69
+ root = path.resolve()
70
+ return {
71
+ m
72
+ for m, mod in sys.modules.items()
73
+ if (f := getattr(mod, "__file__", None))
74
+ and (p := Path(f).resolve()).is_relative_to(root)
75
+ and is_user_code(p.relative_to(root))
76
+ }
77
+ mods = {str(self.target), *(s.fn.__module__ for s in self.registry.functions.values())}
78
+ return {m for m in sys.modules if any(m == r or m.startswith(r + ".") for r in mods)}
79
+
80
+ def reload(self) -> None:
81
+ """Re-import the target; on import errors keep the old functions and expose the errors.
82
+
83
+ Must be called on the event loop thread (it publishes to subscriber queues).
84
+ """
85
+ for name in self._target_modules():
86
+ f = getattr(sys.modules[name], "__file__", None)
87
+ if f and f.endswith(".py"): # a same-size, same-second edit would reuse a stale .pyc
88
+ Path(importlib.util.cache_from_source(f)).unlink(missing_ok=True)
89
+ del sys.modules[name]
90
+ importlib.invalidate_caches()
91
+ new = discover(self.target)
92
+ if new.issues:
93
+ self.registry_errors = new.issues
94
+ else:
95
+ self.registry, self.registry_errors = new, []
96
+ self.publish({"type": "registry_changed"})
vgraph/server/views.py ADDED
@@ -0,0 +1,89 @@
1
+ """JSON-serializable views consumed by the UI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from vgraph.compile import Issue
8
+ from vgraph.engine import Execution
9
+ from vgraph.inputs import type_name
10
+ from vgraph.registry import FunctionSpec, Param
11
+
12
+
13
+ def _safe_str(e: BaseException) -> str:
14
+ try:
15
+ return str(e)
16
+ except Exception:
17
+ return f"<unprintable {type(e).__name__}>"
18
+
19
+
20
+ def _bounded(text: str, limit: int | None) -> str:
21
+ return text if limit is None else text[:limit]
22
+
23
+
24
+ def safe_repr(value: Any, limit: int | None = 4096) -> tuple[str, bool]:
25
+ """Return (repr text, truncated); never raises."""
26
+ try:
27
+ text = repr(value)
28
+ except Exception as e:
29
+ return _bounded(f"<repr failed: {type(e).__name__}: {_safe_str(e)}>", limit), False
30
+ if limit is not None and len(text) > limit:
31
+ return text[:limit], True
32
+ return text, False
33
+
34
+
35
+ def _values(d: dict[str, Any], limit: int | None) -> dict[str, dict[str, Any]]:
36
+ return {
37
+ k: dict(zip(("repr", "truncated"), safe_repr(v, limit), strict=True)) for k, v in d.items()
38
+ }
39
+
40
+
41
+ def execution_view(e: Execution, full: bool = False) -> dict[str, Any]:
42
+ limit = None if full else 4096
43
+ return {
44
+ "node": e.node,
45
+ "number": e.number,
46
+ "status": e.status.value,
47
+ "inputs": _values(e.inputs, limit),
48
+ "outputs": _values(e.outputs, limit),
49
+ "error": None
50
+ if e.error is None
51
+ else _bounded(f"{type(e.error).__name__}: {_safe_str(e.error)}", limit),
52
+ "traceback": e.traceback,
53
+ "skip_reason": e.skip_reason,
54
+ "branch_exit": e.branch_exit,
55
+ "started_at": e.started_at.isoformat() if e.started_at else None,
56
+ "ended_at": e.ended_at.isoformat() if e.ended_at else None,
57
+ }
58
+
59
+
60
+ def _param_view(p: Param) -> dict[str, Any]:
61
+ t = " | ".join([type_name(p.hint), *(c.__name__ for c in p.accepts)])
62
+ return {
63
+ "name": p.name,
64
+ "type": t,
65
+ "required": not p.has_default,
66
+ "default": safe_repr(p.default)[0] if p.has_default else None,
67
+ "accepts": [c.__name__ for c in p.accepts],
68
+ }
69
+
70
+
71
+ def function_view(spec: FunctionSpec) -> dict[str, Any]:
72
+ return {
73
+ "ref": spec.ref,
74
+ "module": spec.fn.__module__,
75
+ "name": spec.fn.__name__,
76
+ "kind": spec.kind,
77
+ "params": [_param_view(p) for p in spec.params],
78
+ "outputs": [{"name": n, "type": type_name(h)} for n, h in spec.outputs.items()],
79
+ "members": list(spec.members),
80
+ }
81
+
82
+
83
+ def issue_view(i: Issue) -> dict[str, Any]:
84
+ return {
85
+ "code": i.code,
86
+ "message": i.message,
87
+ "node": i.node,
88
+ "edge": list(i.edge) if i.edge else None,
89
+ }
vgraph/server/watch.py ADDED
@@ -0,0 +1,48 @@
1
+ """File watcher: .py changes reload the registry, graph .yaml changes are announced."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib.util
7
+ import logging
8
+ from collections.abc import Iterable
9
+ from pathlib import Path
10
+
11
+ from watchfiles import Change, awatch
12
+
13
+ from vgraph.server.state import AppState
14
+
15
+ log = logging.getLogger("vgraph")
16
+
17
+
18
+ def handle_changes(state: AppState, changes: Iterable[tuple[Change, str]]) -> None:
19
+ """Handle one batch of changes. Must run on the event loop thread."""
20
+ paths = [Path(p) for _, p in changes]
21
+ if any(p.suffix == ".py" and "__pycache__" not in p.parts for p in paths):
22
+ state.reload()
23
+ graphs = state.graphs_dir.resolve()
24
+ for name in dict.fromkeys(
25
+ p.stem for p in paths if p.suffix == ".yaml" and p.resolve().parent == graphs
26
+ ):
27
+ state.publish({"type": "graph_changed", "name": name})
28
+
29
+
30
+ def watch_roots(state: AppState) -> list[Path]:
31
+ target = Path(state.target)
32
+ if target.is_dir():
33
+ code = target
34
+ else:
35
+ spec = importlib.util.find_spec(str(state.target).split(".")[0])
36
+ code = Path(spec.origin).parent if spec and spec.origin else None
37
+ return [p for p in (code, state.graphs_dir) if p is not None and p.is_dir()]
38
+
39
+
40
+ async def watch(state: AppState, stop: asyncio.Event) -> None:
41
+ roots = watch_roots(state)
42
+ if not roots:
43
+ return
44
+ async for changes in awatch(*roots, stop_event=stop):
45
+ try:
46
+ handle_changes(state, changes)
47
+ except Exception:
48
+ log.exception("vgraph: failed to handle file changes")