orbit-lang-sdk 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,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: orbit-lang-sdk
3
+ Version: 0.1.0
4
+ Summary: Python worker SDK for the ORBIT orchestration runtime
5
+ Author: ORBIT contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AjmalX0/Orbit
8
+ Project-URL: Documentation, https://github.com/AjmalX0/Orbit/tree/main/sdks/python
9
+ Project-URL: Issues, https://github.com/AjmalX0/Orbit/issues
10
+ Keywords: orbit,workflow,orchestration,durable-execution,saga,worker
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: System :: Distributed Computing
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Dynamic: license-file
21
+
22
+ # orbit-lang-sdk (Python)
23
+
24
+ Python worker SDK for the [ORBIT](../../README.md) runtime. Standard library
25
+ only, Python 3.9+.
26
+
27
+ ```bash
28
+ pip install orbit-lang-sdk
29
+ ```
30
+
31
+ ```python
32
+ from orbit_sdk import Worker, TaskError
33
+
34
+ worker = Worker("payments-worker", concurrency=8) # server: $ORBIT_SERVER, token: $ORBIT_TOKEN
35
+
36
+ @worker.task("payments.charge", version="1.0.0")
37
+ def charge(input, ctx):
38
+ if input["amount"] > 5000:
39
+ raise TaskError("CARD_DECLINED", "limit exceeded", retryable=False)
40
+ # ctx.idempotency_key is stable across retries and redeliveries
41
+ return {"transaction_id": f"tx-{input['order_id']}", "status": "captured"}
42
+
43
+ worker.run() # Ctrl-C / SIGTERM drains in-flight tasks and unregisters
44
+ ```
45
+
46
+ * Handlers receive `(input: dict, ctx: Context)` and return a `dict`. `async def`
47
+ handlers are supported.
48
+ * `ctx` exposes `execution_id`, `step_id`, `attempt`, `idempotency_key`,
49
+ `redelivery`, `deadline_ms`, `remaining_ms()`, `is_cancelled` / `cancelled`
50
+ (a `threading.Event` set when the runtime cancels the attempt) and `log()`.
51
+ * Raise `TaskError(code, message, retryable=..., details=...)` for business
52
+ errors. Any other exception is reported as a retryable `UNHANDLED_EXCEPTION`
53
+ with its traceback.
54
+ * The SDK re-registers after a runtime restart and keeps retrying result
55
+ delivery through outages, so results produced during a crash are not lost.
56
+
57
+ Starting workflows from Python:
58
+
59
+ ```python
60
+ from orbit_sdk import Client
61
+ c = Client()
62
+ eid = c.start("OrderProcessing", {"order_id": "A-1", ...}, execution_id="order-A-1")
63
+ print(c.wait(eid)["status"])
64
+ ```
65
+
66
+ ## Credentials and TLS
67
+
68
+ | Variable | Purpose |
69
+ |---|---|
70
+ | `ORBIT_SERVER` | runtime URL (default `http://127.0.0.1:7233`) |
71
+ | `ORBIT_WORKER_TOKEN` (or `ORBIT_TOKEN`) | bearer token: a per-worker token from `orbit token`, or the shared worker token |
72
+ | `ORBIT_CA_CERT` | PEM CA to trust when the runtime uses a private certificate |
73
+ | `ORBIT_CLIENT_CERT`, `ORBIT_CLIENT_KEY` | PEM client certificate and key for mutual TLS |
@@ -0,0 +1,9 @@
1
+ orbit_lang_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
2
+ orbit_sdk/__init__.py,sha256=w6Naf7riwJfNHl5jXgKnVX4aJMv05zISHXQISE35KmE,777
3
+ orbit_sdk/client.py,sha256=ngVS_DnYnBKy5ymL_jEUGkY95fuPDUdMcRR8mV2e_zk,3632
4
+ orbit_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ orbit_sdk/worker.py,sha256=QyxESAND29tx8tpURQaj66tK_h4FeGmTETeYCf2mhqk,11394
6
+ orbit_lang_sdk-0.1.0.dist-info/METADATA,sha256=03cmB1kwF8mobKYc7qtz-_H9lpWGko4yUkYLeHfc1cA,2831
7
+ orbit_lang_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ orbit_lang_sdk-0.1.0.dist-info/top_level.txt,sha256=cJyAoybkXH5VJ_iJpmwF3IFl0xQYdUZ3fp-7HjBZ8oI,10
9
+ orbit_lang_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ orbit_sdk
orbit_sdk/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """ORBIT worker SDK for Python.
2
+
3
+ A worker announces the tasks it implements, long-polls the ORBIT runtime for
4
+ work, runs your handler and reports the result. It has no dependencies
5
+ outside the standard library.
6
+
7
+ from orbit_sdk import Worker, TaskError
8
+
9
+ worker = Worker("payments-worker")
10
+
11
+ @worker.task("payments.charge", version="1.0.0")
12
+ def charge(input, ctx):
13
+ if input["amount"] <= 0:
14
+ raise TaskError("INVALID_AMOUNT", "amount must be positive", retryable=False)
15
+ return {"transaction_id": f"tx-{ctx.idempotency_key}", "status": "ok"}
16
+
17
+ worker.run()
18
+ """
19
+
20
+ from .client import ApiError, Client
21
+ from .worker import Context, TaskError, Worker
22
+
23
+ __all__ = ["Worker", "Context", "TaskError", "Client", "ApiError"]
24
+ __version__ = "0.1.0"
orbit_sdk/client.py ADDED
@@ -0,0 +1,84 @@
1
+ """Tiny JSON-over-HTTP client for the ORBIT runtime API (standard library only)."""
2
+
3
+ import json
4
+ import os
5
+ import ssl
6
+ import urllib.error
7
+ import urllib.request
8
+ from typing import Any, Optional, Tuple
9
+
10
+ DEFAULT_SERVER = "http://127.0.0.1:7233"
11
+
12
+
13
+ class ApiError(Exception):
14
+ """An error response from the runtime, or a connection failure (status 0)."""
15
+
16
+ def __init__(self, status: int, code: str, message: str):
17
+ super().__init__(f"{code} ({status}): {message}")
18
+ self.status = status
19
+ self.code = code
20
+ self.message = message
21
+
22
+ @property
23
+ def is_connection_error(self) -> bool:
24
+ return self.status == 0
25
+
26
+
27
+ class Client:
28
+ def __init__(
29
+ self,
30
+ server: Optional[str] = None,
31
+ token: Optional[str] = None,
32
+ timeout: float = 70.0,
33
+ ca_cert: Optional[str] = None,
34
+ client_cert: Optional[str] = None,
35
+ client_key: Optional[str] = None,
36
+ ):
37
+ self.server = (server or os.environ.get("ORBIT_SERVER") or DEFAULT_SERVER).rstrip("/")
38
+ # Workers should be given the restricted worker credential when the runtime has one.
39
+ self.token = token if token is not None else (os.environ.get("ORBIT_WORKER_TOKEN") or os.environ.get("ORBIT_TOKEN"))
40
+ self.timeout = timeout
41
+ ca = ca_cert or os.environ.get("ORBIT_CA_CERT")
42
+ # Mutual TLS: a client certificate identifies the worker to the runtime.
43
+ cert = client_cert or os.environ.get("ORBIT_CLIENT_CERT")
44
+ key = client_key or os.environ.get("ORBIT_CLIENT_KEY")
45
+ self._ssl = None
46
+ if ca or cert:
47
+ self._ssl = ssl.create_default_context(cafile=ca)
48
+ if cert:
49
+ self._ssl.load_cert_chain(cert, key)
50
+
51
+ def request(self, method: str, path: str, body: Any = None) -> Tuple[int, Any]:
52
+ data = None if body is None else json.dumps(body).encode()
53
+ req = urllib.request.Request(self.server + path, data=data, method=method)
54
+ req.add_header("content-type", "application/json")
55
+ req.add_header("accept", "application/json")
56
+ if self.token:
57
+ req.add_header("authorization", f"Bearer {self.token}")
58
+ try:
59
+ with urllib.request.urlopen(req, timeout=self.timeout, context=self._ssl) as resp:
60
+ raw = resp.read()
61
+ return resp.status, (json.loads(raw) if raw else None)
62
+ except urllib.error.HTTPError as e:
63
+ raw = e.read()
64
+ try:
65
+ err = json.loads(raw).get("error", {})
66
+ except (ValueError, AttributeError):
67
+ err = {}
68
+ raise ApiError(e.code, err.get("code", "HTTP_ERROR"), err.get("message", raw.decode(errors="replace"))) from None
69
+ except (urllib.error.URLError, ConnectionError, TimeoutError, OSError) as e:
70
+ raise ApiError(0, "CONNECTION", f"cannot reach ORBIT runtime at {self.server}: {e}") from None
71
+
72
+ def get(self, path: str) -> Any:
73
+ return self.request("GET", path)[1]
74
+
75
+ def post(self, path: str, body: Any) -> Tuple[int, Any]:
76
+ return self.request("POST", path, body)
77
+
78
+ # Convenience helpers for applications that start workflows.
79
+ def start(self, workflow: str, input: Any = None, version: Optional[str] = None, execution_id: Optional[str] = None) -> str:
80
+ _, r = self.post("/v1/executions", {"workflow": workflow, "version": version, "input": input or {}, "execution_id": execution_id})
81
+ return r["execution_id"]
82
+
83
+ def wait(self, execution_id: str, timeout_ms: int = 30000) -> Any:
84
+ return self.get(f"/v1/executions/{execution_id}/wait?timeout_ms={timeout_ms}")
orbit_sdk/py.typed ADDED
File without changes
orbit_sdk/worker.py ADDED
@@ -0,0 +1,277 @@
1
+ """ORBIT worker runtime for Python.
2
+
3
+ Delivery is at-least-once: a task can be delivered again after a worker or
4
+ runtime crash (``ctx.redelivery`` is then True). Make side effects idempotent
5
+ using ``ctx.idempotency_key``, which is stable across retries and redeliveries.
6
+ """
7
+
8
+ import asyncio
9
+ import inspect
10
+ import json
11
+ import logging
12
+ import os
13
+ import random
14
+ import signal
15
+ import socket
16
+ import threading
17
+ import time
18
+ import traceback
19
+ from typing import Any, Callable, Dict, Optional, Set
20
+
21
+ from .client import ApiError, Client
22
+
23
+ log = logging.getLogger("orbit")
24
+
25
+
26
+ class TaskError(Exception):
27
+ """Raise from a handler to fail the attempt with a structured error.
28
+
29
+ ``retryable=False`` fails the step immediately regardless of its retry policy.
30
+ """
31
+
32
+ def __init__(self, code: str, message: str = "", retryable: bool = True, details: Any = None):
33
+ super().__init__(f"{code}: {message}")
34
+ self.code = code
35
+ self.message = message
36
+ self.retryable = retryable
37
+ self.details = details
38
+
39
+
40
+ class Context:
41
+ """Information about the attempt being executed."""
42
+
43
+ def __init__(self, task: Dict[str, Any], worker: "Worker"):
44
+ self.token: str = task["token"]
45
+ self.execution_id: str = task["execution_id"]
46
+ self.workflow: str = task.get("workflow", "")
47
+ self.workflow_version: str = task.get("workflow_version", "")
48
+ self.step_id: str = task["step_id"]
49
+ self.task_name: str = task["task_name"]
50
+ self.attempt: int = task.get("attempt", 1)
51
+ self.idempotency_key: str = task.get("idempotency_key", "")
52
+ self.redelivery: bool = task.get("redelivery", False)
53
+ self.deadline_ms: Optional[int] = task.get("deadline_ms")
54
+ self.cancelled = threading.Event()
55
+ self._worker = worker
56
+
57
+ @property
58
+ def is_cancelled(self) -> bool:
59
+ """True once the runtime asked this attempt to stop (timeout, cancellation)."""
60
+ return self.cancelled.is_set()
61
+
62
+ def remaining_ms(self) -> Optional[int]:
63
+ if self.deadline_ms is None:
64
+ return None
65
+ return max(0, self.deadline_ms - int(time.time() * 1000))
66
+
67
+ def log(self, message: str, **fields: Any) -> None:
68
+ record = {"execution_id": self.execution_id, "step": self.step_id, "attempt": self.attempt, **fields}
69
+ log.info("%s %s", message, json.dumps(record, default=str))
70
+
71
+
72
+ Handler = Callable[[Dict[str, Any], Context], Any]
73
+
74
+
75
+ class _Task:
76
+ def __init__(self, name: str, version: str, fn: Handler):
77
+ self.name = name
78
+ self.version = version
79
+ self.fn = fn
80
+
81
+
82
+ class Worker:
83
+ def __init__(
84
+ self,
85
+ worker_id: Optional[str] = None,
86
+ server: Optional[str] = None,
87
+ token: Optional[str] = None,
88
+ concurrency: int = 4,
89
+ runtime: str = "python",
90
+ poll_wait_ms: int = 20000,
91
+ ):
92
+ self.worker_id = worker_id or f"python-{socket.gethostname()}-{os.getpid()}"
93
+ self.client = Client(server, token, timeout=poll_wait_ms / 1000 + 15)
94
+ self.concurrency = max(1, concurrency)
95
+ self.runtime = runtime
96
+ self.poll_wait_ms = poll_wait_ms
97
+ self._tasks: Dict[str, _Task] = {}
98
+ self._session: Optional[str] = None
99
+ self._session_lock = threading.Lock()
100
+ self._heartbeat_interval = 5.0
101
+ self._stop = threading.Event()
102
+ self._active: Dict[str, Context] = {}
103
+ self._active_lock = threading.Lock()
104
+
105
+ # ------------------------------------------------------------ registration
106
+
107
+ def task(self, name: str, version: str = "1.0.0") -> Callable[[Handler], Handler]:
108
+ """Decorator registering ``fn(input, ctx)`` as the implementation of ``name@version``."""
109
+
110
+ def wrap(fn: Handler) -> Handler:
111
+ self.register(name, fn, version)
112
+ return fn
113
+
114
+ return wrap
115
+
116
+ def register(self, name: str, fn: Handler, version: str = "1.0.0") -> None:
117
+ if name in self._tasks:
118
+ raise ValueError(f"task {name!r} is already registered")
119
+ self._tasks[name] = _Task(name, version, fn)
120
+
121
+ def _register_session(self) -> str:
122
+ with self._session_lock:
123
+ body = {
124
+ "worker_id": self.worker_id,
125
+ "runtime": self.runtime,
126
+ "sdk": "orbit-python/0.1.0",
127
+ "contracts": [{"task_name": t.name, "contract_version": t.version} for t in self._tasks.values()],
128
+ }
129
+ _, r = self.client.post("/v1/workers/register", body)
130
+ self._session = r["worker_session_id"]
131
+ self._heartbeat_interval = max(0.5, r.get("heartbeat_interval_ms", 5000) / 1000)
132
+ for w in r.get("warnings", []):
133
+ log.warning("runtime: %s", w)
134
+ log.info("worker %s registered (%d tasks)", self.worker_id, len(self._tasks))
135
+ return self._session
136
+
137
+ def _session_id(self) -> str:
138
+ return self._session or self._register_session()
139
+
140
+ def _with_session(self, fn: Callable[[str], Any]) -> Any:
141
+ """Call ``fn(session)``, re-registering if the runtime forgot the session (e.g. after a restart)."""
142
+ session = self._session_id()
143
+ try:
144
+ return fn(session)
145
+ except ApiError as e:
146
+ if e.status == 404 and e.code == "UNKNOWN_SESSION":
147
+ with self._session_lock:
148
+ if self._session == session:
149
+ self._session = None
150
+ return fn(self._session_id())
151
+ raise
152
+
153
+ # ----------------------------------------------------------------- running
154
+
155
+ def run(self, install_signal_handlers: bool = True) -> None:
156
+ """Run until stopped (SIGINT/SIGTERM or :meth:`stop`)."""
157
+ if not self._tasks:
158
+ raise RuntimeError("no tasks registered")
159
+ logging.basicConfig(level=os.environ.get("ORBIT_LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(name)s %(message)s")
160
+ if install_signal_handlers and threading.current_thread() is threading.main_thread():
161
+ for sig in (signal.SIGINT, signal.SIGTERM):
162
+ signal.signal(sig, lambda *_: self.stop())
163
+ self._retrying(self._register_session)
164
+ threads = [threading.Thread(target=self._heartbeat_loop, name="orbit-heartbeat", daemon=True)]
165
+ threads += [threading.Thread(target=self._poll_loop, name=f"orbit-poll-{i}", daemon=True) for i in range(self.concurrency)]
166
+ for t in threads:
167
+ t.start()
168
+ try:
169
+ while not self._stop.is_set():
170
+ self._stop.wait(0.5)
171
+ finally:
172
+ for t in threads[1:]:
173
+ t.join(timeout=self.poll_wait_ms / 1000 + 5)
174
+ try:
175
+ if self._session:
176
+ self.client.post("/v1/workers/unregister", {"worker_session_id": self._session})
177
+ except ApiError:
178
+ pass
179
+ log.info("worker %s stopped", self.worker_id)
180
+
181
+ def start(self) -> threading.Thread:
182
+ """Run in a background thread (useful in tests and embedded use)."""
183
+ t = threading.Thread(target=self.run, kwargs={"install_signal_handlers": False}, daemon=True)
184
+ t.start()
185
+ return t
186
+
187
+ def stop(self) -> None:
188
+ self._stop.set()
189
+
190
+ def _retrying(self, fn: Callable[[], Any]) -> Any:
191
+ delay = 0.2
192
+ while True:
193
+ try:
194
+ return fn()
195
+ except ApiError as e:
196
+ if not e.is_connection_error and e.status < 500:
197
+ raise
198
+ if self._stop.is_set():
199
+ log.warning("%s; giving up because the worker is stopping", e.message)
200
+ return None
201
+ log.warning("%s; retrying in %.1fs", e.message, delay)
202
+ self._stop.wait(delay)
203
+ delay = min(delay * 2, 5.0) * (0.8 + random.random() * 0.4)
204
+
205
+ def _heartbeat_loop(self) -> None:
206
+ while not self._stop.wait(self._heartbeat_interval):
207
+ try:
208
+ r = self._with_session(lambda s: self.client.post("/v1/workers/heartbeat", {"worker_session_id": s})[1])
209
+ for token in r.get("cancel", []):
210
+ with self._active_lock:
211
+ ctx = self._active.get(token)
212
+ if ctx:
213
+ ctx.log("cancellation requested by runtime")
214
+ ctx.cancelled.set()
215
+ except ApiError as e:
216
+ log.debug("heartbeat failed: %s", e)
217
+
218
+ def _poll_loop(self) -> None:
219
+ backoff = 0.2
220
+ while not self._stop.is_set():
221
+ try:
222
+ status, task = self._with_session(
223
+ lambda s: self.client.post("/v1/workers/poll", {"worker_session_id": s, "wait_ms": self.poll_wait_ms})
224
+ )
225
+ backoff = 0.2
226
+ except ApiError as e:
227
+ if self._stop.is_set():
228
+ return
229
+ log.warning("poll failed: %s; retrying in %.1fs", e.message, backoff)
230
+ self._stop.wait(backoff)
231
+ backoff = min(backoff * 2, 5.0)
232
+ continue
233
+ if status == 204 or not task:
234
+ continue
235
+ self._execute(task)
236
+
237
+ def _execute(self, task: Dict[str, Any]) -> None:
238
+ ctx = Context(task, self)
239
+ impl = self._tasks.get(task["task_name"])
240
+ with self._active_lock:
241
+ self._active[ctx.token] = ctx
242
+ try:
243
+ if impl is None:
244
+ raise TaskError("UNKNOWN_TASK", f"worker does not implement {task['task_name']}", retryable=True)
245
+ ctx.log("executing", task=ctx.task_name, redelivery=ctx.redelivery)
246
+ result = impl.fn(task.get("input") or {}, ctx)
247
+ if inspect.isawaitable(result):
248
+ result = asyncio.run(_await(result))
249
+ if result is None:
250
+ result = {}
251
+ if not isinstance(result, dict):
252
+ raise TaskError("INVALID_RESULT", f"handler returned {type(result).__name__}; tasks must return a dict", retryable=False)
253
+ self._report("/v1/tasks/complete", {"token": ctx.token, "output": result})
254
+ except TaskError as e:
255
+ ctx.log("task failed", code=e.code)
256
+ self._report("/v1/tasks/fail", {"token": ctx.token, "error_code": e.code, "error_message": e.message, "retryable": e.retryable, "details": e.details})
257
+ except Exception as e: # noqa: BLE001 - report any handler crash to the runtime
258
+ tb = traceback.format_exc(limit=8)
259
+ log.error("task %s raised %s", task["task_name"], tb)
260
+ self._report(
261
+ "/v1/tasks/fail",
262
+ {"token": ctx.token, "error_code": "UNHANDLED_EXCEPTION", "error_message": f"{type(e).__name__}: {e}", "retryable": True, "details": {"traceback": tb}},
263
+ )
264
+ finally:
265
+ with self._active_lock:
266
+ self._active.pop(ctx.token, None)
267
+
268
+ def _report(self, path: str, body: Dict[str, Any]) -> None:
269
+ """Deliver a result, retrying through connection failures so that a
270
+ result survives a runtime restart (the runtime reconciles it)."""
271
+ r = self._retrying(lambda: self.client.post(path, body)[1])
272
+ if r and not r.get("accepted", True):
273
+ log.info("runtime ignored result for %s: %s", body["token"][:8], r.get("reason"))
274
+
275
+
276
+ async def _await(aw: Any) -> Any:
277
+ return await aw