threadify-sdk 0.2.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.
threadify/thread.py ADDED
@@ -0,0 +1,323 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import re
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ if TYPE_CHECKING:
8
+ from threadify.notification import Notification
9
+ from threadify.step import ThreadStep
10
+
11
+ from threadify.models import (
12
+ ACTION_ADD_REFS,
13
+ ACTION_CLOSE_THREAD,
14
+ ACTION_INVITE_PARTY,
15
+ ACTION_THREAD_END,
16
+ DEFAULT_WAIT_TIMEOUT,
17
+ FIELD_ACCESS_LEVEL,
18
+ FIELD_ACTION,
19
+ FIELD_CANCELLED_AT,
20
+ FIELD_CLOSED_AT,
21
+ FIELD_COMPLETED_AT,
22
+ FIELD_EXPIRES_AT,
23
+ FIELD_EXPIRES_IN,
24
+ FIELD_MESSAGE,
25
+ FIELD_REASON,
26
+ FIELD_REFS,
27
+ FIELD_ROLE,
28
+ FIELD_STATUS,
29
+ FIELD_THREAD_ID,
30
+ FIELD_THREAD_STATUS,
31
+ FIELD_THREAD_TOKEN,
32
+ STATUS_CANCELLED,
33
+ STATUS_COMPLETED,
34
+ STATUS_SUCCESS,
35
+ InviteOptions,
36
+ InviteResponse,
37
+ ThreadEndResponse,
38
+ WaitOptions,
39
+ first_non_empty,
40
+ require_non_empty,
41
+ )
42
+
43
+ UUID_REGEX = re.compile(
44
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE
45
+ )
46
+
47
+
48
+ class ThreadInstance:
49
+ """Represents an active thread on the Threadify Engine.
50
+
51
+ Usage::
52
+
53
+ thread = await conn.start(contract_name="order_flow")
54
+ step = thread.step("order_placed")
55
+ result = await step.add_context({"orderId": "ORD-123"}).success("Order received")
56
+ await thread.complete("All done")
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ conn: Any, # Connection (forward ref to avoid circular import)
62
+ thread_id: str,
63
+ contract_id: str = "",
64
+ role: str = "",
65
+ refs: dict[str, str] | None = None,
66
+ ):
67
+ self._conn = conn
68
+ self.thread_id = thread_id
69
+ self.contract_id = contract_id
70
+ self.role = role
71
+ self.refs: dict[str, str] = refs or {}
72
+
73
+ self._steps: dict[str, Any] = {}
74
+ self._pending_waits: dict[str, _PendingWait] = {}
75
+
76
+ def step(self, step_name: str) -> ThreadStep:
77
+ """Create a new step builder for this thread.
78
+
79
+ Args:
80
+ step_name: Unique name for the step.
81
+
82
+ Returns:
83
+ A ThreadStep builder.
84
+ """
85
+ from threadify.step import ThreadStep
86
+
87
+ s = ThreadStep(step_name, self, first_non_empty(self._conn.service_name))
88
+ if not step_name or not step_name.strip():
89
+ s._error = ValueError("step_name must be a non-empty string")
90
+
91
+ self._steps[step_name] = s
92
+ return s
93
+
94
+ async def invite_party(self, options: InviteOptions) -> InviteResponse:
95
+ """Create an invitation token for an external party.
96
+
97
+ Args:
98
+ options: Invitation configuration (role is required).
99
+
100
+ Returns:
101
+ InviteResponse with the token and metadata.
102
+ """
103
+ require_non_empty("role", options.role)
104
+
105
+ msg = {
106
+ FIELD_ACTION: ACTION_INVITE_PARTY,
107
+ FIELD_THREAD_ID: self.thread_id,
108
+ FIELD_ROLE: options.role,
109
+ FIELD_ACCESS_LEVEL: options.access_level or "external",
110
+ FIELD_EXPIRES_IN: options.expires_in or "24h",
111
+ }
112
+
113
+ await self._send(msg)
114
+
115
+ resp = await self._conn._wait_response(lambda m: m.get(FIELD_ACTION) == ACTION_INVITE_PARTY)
116
+
117
+ if resp.get(FIELD_STATUS) != STATUS_SUCCESS:
118
+ raise RuntimeError(resp.get(FIELD_MESSAGE, "failed to create invitation token"))
119
+
120
+ return InviteResponse(
121
+ token=resp.get(FIELD_THREAD_TOKEN, ""),
122
+ thread_id=self.thread_id,
123
+ role=resp.get(FIELD_ROLE, ""),
124
+ access_level=resp.get(FIELD_ACCESS_LEVEL, ""),
125
+ expires_at=resp.get(FIELD_EXPIRES_AT, ""),
126
+ )
127
+
128
+ async def wait_for(
129
+ self,
130
+ step_name: str,
131
+ options: WaitOptions | None = None,
132
+ ) -> Notification:
133
+ """Block until a notification arrives for the given step.
134
+
135
+ Args:
136
+ step_name: Step to wait for.
137
+ options: WaitOptions with timeout and status filters.
138
+
139
+ Returns:
140
+ The matching Notification.
141
+
142
+ Raises:
143
+ asyncio.TimeoutError: If the wait times out.
144
+ """
145
+ require_non_empty("step_name", step_name)
146
+
147
+ timeout = DEFAULT_WAIT_TIMEOUT
148
+ statuses: list[str] = []
149
+ if options:
150
+ if options.timeout > 0:
151
+ timeout = options.timeout
152
+ statuses = options.statuses
153
+
154
+ fut: asyncio.Future[Notification] = asyncio.get_event_loop().create_future()
155
+ pw = _PendingWait(future=fut, statuses=statuses)
156
+ self._pending_waits[step_name] = pw
157
+
158
+ try:
159
+ return await asyncio.wait_for(fut, timeout=timeout)
160
+ except asyncio.TimeoutError as err:
161
+ raise asyncio.TimeoutError(
162
+ f"Timeout waiting for step: {step_name} ({timeout}s)"
163
+ ) from err
164
+ finally:
165
+ self._pending_waits.pop(step_name, None)
166
+
167
+ async def add_refs(self, refs: dict[str, str]) -> None:
168
+ """Add external references to this thread.
169
+
170
+ Args:
171
+ refs: Key-value pairs of references.
172
+ """
173
+ if not refs:
174
+ raise ValueError("refs must be a non-empty dict")
175
+
176
+ msg = {
177
+ FIELD_ACTION: ACTION_ADD_REFS,
178
+ FIELD_THREAD_ID: self.thread_id,
179
+ FIELD_REFS: refs,
180
+ }
181
+
182
+ await self._send(msg)
183
+
184
+ resp = await self._conn._wait_response(lambda m: m.get(FIELD_ACTION) == ACTION_ADD_REFS)
185
+
186
+ if resp.get(FIELD_STATUS) != STATUS_SUCCESS:
187
+ raise RuntimeError(resp.get(FIELD_MESSAGE, "failed to add refs"))
188
+
189
+ self.refs.update(refs)
190
+
191
+ async def link_thread(self, thread_id: str, relationship: str = "parent") -> None:
192
+ """Link this thread to another thread via a reference.
193
+
194
+ Args:
195
+ thread_id: UUID of the thread to link.
196
+ relationship: Relationship type (default: "parent").
197
+ """
198
+ require_non_empty("thread_id", thread_id)
199
+ if not UUID_REGEX.match(thread_id):
200
+ raise ValueError("Invalid thread ID format")
201
+
202
+ ref_key = f"linkedThread:{relationship}"
203
+ await self.add_refs({ref_key: thread_id})
204
+
205
+ async def end(
206
+ self, status: str = STATUS_CANCELLED, reason: str | dict[str, Any] = ""
207
+ ) -> ThreadEndResponse:
208
+ """End the thread with the given status.
209
+
210
+ Args:
211
+ status: Thread end status ("cancelled", "completed").
212
+ reason: Optional reason message (string) or data dict.
213
+ """
214
+ return await self._end_thread(status, reason)
215
+
216
+ async def close(self, reason: str | dict[str, Any] = "") -> ThreadEndResponse:
217
+ """Close the thread (convenience for end with 'cancelled')."""
218
+ return await self._end_thread(STATUS_CANCELLED, reason)
219
+
220
+ async def complete(self, reason: str | dict[str, Any] = "") -> ThreadEndResponse:
221
+ """Complete the thread (convenience for end with 'completed')."""
222
+ return await self._end_thread(STATUS_COMPLETED, reason)
223
+
224
+ async def _end_thread(self, status: str, reason: str | dict[str, Any]) -> ThreadEndResponse:
225
+ msg: dict[str, Any] = {
226
+ FIELD_ACTION: ACTION_THREAD_END,
227
+ FIELD_THREAD_ID: self.thread_id,
228
+ FIELD_STATUS: status,
229
+ }
230
+ if isinstance(reason, str) and reason:
231
+ msg[FIELD_REASON] = reason
232
+ elif isinstance(reason, dict) and reason:
233
+ msg.update(reason)
234
+
235
+ await self._send(msg)
236
+
237
+ resp = await self._conn._wait_response(
238
+ lambda m: m.get(FIELD_ACTION) in (ACTION_THREAD_END, ACTION_CLOSE_THREAD)
239
+ )
240
+
241
+ if resp.get(FIELD_STATUS) != STATUS_SUCCESS:
242
+ raise RuntimeError(resp.get(FIELD_MESSAGE, "failed to end thread"))
243
+
244
+ self._cleanup()
245
+
246
+ import datetime as dt
247
+
248
+ ended_at = first_non_empty(
249
+ resp.get(FIELD_CLOSED_AT, ""),
250
+ resp.get(FIELD_COMPLETED_AT, ""),
251
+ resp.get(FIELD_CANCELLED_AT, ""),
252
+ dt.datetime.now(dt.timezone.utc).isoformat(),
253
+ )
254
+
255
+ return ThreadEndResponse(
256
+ thread_id=self.thread_id,
257
+ status=resp.get(FIELD_THREAD_STATUS, ""),
258
+ ended_at=ended_at,
259
+ message=resp.get(FIELD_MESSAGE, ""),
260
+ )
261
+
262
+ async def _send(self, msg: dict[str, Any]) -> None:
263
+ await self._conn._send(msg)
264
+
265
+ def _handle_notification(self, notif: Notification) -> None:
266
+ """Route notification to pending wait_for calls."""
267
+ pw = self._pending_waits.get(notif.step_name)
268
+ if pw is None:
269
+ return
270
+
271
+ # Check status filter.
272
+ if pw.statuses and notif.step_status not in pw.statuses:
273
+ return
274
+
275
+ # Deliver notification.
276
+ if not pw.future.done():
277
+ pw.future.set_result(notif)
278
+
279
+ def get_step(self, step_name: str) -> Any | None:
280
+ """Return the step instance for the given step name, if any."""
281
+ return self._steps.get(step_name)
282
+
283
+ def get_all_steps(self) -> list[Any]:
284
+ """Return all recorded steps for this thread."""
285
+ return list(self._steps.values())
286
+
287
+ def get_thread_id(self) -> str:
288
+ """Return the thread ID."""
289
+ return self.thread_id
290
+
291
+ def get_contract_id(self) -> str:
292
+ """Return the contract ID (or empty string)."""
293
+ return self.contract_id
294
+
295
+ def create_span_exporter(self, options: dict[str, Any] | None = None) -> Any:
296
+ """Create an OpenTelemetry SpanExporter wired to this thread.
297
+
298
+ Args:
299
+ options: Optional configuration dict. Supported keys:
300
+ - ``refs``: list of attribute keys to map to Threadify refs.
301
+
302
+ Returns:
303
+ A :class:`~threadify.otel_exporter.ThreadifySpanExporter` instance.
304
+ """
305
+ from threadify.otel_exporter import ThreadifySpanExporter
306
+
307
+ return ThreadifySpanExporter(self._conn, options or {})
308
+
309
+ def _cleanup(self) -> None:
310
+ """Cancel pending waits and unregister from connection."""
311
+ for pw in self._pending_waits.values():
312
+ if not pw.future.done():
313
+ pw.future.cancel()
314
+ self._pending_waits.clear()
315
+ self._conn._remove_thread(self.thread_id)
316
+
317
+
318
+ class _PendingWait:
319
+ """Internal state for a pending wait_for call."""
320
+
321
+ def __init__(self, future: asyncio.Future, statuses: list[str]):
322
+ self.future = future
323
+ self.statuses = statuses
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: threadify-sdk
3
+ Version: 0.2.0
4
+ Summary: Python SDK for the Threadify Engine — workflow orchestration via WebSocket and GraphQL
5
+ Author-email: Threadify Team <team@threadify.dev>
6
+ License: MIT
7
+ Keywords: threadify,workflow,orchestration,websocket,graphql
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: websockets>=12.0
21
+ Requires-Dist: httpx>=0.27.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8.0; extra == "dev"
24
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
25
+ Requires-Dist: ruff>=0.3; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ # Threadify Python SDK
29
+
30
+ Python SDK for connecting to the Threadify Engine over WebSocket and querying archived data over GraphQL.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install threadify-sdk
36
+ ```
37
+
38
+ For local development:
39
+
40
+ ```bash
41
+ pip install -e ".[dev]"
42
+ ```
43
+
44
+ ## Quick Start
45
+
46
+ ```python
47
+ import asyncio
48
+ import logging
49
+ from threadify import Threadify
50
+
51
+
52
+ async def main():
53
+ try:
54
+ conn = await Threadify.connect(
55
+ "your-api-key",
56
+ service_name="orders-service",
57
+ ws_url="wss://eng.threadify.dev/threads",
58
+ )
59
+ except Exception as e:
60
+ logging.error(f"Failed to connect: {e}")
61
+ return
62
+
63
+ try:
64
+ thread = await conn.start(contract_name="order_flow")
65
+
66
+ # Easy chaining!
67
+ await (
68
+ thread.step("order_received")
69
+ .add_context({"orderId": "ORD-123"})
70
+ .success("Order accepted")
71
+ )
72
+ except Exception as e:
73
+ logging.error(f"Error in thread: {e}")
74
+ finally:
75
+ await conn.close()
76
+
77
+
78
+ if __name__ == "__main__":
79
+ asyncio.run(main())
80
+ ```
81
+
82
+ `ws_url` is required. The SDK no longer uses a hardcoded default URL.
83
+
84
+ ## Configuration
85
+
86
+ ### Connect options
87
+
88
+ Use keyword arguments with `Threadify.connect(...)`:
89
+
90
+ - `service_name`
91
+ - `ws_url` (required)
92
+ - `graphql_url`
93
+ - `debug`
94
+ - `max_in_flight`
95
+ - `connect_timeout`
96
+
97
+ Example:
98
+
99
+ ```python
100
+ from threadify import Threadify
101
+
102
+ conn = await Threadify.connect(
103
+ "your-api-key",
104
+ service_name="inventory-service",
105
+ ws_url="wss://eng.threadify.dev/threads",
106
+ debug=True,
107
+ )
108
+ ```
109
+
110
+ ### Join options
111
+
112
+ Use `Connection.join(...)` with keyword arguments:
113
+
114
+ - `token=...`
115
+ - `thread_id=...` and `role=...`
116
+
117
+ Example:
118
+
119
+ ```python
120
+ thread = await conn.join(token="jwt-token")
121
+ ```
122
+
123
+ Or:
124
+
125
+ ```python
126
+ thread = await conn.join(
127
+ thread_id="thread-123",
128
+ role="supplier",
129
+ )
130
+ ```
131
+
132
+ ## Subscriptions
133
+
134
+ Preferred API:
135
+
136
+ - `subscribe(event, step_name, handler)`
137
+ - `unsubscribe(event, step_name)`
138
+
139
+ Supported event patterns:
140
+
141
+ - `step.success`
142
+ - `step.failed`
143
+ - `step.*`
144
+ - `rule.passed`
145
+ - `rule.violated`
146
+ - `rule.*`
147
+ - `*`
148
+
149
+ Example:
150
+
151
+ ```python
152
+ def handle_notification(notification):
153
+ if notification.is_violated:
154
+ print(notification.message)
155
+
156
+
157
+
158
+ conn.subscribe("rule.violated", "payment_step", handle_notification)
159
+ ```
160
+
161
+ ## Versioning & Releases
162
+
163
+ This SDK follows [Semantic Versioning](https://semver.org/) and [Conventional Commits](https://www.conventionalcommits.org/). Releases are automated via GitHub Actions.
164
+
165
+ - `fix: ...` -> Patch bump
166
+ - `feat: ...` -> Minor bump
167
+ - `feat!: ...` or `BREAKING CHANGE: ...` -> Major bump
168
+
169
+ ## Testing
170
+
171
+ To run the SDK tests, execute:
172
+
173
+ ```bash
174
+ make test
175
+ ```
176
+
177
+ Alternatively, use `pytest`:
178
+
179
+ ```bash
180
+ python3 -m pytest
181
+ ```
@@ -0,0 +1,14 @@
1
+ threadify/__init__.py,sha256=hlYiyomlvtHxKh0c-hU-pNtCidkdxvC7ymcKJyFRUqI,1215
2
+ threadify/client.py,sha256=uS2IFZVzBY2siTDYcxZ3L_7f9j2uV4oH-mdlhRnTyds,5782
3
+ threadify/connection.py,sha256=TXxC95vnPfmL77tVjJI6QSTOVJXBslKzUsoRG5MM0ys,17869
4
+ threadify/data_retriever.py,sha256=jjI6nljYd8h1yF06rGUmSwLtGqHBNBHemVaDlYMmFeg,15484
5
+ threadify/models.py,sha256=TMdXJQCG7kCRepyeWSBXimK5Toxt9K7oTZPChxhwFUM,7224
6
+ threadify/notification.py,sha256=lYddMp9xtp5-4I4vB41MKwviEyhZ5rMJ0QvQodzOHac,4886
7
+ threadify/otel_exporter.py,sha256=OrQwfz_MIL2vF9SzwcylgQCu3WLUDd1-AmVg9C_8gzg,11807
8
+ threadify/step.py,sha256=-z0HL-aqz3qBzwgUQPWYrct3lCSOpviARUqQA5qhGWw,9950
9
+ threadify/thread.py,sha256=KllVL9Zi5xp30bXxuyoZAD64Nj7rcB8TSUNnNHndOIQ,10295
10
+ threadify_sdk-0.2.0.dist-info/licenses/LICENSE,sha256=orhDDcZEkD3EZpCpx7e7e1_dP_cI0Udimcoz6Kl9iW0,1066
11
+ threadify_sdk-0.2.0.dist-info/METADATA,sha256=5namSZAJQKMV4AyXbmthhUHBMpEn5jww881tPbz9_l8,3769
12
+ threadify_sdk-0.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
13
+ threadify_sdk-0.2.0.dist-info/top_level.txt,sha256=xeA9h3XRewc6Orx51hv8tBaiRU9FvmVP9wJrG54_xew,10
14
+ threadify_sdk-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Threadify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ threadify