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.
@@ -0,0 +1,56 @@
1
+ {
2
+ "$defs": {
3
+ "NodeSpec": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "fn": {
7
+ "title": "Fn",
8
+ "type": "string"
9
+ },
10
+ "next": {
11
+ "anyOf": [
12
+ {
13
+ "items": {
14
+ "type": "string"
15
+ },
16
+ "type": "array"
17
+ },
18
+ {
19
+ "additionalProperties": {
20
+ "type": "string"
21
+ },
22
+ "type": "object"
23
+ }
24
+ ],
25
+ "default": [],
26
+ "title": "Next"
27
+ }
28
+ },
29
+ "required": [
30
+ "fn"
31
+ ],
32
+ "title": "NodeSpec",
33
+ "type": "object"
34
+ }
35
+ },
36
+ "additionalProperties": false,
37
+ "properties": {
38
+ "vgraph": {
39
+ "title": "Vgraph",
40
+ "type": "integer"
41
+ },
42
+ "nodes": {
43
+ "additionalProperties": {
44
+ "$ref": "#/$defs/NodeSpec"
45
+ },
46
+ "title": "Nodes",
47
+ "type": "object"
48
+ }
49
+ },
50
+ "required": [
51
+ "vgraph",
52
+ "nodes"
53
+ ],
54
+ "title": "GraphFile",
55
+ "type": "object"
56
+ }
vgraph/inputs.py ADDED
@@ -0,0 +1,82 @@
1
+ """Run inputs: YAML skeleton for the Run dialog, parsing and validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping
7
+ from typing import Any, get_args, get_origin
8
+
9
+ import yaml
10
+ from pydantic import TypeAdapter, ValidationError
11
+
12
+ from vgraph.compile import CompiledGraph
13
+ from vgraph.model import StrictLoader
14
+
15
+ _NULLS = ("null", "Null", "NULL", "~")
16
+
17
+
18
+ class InputError(ValueError):
19
+ def __init__(self, errors: list[str]):
20
+ super().__init__("; ".join(errors))
21
+ self.errors = errors
22
+
23
+
24
+ def type_name(hint: Any) -> str:
25
+ if isinstance(hint, type) and get_origin(hint) is None:
26
+ return hint.__name__
27
+ return re.sub(r"\b(?:\w+\.)+", "", str(hint))
28
+
29
+
30
+ def _dump(value: Any) -> str:
31
+ return yaml.safe_dump(value, default_flow_style=True, width=10**9).split("\n...")[0].strip()
32
+
33
+
34
+ def input_skeleton(cg: CompiledGraph) -> str:
35
+ lines = []
36
+ for name, p in cg.inputs.items():
37
+ t = type_name(p.hint)
38
+ lines.append(
39
+ f"{name}: # {t} (required)"
40
+ if not p.has_default
41
+ else f"{name}: {_dump(p.default)} # {t}"
42
+ )
43
+ return "".join(line + "\n" for line in lines)
44
+
45
+
46
+ def coerce_inputs(cg: CompiledGraph, values: Mapping[str, Any]) -> dict[str, Any]:
47
+ out: dict[str, Any] = {}
48
+ errors: list[str] = []
49
+ for name, p in cg.inputs.items():
50
+ if name not in values or values[name] == "": # "" = empty YAML scalar
51
+ if p.has_default:
52
+ out[name] = p.default
53
+ else:
54
+ errors.append(f"{name}: required")
55
+ continue
56
+ try:
57
+ out[name] = TypeAdapter(p.hint).validate_python(values[name])
58
+ except ValidationError as e:
59
+ errors.extend(f"{name}: {err['msg']}" for err in e.errors())
60
+ errors.extend(f"{k}: unknown input" for k in values if k not in cg.inputs)
61
+ if errors:
62
+ raise InputError(errors)
63
+ return out
64
+
65
+
66
+ def parse_inputs(cg: CompiledGraph, text: str) -> dict[str, Any]:
67
+ try:
68
+ data = yaml.load(text, Loader=StrictLoader) # noqa: S506 - yields only str/list/dict
69
+ except yaml.YAMLError as e: # ReaderError (control characters) has no mark or problem
70
+ m = getattr(e, "problem_mark", None)
71
+ at = f" (line {m.line + 1}, column {m.column + 1})" if m else ""
72
+ problem = getattr(e, "problem", None) or getattr(e, "reason", None) or "syntax error"
73
+ raise InputError([f"inputs are not valid YAML: {problem}{at}"]) from e
74
+ if data is None:
75
+ data = {}
76
+ if not isinstance(data, dict):
77
+ raise InputError(["inputs must be a mapping"])
78
+ for k, v in data.items():
79
+ hint = cg.inputs[k].hint if k in cg.inputs else None
80
+ if v in _NULLS and (hint is type(None) or type(None) in get_args(hint)):
81
+ data[k] = None # YAML null only where the hint allows None; a str input keeps "null"
82
+ return coerce_inputs(cg, data)
vgraph/model.py ADDED
@@ -0,0 +1,63 @@
1
+ """YAML graph file model: parsing, canonical dump and JSON Schema."""
2
+
3
+ from typing import Any
4
+
5
+ import yaml
6
+ from pydantic import BaseModel, ConfigDict, field_validator
7
+ from yaml.constructor import ConstructorError
8
+
9
+
10
+ class StrictLoader(yaml.BaseLoader):
11
+ """BaseLoader (every scalar stays a string) that refuses duplicate mapping keys.
12
+
13
+ Plain YAML keeps the last duplicate, which would silently drop a node or an input.
14
+ """
15
+
16
+ def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]:
17
+ seen: set[str] = set()
18
+ for key, _ in node.value:
19
+ if isinstance(key, yaml.ScalarNode):
20
+ if key.value in seen:
21
+ raise ConstructorError(
22
+ "while constructing a mapping",
23
+ node.start_mark,
24
+ f"found duplicate key {key.value!r}",
25
+ key.start_mark,
26
+ )
27
+ seen.add(key.value)
28
+ return super().construct_mapping(node, deep)
29
+
30
+
31
+ class NodeSpec(BaseModel):
32
+ model_config = ConfigDict(extra="forbid")
33
+
34
+ fn: str
35
+ next: list[str] | dict[str, str] = []
36
+
37
+
38
+ class GraphFile(BaseModel):
39
+ model_config = ConfigDict(extra="forbid")
40
+
41
+ vgraph: int
42
+ nodes: dict[str, NodeSpec]
43
+
44
+ @field_validator("vgraph")
45
+ @classmethod
46
+ def _check_version(cls, v: int) -> int:
47
+ if v != 1:
48
+ raise ValueError(f"unsupported format version: {v}")
49
+ return v
50
+
51
+
52
+ def parse_graph_yaml(text: str) -> GraphFile:
53
+ # Strings only, so keys like YES/NO/ON are not turned into bools.
54
+ return GraphFile.model_validate(yaml.load(text, Loader=StrictLoader)) # noqa: S506
55
+
56
+
57
+ def dump_graph_yaml(graph: GraphFile) -> str:
58
+ data = graph.model_dump(exclude_defaults=True)
59
+ return yaml.safe_dump(data, sort_keys=False, default_flow_style=None)
60
+
61
+
62
+ def graph_json_schema() -> dict[str, Any]:
63
+ return GraphFile.model_json_schema()
vgraph/py.typed ADDED
File without changes
vgraph/registry.py ADDED
@@ -0,0 +1,183 @@
1
+ """``@node`` / ``@branch`` decorators, function specs and discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import inspect
7
+ import pkgutil
8
+ import sys
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass, field
11
+ from enum import Enum
12
+ from pathlib import Path
13
+ from typing import Any, Literal, get_type_hints
14
+
15
+ from vgraph.typing_utils import exception_classes, output_fields, value_hint
16
+
17
+
18
+ def _check(fn: Callable[..., Any]) -> None:
19
+ sig = inspect.signature(fn)
20
+ name = fn.__name__
21
+ for p in sig.parameters.values():
22
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
23
+ raise TypeError(f"{name}: variadic parameters are not supported")
24
+ if p.annotation is p.empty:
25
+ raise TypeError(f"{name}: parameter '{p.name}' has no type annotation")
26
+ if sig.return_annotation is sig.empty:
27
+ raise TypeError(f"{name}: missing return annotation")
28
+
29
+
30
+ def _mark(fn: Callable[..., Any], kind: str, out: str | None) -> Callable[..., Any]:
31
+ _check(fn)
32
+ fn.__vgraph__ = (kind, out) # type: ignore[attr-defined]
33
+ return fn
34
+
35
+
36
+ def node(fn: Callable[..., Any] | None = None, *, out: str | None = None) -> Any:
37
+ """Register a function as a graph node (use ``out=`` to name its single output)."""
38
+ if fn is None:
39
+ return lambda f: _mark(f, "node", out)
40
+ return _mark(fn, "node", out)
41
+
42
+
43
+ def branch(fn: Callable[..., Any]) -> Callable[..., Any]:
44
+ """Register a function returning an Enum as a branch."""
45
+ return _mark(fn, "branch", None)
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Param:
50
+ name: str
51
+ hint: Any
52
+ has_default: bool
53
+ default: Any
54
+ accepts: tuple[type[Exception], ...]
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class FunctionSpec:
59
+ ref: str
60
+ fn: Callable[..., Any]
61
+ kind: Literal["node", "branch"]
62
+ params: tuple[Param, ...]
63
+ outputs: dict[str, Any]
64
+ return_hint: Any
65
+ enum: type[Enum] | None
66
+ is_async: bool
67
+
68
+ @property
69
+ def members(self) -> tuple[str, ...]:
70
+ return tuple(m.name for m in self.enum) if self.enum else ()
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class ImportIssue:
75
+ module: str
76
+ message: str
77
+
78
+
79
+ def ref_of(fn: Callable[..., Any]) -> str:
80
+ return f"{fn.__module__}:{fn.__qualname__}"
81
+
82
+
83
+ def _spec(fn: Callable[..., Any]) -> FunctionSpec:
84
+ kind, out = fn.__vgraph__ # type: ignore[attr-defined]
85
+ hints = get_type_hints(fn)
86
+ ret = hints["return"]
87
+ params = tuple(
88
+ Param(
89
+ p.name,
90
+ value_hint(hints[p.name]),
91
+ p.default is not p.empty,
92
+ None if p.default is p.empty else p.default,
93
+ exception_classes(hints[p.name]),
94
+ )
95
+ for p in inspect.signature(fn).parameters.values()
96
+ )
97
+ enum = None
98
+ if kind == "branch":
99
+ enum = value_hint(ret)
100
+ if not (isinstance(enum, type) and issubclass(enum, Enum)):
101
+ raise TypeError(f"{fn.__name__}: @branch must return an Enum")
102
+ outputs: dict[str, Any] = {fn.__name__: enum}
103
+ else:
104
+ outputs = output_fields(ret, fn.__name__, out)
105
+ return FunctionSpec(
106
+ ref_of(fn), fn, kind, params, outputs, ret, enum, inspect.iscoroutinefunction(fn)
107
+ )
108
+
109
+
110
+ @dataclass
111
+ class Registry:
112
+ functions: dict[str, FunctionSpec] = field(default_factory=dict)
113
+ issues: list[ImportIssue] = field(default_factory=list)
114
+
115
+ @classmethod
116
+ def of(cls, *fns: Callable[..., Any]) -> Registry:
117
+ reg = cls()
118
+ for fn in fns:
119
+ spec = _spec(fn)
120
+ reg.functions[spec.ref] = spec
121
+ return reg
122
+
123
+
124
+ def _import(name: str, reg: Registry) -> Any:
125
+ try:
126
+ return importlib.import_module(name)
127
+ except (Exception, SystemExit) as e: # noqa: BLE001 - any import failure becomes an issue
128
+ reg.issues.append(ImportIssue(name, f"{type(e).__name__}: {e}"))
129
+ return None
130
+
131
+
132
+ def _collect(mod: Any, reg: Registry) -> None:
133
+ for obj in vars(mod).values():
134
+ if callable(obj) and hasattr(obj, "__vgraph__") and obj.__module__ == mod.__name__:
135
+ try:
136
+ spec = _spec(obj)
137
+ except Exception as e: # noqa: BLE001
138
+ reg.issues.append(ImportIssue(mod.__name__, f"{type(e).__name__}: {e}"))
139
+ continue
140
+ reg.functions[spec.ref] = spec
141
+
142
+
143
+ def is_user_code(rel: Path) -> bool:
144
+ """False for a path (relative to a directory target) in a cache, hidden dir or venv."""
145
+ return not any(p.startswith(("__pycache__", ".")) or p == "site-packages" for p in rel.parts)
146
+
147
+
148
+ def discover(target: str | Path) -> Registry:
149
+ """Import a module/package name or a directory and register its functions."""
150
+ reg = Registry()
151
+ path = Path(target)
152
+ if isinstance(target, Path) or path.is_dir():
153
+ root, prefix = path.resolve(), ""
154
+ if (root / "__init__.py").exists(): # a package dir: import it by name
155
+ root, prefix = root.parent, root.name + "."
156
+ if str(root) not in sys.path:
157
+ sys.path.insert(0, str(root))
158
+ names = []
159
+ for py in sorted(path.resolve().rglob("*.py")):
160
+ rel = py.relative_to(path.resolve()).with_suffix("")
161
+ if not is_user_code(rel):
162
+ continue
163
+ parts = rel.parts[:-1] if rel.name == "__init__" else rel.parts
164
+ if parts:
165
+ names.append(prefix + ".".join(parts))
166
+ if prefix:
167
+ names.insert(0, prefix.rstrip("."))
168
+ else:
169
+ top = _import(str(target), reg)
170
+ if top is None: # already recorded as an issue
171
+ return reg
172
+ names = [str(target)]
173
+ if hasattr(top, "__path__"):
174
+ names += [
175
+ m.name
176
+ for m in pkgutil.walk_packages(
177
+ top.__path__, f"{top.__name__}.", onerror=lambda _n: None
178
+ )
179
+ ]
180
+ for name in dict.fromkeys(names):
181
+ if (mod := _import(name, reg)) is not None:
182
+ _collect(mod, reg)
183
+ return reg
@@ -0,0 +1 @@
1
+ """vgraph server: views, run history, HTTP app."""
vgraph/server/app.py ADDED
@@ -0,0 +1,248 @@
1
+ """FastAPI app: REST for graphs and runs, one WebSocket for live events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import re
8
+ from collections.abc import AsyncIterator, Awaitable, Callable
9
+ from contextlib import asynccontextmanager, suppress
10
+ from datetime import UTC, datetime
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlsplit
14
+ from uuid import UUID, uuid4
15
+
16
+ from fastapi import FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
17
+ from fastapi.middleware.trustedhost import TrustedHostMiddleware
18
+ from fastapi.responses import JSONResponse, PlainTextResponse
19
+ from fastapi.staticfiles import StaticFiles
20
+ from pydantic import BaseModel
21
+
22
+ from vgraph.compile import CompiledGraph, compile_graph
23
+ from vgraph.engine import Event, NodeEvent, PassEvent, RunEvent, RunStatus, execute
24
+ from vgraph.inputs import InputError, input_skeleton, parse_inputs
25
+ from vgraph.model import GraphFile, dump_graph_yaml, parse_graph_yaml
26
+ from vgraph.server.state import AppState, RunRecord
27
+ from vgraph.server.views import execution_view, function_view, issue_view
28
+ from vgraph.server.watch import watch
29
+
30
+ _NAME = re.compile(r"^[A-Za-z0-9_-]+$")
31
+ _SHUTDOWN_GRACE = 5.0
32
+ _LOCAL_HOSTS = ["127.0.0.1", "localhost"]
33
+
34
+
35
+ class RunRequest(BaseModel):
36
+ inputs: str = ""
37
+
38
+
39
+ def _check(g: GraphFile, state: AppState) -> tuple[CompiledGraph | None, dict[str, Any]]:
40
+ cg, issues = compile_graph(g, state.registry)
41
+ return cg, {
42
+ "issues": [issue_view(i) for i in issues],
43
+ "skeleton": input_skeleton(cg) if cg else "",
44
+ }
45
+
46
+
47
+ def _foreign_origin(origin: str | None) -> bool:
48
+ """A page from another site (any port of a local host is ours: the Vite dev server)."""
49
+ return origin is not None and urlsplit(origin).hostname not in _LOCAL_HOSTS
50
+
51
+
52
+ def _record_view(r: RunRecord) -> dict[str, Any]:
53
+ return {
54
+ "run_id": str(r.run_id),
55
+ "status": r.status.value,
56
+ "started_at": r.started_at.isoformat(),
57
+ }
58
+
59
+
60
+ def create_app(target: str | Path, graphs_dir: Path) -> FastAPI:
61
+ state = AppState(target, graphs_dir)
62
+
63
+ @asynccontextmanager
64
+ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
65
+ stop_watch = asyncio.Event()
66
+ watcher = asyncio.create_task(watch(state, stop_watch))
67
+ yield
68
+ stop_watch.set()
69
+ with suppress(Exception): # a dead watcher must not skip run cleanup
70
+ await watcher
71
+ for stop in state.running.values():
72
+ stop.set()
73
+ if state.running:
74
+ _done, pending = await asyncio.wait(list(state.running), timeout=_SHUTDOWN_GRACE)
75
+ for t in pending:
76
+ t.cancel()
77
+
78
+ app = FastAPI(title="vgraph", lifespan=lifespan)
79
+ app.state.vgraph = state
80
+ # DNS rebinding: a foreign page reaching us by IP still sends its own Host
81
+ app.add_middleware(TrustedHostMiddleware, allowed_hosts=_LOCAL_HOSTS)
82
+
83
+ @app.middleware("http")
84
+ async def same_origin_writes(
85
+ request: Request, call_next: Callable[[Request], Awaitable[Response]]
86
+ ) -> Response:
87
+ if request.method not in ("GET", "HEAD") and _foreign_origin(request.headers.get("origin")):
88
+ return PlainTextResponse("cross-origin request refused", status_code=403)
89
+ return await call_next(request)
90
+
91
+ def graph_path(name: str) -> Path:
92
+ if not _NAME.fullmatch(name):
93
+ raise HTTPException(400, f"invalid graph name: {name!r}")
94
+ return state.graphs_dir / f"{name}.yaml"
95
+
96
+ def load(name: str) -> GraphFile:
97
+ path = graph_path(name)
98
+ if not path.is_file():
99
+ raise HTTPException(404, f"no such graph: {name}")
100
+ try:
101
+ return parse_graph_yaml(path.read_text())
102
+ except Exception as e: # noqa: BLE001 - unreadable file is reported, not a crash
103
+ raise HTTPException(422, f"invalid graph file: {e}") from e
104
+
105
+ def get_run(run_id: UUID) -> RunRecord:
106
+ if (r := state.history.get(run_id)) is None:
107
+ raise HTTPException(404, "no such run")
108
+ return r
109
+
110
+ @app.get("/api/functions")
111
+ def functions() -> dict[str, Any]:
112
+ return {
113
+ "functions": [function_view(s) for s in state.registry.functions.values()],
114
+ "errors": [{"module": e.module, "message": e.message} for e in state.registry_errors],
115
+ }
116
+
117
+ @app.get("/api/graphs")
118
+ def list_graphs() -> dict[str, Any]:
119
+ return {"graphs": sorted(p.stem for p in state.graphs_dir.glob("*.yaml"))}
120
+
121
+ @app.get("/api/graphs/{name:path}/runs")
122
+ def list_runs(name: str) -> dict[str, Any]:
123
+ graph_path(name)
124
+ return {"runs": [_record_view(r) for r in state.history.list(name)]}
125
+
126
+ @app.post("/api/graphs/{name:path}/runs", status_code=201)
127
+ async def start_run(name: str, body: RunRequest) -> Response:
128
+ cg, view = _check(load(name), state)
129
+ if cg is None or view["issues"]:
130
+ return JSONResponse({"issues": view["issues"]}, status_code=409)
131
+ try:
132
+ inputs = parse_inputs(cg, body.inputs)
133
+ except InputError as e:
134
+ return JSONResponse({"errors": e.errors}, status_code=422)
135
+ record = RunRecord(uuid4(), name, RunStatus.RUNNING, datetime.now(UTC), {}, asyncio.Event())
136
+ state.history.add(name, record)
137
+
138
+ def on_event(ev: Event) -> None:
139
+ base = {"run_id": str(record.run_id), "graph": name}
140
+ match ev:
141
+ case NodeEvent(execution=ex):
142
+ seen = record.executions.setdefault(ex.node, [])
143
+ if not any(x is ex for x in seen):
144
+ seen.append(ex)
145
+ state.publish({"type": "node", **base, "execution": execution_view(ex)})
146
+ case PassEvent():
147
+ msg = {"type": "pass", **base, "target": ev.target, "reset": list(ev.reset)}
148
+ state.publish(msg)
149
+ case RunEvent():
150
+ record.status = ev.status
151
+ state.publish({"type": "run", **base, "status": ev.status.value})
152
+
153
+ task = asyncio.create_task(
154
+ execute(cg, inputs, run_id=record.run_id, on_event=on_event, stop=record.stop)
155
+ )
156
+ state.running[task] = record.stop
157
+
158
+ def done(t: asyncio.Task[Any]) -> None:
159
+ state.running.pop(t, None)
160
+ if (
161
+ not t.cancelled() and t.exception() is not None
162
+ ): # engine crashed: never leave RUNNING
163
+ record.status = RunStatus.FAILED
164
+ state.publish(
165
+ {"type": "run", "run_id": str(record.run_id), "graph": name, "status": "failed"}
166
+ )
167
+
168
+ task.add_done_callback(done)
169
+ return JSONResponse({"run_id": str(record.run_id)}, status_code=201)
170
+
171
+ @app.get("/api/graphs/{name:path}")
172
+ def get_graph(name: str) -> dict[str, Any]:
173
+ g = load(name)
174
+ return {"graph": g.model_dump(), **_check(g, state)[1]}
175
+
176
+ @app.put("/api/graphs/{name:path}")
177
+ def put_graph(name: str, graph: GraphFile) -> dict[str, Any]:
178
+ path = graph_path(name)
179
+ path.parent.mkdir(parents=True, exist_ok=True)
180
+ tmp = path.with_name(f".{path.name}.tmp") # same dir so os.replace is atomic
181
+ tmp.write_text(dump_graph_yaml(graph))
182
+ os.replace(tmp, path)
183
+ state.publish({"type": "graph_changed", "name": name})
184
+ return _check(graph, state)[1]
185
+
186
+ @app.delete("/api/graphs/{name:path}", status_code=204)
187
+ def delete_graph(name: str) -> Response:
188
+ path = graph_path(name)
189
+ if not path.is_file():
190
+ raise HTTPException(404, f"no such graph: {name}")
191
+ path.unlink()
192
+ state.publish({"type": "graph_changed", "name": name})
193
+ return Response(status_code=204)
194
+
195
+ @app.post("/api/validate")
196
+ def validate(graph: GraphFile) -> dict[str, Any]:
197
+ return _check(graph, state)[1]
198
+
199
+ @app.post("/api/runs/{run_id}/stop", status_code=202)
200
+ def stop_run(run_id: UUID) -> Response:
201
+ get_run(run_id).stop.set()
202
+ return Response(status_code=202)
203
+
204
+ @app.get("/api/runs/{run_id}/nodes/{node}/{number}")
205
+ def run_execution(run_id: UUID, node: str, number: int) -> dict[str, Any]:
206
+ for ex in get_run(run_id).executions.get(node, []):
207
+ if ex.number == number:
208
+ return execution_view(ex, full=True)
209
+ raise HTTPException(404, "no such execution")
210
+
211
+ @app.get("/api/runs/{run_id}")
212
+ def run_snapshot(run_id: UUID) -> dict[str, Any]:
213
+ r = get_run(run_id)
214
+ return {
215
+ **_record_view(r),
216
+ "graph": r.graph,
217
+ "executions": {n: [execution_view(e) for e in es] for n, es in r.executions.items()},
218
+ }
219
+
220
+ @app.websocket("/api/events")
221
+ async def events(ws: WebSocket) -> None:
222
+ if _foreign_origin(ws.headers.get("origin")):
223
+ await ws.close(code=1008) # policy violation; a missing Origin is a non-browser client
224
+ return
225
+ await ws.accept()
226
+ q: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
227
+ state.subscribers.add(q)
228
+
229
+ async def pump() -> None:
230
+ while True:
231
+ await ws.send_json(await q.get())
232
+
233
+ pump_task = asyncio.create_task(pump())
234
+ try:
235
+ while True:
236
+ await ws.receive_text() # only to notice the client leaving
237
+ except WebSocketDisconnect:
238
+ pass
239
+ finally:
240
+ pump_task.cancel()
241
+ with suppress(asyncio.CancelledError, Exception):
242
+ await pump_task
243
+ state.subscribers.discard(q)
244
+
245
+ static = Path(__file__).resolve().parent.parent / "static"
246
+ if (static / "index.html").exists():
247
+ app.mount("/", StaticFiles(directory=static, html=True), name="static")
248
+ return app