kairo-sdk 0.1.0__tar.gz
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.
- kairo_sdk-0.1.0/PKG-INFO +10 -0
- kairo_sdk-0.1.0/README.md +51 -0
- kairo_sdk-0.1.0/kairo_sdk/__init__.py +45 -0
- kairo_sdk-0.1.0/kairo_sdk/backend.py +163 -0
- kairo_sdk-0.1.0/kairo_sdk/client.py +104 -0
- kairo_sdk-0.1.0/kairo_sdk/core.py +103 -0
- kairo_sdk-0.1.0/kairo_sdk/embedded.py +472 -0
- kairo_sdk-0.1.0/kairo_sdk/graphon.py +231 -0
- kairo_sdk-0.1.0/kairo_sdk/http.py +87 -0
- kairo_sdk-0.1.0/kairo_sdk/protocol.py +139 -0
- kairo_sdk-0.1.0/kairo_sdk/serve.py +41 -0
- kairo_sdk-0.1.0/kairo_sdk/store.py +423 -0
- kairo_sdk-0.1.0/kairo_sdk/wasm/kairo.wasm +0 -0
- kairo_sdk-0.1.0/kairo_sdk/worker.py +200 -0
- kairo_sdk-0.1.0/kairo_sdk/workflow.py +649 -0
- kairo_sdk-0.1.0/kairo_sdk.egg-info/PKG-INFO +10 -0
- kairo_sdk-0.1.0/kairo_sdk.egg-info/SOURCES.txt +26 -0
- kairo_sdk-0.1.0/kairo_sdk.egg-info/dependency_links.txt +1 -0
- kairo_sdk-0.1.0/kairo_sdk.egg-info/requires.txt +6 -0
- kairo_sdk-0.1.0/kairo_sdk.egg-info/top_level.txt +1 -0
- kairo_sdk-0.1.0/pyproject.toml +26 -0
- kairo_sdk-0.1.0/setup.cfg +4 -0
- kairo_sdk-0.1.0/tests/test_embedded.py +252 -0
- kairo_sdk-0.1.0/tests/test_http.py +383 -0
- kairo_sdk-0.1.0/tests/test_retention.py +215 -0
- kairo_sdk-0.1.0/tests/test_schedule.py +165 -0
- kairo_sdk-0.1.0/tests/test_worker.py +101 -0
- kairo_sdk-0.1.0/tests/test_workflow.py +277 -0
kairo_sdk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kairo-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SDK for the kairo workflow runtime: workflows written as code, run by the runtime embedded here (a WASM core and a database) or by kairod; the worker protocol; graphon (Dify) nodes as kairo tasks.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Provides-Extra: embedded
|
|
8
|
+
Requires-Dist: wasmtime; extra == "embedded"
|
|
9
|
+
Provides-Extra: graphon
|
|
10
|
+
Requires-Dist: graphon==0.7.0; extra == "graphon"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# kairo-sdk — kairo の SDK(Python)
|
|
2
|
+
|
|
3
|
+
kairo のワーカープロトコル(ADR 0009。取り消しは ADR 0026)の Python 実装と、Dify のワークフローのノード(graphon)を kairo のタスクとして実行する実行器です(ADR 0028)。
|
|
4
|
+
|
|
5
|
+
## ワーカー
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from kairo_sdk import Result, Worker
|
|
9
|
+
|
|
10
|
+
def handler(task, ctx):
|
|
11
|
+
ctx.emit("streamed text") # ライブの出力
|
|
12
|
+
if ctx.cancelled.is_set(): # 手順が打ち切られた(ADR 0026)
|
|
13
|
+
return Result(error="cancelled", retryable=True)
|
|
14
|
+
return Result(output={"echo": task.input}, meta={"usage": 1})
|
|
15
|
+
|
|
16
|
+
Worker("py-1", ["my.action"], handler, concurrency=8).run("/path/to/worker.sock")
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- ハンドラは、取り消されたときも必ず `Result` を返します。返すことで、ランタイム側の同時実行の枠とクレジットが空きます。
|
|
20
|
+
- 失敗は、確定した失敗(`retryable`)と、結果が不明なもの(`unknown`)を分けて返します。
|
|
21
|
+
- 依存はありません(標準ライブラリだけ)。
|
|
22
|
+
|
|
23
|
+
## graphon のノードの実行(`kairo_sdk.graphon`)
|
|
24
|
+
|
|
25
|
+
`compat/dify` が変換したワークフローの `dify.<種類>` のステップを、graphon 0.7.0 のノードで実行します。
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from kairo_sdk import Worker
|
|
29
|
+
from kairo_sdk.graphon import GraphonNodeRunner, slim_factory
|
|
30
|
+
|
|
31
|
+
runner = GraphonNodeRunner(slim_factory()) # Dify では DifyNodeFactory を作る関数を渡す
|
|
32
|
+
Worker("graphon", ["dify.template-transform", "dify.http-request"], runner).run(sock)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
コマンドとしても起動できます: `python -m kairo_sdk.serve --socket <path> --actions dify.template-transform,dify.http-request`
|
|
36
|
+
|
|
37
|
+
- **入力:** タスクの入力(セレクタ → 値)を新しい変数プールに入れ、ノードを作って実行します。
|
|
38
|
+
- **出力:**
|
|
39
|
+
- ストリームのチャンクは、ライブの出力として送ります。
|
|
40
|
+
- 出力はタスクの出力にします。
|
|
41
|
+
- `inputs`、`process_data`、`metadata` は `meta` に入れます(実行イベントの出口、ADR 0034)。
|
|
42
|
+
- **失敗:**
|
|
43
|
+
- graphon の `error_type` をエラーの種類にします。
|
|
44
|
+
- 外部に作用するノード(http-request、tool、agent)がタイムアウトや切断で失敗したときは、「結果が不明」として返します(ADR 0035)。
|
|
45
|
+
|
|
46
|
+
## テスト
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
python3 -m unittest discover -s tests # プロトコルとワーカー(依存なし)
|
|
50
|
+
GRAPHON_PYTHON=/path/to/python go test ./compat/dify -run EndToEnd # graphon のノードを含むエンドツーエンド
|
|
51
|
+
```
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""SDK for kairo (ADR 0009, 0026, 0028, 0049).
|
|
2
|
+
|
|
3
|
+
A worker connects to the runtime, announces the actions it serves and how
|
|
4
|
+
many tasks it can hold, and pulls tasks. ``Worker`` runs a handler per task
|
|
5
|
+
on a pool of threads; ``kairo_sdk.graphon`` runs Dify's workflow nodes
|
|
6
|
+
(graphon) as such handlers. ``Client`` is the graph API (kairod's HTTP
|
|
7
|
+
API); ``Kairo`` declares actions and workflows written as code.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .backend import Backend, EmbeddedBackend, HttpBackend
|
|
11
|
+
from .client import Client, KairoError
|
|
12
|
+
from .http import SignatureError
|
|
13
|
+
from .protocol import Cancel, Chunk, Credit, Hello, MsgType, ProtocolError, Result, read_frame, write_frame
|
|
14
|
+
from .worker import Task, TaskContext, Worker
|
|
15
|
+
from .store import PostgresStore, SQLiteStore
|
|
16
|
+
from .workflow import Cancelled, Context, Kairo, ResultLostError, Suspended, tick_handler
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Backend",
|
|
20
|
+
"EmbeddedBackend",
|
|
21
|
+
"HttpBackend",
|
|
22
|
+
"PostgresStore",
|
|
23
|
+
"SQLiteStore",
|
|
24
|
+
"Suspended",
|
|
25
|
+
"Cancel",
|
|
26
|
+
"Cancelled",
|
|
27
|
+
"Client",
|
|
28
|
+
"Context",
|
|
29
|
+
"Kairo",
|
|
30
|
+
"KairoError",
|
|
31
|
+
"ResultLostError",
|
|
32
|
+
"Chunk",
|
|
33
|
+
"Credit",
|
|
34
|
+
"Hello",
|
|
35
|
+
"MsgType",
|
|
36
|
+
"ProtocolError",
|
|
37
|
+
"Result",
|
|
38
|
+
"SignatureError",
|
|
39
|
+
"Task",
|
|
40
|
+
"TaskContext",
|
|
41
|
+
"Worker",
|
|
42
|
+
"read_frame",
|
|
43
|
+
"tick_handler",
|
|
44
|
+
"write_frame",
|
|
45
|
+
]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Where workflows written as code run their calls (ADR 0049, 0051): kairod
|
|
2
|
+
over HTTP and the worker protocol, or the runtime embedded in this process
|
|
3
|
+
with a database."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from typing import Any, Protocol
|
|
13
|
+
|
|
14
|
+
from .client import Client
|
|
15
|
+
from .embedded import ActionHandler, Embedded
|
|
16
|
+
from .protocol import Result
|
|
17
|
+
from .store import Store
|
|
18
|
+
from .worker import Worker
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Backend(Protocol):
|
|
22
|
+
async def start(self, specs: list[dict[str, Any]], serve: ActionHandler) -> None:
|
|
23
|
+
"""Registers the actions, and runs their steps with serve (here, or on a worker)."""
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
async def register_plan(self, definition: dict[str, Any]) -> None: ...
|
|
27
|
+
|
|
28
|
+
async def run(
|
|
29
|
+
self, plan: str, input: Any, *, run_id: str, vars: dict[str, Any] | None = None, parent: str | None = None
|
|
30
|
+
) -> dict[str, Any]:
|
|
31
|
+
"""Starts a run, or finds it: the run id is an idempotency key. Runs are durable.
|
|
32
|
+
parent: the run that makes this one (the embedded runtime keeps and
|
|
33
|
+
removes them together, ADR 0054)."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
async def get(self, run_id: str) -> dict[str, Any]:
|
|
37
|
+
"""Raises KairoError 404 for a run that does not exist."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
async def wait(self, run_id: str) -> dict[str, Any]: ...
|
|
41
|
+
async def signal(self, run_id: str, name: str, payload: Any) -> None: ...
|
|
42
|
+
async def cancel(self, run_id: str) -> None: ...
|
|
43
|
+
async def close(self) -> None: ...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class HttpBackend:
|
|
47
|
+
"""kairod: its HTTP API, and a worker that pulls this process's actions."""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
url: str = "http://127.0.0.1:8420",
|
|
52
|
+
*,
|
|
53
|
+
worker: str | tuple[str, int] | None = None,
|
|
54
|
+
token: str = "",
|
|
55
|
+
tenant: str = "default",
|
|
56
|
+
concurrency: int | None = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
self.client = Client(url)
|
|
59
|
+
self._addr = worker
|
|
60
|
+
self._token = token
|
|
61
|
+
self._tenant = tenant
|
|
62
|
+
self._concurrency = concurrency
|
|
63
|
+
self._worker: Worker | None = None
|
|
64
|
+
|
|
65
|
+
async def start(self, specs: list[dict[str, Any]], serve: ActionHandler) -> None:
|
|
66
|
+
await asyncio.to_thread(self.client.register_nodes, specs)
|
|
67
|
+
if self._addr is None:
|
|
68
|
+
return
|
|
69
|
+
self._worker = Worker(f"kairo-sdk-{os.getpid()}", [s["action"] for s in specs], serve, self._concurrency, token=self._token)
|
|
70
|
+
threading.Thread(target=self._serve_forever, args=(self._worker,), daemon=True).start()
|
|
71
|
+
|
|
72
|
+
def _serve_forever(self, w: Worker) -> None:
|
|
73
|
+
while self._worker is w:
|
|
74
|
+
try:
|
|
75
|
+
w.run(self._addr) # type: ignore[arg-type]
|
|
76
|
+
except OSError:
|
|
77
|
+
pass # kairod went away: connect again
|
|
78
|
+
if self._worker is w:
|
|
79
|
+
time.sleep(0.5)
|
|
80
|
+
|
|
81
|
+
async def register_plan(self, definition: dict[str, Any]) -> None:
|
|
82
|
+
await asyncio.to_thread(self.client.register_plan, definition)
|
|
83
|
+
|
|
84
|
+
async def run(
|
|
85
|
+
self, plan: str, input: Any, *, run_id: str, vars: dict[str, Any] | None = None, parent: str | None = None
|
|
86
|
+
) -> dict[str, Any]:
|
|
87
|
+
return await asyncio.to_thread(lambda: self.client.run(plan, input, run_id=run_id, tenant=self._tenant, tier="file", vars=vars))
|
|
88
|
+
|
|
89
|
+
async def get(self, run_id: str) -> dict[str, Any]:
|
|
90
|
+
return await asyncio.to_thread(self.client.get, run_id)
|
|
91
|
+
|
|
92
|
+
async def wait(self, run_id: str) -> dict[str, Any]:
|
|
93
|
+
while True:
|
|
94
|
+
r = await asyncio.to_thread(self.client.wait_once, run_id)
|
|
95
|
+
if r is not None:
|
|
96
|
+
return r
|
|
97
|
+
|
|
98
|
+
async def signal(self, run_id: str, name: str, payload: Any) -> None:
|
|
99
|
+
await asyncio.to_thread(self.client.signal, run_id, name, payload)
|
|
100
|
+
|
|
101
|
+
async def cancel(self, run_id: str) -> None:
|
|
102
|
+
await asyncio.to_thread(self.client.cancel, run_id)
|
|
103
|
+
|
|
104
|
+
async def close(self) -> None:
|
|
105
|
+
w, self._worker = self._worker, None
|
|
106
|
+
if w is not None:
|
|
107
|
+
w.stop()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class EmbeddedBackend:
|
|
111
|
+
"""The runtime embedded in this process, with a database (ADR 0051)."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, runtime: Embedded) -> None:
|
|
114
|
+
self.runtime = runtime
|
|
115
|
+
|
|
116
|
+
@classmethod
|
|
117
|
+
async def open(cls, store: Store, **kw: Any) -> EmbeddedBackend:
|
|
118
|
+
"""Opens the runtime on store (kw: wasm, lease_ms, owner, now)."""
|
|
119
|
+
return cls(await Embedded(store, **kw).open())
|
|
120
|
+
|
|
121
|
+
async def start(self, specs: list[dict[str, Any]], serve: ActionHandler) -> None:
|
|
122
|
+
self.runtime.register_actions(specs, serve)
|
|
123
|
+
|
|
124
|
+
async def register_plan(self, definition: dict[str, Any]) -> None:
|
|
125
|
+
self.runtime.register_plan(definition)
|
|
126
|
+
|
|
127
|
+
#: Keeps a workflow's calls while it runs, however long (ADR 0054).
|
|
128
|
+
keeps_calls = True
|
|
129
|
+
|
|
130
|
+
async def run(
|
|
131
|
+
self, plan: str, input: Any, *, run_id: str, vars: dict[str, Any] | None = None, parent: str | None = None
|
|
132
|
+
) -> dict[str, Any]:
|
|
133
|
+
return await self.runtime.run(plan, input, run_id=run_id, vars=vars, parent=parent)
|
|
134
|
+
|
|
135
|
+
async def get(self, run_id: str) -> dict[str, Any]:
|
|
136
|
+
return await self.runtime.get(run_id)
|
|
137
|
+
|
|
138
|
+
async def wait(self, run_id: str) -> dict[str, Any]:
|
|
139
|
+
return await self.runtime.wait(run_id)
|
|
140
|
+
|
|
141
|
+
async def signal(self, run_id: str, name: str, payload: Any) -> None:
|
|
142
|
+
await self.runtime.signal(run_id, name, payload)
|
|
143
|
+
|
|
144
|
+
async def cancel(self, run_id: str) -> None:
|
|
145
|
+
await self.runtime.cancel(run_id)
|
|
146
|
+
|
|
147
|
+
async def close(self) -> None:
|
|
148
|
+
await self.runtime.close()
|
|
149
|
+
|
|
150
|
+
async def idle(self) -> None:
|
|
151
|
+
await self.runtime.idle()
|
|
152
|
+
|
|
153
|
+
def on_settled(self, hook: Callable[[dict[str, Any]], None]) -> Callable[[], None]:
|
|
154
|
+
return self.runtime.on_settled(hook)
|
|
155
|
+
|
|
156
|
+
async def tick(self) -> None:
|
|
157
|
+
await self.runtime.tick()
|
|
158
|
+
|
|
159
|
+
async def next_wake(self) -> int | None:
|
|
160
|
+
return await self.runtime.next_wake()
|
|
161
|
+
|
|
162
|
+
async def complete(self, run_id: str, act: int, attempt: int, res: Result) -> None:
|
|
163
|
+
await self.runtime.complete(run_id, act, attempt, res)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The graph API (ADR 0049): a thin client of kairod's HTTP API (/v1/...)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
DONE = ("completed", "failed", "cancelled")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class KairoError(Exception):
|
|
15
|
+
def __init__(self, status: int, message: str) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status = status
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def finished(run: dict[str, Any]) -> bool:
|
|
21
|
+
"""Whether a run (engine.RunInfo) has finished."""
|
|
22
|
+
return run.get("status") in DONE
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Client:
|
|
26
|
+
"""Calls kairod's HTTP API. Blocking; the workflow API runs it on threads."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, url: str = "http://127.0.0.1:8420", timeout: float = 90.0) -> None:
|
|
29
|
+
self.url = url.rstrip("/")
|
|
30
|
+
self.timeout = timeout
|
|
31
|
+
|
|
32
|
+
def _call(self, method: str, path: str, body: Any = None) -> tuple[int, Any]:
|
|
33
|
+
data = None if body is None else json.dumps(body).encode()
|
|
34
|
+
req = urllib.request.Request(self.url + path, data=data, method=method)
|
|
35
|
+
if data is not None:
|
|
36
|
+
req.add_header("Content-Type", "application/json")
|
|
37
|
+
try:
|
|
38
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
39
|
+
status, text = res.status, res.read()
|
|
40
|
+
except urllib.error.HTTPError as e:
|
|
41
|
+
with e:
|
|
42
|
+
status, text = e.code, e.read()
|
|
43
|
+
out = json.loads(text) if text else None
|
|
44
|
+
if status >= 400 and status != 504:
|
|
45
|
+
msg = out.get("error") if isinstance(out, dict) else None
|
|
46
|
+
raise KairoError(status, msg or f"{method} {path}: {status}")
|
|
47
|
+
return status, out
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def _id(run_id: str) -> str:
|
|
51
|
+
return urllib.parse.quote(run_id, safe="")
|
|
52
|
+
|
|
53
|
+
def register_nodes(self, specs: list[dict[str, Any]]) -> None:
|
|
54
|
+
"""Registers node specs (ir.NodeSpec): effect is "real" (the default) or "unprotected"."""
|
|
55
|
+
self._call("POST", "/v1/nodes", specs)
|
|
56
|
+
|
|
57
|
+
def register_plan(self, definition: dict[str, Any]) -> dict[str, Any]:
|
|
58
|
+
"""Registers a plan (a workflow definition, ir.Definition)."""
|
|
59
|
+
return self._call("POST", "/v1/plans", definition)[1]
|
|
60
|
+
|
|
61
|
+
def run(
|
|
62
|
+
self,
|
|
63
|
+
plan: str,
|
|
64
|
+
input: Any,
|
|
65
|
+
*,
|
|
66
|
+
run_id: str = "",
|
|
67
|
+
tenant: str = "default",
|
|
68
|
+
tier: str = "",
|
|
69
|
+
vars: dict[str, Any] | None = None,
|
|
70
|
+
) -> dict[str, Any]:
|
|
71
|
+
"""Starts a run of plan once its start is durable. With a run id already
|
|
72
|
+
running or recently finished, nothing new starts ("existing")."""
|
|
73
|
+
body: dict[str, Any] = {"plan": plan, "input": input, "tenant": tenant}
|
|
74
|
+
if run_id:
|
|
75
|
+
body["run_id"] = run_id
|
|
76
|
+
if tier:
|
|
77
|
+
body["tier"] = tier
|
|
78
|
+
if vars:
|
|
79
|
+
body["vars"] = vars
|
|
80
|
+
status, out = self._call("POST", "/v1/runs", body)
|
|
81
|
+
if status == 504:
|
|
82
|
+
raise KairoError(504, f"run {out.get('run_id')}: start not confirmed")
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
def get(self, run_id: str) -> dict[str, Any]:
|
|
86
|
+
return self._call("GET", f"/v1/runs/{self._id(run_id)}")[1]
|
|
87
|
+
|
|
88
|
+
def wait(self, run_id: str, poll: str = "10s") -> dict[str, Any]:
|
|
89
|
+
"""Waits until the run has finished."""
|
|
90
|
+
while True:
|
|
91
|
+
status, out = self._call("GET", f"/v1/runs/{self._id(run_id)}/wait?timeout={poll}")
|
|
92
|
+
if status == 200:
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
def wait_once(self, run_id: str, poll: str = "10s") -> dict[str, Any] | None:
|
|
96
|
+
"""The finished run, or None if it is still going after poll."""
|
|
97
|
+
status, out = self._call("GET", f"/v1/runs/{self._id(run_id)}/wait?timeout={poll}")
|
|
98
|
+
return out if status == 200 else None
|
|
99
|
+
|
|
100
|
+
def signal(self, run_id: str, name: str, payload: Any = None) -> None:
|
|
101
|
+
self._call("POST", f"/v1/runs/{self._id(run_id)}/signals/{urllib.parse.quote(name, safe='')}", payload)
|
|
102
|
+
|
|
103
|
+
def cancel(self, run_id: str) -> None:
|
|
104
|
+
self._call("POST", f"/v1/runs/{self._id(run_id)}/cancel")
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""The pure core of kairo as a WASM module (cmd/kairo-wasm, ADR 0051).
|
|
2
|
+
|
|
3
|
+
Plans are compiled once, then events applied to a run's state given as
|
|
4
|
+
bytes. No I/O happens here; the embedded runtime reads and writes the state.
|
|
5
|
+
Needs wasmtime (``pip install "kairo-sdk[embedded]"``).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import struct
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
#: The ABI version this SDK speaks (wasmcore.ABIVersion).
|
|
16
|
+
ABI_VERSION = 1
|
|
17
|
+
|
|
18
|
+
DEFAULT_WASM = Path(__file__).parent / "wasm" / "kairo.wasm"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CoreError(Exception):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Core:
|
|
26
|
+
def __init__(self, wasm: str | Path | bytes | None = None) -> None:
|
|
27
|
+
try:
|
|
28
|
+
from wasmtime import Engine, Linker, Module, Store, WasiConfig
|
|
29
|
+
except ImportError as e: # pragma: no cover - depends on the install
|
|
30
|
+
raise CoreError("the embedded runtime needs wasmtime: pip install 'kairo-sdk[embedded]'") from e
|
|
31
|
+
engine = Engine()
|
|
32
|
+
data = wasm if isinstance(wasm, bytes) else Path(wasm or DEFAULT_WASM).read_bytes()
|
|
33
|
+
module = Module(engine, data)
|
|
34
|
+
self._store = Store(engine)
|
|
35
|
+
self._store.set_wasi(WasiConfig())
|
|
36
|
+
linker = Linker(engine)
|
|
37
|
+
linker.define_wasi()
|
|
38
|
+
ex = linker.instantiate(self._store, module).exports(self._store)
|
|
39
|
+
ex["_initialize"](self._store)
|
|
40
|
+
self._mem = ex["memory"]
|
|
41
|
+
self._alloc = ex["kairo_alloc"]
|
|
42
|
+
self._free = ex["kairo_free"]
|
|
43
|
+
self._result = ex["kairo_result"]
|
|
44
|
+
self._register = ex["kairo_register"]
|
|
45
|
+
self._compile = ex["kairo_compile"]
|
|
46
|
+
self._apply = ex["kairo_apply"]
|
|
47
|
+
v = ex["kairo_abi_version"](self._store)
|
|
48
|
+
if v != ABI_VERSION:
|
|
49
|
+
raise CoreError(f"kairo.wasm speaks ABI {v}, this SDK {ABI_VERSION}")
|
|
50
|
+
|
|
51
|
+
def _put(self, b: bytes) -> tuple[int, int]:
|
|
52
|
+
if not b:
|
|
53
|
+
return 0, 0
|
|
54
|
+
p = self._alloc(self._store, len(b))
|
|
55
|
+
self._mem.write(self._store, b, p)
|
|
56
|
+
return p, len(b)
|
|
57
|
+
|
|
58
|
+
def _read(self, n: int) -> bytes:
|
|
59
|
+
p = self._result(self._store)
|
|
60
|
+
b = bytes(self._mem.read(self._store, p, p + abs(n))) if n else b""
|
|
61
|
+
if n < 0:
|
|
62
|
+
raise CoreError(b.decode())
|
|
63
|
+
return b
|
|
64
|
+
|
|
65
|
+
def _call(self, f: Any, *bufs: bytes) -> bytes:
|
|
66
|
+
args: list[int] = []
|
|
67
|
+
ptrs: list[int] = []
|
|
68
|
+
for b in bufs:
|
|
69
|
+
p, n = self._put(b)
|
|
70
|
+
args += [p, n]
|
|
71
|
+
if p:
|
|
72
|
+
ptrs.append(p)
|
|
73
|
+
try:
|
|
74
|
+
return self._read(f(self._store, *args))
|
|
75
|
+
finally:
|
|
76
|
+
for p in ptrs:
|
|
77
|
+
self._free(self._store, p)
|
|
78
|
+
|
|
79
|
+
def register(self, specs: list[dict[str, Any]]) -> None:
|
|
80
|
+
"""Registers node specs (ir.NodeSpec)."""
|
|
81
|
+
self._call(self._register, json.dumps(specs).encode())
|
|
82
|
+
|
|
83
|
+
def compile(self, definition: dict[str, Any]) -> dict[str, Any]:
|
|
84
|
+
"""Compiles a workflow definition (ir.Definition): {plan, name, hash, has_real, effects}."""
|
|
85
|
+
return json.loads(self._call(self._compile, json.dumps(definition).encode()))
|
|
86
|
+
|
|
87
|
+
def apply(self, plan: int, run_id: str, state: bytes, event: dict[str, Any], traced: bool = False) -> tuple[bytes, dict[str, Any]]:
|
|
88
|
+
"""Applies event (wasmcore.Event) to a run's state (empty for a new run)."""
|
|
89
|
+
bufs = [run_id.encode(), state, json.dumps(event).encode()]
|
|
90
|
+
args: list[int] = []
|
|
91
|
+
ptrs: list[int] = []
|
|
92
|
+
for b in bufs:
|
|
93
|
+
p, n = self._put(b)
|
|
94
|
+
args += [p, n]
|
|
95
|
+
if p:
|
|
96
|
+
ptrs.append(p)
|
|
97
|
+
try:
|
|
98
|
+
out = self._read(self._apply(self._store, plan, *args, 1 if traced else 0))
|
|
99
|
+
finally:
|
|
100
|
+
for p in ptrs:
|
|
101
|
+
self._free(self._store, p)
|
|
102
|
+
n = struct.unpack_from("<I", out, 0)[0]
|
|
103
|
+
return out[4 : 4 + n], json.loads(out[4 + n :])
|