forge-worker-sdk 0.0.12__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.
- forge_worker_sdk-0.0.12/PKG-INFO +51 -0
- forge_worker_sdk-0.0.12/README.md +27 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/__init__.py +43 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/dispatcher.py +161 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/framing.py +72 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/job_registry.py +164 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/protocol.py +92 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk/server.py +163 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk.egg-info/PKG-INFO +51 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk.egg-info/SOURCES.txt +16 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk.egg-info/dependency_links.txt +1 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk.egg-info/requires.txt +4 -0
- forge_worker_sdk-0.0.12/forge_worker_sdk.egg-info/top_level.txt +1 -0
- forge_worker_sdk-0.0.12/pyproject.toml +50 -0
- forge_worker_sdk-0.0.12/setup.cfg +4 -0
- forge_worker_sdk-0.0.12/tests/test_event_fixture.py +21 -0
- forge_worker_sdk-0.0.12/tests/test_protocol_fixtures.py +112 -0
- forge_worker_sdk-0.0.12/tests/test_streaming_cancel.py +89 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: forge-worker-sdk
|
|
3
|
+
Version: 0.0.12
|
|
4
|
+
Summary: Organizyio Forge — Python worker IPC SDK (framing, server runtime, job registry, dispatcher).
|
|
5
|
+
Author-email: Organizyio <opensource@organizy.io>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/organizyio/forge
|
|
8
|
+
Project-URL: Repository, https://github.com/organizyio/forge
|
|
9
|
+
Project-URL: Documentation, https://github.com/organizyio/forge/blob/main/docs/python-worker.md
|
|
10
|
+
Project-URL: Changelog, https://github.com/organizyio/forge/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: forge,ipc,worker,msgpack,organizy
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: msgpack>=1.0.0
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
|
|
25
|
+
# forge-worker-sdk (Python)
|
|
26
|
+
|
|
27
|
+
Python peer of the Rust `forge-worker-sdk` crate. Speaks Forge framed IPC over Unix domain sockets or framed stdio.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install forge-worker-sdk
|
|
33
|
+
# or
|
|
34
|
+
uv add forge-worker-sdk
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
From source (contrib / tests):
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
cd forge/python
|
|
41
|
+
python3 -m pip install -e ".[dev]"
|
|
42
|
+
FORGE_WORKER_TEST=1 pytest
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Example worker
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
python3 examples/minimal-python-worker/main.py --socket /tmp/forge-py.sock --encoding json
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
See [docs/python-worker.md](../docs/python-worker.md).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# forge-worker-sdk (Python)
|
|
2
|
+
|
|
3
|
+
Python peer of the Rust `forge-worker-sdk` crate. Speaks Forge framed IPC over Unix domain sockets or framed stdio.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install forge-worker-sdk
|
|
9
|
+
# or
|
|
10
|
+
uv add forge-worker-sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
From source (contrib / tests):
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cd forge/python
|
|
17
|
+
python3 -m pip install -e ".[dev]"
|
|
18
|
+
FORGE_WORKER_TEST=1 pytest
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Example worker
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python3 examples/minimal-python-worker/main.py --socket /tmp/forge-py.sock --encoding json
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
See [docs/python-worker.md](../docs/python-worker.md).
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Forge Python worker SDK — framed IPC with a Go supervisor."""
|
|
2
|
+
|
|
3
|
+
from forge_worker_sdk.dispatcher import (
|
|
4
|
+
BaseDispatcher,
|
|
5
|
+
WorkerHandler,
|
|
6
|
+
err_response,
|
|
7
|
+
ok_response,
|
|
8
|
+
unknown_method,
|
|
9
|
+
)
|
|
10
|
+
from forge_worker_sdk.framing import (
|
|
11
|
+
KIND_EVENT,
|
|
12
|
+
KIND_REQUEST,
|
|
13
|
+
KIND_RESPONSE,
|
|
14
|
+
MAX_FRAME_PAYLOAD,
|
|
15
|
+
Encoding,
|
|
16
|
+
Frame,
|
|
17
|
+
)
|
|
18
|
+
from forge_worker_sdk.job_registry import Job, JobRegistry, JobState
|
|
19
|
+
from forge_worker_sdk.protocol import ErrorPayload, WireEvent, WireRequest, WireResponse
|
|
20
|
+
from forge_worker_sdk.server import run_worker, run_worker_stdio
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"BaseDispatcher",
|
|
24
|
+
"WorkerHandler",
|
|
25
|
+
"ok_response",
|
|
26
|
+
"err_response",
|
|
27
|
+
"unknown_method",
|
|
28
|
+
"KIND_REQUEST",
|
|
29
|
+
"KIND_RESPONSE",
|
|
30
|
+
"KIND_EVENT",
|
|
31
|
+
"MAX_FRAME_PAYLOAD",
|
|
32
|
+
"Encoding",
|
|
33
|
+
"Frame",
|
|
34
|
+
"Job",
|
|
35
|
+
"JobRegistry",
|
|
36
|
+
"JobState",
|
|
37
|
+
"ErrorPayload",
|
|
38
|
+
"WireEvent",
|
|
39
|
+
"WireRequest",
|
|
40
|
+
"WireResponse",
|
|
41
|
+
"run_worker",
|
|
42
|
+
"run_worker_stdio",
|
|
43
|
+
]
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Control-plane BaseDispatcher and WorkerHandler protocol."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Protocol, runtime_checkable
|
|
9
|
+
|
|
10
|
+
from forge_worker_sdk.framing import Encoding
|
|
11
|
+
from forge_worker_sdk.job_registry import JobRegistry, JobState
|
|
12
|
+
from forge_worker_sdk.protocol import ErrorPayload, WireRequest, WireResponse
|
|
13
|
+
|
|
14
|
+
DEFAULT_SHUTDOWN_DELAY_MS = 100
|
|
15
|
+
MAX_SHUTDOWN_DELAY_MS = 5 * 60 * 1000
|
|
16
|
+
|
|
17
|
+
EventSink = Any # Callable[[WireEvent], None] — kept loose for handler signature
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@runtime_checkable
|
|
21
|
+
class WorkerHandler(Protocol):
|
|
22
|
+
def handle_method(
|
|
23
|
+
self,
|
|
24
|
+
req_id: str,
|
|
25
|
+
method: str,
|
|
26
|
+
params: Any,
|
|
27
|
+
event_sink: EventSink,
|
|
28
|
+
registry: JobRegistry,
|
|
29
|
+
) -> WireResponse: ...
|
|
30
|
+
|
|
31
|
+
def worker_version(self) -> str: ...
|
|
32
|
+
|
|
33
|
+
def features(self) -> list[str]: ...
|
|
34
|
+
|
|
35
|
+
def max_concurrent_jobs(self) -> int:
|
|
36
|
+
return 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def ok_response(req_id: str, payload: Any) -> WireResponse:
|
|
40
|
+
return WireResponse(id=req_id, ok=True, payload=payload)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def err_response(req_id: str, code: str, message: str) -> WireResponse:
|
|
44
|
+
return WireResponse(
|
|
45
|
+
id=req_id,
|
|
46
|
+
ok=False,
|
|
47
|
+
error=ErrorPayload(code=code, message=message),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def unknown_method(req_id: str, method: str) -> WireResponse:
|
|
52
|
+
return err_response(req_id, "UNKNOWN_METHOD", f"unknown method: {method}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _str_param(params: Any, key: str) -> str:
|
|
56
|
+
if not isinstance(params, dict):
|
|
57
|
+
return ""
|
|
58
|
+
v = params.get(key)
|
|
59
|
+
return str(v) if v is not None else ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _shutdown_delay_ms(params: Any) -> int:
|
|
63
|
+
if not isinstance(params, dict) or "delay_ms" not in params:
|
|
64
|
+
return DEFAULT_SHUTDOWN_DELAY_MS
|
|
65
|
+
v = params["delay_ms"]
|
|
66
|
+
try:
|
|
67
|
+
n = int(v)
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
return DEFAULT_SHUTDOWN_DELAY_MS
|
|
70
|
+
if n < 0:
|
|
71
|
+
return DEFAULT_SHUTDOWN_DELAY_MS
|
|
72
|
+
return min(n, MAX_SHUTDOWN_DELAY_MS)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class BaseDispatcher:
|
|
76
|
+
def __init__(self, handler: WorkerHandler, encoding: Encoding) -> None:
|
|
77
|
+
self.handler = handler
|
|
78
|
+
self.registry = JobRegistry()
|
|
79
|
+
self.encoding = encoding
|
|
80
|
+
self._start = time.monotonic()
|
|
81
|
+
self._accepting = True
|
|
82
|
+
self._test_mode = os.environ.get("FORGE_WORKER_TEST", "").strip() in {
|
|
83
|
+
"1",
|
|
84
|
+
"true",
|
|
85
|
+
"yes",
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
def dispatch(self, req: WireRequest, event_sink: EventSink) -> WireResponse:
|
|
89
|
+
method = req.method
|
|
90
|
+
params = req.params
|
|
91
|
+
rid = req.id
|
|
92
|
+
|
|
93
|
+
if method == "ping":
|
|
94
|
+
return ok_response(rid, {"pong": True})
|
|
95
|
+
|
|
96
|
+
if method == "health":
|
|
97
|
+
active = self.registry.active_count()
|
|
98
|
+
return ok_response(
|
|
99
|
+
rid,
|
|
100
|
+
{
|
|
101
|
+
"status": "busy" if active > 0 else "ok",
|
|
102
|
+
"active_jobs": active,
|
|
103
|
+
"uptime_secs": int(time.monotonic() - self._start),
|
|
104
|
+
"pid": os.getpid(),
|
|
105
|
+
"version": self.handler.worker_version(),
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if method == "capabilities":
|
|
110
|
+
max_jobs = 1
|
|
111
|
+
if hasattr(self.handler, "max_concurrent_jobs"):
|
|
112
|
+
max_jobs = int(self.handler.max_concurrent_jobs())
|
|
113
|
+
return ok_response(
|
|
114
|
+
rid,
|
|
115
|
+
{
|
|
116
|
+
"version": self.handler.worker_version(),
|
|
117
|
+
"protocol_version": 1,
|
|
118
|
+
"features": list(self.handler.features()),
|
|
119
|
+
"max_concurrent_jobs": max_jobs,
|
|
120
|
+
"encoding": self.encoding.wire_name(),
|
|
121
|
+
},
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
if method == "shutdown":
|
|
125
|
+
self._accepting = False
|
|
126
|
+
delay_ms = _shutdown_delay_ms(params)
|
|
127
|
+
if not self._test_mode:
|
|
128
|
+
|
|
129
|
+
def _exit() -> None:
|
|
130
|
+
time.sleep(delay_ms / 1000.0)
|
|
131
|
+
os._exit(0)
|
|
132
|
+
|
|
133
|
+
threading.Thread(target=_exit, name="forge-shutdown", daemon=True).start()
|
|
134
|
+
return ok_response(rid, {"bye": True})
|
|
135
|
+
|
|
136
|
+
if method == "cancel_job":
|
|
137
|
+
job_id = _str_param(params, "job_id")
|
|
138
|
+
if self.registry.cancel(job_id):
|
|
139
|
+
st = self.registry.status(job_id)
|
|
140
|
+
state = st.state if st is not None else JobState.CANCELLED.value
|
|
141
|
+
return ok_response(
|
|
142
|
+
rid,
|
|
143
|
+
{
|
|
144
|
+
"cancelled": True,
|
|
145
|
+
"job_id": job_id,
|
|
146
|
+
"cancel_requested": True,
|
|
147
|
+
"state": state,
|
|
148
|
+
},
|
|
149
|
+
)
|
|
150
|
+
return err_response(rid, "JOB_NOT_FOUND", f"job {job_id} not found")
|
|
151
|
+
|
|
152
|
+
if method == "job_status":
|
|
153
|
+
job_id = _str_param(params, "job_id")
|
|
154
|
+
st = self.registry.status(job_id)
|
|
155
|
+
if st is None:
|
|
156
|
+
return err_response(rid, "JOB_NOT_FOUND", f"job {job_id} not found")
|
|
157
|
+
return ok_response(rid, st.to_dict())
|
|
158
|
+
|
|
159
|
+
return self.handler.handle_method(
|
|
160
|
+
rid, method, params, event_sink, self.registry
|
|
161
|
+
)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Length-prefixed framing: `[u32 BE length][u8 kind][payload]`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
KIND_REQUEST = 1
|
|
10
|
+
KIND_RESPONSE = 2
|
|
11
|
+
KIND_EVENT = 3
|
|
12
|
+
MAX_FRAME_PAYLOAD = 64 * 1024 * 1024
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Encoding(Enum):
|
|
16
|
+
MSGPACK = "msgpack"
|
|
17
|
+
JSON = "json"
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def from_flag(cls, s: str) -> Encoding:
|
|
21
|
+
if s.lower() == "json":
|
|
22
|
+
return cls.JSON
|
|
23
|
+
return cls.MSGPACK
|
|
24
|
+
|
|
25
|
+
def wire_name(self) -> str:
|
|
26
|
+
return self.value
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Frame:
|
|
31
|
+
kind: int
|
|
32
|
+
payload: bytes
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def encode_frame(kind: int, payload: bytes) -> bytes:
|
|
36
|
+
if len(payload) > MAX_FRAME_PAYLOAD:
|
|
37
|
+
raise ValueError(f"frame payload too large: {len(payload)}")
|
|
38
|
+
return len(payload).to_bytes(4, "big") + bytes([kind]) + payload
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def try_decode_frame(buf: bytearray) -> Frame | None:
|
|
42
|
+
if len(buf) < 5:
|
|
43
|
+
return None
|
|
44
|
+
length = int.from_bytes(buf[0:4], "big")
|
|
45
|
+
kind = buf[4]
|
|
46
|
+
if length > MAX_FRAME_PAYLOAD:
|
|
47
|
+
raise ValueError(f"frame payload too large: {length}")
|
|
48
|
+
if len(buf) < 5 + length:
|
|
49
|
+
return None
|
|
50
|
+
payload = bytes(buf[5 : 5 + length])
|
|
51
|
+
del buf[: 5 + length]
|
|
52
|
+
return Frame(kind=kind, payload=payload)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def marshal(encoding: Encoding, obj: Any) -> bytes:
|
|
56
|
+
if encoding is Encoding.JSON:
|
|
57
|
+
import json
|
|
58
|
+
|
|
59
|
+
return json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
60
|
+
import msgpack
|
|
61
|
+
|
|
62
|
+
return msgpack.packb(obj, use_bin_type=True)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def unmarshal(encoding: Encoding, data: bytes) -> Any:
|
|
66
|
+
if encoding is Encoding.JSON:
|
|
67
|
+
import json
|
|
68
|
+
|
|
69
|
+
return json.loads(data.decode("utf-8"))
|
|
70
|
+
import msgpack
|
|
71
|
+
|
|
72
|
+
return msgpack.unpackb(data, raw=False)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Job tracking, cooperative cancel, and event routing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from forge_worker_sdk.protocol import WireEvent
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class JobState(str, Enum):
|
|
16
|
+
PENDING = "pending"
|
|
17
|
+
RUNNING = "running"
|
|
18
|
+
COMPLETED = "completed"
|
|
19
|
+
FAILED = "failed"
|
|
20
|
+
CANCELLED = "cancelled"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class JobStatus:
|
|
25
|
+
job_id: str
|
|
26
|
+
state: str
|
|
27
|
+
progress: Any = None
|
|
28
|
+
error: str = ""
|
|
29
|
+
cancel_requested: bool = False
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict[str, Any]:
|
|
32
|
+
d: dict[str, Any] = {
|
|
33
|
+
"job_id": self.job_id,
|
|
34
|
+
"state": self.state,
|
|
35
|
+
"cancel_requested": self.cancel_requested,
|
|
36
|
+
}
|
|
37
|
+
if self.progress is not None:
|
|
38
|
+
d["progress"] = self.progress
|
|
39
|
+
if self.error:
|
|
40
|
+
d["error"] = self.error
|
|
41
|
+
return d
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
EventSink = Callable[[WireEvent], None]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Job:
|
|
49
|
+
job_id: str
|
|
50
|
+
cancel_event: threading.Event = field(default_factory=threading.Event)
|
|
51
|
+
state: JobState = JobState.PENDING
|
|
52
|
+
started_at: float = field(default_factory=time.monotonic)
|
|
53
|
+
progress: Any = None
|
|
54
|
+
error_msg: str | None = None
|
|
55
|
+
event_sink: EventSink | None = None
|
|
56
|
+
|
|
57
|
+
def cancel(self) -> None:
|
|
58
|
+
self.cancel_event.set()
|
|
59
|
+
if self.state in (JobState.PENDING, JobState.RUNNING):
|
|
60
|
+
self.state = JobState.CANCELLED
|
|
61
|
+
|
|
62
|
+
def is_cancelled(self) -> bool:
|
|
63
|
+
return self.cancel_event.is_set()
|
|
64
|
+
|
|
65
|
+
def wait_cancelled(self, timeout: float | None = None) -> bool:
|
|
66
|
+
return self.cancel_event.wait(timeout)
|
|
67
|
+
|
|
68
|
+
def emit(self, ev: WireEvent) -> None:
|
|
69
|
+
if self.event_sink is not None:
|
|
70
|
+
self.event_sink(ev)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class JobRegistry:
|
|
74
|
+
def __init__(self) -> None:
|
|
75
|
+
self._lock = threading.Lock()
|
|
76
|
+
self._jobs: dict[str, Job] = {}
|
|
77
|
+
self._total_completed = 0
|
|
78
|
+
|
|
79
|
+
def register(self, job: Job) -> None:
|
|
80
|
+
with self._lock:
|
|
81
|
+
if job.job_id in self._jobs:
|
|
82
|
+
raise ValueError(f"job {job.job_id} already registered")
|
|
83
|
+
self._jobs[job.job_id] = job
|
|
84
|
+
|
|
85
|
+
def set_running(self, job_id: str) -> None:
|
|
86
|
+
with self._lock:
|
|
87
|
+
j = self._jobs.get(job_id)
|
|
88
|
+
if j:
|
|
89
|
+
j.state = JobState.RUNNING
|
|
90
|
+
|
|
91
|
+
def set_completed(self, job_id: str, progress: Any = None) -> None:
|
|
92
|
+
with self._lock:
|
|
93
|
+
j = self._jobs.get(job_id)
|
|
94
|
+
if j:
|
|
95
|
+
j.state = JobState.COMPLETED
|
|
96
|
+
if progress is not None:
|
|
97
|
+
j.progress = progress
|
|
98
|
+
self._total_completed += 1
|
|
99
|
+
|
|
100
|
+
def set_failed(self, job_id: str, err: str) -> None:
|
|
101
|
+
with self._lock:
|
|
102
|
+
j = self._jobs.get(job_id)
|
|
103
|
+
if j:
|
|
104
|
+
j.state = JobState.FAILED
|
|
105
|
+
j.error_msg = err
|
|
106
|
+
self._total_completed += 1
|
|
107
|
+
|
|
108
|
+
def cancel(self, job_id: str) -> bool:
|
|
109
|
+
with self._lock:
|
|
110
|
+
j = self._jobs.get(job_id)
|
|
111
|
+
if not j:
|
|
112
|
+
return False
|
|
113
|
+
j.cancel()
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
def update_progress(self, job_id: str, progress: Any) -> None:
|
|
117
|
+
with self._lock:
|
|
118
|
+
j = self._jobs.get(job_id)
|
|
119
|
+
if j:
|
|
120
|
+
j.progress = progress
|
|
121
|
+
|
|
122
|
+
def emit(self, job_id: str, ev: WireEvent) -> None:
|
|
123
|
+
with self._lock:
|
|
124
|
+
j = self._jobs.get(job_id)
|
|
125
|
+
if j:
|
|
126
|
+
j.emit(ev)
|
|
127
|
+
|
|
128
|
+
def get(self, job_id: str) -> Job | None:
|
|
129
|
+
with self._lock:
|
|
130
|
+
return self._jobs.get(job_id)
|
|
131
|
+
|
|
132
|
+
def status(self, job_id: str) -> JobStatus | None:
|
|
133
|
+
with self._lock:
|
|
134
|
+
j = self._jobs.get(job_id)
|
|
135
|
+
if not j:
|
|
136
|
+
return None
|
|
137
|
+
return JobStatus(
|
|
138
|
+
job_id=j.job_id,
|
|
139
|
+
state=j.state.value,
|
|
140
|
+
progress=j.progress,
|
|
141
|
+
error=j.error_msg or "",
|
|
142
|
+
cancel_requested=j.cancel_event.is_set(),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def active_count(self) -> int:
|
|
146
|
+
with self._lock:
|
|
147
|
+
return sum(
|
|
148
|
+
1
|
|
149
|
+
for j in self._jobs.values()
|
|
150
|
+
if j.state in (JobState.PENDING, JobState.RUNNING)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def gc(self, keep_n: int = 50) -> None:
|
|
154
|
+
with self._lock:
|
|
155
|
+
done = [
|
|
156
|
+
(jid, j.started_at)
|
|
157
|
+
for jid, j in self._jobs.items()
|
|
158
|
+
if j.state not in (JobState.PENDING, JobState.RUNNING)
|
|
159
|
+
]
|
|
160
|
+
if len(done) <= keep_n:
|
|
161
|
+
return
|
|
162
|
+
done.sort(key=lambda x: x[1], reverse=True)
|
|
163
|
+
for jid, _ in done[keep_n:]:
|
|
164
|
+
self._jobs.pop(jid, None)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Wire envelopes aligned with Go / Rust Forge SDKs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class ErrorPayload:
|
|
11
|
+
code: str
|
|
12
|
+
message: str
|
|
13
|
+
detail: str = ""
|
|
14
|
+
|
|
15
|
+
def to_dict(self) -> dict[str, Any]:
|
|
16
|
+
d: dict[str, Any] = {"code": self.code, "message": self.message}
|
|
17
|
+
if self.detail:
|
|
18
|
+
d["detail"] = self.detail
|
|
19
|
+
return d
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def from_dict(cls, d: dict[str, Any] | None) -> ErrorPayload | None:
|
|
23
|
+
if not d:
|
|
24
|
+
return None
|
|
25
|
+
return cls(
|
|
26
|
+
code=str(d.get("code", "")),
|
|
27
|
+
message=str(d.get("message", "")),
|
|
28
|
+
detail=str(d.get("detail", "")),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class WireRequest:
|
|
34
|
+
id: str
|
|
35
|
+
method: str
|
|
36
|
+
params: Any = None
|
|
37
|
+
|
|
38
|
+
def to_dict(self) -> dict[str, Any]:
|
|
39
|
+
d: dict[str, Any] = {"id": self.id, "method": self.method}
|
|
40
|
+
if self.params is not None:
|
|
41
|
+
d["params"] = self.params
|
|
42
|
+
return d
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_dict(cls, d: dict[str, Any]) -> WireRequest:
|
|
46
|
+
return cls(id=str(d["id"]), method=str(d["method"]), params=d.get("params"))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class WireResponse:
|
|
51
|
+
id: str
|
|
52
|
+
ok: bool
|
|
53
|
+
error: ErrorPayload | None = None
|
|
54
|
+
payload: Any = None
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> dict[str, Any]:
|
|
57
|
+
d: dict[str, Any] = {"id": self.id, "ok": self.ok}
|
|
58
|
+
if self.error is not None:
|
|
59
|
+
d["error"] = self.error.to_dict()
|
|
60
|
+
if self.payload is not None:
|
|
61
|
+
d["payload"] = self.payload
|
|
62
|
+
return d
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_dict(cls, d: dict[str, Any]) -> WireResponse:
|
|
66
|
+
return cls(
|
|
67
|
+
id=str(d["id"]),
|
|
68
|
+
ok=bool(d.get("ok")),
|
|
69
|
+
error=ErrorPayload.from_dict(d.get("error")),
|
|
70
|
+
payload=d.get("payload"),
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass
|
|
75
|
+
class WireEvent:
|
|
76
|
+
type: str
|
|
77
|
+
job_id: str
|
|
78
|
+
payload: Any = None
|
|
79
|
+
|
|
80
|
+
def to_dict(self) -> dict[str, Any]:
|
|
81
|
+
d: dict[str, Any] = {"type": self.type, "job_id": self.job_id}
|
|
82
|
+
if self.payload is not None:
|
|
83
|
+
d["payload"] = self.payload
|
|
84
|
+
return d
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def from_dict(cls, d: dict[str, Any]) -> WireEvent:
|
|
88
|
+
return cls(
|
|
89
|
+
type=str(d.get("type", "")),
|
|
90
|
+
job_id=str(d.get("job_id", "")),
|
|
91
|
+
payload=d.get("payload"),
|
|
92
|
+
)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Unix socket and stdio framed IPC servers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from forge_worker_sdk.dispatcher import BaseDispatcher, WorkerHandler
|
|
12
|
+
from forge_worker_sdk.framing import (
|
|
13
|
+
KIND_EVENT,
|
|
14
|
+
KIND_REQUEST,
|
|
15
|
+
KIND_RESPONSE,
|
|
16
|
+
Encoding,
|
|
17
|
+
encode_frame,
|
|
18
|
+
marshal,
|
|
19
|
+
try_decode_frame,
|
|
20
|
+
unmarshal,
|
|
21
|
+
)
|
|
22
|
+
from forge_worker_sdk.protocol import WireEvent, WireRequest
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_worker(socket_path: str, handler: WorkerHandler, encoding: Encoding) -> None:
|
|
26
|
+
"""Listen on a Unix domain socket until process exit."""
|
|
27
|
+
dispatcher = BaseDispatcher(handler, encoding)
|
|
28
|
+
_start_gc(dispatcher)
|
|
29
|
+
|
|
30
|
+
if os.path.exists(socket_path):
|
|
31
|
+
os.remove(socket_path)
|
|
32
|
+
|
|
33
|
+
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
34
|
+
srv.bind(socket_path)
|
|
35
|
+
srv.listen(16)
|
|
36
|
+
try:
|
|
37
|
+
while True:
|
|
38
|
+
conn, _ = srv.accept()
|
|
39
|
+
threading.Thread(
|
|
40
|
+
target=_handle_socket,
|
|
41
|
+
args=(conn, dispatcher, encoding),
|
|
42
|
+
daemon=True,
|
|
43
|
+
).start()
|
|
44
|
+
finally:
|
|
45
|
+
srv.close()
|
|
46
|
+
try:
|
|
47
|
+
os.remove(socket_path)
|
|
48
|
+
except OSError:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run_worker_stdio(handler: WorkerHandler, encoding: Encoding) -> None:
|
|
53
|
+
"""Serve framed IPC on stdin/stdout. Logs must go to stderr only."""
|
|
54
|
+
dispatcher = BaseDispatcher(handler, encoding)
|
|
55
|
+
_start_gc(dispatcher)
|
|
56
|
+
# Use raw OS fds — BufferedReader.read can interact poorly with piped IPC.
|
|
57
|
+
_handle_raw_stdio(dispatcher, encoding)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _handle_raw_stdio(dispatcher: BaseDispatcher, encoding: Encoding) -> None:
|
|
61
|
+
write_lock = threading.Lock()
|
|
62
|
+
buf = bytearray()
|
|
63
|
+
in_fd = sys.stdin.fileno()
|
|
64
|
+
out_fd = sys.stdout.fileno()
|
|
65
|
+
|
|
66
|
+
def send_frame(kind: int, obj: dict) -> None:
|
|
67
|
+
payload = marshal(encoding, obj)
|
|
68
|
+
data = encode_frame(kind, payload)
|
|
69
|
+
with write_lock:
|
|
70
|
+
view = memoryview(data)
|
|
71
|
+
while len(view):
|
|
72
|
+
n = os.write(out_fd, view)
|
|
73
|
+
view = view[n:]
|
|
74
|
+
|
|
75
|
+
def event_sink(ev: WireEvent) -> None:
|
|
76
|
+
send_frame(KIND_EVENT, ev.to_dict())
|
|
77
|
+
|
|
78
|
+
def dispatch_one(req: WireRequest) -> None:
|
|
79
|
+
resp = dispatcher.dispatch(req, event_sink)
|
|
80
|
+
send_frame(KIND_RESPONSE, resp.to_dict())
|
|
81
|
+
|
|
82
|
+
while True:
|
|
83
|
+
try:
|
|
84
|
+
chunk = os.read(in_fd, 65536)
|
|
85
|
+
except OSError:
|
|
86
|
+
break
|
|
87
|
+
if not chunk:
|
|
88
|
+
break
|
|
89
|
+
buf.extend(chunk)
|
|
90
|
+
while True:
|
|
91
|
+
try:
|
|
92
|
+
frame = try_decode_frame(buf)
|
|
93
|
+
except ValueError:
|
|
94
|
+
return
|
|
95
|
+
if frame is None:
|
|
96
|
+
break
|
|
97
|
+
if frame.kind != KIND_REQUEST:
|
|
98
|
+
continue
|
|
99
|
+
raw = unmarshal(encoding, frame.payload)
|
|
100
|
+
req = WireRequest.from_dict(raw)
|
|
101
|
+
threading.Thread(
|
|
102
|
+
target=dispatch_one, args=(req,), daemon=True, name=f"rpc-{req.id}"
|
|
103
|
+
).start()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _start_gc(dispatcher: BaseDispatcher) -> None:
|
|
107
|
+
def loop() -> None:
|
|
108
|
+
while True:
|
|
109
|
+
time.sleep(60)
|
|
110
|
+
dispatcher.registry.gc(50)
|
|
111
|
+
|
|
112
|
+
threading.Thread(target=loop, name="forge-gc", daemon=True).start()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _handle_socket(
|
|
116
|
+
conn: socket.socket, dispatcher: BaseDispatcher, encoding: Encoding
|
|
117
|
+
) -> None:
|
|
118
|
+
write_lock = threading.Lock()
|
|
119
|
+
buf = bytearray()
|
|
120
|
+
|
|
121
|
+
def send_frame(kind: int, obj: dict) -> None:
|
|
122
|
+
payload = marshal(encoding, obj)
|
|
123
|
+
data = encode_frame(kind, payload)
|
|
124
|
+
with write_lock:
|
|
125
|
+
conn.sendall(data)
|
|
126
|
+
|
|
127
|
+
def event_sink(ev: WireEvent) -> None:
|
|
128
|
+
send_frame(KIND_EVENT, ev.to_dict())
|
|
129
|
+
|
|
130
|
+
def dispatch_one(req: WireRequest) -> None:
|
|
131
|
+
resp = dispatcher.dispatch(req, event_sink)
|
|
132
|
+
send_frame(KIND_RESPONSE, resp.to_dict())
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
while True:
|
|
136
|
+
chunk = conn.recv(65536)
|
|
137
|
+
if not chunk:
|
|
138
|
+
break
|
|
139
|
+
buf.extend(chunk)
|
|
140
|
+
while True:
|
|
141
|
+
try:
|
|
142
|
+
frame = try_decode_frame(buf)
|
|
143
|
+
except ValueError:
|
|
144
|
+
return
|
|
145
|
+
if frame is None:
|
|
146
|
+
break
|
|
147
|
+
if frame.kind != KIND_REQUEST:
|
|
148
|
+
continue
|
|
149
|
+
raw = unmarshal(encoding, frame.payload)
|
|
150
|
+
req = WireRequest.from_dict(raw)
|
|
151
|
+
threading.Thread(
|
|
152
|
+
target=dispatch_one,
|
|
153
|
+
args=(req,),
|
|
154
|
+
daemon=True,
|
|
155
|
+
name=f"rpc-{req.id}",
|
|
156
|
+
).start()
|
|
157
|
+
except OSError:
|
|
158
|
+
pass
|
|
159
|
+
finally:
|
|
160
|
+
try:
|
|
161
|
+
conn.close()
|
|
162
|
+
except OSError:
|
|
163
|
+
pass
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: forge-worker-sdk
|
|
3
|
+
Version: 0.0.12
|
|
4
|
+
Summary: Organizyio Forge — Python worker IPC SDK (framing, server runtime, job registry, dispatcher).
|
|
5
|
+
Author-email: Organizyio <opensource@organizy.io>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/organizyio/forge
|
|
8
|
+
Project-URL: Repository, https://github.com/organizyio/forge
|
|
9
|
+
Project-URL: Documentation, https://github.com/organizyio/forge/blob/main/docs/python-worker.md
|
|
10
|
+
Project-URL: Changelog, https://github.com/organizyio/forge/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: forge,ipc,worker,msgpack,organizy
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
Requires-Dist: msgpack>=1.0.0
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
|
|
25
|
+
# forge-worker-sdk (Python)
|
|
26
|
+
|
|
27
|
+
Python peer of the Rust `forge-worker-sdk` crate. Speaks Forge framed IPC over Unix domain sockets or framed stdio.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install forge-worker-sdk
|
|
33
|
+
# or
|
|
34
|
+
uv add forge-worker-sdk
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
From source (contrib / tests):
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
cd forge/python
|
|
41
|
+
python3 -m pip install -e ".[dev]"
|
|
42
|
+
FORGE_WORKER_TEST=1 pytest
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Example worker
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
python3 examples/minimal-python-worker/main.py --socket /tmp/forge-py.sock --encoding json
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
See [docs/python-worker.md](../docs/python-worker.md).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
forge_worker_sdk/__init__.py
|
|
4
|
+
forge_worker_sdk/dispatcher.py
|
|
5
|
+
forge_worker_sdk/framing.py
|
|
6
|
+
forge_worker_sdk/job_registry.py
|
|
7
|
+
forge_worker_sdk/protocol.py
|
|
8
|
+
forge_worker_sdk/server.py
|
|
9
|
+
forge_worker_sdk.egg-info/PKG-INFO
|
|
10
|
+
forge_worker_sdk.egg-info/SOURCES.txt
|
|
11
|
+
forge_worker_sdk.egg-info/dependency_links.txt
|
|
12
|
+
forge_worker_sdk.egg-info/requires.txt
|
|
13
|
+
forge_worker_sdk.egg-info/top_level.txt
|
|
14
|
+
tests/test_event_fixture.py
|
|
15
|
+
tests/test_protocol_fixtures.py
|
|
16
|
+
tests/test_streaming_cancel.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
forge_worker_sdk
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "forge-worker-sdk"
|
|
7
|
+
version = "0.0.12"
|
|
8
|
+
description = "Organizyio Forge — Python worker IPC SDK (framing, server runtime, job registry, dispatcher)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Organizyio", email = "opensource@organizy.io" },
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"forge",
|
|
17
|
+
"ipc",
|
|
18
|
+
"worker",
|
|
19
|
+
"msgpack",
|
|
20
|
+
"organizy",
|
|
21
|
+
]
|
|
22
|
+
classifiers = [
|
|
23
|
+
"Development Status :: 3 - Alpha",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Topic :: Software Development :: Libraries",
|
|
29
|
+
"Typing :: Typed",
|
|
30
|
+
]
|
|
31
|
+
dependencies = [
|
|
32
|
+
"msgpack>=1.0.0",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
dev = ["pytest>=8.0"]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/organizyio/forge"
|
|
40
|
+
Repository = "https://github.com/organizyio/forge"
|
|
41
|
+
Documentation = "https://github.com/organizyio/forge/blob/main/docs/python-worker.md"
|
|
42
|
+
Changelog = "https://github.com/organizyio/forge/blob/main/CHANGELOG.md"
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
where = ["."]
|
|
46
|
+
include = ["forge_worker_sdk*"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests"]
|
|
50
|
+
pythonpath = ["."]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Generic event fixture encode/decode (kind-3 payload shape)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from forge_worker_sdk.framing import Encoding, marshal, unmarshal
|
|
9
|
+
from forge_worker_sdk.protocol import WireEvent
|
|
10
|
+
|
|
11
|
+
FIXTURES = Path(__file__).resolve().parents[2] / "protocol" / "fixtures"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_event_example_roundtrip_json() -> None:
|
|
15
|
+
raw = json.loads((FIXTURES / "event-example.json").read_text(encoding="utf-8"))
|
|
16
|
+
ev = WireEvent.from_dict(raw)
|
|
17
|
+
assert ev.type == "progress"
|
|
18
|
+
assert ev.job_id == "job-123"
|
|
19
|
+
encoded = marshal(Encoding.JSON, ev.to_dict())
|
|
20
|
+
got = WireEvent.from_dict(unmarshal(Encoding.JSON, encoded))
|
|
21
|
+
assert got == ev
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Contract tests: protocol/fixtures vs BaseDispatcher (mirror Rust protocol_fixtures)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
# Ensure shutdown does not exit the test process.
|
|
13
|
+
os.environ["FORGE_WORKER_TEST"] = "1"
|
|
14
|
+
|
|
15
|
+
from forge_worker_sdk import ( # noqa: E402
|
|
16
|
+
BaseDispatcher,
|
|
17
|
+
Encoding,
|
|
18
|
+
Job,
|
|
19
|
+
WireRequest,
|
|
20
|
+
unknown_method,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
FIXTURES = Path(__file__).resolve().parents[2] / "protocol" / "fixtures"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FixtureHandler:
|
|
27
|
+
def worker_version(self) -> str:
|
|
28
|
+
return "0.1.0"
|
|
29
|
+
|
|
30
|
+
def features(self) -> list[str]:
|
|
31
|
+
return ["hash.xxh64", "reliable_events_v1"]
|
|
32
|
+
|
|
33
|
+
def max_concurrent_jobs(self) -> int:
|
|
34
|
+
return 1
|
|
35
|
+
|
|
36
|
+
def handle_method(self, req_id, method, params, event_sink, registry):
|
|
37
|
+
return unknown_method(req_id, method)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def read_fixture(name: str) -> Any:
|
|
41
|
+
return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def normalize_health(v: dict) -> dict:
|
|
45
|
+
payload = v.get("payload")
|
|
46
|
+
if isinstance(payload, dict):
|
|
47
|
+
payload = dict(payload)
|
|
48
|
+
payload.pop("uptime_secs", None)
|
|
49
|
+
payload.pop("pid", None)
|
|
50
|
+
v = dict(v)
|
|
51
|
+
v["payload"] = payload
|
|
52
|
+
return v
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def dispatch(d: BaseDispatcher, req_dict: dict) -> dict:
|
|
56
|
+
req = WireRequest.from_dict(req_dict)
|
|
57
|
+
resp = d.dispatch(req, event_sink=lambda _ev: None)
|
|
58
|
+
return resp.to_dict()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@pytest.fixture
|
|
62
|
+
def dispatcher() -> BaseDispatcher:
|
|
63
|
+
return BaseDispatcher(FixtureHandler(), Encoding.MSGPACK)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_ping(dispatcher: BaseDispatcher) -> None:
|
|
67
|
+
actual = dispatch(dispatcher, read_fixture("ping-request.json"))
|
|
68
|
+
assert actual == read_fixture("ping-response.json")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_health(dispatcher: BaseDispatcher) -> None:
|
|
72
|
+
actual = normalize_health(dispatch(dispatcher, read_fixture("health-request.json")))
|
|
73
|
+
expected = normalize_health(read_fixture("health-response.json"))
|
|
74
|
+
assert actual == expected
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_capabilities(dispatcher: BaseDispatcher) -> None:
|
|
78
|
+
actual = dispatch(dispatcher, read_fixture("capabilities-request.json"))
|
|
79
|
+
assert actual == read_fixture("capabilities-response.json")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_shutdown(dispatcher: BaseDispatcher) -> None:
|
|
83
|
+
actual = dispatch(dispatcher, read_fixture("shutdown-request.json"))
|
|
84
|
+
assert actual == read_fixture("shutdown-response.json")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_cancel_job_ok(dispatcher: BaseDispatcher) -> None:
|
|
88
|
+
job = Job(job_id="job-123")
|
|
89
|
+
dispatcher.registry.register(job)
|
|
90
|
+
actual = dispatch(dispatcher, read_fixture("cancel_job-request.json"))
|
|
91
|
+
assert actual == read_fixture("cancel_job-response.json")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_cancel_job_not_found(dispatcher: BaseDispatcher) -> None:
|
|
95
|
+
actual = dispatch(dispatcher, read_fixture("cancel_job-request.json"))
|
|
96
|
+
assert actual == read_fixture("cancel_job-error-not-found.json")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_job_status_ok(dispatcher: BaseDispatcher) -> None:
|
|
100
|
+
job = Job(job_id="job-123")
|
|
101
|
+
dispatcher.registry.register(job)
|
|
102
|
+
dispatcher.registry.set_running("job-123")
|
|
103
|
+
dispatcher.registry.update_progress(
|
|
104
|
+
"job-123", {"phase": "walk", "items_done": 5000}
|
|
105
|
+
)
|
|
106
|
+
actual = dispatch(dispatcher, read_fixture("job_status-request.json"))
|
|
107
|
+
assert actual == read_fixture("job_status-response.json")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_job_status_not_found(dispatcher: BaseDispatcher) -> None:
|
|
111
|
+
actual = dispatch(dispatcher, read_fixture("job_status-request.json"))
|
|
112
|
+
assert actual == read_fixture("job_status-error-not-found.json")
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Long-job pattern: register, emit progress events, cooperative cancel."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
os.environ["FORGE_WORKER_TEST"] = "1"
|
|
11
|
+
|
|
12
|
+
from forge_worker_sdk import (
|
|
13
|
+
BaseDispatcher,
|
|
14
|
+
Encoding,
|
|
15
|
+
Job,
|
|
16
|
+
JobRegistry,
|
|
17
|
+
WireEvent,
|
|
18
|
+
WireRequest,
|
|
19
|
+
WireResponse,
|
|
20
|
+
ok_response,
|
|
21
|
+
unknown_method,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DemoHandler:
|
|
26
|
+
def worker_version(self) -> str:
|
|
27
|
+
return "0.1.0"
|
|
28
|
+
|
|
29
|
+
def features(self) -> list[str]:
|
|
30
|
+
return ["demo.job"]
|
|
31
|
+
|
|
32
|
+
def max_concurrent_jobs(self) -> int:
|
|
33
|
+
return 1
|
|
34
|
+
|
|
35
|
+
def handle_method(
|
|
36
|
+
self,
|
|
37
|
+
req_id: str,
|
|
38
|
+
method: str,
|
|
39
|
+
params: Any,
|
|
40
|
+
event_sink: Any,
|
|
41
|
+
registry: JobRegistry,
|
|
42
|
+
) -> WireResponse:
|
|
43
|
+
if method != "start_demo_job":
|
|
44
|
+
return unknown_method(req_id, method)
|
|
45
|
+
job_id = "job-demo"
|
|
46
|
+
if isinstance(params, dict) and params.get("job_id"):
|
|
47
|
+
job_id = str(params["job_id"])
|
|
48
|
+
job = Job(job_id=job_id, event_sink=event_sink)
|
|
49
|
+
registry.register(job)
|
|
50
|
+
registry.set_running(job_id)
|
|
51
|
+
|
|
52
|
+
def runner() -> None:
|
|
53
|
+
for n in (1, 2, 3):
|
|
54
|
+
if job.is_cancelled():
|
|
55
|
+
break
|
|
56
|
+
ev = WireEvent(
|
|
57
|
+
type="progress",
|
|
58
|
+
job_id=job_id,
|
|
59
|
+
payload={"n": n, "phase": "demo"},
|
|
60
|
+
)
|
|
61
|
+
registry.emit(job_id, ev)
|
|
62
|
+
time.sleep(0.05)
|
|
63
|
+
if job.is_cancelled():
|
|
64
|
+
return
|
|
65
|
+
registry.set_completed(job_id, {"n": 3})
|
|
66
|
+
|
|
67
|
+
threading.Thread(target=runner, daemon=True).start()
|
|
68
|
+
return ok_response(req_id, {"accepted": True, "job_id": job_id})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_demo_job_cancel_stops_progress() -> None:
|
|
72
|
+
d = BaseDispatcher(DemoHandler(), Encoding.JSON)
|
|
73
|
+
events: list[WireEvent] = []
|
|
74
|
+
|
|
75
|
+
def sink(ev: WireEvent) -> None:
|
|
76
|
+
events.append(ev)
|
|
77
|
+
|
|
78
|
+
start = WireRequest(id="r1", method="start_demo_job", params={"job_id": "job-demo"})
|
|
79
|
+
resp = d.dispatch(start, sink)
|
|
80
|
+
assert resp.ok
|
|
81
|
+
time.sleep(0.02)
|
|
82
|
+
cancel = WireRequest(id="r2", method="cancel_job", params={"job_id": "job-demo"})
|
|
83
|
+
assert d.dispatch(cancel, sink).ok
|
|
84
|
+
time.sleep(0.2)
|
|
85
|
+
st = d.registry.status("job-demo")
|
|
86
|
+
assert st is not None
|
|
87
|
+
assert st.state == "cancelled"
|
|
88
|
+
assert len(events) >= 1
|
|
89
|
+
assert events[0].type == "progress"
|