microoflow 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.
- microoflow/__init__.py +38 -0
- microoflow/__main__.py +7 -0
- microoflow/app.py +165 -0
- microoflow/cli.py +150 -0
- microoflow/events.py +135 -0
- microoflow/graph.py +194 -0
- microoflow/py.typed +1 -0
- microoflow/registry.py +319 -0
- microoflow/reloader.py +462 -0
- microoflow/runner.py +775 -0
- microoflow/server.py +208 -0
- microoflow/static/index.html +282 -0
- microoflow/static/sdk/canvas.js +990 -0
- microoflow/static/sdk/geometry.js +32 -0
- microoflow/static/sdk/minimap.js +208 -0
- microoflow/static/sdk/node_menu.js +480 -0
- microoflow/static/sdk/output_viewer.js +109 -0
- microoflow/static/sdk/renderers/base.js +174 -0
- microoflow/static/sdk/renderers/data_view.js +162 -0
- microoflow/static/sdk/renderers/html.js +694 -0
- microoflow/static/sdk/renderers/index.js +35 -0
- microoflow/static/sdk/renderers/markdown.js +622 -0
- microoflow/static/sdk/renderers/raw_csv.js +50 -0
- microoflow/static/sdk/renderers/raw_dict.js +123 -0
- microoflow/static/sdk/renderers/raw_json.js +71 -0
- microoflow/static/sdk/renderers/raw_list.js +84 -0
- microoflow/static/sdk/renderers/syntax.js +585 -0
- microoflow/static/sdk/renderers/table.js +323 -0
- microoflow/static/sdk/store.js +507 -0
- microoflow/static/sdk/viewport.js +165 -0
- microoflow/static/studio/app.js +689 -0
- microoflow/static/studio.css +1818 -0
- microoflow/views.py +102 -0
- microoflow-0.1.0.dist-info/METADATA +165 -0
- microoflow-0.1.0.dist-info/RECORD +38 -0
- microoflow-0.1.0.dist-info/WHEEL +4 -0
- microoflow-0.1.0.dist-info/entry_points.txt +2 -0
- microoflow-0.1.0.dist-info/licenses/LICENSE +22 -0
microoflow/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
2
|
+
|
|
3
|
+
from .app import App
|
|
4
|
+
from .graph import GraphError
|
|
5
|
+
from .registry import NodeContractError
|
|
6
|
+
from .runner import NodeRunRecord, RunContext
|
|
7
|
+
from .views import (
|
|
8
|
+
CsvView,
|
|
9
|
+
DataView,
|
|
10
|
+
DictView,
|
|
11
|
+
HTMLView,
|
|
12
|
+
JsonView,
|
|
13
|
+
ListView,
|
|
14
|
+
MarkdownView,
|
|
15
|
+
TableView,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
__version__ = version("microoflow")
|
|
20
|
+
except PackageNotFoundError: # pragma: no cover - source checkout fallback
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"App",
|
|
25
|
+
"CsvView",
|
|
26
|
+
"DataView",
|
|
27
|
+
"DictView",
|
|
28
|
+
"GraphError",
|
|
29
|
+
"HTMLView",
|
|
30
|
+
"JsonView",
|
|
31
|
+
"ListView",
|
|
32
|
+
"MarkdownView",
|
|
33
|
+
"NodeContractError",
|
|
34
|
+
"NodeRunRecord",
|
|
35
|
+
"RunContext",
|
|
36
|
+
"TableView",
|
|
37
|
+
"__version__",
|
|
38
|
+
]
|
microoflow/__main__.py
ADDED
microoflow/app.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import threading
|
|
7
|
+
import webbrowser
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from .events import EventBus
|
|
13
|
+
from .registry import NodeRegistry
|
|
14
|
+
from .reloader import (
|
|
15
|
+
ProcessReloader,
|
|
16
|
+
StaticWatcher,
|
|
17
|
+
_has_ignored_ancestor,
|
|
18
|
+
collect_python_watch_targets,
|
|
19
|
+
install_child_shutdown_hook,
|
|
20
|
+
)
|
|
21
|
+
from .runner import RunContext, WorkflowRunner
|
|
22
|
+
from .server import MicrooflowHTTPServer
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _resolve_reload_target() -> tuple[list[str] | None, Path | None]:
|
|
26
|
+
arg0 = sys.argv[0] if sys.argv else ""
|
|
27
|
+
if not arg0 or arg0 in ("-c", "-m"):
|
|
28
|
+
return None, None
|
|
29
|
+
candidate = Path(arg0)
|
|
30
|
+
if "pytest" in candidate.stem.lower():
|
|
31
|
+
return None, None
|
|
32
|
+
|
|
33
|
+
main_mod = sys.modules.get("__main__")
|
|
34
|
+
main_spec = getattr(main_mod, "__spec__", None)
|
|
35
|
+
spec_name = getattr(main_spec, "name", None)
|
|
36
|
+
if isinstance(spec_name, str) and spec_name and spec_name != "__main__":
|
|
37
|
+
origin = getattr(main_spec, "origin", None)
|
|
38
|
+
entry_path = (
|
|
39
|
+
Path(origin).resolve()
|
|
40
|
+
if isinstance(origin, str) and Path(origin).is_file()
|
|
41
|
+
else (candidate.resolve() if candidate.is_file() else None)
|
|
42
|
+
)
|
|
43
|
+
return [sys.executable, "-m", spec_name, *sys.argv[1:]], entry_path
|
|
44
|
+
|
|
45
|
+
if candidate.suffix.lower() != ".py" or not candidate.is_file():
|
|
46
|
+
return None, None
|
|
47
|
+
return [sys.executable, *sys.argv], candidate.resolve()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class App:
|
|
51
|
+
"""Microoflow application entry point."""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
title: str = "Microoflow Studio",
|
|
56
|
+
host: str = "127.0.0.1",
|
|
57
|
+
port: int = 8765,
|
|
58
|
+
) -> None:
|
|
59
|
+
self.title = title
|
|
60
|
+
self.host = host
|
|
61
|
+
self.port = port
|
|
62
|
+
self.registry = NodeRegistry()
|
|
63
|
+
self.bus = EventBus()
|
|
64
|
+
self.runner = WorkflowRunner(self.registry, self.bus)
|
|
65
|
+
self._static_dir = Path(__file__).parent / "static"
|
|
66
|
+
|
|
67
|
+
def register(self, *node_classes: type[BaseModel]) -> App:
|
|
68
|
+
for cls in node_classes:
|
|
69
|
+
self.registry.register(cls)
|
|
70
|
+
return self
|
|
71
|
+
|
|
72
|
+
def run_file(self, path: str | Path) -> RunContext:
|
|
73
|
+
"""Executes a saved .json workflow headlessly without opening the Studio."""
|
|
74
|
+
payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
|
75
|
+
return self.runner.run_sync(payload)
|
|
76
|
+
|
|
77
|
+
def start(
|
|
78
|
+
self,
|
|
79
|
+
open_browser: bool = True,
|
|
80
|
+
*,
|
|
81
|
+
reload: bool = True,
|
|
82
|
+
watch_static: bool | None = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
is_child = os.environ.get("MICROOFLOW_RELOAD_CHILD") == "1"
|
|
85
|
+
if reload and not is_child:
|
|
86
|
+
reload_cmd, entry_script = _resolve_reload_target()
|
|
87
|
+
if reload_cmd is not None:
|
|
88
|
+
watch_dirs, watch_files = collect_python_watch_targets(
|
|
89
|
+
entry_script=entry_script,
|
|
90
|
+
node_classes=(s.cls for s in self.registry.all_specs()),
|
|
91
|
+
)
|
|
92
|
+
reloader = ProcessReloader(
|
|
93
|
+
reload_cmd,
|
|
94
|
+
watch_dirs=watch_dirs,
|
|
95
|
+
watch_files=watch_files,
|
|
96
|
+
suppress_browser_on_reload=True,
|
|
97
|
+
)
|
|
98
|
+
reloader.run()
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
server = MicrooflowHTTPServer(
|
|
103
|
+
(self.host, self.port),
|
|
104
|
+
title=self.title,
|
|
105
|
+
registry=self.registry,
|
|
106
|
+
runner=self.runner,
|
|
107
|
+
bus=self.bus,
|
|
108
|
+
static_dir=self._static_dir,
|
|
109
|
+
)
|
|
110
|
+
except OSError as exc:
|
|
111
|
+
print(
|
|
112
|
+
f"[Microoflow] Unable to bind {self.host}:{self.port} ({exc}). "
|
|
113
|
+
"Another server may already be using this port; pass --port <port> "
|
|
114
|
+
"or App(port=...) to use a different port.",
|
|
115
|
+
file=sys.stderr,
|
|
116
|
+
flush=True,
|
|
117
|
+
)
|
|
118
|
+
raise SystemExit(1) from exc
|
|
119
|
+
|
|
120
|
+
install_child_shutdown_hook(server.shutdown)
|
|
121
|
+
|
|
122
|
+
enable_static_watch = (
|
|
123
|
+
((reload or is_child) and not _has_ignored_ancestor(self._static_dir))
|
|
124
|
+
if watch_static is None
|
|
125
|
+
else watch_static
|
|
126
|
+
)
|
|
127
|
+
static_watcher: StaticWatcher | None = None
|
|
128
|
+
if enable_static_watch and self._static_dir.is_dir():
|
|
129
|
+
static_watcher = StaticWatcher(self._static_dir, self.bus)
|
|
130
|
+
static_watcher.start()
|
|
131
|
+
|
|
132
|
+
actual_host, actual_port = server.server_address[:2]
|
|
133
|
+
client_host = (
|
|
134
|
+
"127.0.0.1" if actual_host in ("0.0.0.0", "::", "") else actual_host
|
|
135
|
+
)
|
|
136
|
+
url = f"http://{client_host}:{actual_port}"
|
|
137
|
+
bind_note = (
|
|
138
|
+
f" (bound to {actual_host}:{actual_port})"
|
|
139
|
+
if actual_host != client_host
|
|
140
|
+
else ""
|
|
141
|
+
)
|
|
142
|
+
registered = ", ".join(s.type_name for s in self.registry.all_specs()) or "(none)"
|
|
143
|
+
mode_note = " (hot reload active)" if enable_static_watch else ""
|
|
144
|
+
print(f"{self.title} running at {url}{bind_note}{mode_note}", flush=True)
|
|
145
|
+
print(f"Registered nodes: {registered}", flush=True)
|
|
146
|
+
print("Press Ctrl+C to stop.", flush=True)
|
|
147
|
+
|
|
148
|
+
should_open_browser = open_browser and os.environ.get("MICROOFLOW_NO_BROWSER") != "1"
|
|
149
|
+
browser_timer: threading.Timer | None = None
|
|
150
|
+
if should_open_browser:
|
|
151
|
+
browser_timer = threading.Timer(0.35, lambda: webbrowser.open(url))
|
|
152
|
+
browser_timer.start()
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
server.serve_forever()
|
|
156
|
+
except KeyboardInterrupt:
|
|
157
|
+
print("\nShutting down Microoflow Studio...")
|
|
158
|
+
finally:
|
|
159
|
+
if browser_timer is not None:
|
|
160
|
+
browser_timer.cancel()
|
|
161
|
+
if static_watcher is not None:
|
|
162
|
+
static_watcher.stop()
|
|
163
|
+
self.bus.wake_all()
|
|
164
|
+
self.runner.stop()
|
|
165
|
+
server.server_close()
|
microoflow/cli.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import importlib
|
|
5
|
+
import importlib.util
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .app import App
|
|
12
|
+
from .reloader import ProcessReloader, collect_python_watch_targets
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _validate_target(target: str) -> tuple[str, str]:
|
|
16
|
+
if ":" not in target:
|
|
17
|
+
raise SystemExit(
|
|
18
|
+
f"Invalid target '{target}'. Expected 'module:attribute' (e.g. main:app)."
|
|
19
|
+
)
|
|
20
|
+
module_name, attr_name = target.split(":", 1)
|
|
21
|
+
if not module_name or not attr_name:
|
|
22
|
+
raise SystemExit(
|
|
23
|
+
f"Invalid target '{target}'. Expected 'module:attribute' (e.g. main:app)."
|
|
24
|
+
)
|
|
25
|
+
return module_name, attr_name
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _locate_module_file(module_name: str) -> Path | None:
|
|
29
|
+
cwd = os.getcwd()
|
|
30
|
+
if cwd not in sys.path:
|
|
31
|
+
sys.path.insert(0, cwd)
|
|
32
|
+
try:
|
|
33
|
+
spec = importlib.util.find_spec(module_name)
|
|
34
|
+
except Exception:
|
|
35
|
+
return None
|
|
36
|
+
if spec is None or not spec.origin or spec.origin == "built-in":
|
|
37
|
+
return None
|
|
38
|
+
path = Path(spec.origin)
|
|
39
|
+
return path.resolve() if path.is_file() else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _load_app(target: str) -> App:
|
|
43
|
+
"""Loads an App instance from a 'module:attribute' reference (e.g., main:app)."""
|
|
44
|
+
module_name, attr_name = _validate_target(target)
|
|
45
|
+
|
|
46
|
+
cwd = os.getcwd()
|
|
47
|
+
if cwd not in sys.path:
|
|
48
|
+
sys.path.insert(0, cwd)
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
module = importlib.import_module(module_name)
|
|
52
|
+
except Exception as exc:
|
|
53
|
+
raise SystemExit(f"Failed to import '{module_name}': {exc}") from exc
|
|
54
|
+
|
|
55
|
+
obj = getattr(module, attr_name, None)
|
|
56
|
+
if not isinstance(obj, App):
|
|
57
|
+
raise SystemExit(f"'{target}' is not a microoflow.App instance.")
|
|
58
|
+
return obj
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def main(argv: list[str] | None = None) -> int:
|
|
62
|
+
parser = argparse.ArgumentParser(
|
|
63
|
+
prog="microoflow", description="Microoflow Studio & headless runner."
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--version", action="version", version=f"%(prog)s {__version__}"
|
|
67
|
+
)
|
|
68
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
69
|
+
|
|
70
|
+
serve_p = sub.add_parser("serve", help="Start the local Microoflow Studio server.")
|
|
71
|
+
serve_p.add_argument(
|
|
72
|
+
"target", help="App import path in 'module:attr' form (e.g. main:app)."
|
|
73
|
+
)
|
|
74
|
+
serve_p.add_argument(
|
|
75
|
+
"--host", default=None, help="Bind host (default: app setting / 127.0.0.1)."
|
|
76
|
+
)
|
|
77
|
+
serve_p.add_argument(
|
|
78
|
+
"--port", type=int, default=None, help="Bind port (default: app setting / 8765)."
|
|
79
|
+
)
|
|
80
|
+
serve_p.add_argument(
|
|
81
|
+
"--no-browser", action="store_true", help="Do not auto-open browser tab."
|
|
82
|
+
)
|
|
83
|
+
serve_p.add_argument(
|
|
84
|
+
"--no-reload",
|
|
85
|
+
action="store_true",
|
|
86
|
+
help="Disable automatic hot live reloading on code changes.",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
run_p = sub.add_parser("run", help="Run a saved .flow.json workflow headlessly.")
|
|
90
|
+
run_p.add_argument(
|
|
91
|
+
"target", help="App import path in 'module:attr' form (e.g. main:app)."
|
|
92
|
+
)
|
|
93
|
+
run_p.add_argument("flow", type=Path, help="Path to workflow .flow.json file.")
|
|
94
|
+
|
|
95
|
+
args = parser.parse_args(argv)
|
|
96
|
+
|
|
97
|
+
if args.command == "serve":
|
|
98
|
+
module_name, _ = _validate_target(args.target)
|
|
99
|
+
is_child = os.environ.get("MICROOFLOW_RELOAD_CHILD") == "1"
|
|
100
|
+
if not args.no_reload and not is_child:
|
|
101
|
+
child_cmd = [sys.executable, "-m", "microoflow.cli", "serve", args.target]
|
|
102
|
+
if args.host is not None:
|
|
103
|
+
child_cmd.extend(["--host", args.host])
|
|
104
|
+
if args.port is not None:
|
|
105
|
+
child_cmd.extend(["--port", str(args.port)])
|
|
106
|
+
if args.no_browser:
|
|
107
|
+
child_cmd.append("--no-browser")
|
|
108
|
+
|
|
109
|
+
target_file = _locate_module_file(module_name)
|
|
110
|
+
watch_dirs, watch_files = collect_python_watch_targets(
|
|
111
|
+
extra_files=(target_file,) if target_file is not None else (),
|
|
112
|
+
)
|
|
113
|
+
return ProcessReloader(
|
|
114
|
+
child_cmd,
|
|
115
|
+
watch_dirs=watch_dirs,
|
|
116
|
+
watch_files=watch_files,
|
|
117
|
+
suppress_browser_on_reload=True,
|
|
118
|
+
).run()
|
|
119
|
+
|
|
120
|
+
app = _load_app(args.target)
|
|
121
|
+
if args.host is not None:
|
|
122
|
+
app.host = args.host
|
|
123
|
+
if args.port is not None:
|
|
124
|
+
app.port = args.port
|
|
125
|
+
app.start(
|
|
126
|
+
open_browser=not args.no_browser,
|
|
127
|
+
reload=False,
|
|
128
|
+
watch_static=False if args.no_reload else None,
|
|
129
|
+
)
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
if args.command == "run":
|
|
133
|
+
app = _load_app(args.target)
|
|
134
|
+
try:
|
|
135
|
+
ctx = app.run_file(args.flow)
|
|
136
|
+
except (OSError, ValueError) as exc:
|
|
137
|
+
print(f"Error running workflow '{args.flow}': {exc}", file=sys.stderr)
|
|
138
|
+
return 1
|
|
139
|
+
print(f"Run {ctx.run_id}: {ctx.status} ({ctx.passed} passed, {ctx.failed} failed)")
|
|
140
|
+
for rec in ctx.records.values():
|
|
141
|
+
if rec.error:
|
|
142
|
+
print(f" [ERROR] {rec.type_name} ({rec.node_id}): {rec.error}")
|
|
143
|
+
return 0 if ctx.failed == 0 else 1
|
|
144
|
+
|
|
145
|
+
return 1
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
if __name__ == "__main__":
|
|
149
|
+
raise SystemExit(main())
|
|
150
|
+
|
microoflow/events.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import queue
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_preview(value: Any, max_chars: int = 400) -> dict[str, Any]:
|
|
11
|
+
"""Produces a compact, JSON-safe summary so large payloads never stall the UI."""
|
|
12
|
+
type_name = type(value).__name__
|
|
13
|
+
|
|
14
|
+
if value is None or isinstance(value, (bool, int, float)):
|
|
15
|
+
return {"type": type_name, "preview": repr(value), "truncated": False}
|
|
16
|
+
|
|
17
|
+
if isinstance(value, str):
|
|
18
|
+
truncated = len(value) > max_chars
|
|
19
|
+
text = value[:max_chars] + ("..." if truncated else "")
|
|
20
|
+
return {
|
|
21
|
+
"type": "str",
|
|
22
|
+
"length": len(value),
|
|
23
|
+
"preview": text,
|
|
24
|
+
"truncated": truncated,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if isinstance(value, (bytes, bytearray)):
|
|
28
|
+
return {
|
|
29
|
+
"type": type_name,
|
|
30
|
+
"length": len(value),
|
|
31
|
+
"preview": f"<{type_name} {len(value)} bytes>",
|
|
32
|
+
"truncated": True,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if isinstance(value, (list, tuple, set)):
|
|
36
|
+
raw = repr(value)
|
|
37
|
+
truncated = len(raw) > max_chars
|
|
38
|
+
return {
|
|
39
|
+
"type": type_name,
|
|
40
|
+
"length": len(value),
|
|
41
|
+
"preview": raw[:max_chars] + ("..." if truncated else ""),
|
|
42
|
+
"truncated": truncated,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if isinstance(value, dict):
|
|
46
|
+
raw = repr(value)
|
|
47
|
+
truncated = len(raw) > max_chars
|
|
48
|
+
return {
|
|
49
|
+
"type": "dict",
|
|
50
|
+
"length": len(value),
|
|
51
|
+
"preview": raw[:max_chars] + ("..." if truncated else ""),
|
|
52
|
+
"truncated": truncated,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
raw = repr(value)
|
|
56
|
+
truncated = len(raw) > max_chars
|
|
57
|
+
return {
|
|
58
|
+
"type": type_name,
|
|
59
|
+
"preview": raw[:max_chars] + ("..." if truncated else ""),
|
|
60
|
+
"truncated": truncated,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class EventBus:
|
|
65
|
+
"""Thread-safe pub/sub broker streaming SSE payloads to connected studio tabs."""
|
|
66
|
+
|
|
67
|
+
def __init__(self) -> None:
|
|
68
|
+
self._lock = threading.Lock()
|
|
69
|
+
self._subscribers: list[queue.Queue[str]] = []
|
|
70
|
+
self._closed_signals: dict[int, threading.Event] = {}
|
|
71
|
+
|
|
72
|
+
def subscribe(self) -> queue.Queue[str]:
|
|
73
|
+
q, _ = self.subscribe_stream()
|
|
74
|
+
return q
|
|
75
|
+
|
|
76
|
+
def subscribe_stream(self) -> tuple[queue.Queue[str], threading.Event]:
|
|
77
|
+
q: queue.Queue[str] = queue.Queue(maxsize=256)
|
|
78
|
+
closed = threading.Event()
|
|
79
|
+
with self._lock:
|
|
80
|
+
self._subscribers.append(q)
|
|
81
|
+
self._closed_signals[id(q)] = closed
|
|
82
|
+
return q, closed
|
|
83
|
+
|
|
84
|
+
def unsubscribe(self, q: queue.Queue[str]) -> None:
|
|
85
|
+
with self._lock:
|
|
86
|
+
if q in self._subscribers:
|
|
87
|
+
self._subscribers.remove(q)
|
|
88
|
+
self._closed_signals.pop(id(q), None)
|
|
89
|
+
|
|
90
|
+
def wake_all(self) -> None:
|
|
91
|
+
"""Signals active SSE subscriber loops to exit cleanly on server shutdown."""
|
|
92
|
+
with self._lock:
|
|
93
|
+
for q in self._subscribers:
|
|
94
|
+
ev = self._closed_signals.get(id(q))
|
|
95
|
+
if ev is not None:
|
|
96
|
+
ev.set()
|
|
97
|
+
_signal_queue_close(q)
|
|
98
|
+
|
|
99
|
+
def emit(self, event_type: str, payload: dict[str, Any]) -> None:
|
|
100
|
+
envelope = {
|
|
101
|
+
"event": event_type,
|
|
102
|
+
"ts": round(time.time(), 3),
|
|
103
|
+
**payload,
|
|
104
|
+
}
|
|
105
|
+
try:
|
|
106
|
+
serialized = json.dumps(envelope, ensure_ascii=False, allow_nan=False)
|
|
107
|
+
except ValueError:
|
|
108
|
+
serialized = json.dumps(envelope, ensure_ascii=False)
|
|
109
|
+
message = f"data: {serialized}\n\n"
|
|
110
|
+
with self._lock:
|
|
111
|
+
dead: list[queue.Queue[str]] = []
|
|
112
|
+
for q in self._subscribers:
|
|
113
|
+
try:
|
|
114
|
+
q.put_nowait(message)
|
|
115
|
+
except queue.Full:
|
|
116
|
+
dead.append(q)
|
|
117
|
+
for q in dead:
|
|
118
|
+
self._subscribers.remove(q)
|
|
119
|
+
ev = self._closed_signals.pop(id(q), None)
|
|
120
|
+
if ev is not None:
|
|
121
|
+
ev.set()
|
|
122
|
+
_signal_queue_close(q)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _signal_queue_close(q: queue.Queue[str]) -> None:
|
|
126
|
+
try:
|
|
127
|
+
q.put_nowait("")
|
|
128
|
+
return
|
|
129
|
+
except queue.Full:
|
|
130
|
+
pass
|
|
131
|
+
try:
|
|
132
|
+
q.get_nowait()
|
|
133
|
+
q.put_nowait("")
|
|
134
|
+
except (queue.Empty, queue.Full):
|
|
135
|
+
pass
|
microoflow/graph.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from graphlib import CycleError, TopologicalSorter
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .registry import NodeRegistry
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GraphError(ValueError):
|
|
11
|
+
"""Raised when a workflow graph has invalid nodes, wires, types, or cycles."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(slots=True)
|
|
15
|
+
class NodeInstance:
|
|
16
|
+
id: str
|
|
17
|
+
type_name: str
|
|
18
|
+
values: dict[str, Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(slots=True)
|
|
22
|
+
class Edge:
|
|
23
|
+
id: str
|
|
24
|
+
source: str
|
|
25
|
+
source_port: str
|
|
26
|
+
target: str
|
|
27
|
+
target_port: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(slots=True)
|
|
31
|
+
class CompiledGraph:
|
|
32
|
+
nodes: dict[str, NodeInstance]
|
|
33
|
+
edges: list[Edge]
|
|
34
|
+
order: list[str]
|
|
35
|
+
incoming: dict[tuple[str, str], Edge]
|
|
36
|
+
fanout: dict[tuple[str, str], int]
|
|
37
|
+
dependents: dict[str, set[str]]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def are_types_compatible(src_kind: str, dst_kind: str) -> bool:
|
|
41
|
+
if src_kind == "any" or dst_kind == "any":
|
|
42
|
+
return True
|
|
43
|
+
if src_kind == dst_kind:
|
|
44
|
+
return True
|
|
45
|
+
# Allow widening int -> float
|
|
46
|
+
if src_kind == "int" and dst_kind == "float":
|
|
47
|
+
return True
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _require_non_empty_str(raw: Any, message: str) -> str:
|
|
52
|
+
if not isinstance(raw, str):
|
|
53
|
+
raise GraphError(message)
|
|
54
|
+
value = raw.strip()
|
|
55
|
+
if not value:
|
|
56
|
+
raise GraphError(message)
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def compile_graph(payload: dict[str, Any], registry: NodeRegistry) -> CompiledGraph:
|
|
61
|
+
if not isinstance(payload, dict):
|
|
62
|
+
raise GraphError("Graph payload must be a JSON object.")
|
|
63
|
+
|
|
64
|
+
raw_nodes = payload.get("nodes", [])
|
|
65
|
+
raw_edges = payload.get("edges", [])
|
|
66
|
+
|
|
67
|
+
if not isinstance(raw_nodes, list) or not isinstance(raw_edges, list):
|
|
68
|
+
raise GraphError("Graph payload must include 'nodes' and 'edges' lists.")
|
|
69
|
+
|
|
70
|
+
nodes: dict[str, NodeInstance] = {}
|
|
71
|
+
for item in raw_nodes:
|
|
72
|
+
if not isinstance(item, dict):
|
|
73
|
+
raise GraphError("Every node entry must be an object.")
|
|
74
|
+
node_id = _require_non_empty_str(
|
|
75
|
+
item.get("id"), "Every node requires non-empty 'id' and 'type'."
|
|
76
|
+
)
|
|
77
|
+
type_name = _require_non_empty_str(
|
|
78
|
+
item.get("type"), "Every node requires non-empty 'id' and 'type'."
|
|
79
|
+
)
|
|
80
|
+
if node_id in nodes:
|
|
81
|
+
raise GraphError(f"Duplicate node id: '{node_id}'.")
|
|
82
|
+
# Ensure registered
|
|
83
|
+
registry.get(type_name)
|
|
84
|
+
raw_values = item.get("values")
|
|
85
|
+
values = {} if raw_values is None else raw_values
|
|
86
|
+
if not isinstance(values, dict):
|
|
87
|
+
raise GraphError(f"Node '{node_id}' values must be an object.")
|
|
88
|
+
nodes[node_id] = NodeInstance(id=node_id, type_name=type_name, values=values)
|
|
89
|
+
|
|
90
|
+
edges: list[Edge] = []
|
|
91
|
+
incoming: dict[tuple[str, str], Edge] = {}
|
|
92
|
+
fanout: dict[tuple[str, str], int] = {}
|
|
93
|
+
deps: dict[str, set[str]] = {nid: set() for nid in nodes}
|
|
94
|
+
dependents: dict[str, set[str]] = {nid: set() for nid in nodes}
|
|
95
|
+
|
|
96
|
+
for idx, raw in enumerate(raw_edges):
|
|
97
|
+
if not isinstance(raw, dict):
|
|
98
|
+
raise GraphError("Every edge entry must be an object.")
|
|
99
|
+
raw_edge_id = raw.get("id")
|
|
100
|
+
if raw_edge_id is None or raw_edge_id == "":
|
|
101
|
+
edge_id = f"edge_{idx}"
|
|
102
|
+
else:
|
|
103
|
+
edge_id = _require_non_empty_str(
|
|
104
|
+
raw_edge_id, f"Edge at index {idx} has an invalid 'id'."
|
|
105
|
+
)
|
|
106
|
+
source = _require_non_empty_str(
|
|
107
|
+
raw.get("source"), f"Edge '{edge_id}' requires non-empty 'source'."
|
|
108
|
+
)
|
|
109
|
+
source_port = _require_non_empty_str(
|
|
110
|
+
raw.get("source_port"), f"Edge '{edge_id}' requires non-empty 'source_port'."
|
|
111
|
+
)
|
|
112
|
+
target = _require_non_empty_str(
|
|
113
|
+
raw.get("target"), f"Edge '{edge_id}' requires non-empty 'target'."
|
|
114
|
+
)
|
|
115
|
+
target_port = _require_non_empty_str(
|
|
116
|
+
raw.get("target_port"), f"Edge '{edge_id}' requires non-empty 'target_port'."
|
|
117
|
+
)
|
|
118
|
+
edge = Edge(
|
|
119
|
+
id=edge_id,
|
|
120
|
+
source=source,
|
|
121
|
+
source_port=source_port,
|
|
122
|
+
target=target,
|
|
123
|
+
target_port=target_port,
|
|
124
|
+
)
|
|
125
|
+
if edge.source not in nodes:
|
|
126
|
+
raise GraphError(f"Edge '{edge.id}' references missing source '{edge.source}'.")
|
|
127
|
+
if edge.target not in nodes:
|
|
128
|
+
raise GraphError(f"Edge '{edge.id}' references missing target '{edge.target}'.")
|
|
129
|
+
if edge.source == edge.target:
|
|
130
|
+
raise GraphError(f"Self-loop detected on node '{edge.source}'.")
|
|
131
|
+
|
|
132
|
+
src_spec = registry.get(nodes[edge.source].type_name)
|
|
133
|
+
dst_spec = registry.get(nodes[edge.target].type_name)
|
|
134
|
+
|
|
135
|
+
if edge.source_port not in src_spec.outputs:
|
|
136
|
+
raise GraphError(
|
|
137
|
+
f"Output port '{edge.source_port}' not found on '{src_spec.type_name}'."
|
|
138
|
+
)
|
|
139
|
+
if edge.target_port not in dst_spec.inputs:
|
|
140
|
+
raise GraphError(
|
|
141
|
+
f"Input port '{edge.target_port}' not found on '{dst_spec.type_name}'."
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
dst_key = (edge.target, edge.target_port)
|
|
145
|
+
if dst_key in incoming:
|
|
146
|
+
raise GraphError(
|
|
147
|
+
f"Input '{edge.target}.{edge.target_port}' already has an incoming wire."
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
src_port = src_spec.outputs[edge.source_port]
|
|
151
|
+
dst_port = dst_spec.inputs[edge.target_port]
|
|
152
|
+
if not are_types_compatible(src_port.type_kind, dst_port.type_kind):
|
|
153
|
+
raise GraphError(
|
|
154
|
+
f"Type mismatch: '{src_port.type_label}' cannot connect to "
|
|
155
|
+
f"'{dst_port.type_label}'."
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
incoming[dst_key] = edge
|
|
159
|
+
src_key = (edge.source, edge.source_port)
|
|
160
|
+
fanout[src_key] = fanout.get(src_key, 0) + 1
|
|
161
|
+
deps[edge.target].add(edge.source)
|
|
162
|
+
dependents[edge.source].add(edge.target)
|
|
163
|
+
edges.append(edge)
|
|
164
|
+
|
|
165
|
+
sorter = TopologicalSorter(deps)
|
|
166
|
+
try:
|
|
167
|
+
order = list(sorter.static_order())
|
|
168
|
+
except CycleError as exc:
|
|
169
|
+
raise GraphError("Workflow contains a cycle and cannot be executed.") from exc
|
|
170
|
+
|
|
171
|
+
target_node_id = payload.get("target_node_id")
|
|
172
|
+
if target_node_id is not None:
|
|
173
|
+
if not isinstance(target_node_id, str):
|
|
174
|
+
raise GraphError(f"Unknown target node: '{target_node_id}'.")
|
|
175
|
+
target_id = target_node_id.strip()
|
|
176
|
+
if not target_id or target_id not in nodes:
|
|
177
|
+
raise GraphError(f"Unknown target node: '{target_id}'.")
|
|
178
|
+
keep: set[str] = set()
|
|
179
|
+
stack = [target_id]
|
|
180
|
+
while stack:
|
|
181
|
+
cur = stack.pop()
|
|
182
|
+
if cur not in keep:
|
|
183
|
+
keep.add(cur)
|
|
184
|
+
stack.extend(deps[cur])
|
|
185
|
+
order = [nid for nid in order if nid in keep]
|
|
186
|
+
|
|
187
|
+
return CompiledGraph(
|
|
188
|
+
nodes=nodes,
|
|
189
|
+
edges=edges,
|
|
190
|
+
order=order,
|
|
191
|
+
incoming=incoming,
|
|
192
|
+
fanout=fanout,
|
|
193
|
+
dependents=dependents,
|
|
194
|
+
)
|
microoflow/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|