flowsmith 0.6.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.
- flowsmith/__init__.py +80 -0
- flowsmith/__main__.py +183 -0
- flowsmith/config.py +137 -0
- flowsmith/context.py +34 -0
- flowsmith/contrib/__init__.py +1 -0
- flowsmith/decorators.py +147 -0
- flowsmith/exceptions.py +52 -0
- flowsmith/executor.py +291 -0
- flowsmith/flow.py +172 -0
- flowsmith/migrations/__init__.py +0 -0
- flowsmith/models/__init__.py +4 -0
- flowsmith/models/flow_record.py +19 -0
- flowsmith/models/node_record.py +21 -0
- flowsmith/py.typed +1 -0
- flowsmith/step.py +66 -0
- flowsmith/storage/__init__.py +6 -0
- flowsmith/storage/base.py +87 -0
- flowsmith/storage/memory.py +127 -0
- flowsmith/storage/mysql.py +203 -0
- flowsmith/storage/postgres.py +194 -0
- flowsmith/watchdog.py +133 -0
- flowsmith-0.6.0.dist-info/METADATA +430 -0
- flowsmith-0.6.0.dist-info/RECORD +27 -0
- flowsmith-0.6.0.dist-info/WHEEL +5 -0
- flowsmith-0.6.0.dist-info/entry_points.txt +2 -0
- flowsmith-0.6.0.dist-info/licenses/LICENSE +21 -0
- flowsmith-0.6.0.dist-info/top_level.txt +1 -0
flowsmith/executor.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import logging
|
|
3
|
+
import platform
|
|
4
|
+
import random
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from contextlib import suppress
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from flowsmith.context import Context
|
|
11
|
+
from flowsmith.exceptions import StepFailed, StepTimeoutError
|
|
12
|
+
from flowsmith.models import FlowRecord
|
|
13
|
+
from flowsmith.step import ParallelGroup, Step
|
|
14
|
+
from flowsmith.storage.base import StorageBackend
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("flowsmith.executor")
|
|
17
|
+
|
|
18
|
+
# Grace period given to a timed-out thread to clean up after receiving
|
|
19
|
+
# StepTimeoutError before the hard kill fires.
|
|
20
|
+
_HARD_KILL_GRACE_SECONDS = 2
|
|
21
|
+
|
|
22
|
+
# Thread ident type varies by platform — unsigned on Windows, signed on
|
|
23
|
+
# Linux/macOS. Using the wrong type causes ctypes to silently target the
|
|
24
|
+
# wrong thread (or no thread at all).
|
|
25
|
+
_THREAD_ID_TYPE = ctypes.c_ulong if platform.system() == "Windows" else ctypes.c_ulong
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _calc_backoff(step: Step, attempt: int) -> float:
|
|
29
|
+
"""
|
|
30
|
+
Calculate the delay in seconds before the next retry attempt.
|
|
31
|
+
|
|
32
|
+
attempt is 1-indexed — attempt=1 means the first failure just happened,
|
|
33
|
+
so we're calculating the delay before attempt 2.
|
|
34
|
+
|
|
35
|
+
Strategies:
|
|
36
|
+
fixed — constant backoff_base seconds every retry
|
|
37
|
+
exponential — backoff_base * 2^(attempt-1), capped at 60s
|
|
38
|
+
jitter — exponential base + uniform random jitter up to the base
|
|
39
|
+
avoids thundering herd when many flows retry simultaneously
|
|
40
|
+
"""
|
|
41
|
+
if step.backoff_base == 0.0:
|
|
42
|
+
return 0.0
|
|
43
|
+
|
|
44
|
+
if step.backoff == "fixed":
|
|
45
|
+
return step.backoff_base
|
|
46
|
+
|
|
47
|
+
# exponential base: backoff_base * 2^(attempt-1)
|
|
48
|
+
exp_delay = step.backoff_base * (2 ** (attempt - 1))
|
|
49
|
+
exp_delay = min(exp_delay, 60.0) # cap at 60s
|
|
50
|
+
|
|
51
|
+
if step.backoff == "exponential":
|
|
52
|
+
return float(exp_delay)
|
|
53
|
+
|
|
54
|
+
# jitter: exponential + random noise up to the exponential value
|
|
55
|
+
# keeps retries spread out even when many processes crash simultaneously
|
|
56
|
+
return float(exp_delay + random.uniform(0, exp_delay))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _raise_in_thread(thread: threading.Thread, exc_type: type) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Inject an exception into a running thread using ctypes.
|
|
62
|
+
|
|
63
|
+
This is the standard Python pattern for interrupting a thread from outside.
|
|
64
|
+
The exception is delivered at the next Python bytecode boundary — it will
|
|
65
|
+
NOT interrupt a thread blocked in a C extension or I/O syscall.
|
|
66
|
+
If the thread is stuck in C code, the hard kill grace period fires instead.
|
|
67
|
+
"""
|
|
68
|
+
if thread.ident is None:
|
|
69
|
+
raise ValueError("Thread is not started")
|
|
70
|
+
|
|
71
|
+
result = ctypes.pythonapi.PyThreadState_SetAsyncExc(
|
|
72
|
+
_THREAD_ID_TYPE(thread.ident),
|
|
73
|
+
ctypes.py_object(exc_type),
|
|
74
|
+
)
|
|
75
|
+
if result == 0:
|
|
76
|
+
raise ValueError(f"Thread {thread.ident} not found — already finished?")
|
|
77
|
+
if result > 1:
|
|
78
|
+
# More than one thread affected — undo and raise
|
|
79
|
+
ctypes.pythonapi.PyThreadState_SetAsyncExc(_THREAD_ID_TYPE(thread.ident), None)
|
|
80
|
+
raise SystemError("PyThreadState_SetAsyncExc affected multiple threads")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class _StepRunner:
|
|
84
|
+
"""
|
|
85
|
+
Runs a single step function in a worker thread with optional timeout.
|
|
86
|
+
|
|
87
|
+
Timeout behaviour (when step.timeout is set):
|
|
88
|
+
1. Step runs in a daemon worker thread.
|
|
89
|
+
2. Main thread waits up to step.timeout seconds.
|
|
90
|
+
3. On timeout: inject StepTimeoutError into the worker thread (clean kill).
|
|
91
|
+
4. Give the worker _HARD_KILL_GRACE_SECONDS to finish cleanup.
|
|
92
|
+
5. If still running: hard kill via ctypes (brutal — last resort).
|
|
93
|
+
|
|
94
|
+
Without timeout: step runs in the calling thread directly (no overhead).
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
def __init__(self, step: Step, ctx: Context):
|
|
98
|
+
self._step = step
|
|
99
|
+
self._ctx = ctx
|
|
100
|
+
self._result = None
|
|
101
|
+
self._exception: Exception | None = None
|
|
102
|
+
self._thread: threading.Thread | None = None
|
|
103
|
+
|
|
104
|
+
def run(self) -> dict[str, Any]:
|
|
105
|
+
"""
|
|
106
|
+
Execute the step. Returns the step's output dict.
|
|
107
|
+
Raises StepTimeoutError or any exception thrown by the step function.
|
|
108
|
+
"""
|
|
109
|
+
if self._step.timeout is None:
|
|
110
|
+
return self._run_direct()
|
|
111
|
+
return self._run_with_timeout()
|
|
112
|
+
|
|
113
|
+
def _run_direct(self) -> dict[str, Any]:
|
|
114
|
+
"""Run step in the calling thread — no timeout, no overhead."""
|
|
115
|
+
result = self._step.fn(self._ctx)
|
|
116
|
+
return result if isinstance(result, dict) else {}
|
|
117
|
+
|
|
118
|
+
def _run_with_timeout(self) -> dict[str, Any]:
|
|
119
|
+
"""Run step in a worker thread, enforce timeout."""
|
|
120
|
+
self._thread = threading.Thread(
|
|
121
|
+
target=self._worker,
|
|
122
|
+
daemon=True,
|
|
123
|
+
name=f"ff-step-{self._step.name}",
|
|
124
|
+
)
|
|
125
|
+
self._thread.start()
|
|
126
|
+
self._thread.join(timeout=self._step.timeout)
|
|
127
|
+
|
|
128
|
+
if not self._thread.is_alive():
|
|
129
|
+
# Step finished within timeout
|
|
130
|
+
if self._exception is not None:
|
|
131
|
+
raise self._exception
|
|
132
|
+
return self._result if isinstance(self._result, dict) else {}
|
|
133
|
+
|
|
134
|
+
# ---- Timeout exceeded ----
|
|
135
|
+
|
|
136
|
+
# Step 1: clean kill — inject StepTimeoutError into the worker
|
|
137
|
+
with suppress(ValueError, SystemError): # thread already finished between join() and here
|
|
138
|
+
_raise_in_thread(self._thread, StepTimeoutError)
|
|
139
|
+
|
|
140
|
+
# Step 2: give it grace period to handle the exception and clean up
|
|
141
|
+
self._thread.join(timeout=_HARD_KILL_GRACE_SECONDS)
|
|
142
|
+
|
|
143
|
+
if self._thread.is_alive():
|
|
144
|
+
# Step 3: hard kill — thread is stuck in C code or ignoring exception
|
|
145
|
+
# This is a last resort — the thread becomes a zombie but the
|
|
146
|
+
# main process can continue. Log the situation clearly.
|
|
147
|
+
with suppress(ValueError, SystemError):# thread already finished between join() and here
|
|
148
|
+
_raise_in_thread(self._thread, SystemExit)
|
|
149
|
+
|
|
150
|
+
raise StepTimeoutError(
|
|
151
|
+
step_name=self._step.name,
|
|
152
|
+
timeout=self._step.timeout or 0,
|
|
153
|
+
attempt=1, # caller will set the real attempt number
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def _worker(self) -> None:
|
|
157
|
+
"""Worker thread body — captures result or exception."""
|
|
158
|
+
try:
|
|
159
|
+
self._result = self._step.fn(self._ctx)
|
|
160
|
+
except Exception as exc:
|
|
161
|
+
self._exception = exc
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class Executor:
|
|
165
|
+
"""
|
|
166
|
+
Runs the steps of a flow in order, handling:
|
|
167
|
+
- Skip: completed steps are never re-run, output is restored to ctx
|
|
168
|
+
- Retry: attempt a step up to step.retries times before raising StepFailed
|
|
169
|
+
- Backoff: configurable delay between retries (fixed, exponential, jitter)
|
|
170
|
+
- Timeout: steps exceeding step.timeout seconds are killed and retried
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def __init__(self, storage: StorageBackend):
|
|
174
|
+
self._storage = storage
|
|
175
|
+
|
|
176
|
+
def run(self, flow: FlowRecord, steps: list[Step | ParallelGroup], ctx: Context) -> None:
|
|
177
|
+
"""
|
|
178
|
+
Execute all steps (or step groups) in order. Modifies ctx in-place as tasks complete.
|
|
179
|
+
"""
|
|
180
|
+
for item in steps:
|
|
181
|
+
if isinstance(item, ParallelGroup):
|
|
182
|
+
self._execute_group(flow, item, ctx)
|
|
183
|
+
else:
|
|
184
|
+
self._execute_step(flow, item, ctx)
|
|
185
|
+
|
|
186
|
+
def _execute_group(self, flow: FlowRecord, group: ParallelGroup, ctx: Context) -> None:
|
|
187
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
188
|
+
|
|
189
|
+
if not group.steps:
|
|
190
|
+
return
|
|
191
|
+
|
|
192
|
+
with ThreadPoolExecutor(max_workers=len(group.steps)) as pool:
|
|
193
|
+
futures = [
|
|
194
|
+
pool.submit(self._execute_step, flow, step, ctx)
|
|
195
|
+
for step in group.steps
|
|
196
|
+
]
|
|
197
|
+
|
|
198
|
+
exceptions = []
|
|
199
|
+
for future in as_completed(futures):
|
|
200
|
+
try:
|
|
201
|
+
future.result()
|
|
202
|
+
except Exception as exc:
|
|
203
|
+
exceptions.append(exc)
|
|
204
|
+
|
|
205
|
+
if exceptions:
|
|
206
|
+
# Raise the first exception to fail the group iteration
|
|
207
|
+
raise exceptions[0]
|
|
208
|
+
|
|
209
|
+
def _execute_step(self, flow: FlowRecord, step: Step, ctx: Context) -> None:
|
|
210
|
+
node = self._storage.get_node(flow.id, step.name)
|
|
211
|
+
|
|
212
|
+
# Already completed on a previous run — restore output and skip
|
|
213
|
+
if node and node.status == "COMPLETED":
|
|
214
|
+
if node.output_data:
|
|
215
|
+
ctx.store(step.name, node.output_data)
|
|
216
|
+
logger.debug("Step '%s' already completed — skipped", step.name)
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
if step.condition is not None and not step.condition(ctx):
|
|
220
|
+
logger.info("Step '%s' condition evaluated to False — skipped", step.name)
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
last_exception: Exception | None = None
|
|
224
|
+
|
|
225
|
+
for attempt in range(1, step.retries + 1):
|
|
226
|
+
logger.info(
|
|
227
|
+
"Step '%s' starting (attempt %d/%d)",
|
|
228
|
+
step.name, attempt, step.retries,
|
|
229
|
+
)
|
|
230
|
+
self._storage.start_node(
|
|
231
|
+
flow_id=flow.id,
|
|
232
|
+
step_name=step.name,
|
|
233
|
+
input_data=ctx.snapshot(),
|
|
234
|
+
)
|
|
235
|
+
try:
|
|
236
|
+
runner = _StepRunner(step, ctx)
|
|
237
|
+
output = runner.run()
|
|
238
|
+
|
|
239
|
+
self._storage.complete_node(
|
|
240
|
+
flow_id=flow.id,
|
|
241
|
+
step_name=step.name,
|
|
242
|
+
output_data=output,
|
|
243
|
+
)
|
|
244
|
+
ctx.store(step.name, output)
|
|
245
|
+
logger.info("Step '%s' completed (attempt %d/%d)", step.name, attempt, step.retries)
|
|
246
|
+
return # success
|
|
247
|
+
|
|
248
|
+
except StepTimeoutError as exc:
|
|
249
|
+
# Re-raise with the correct attempt number
|
|
250
|
+
exc.attempt = attempt
|
|
251
|
+
last_exception = exc
|
|
252
|
+
self._storage.fail_node(
|
|
253
|
+
flow_id=flow.id,
|
|
254
|
+
step_name=step.name,
|
|
255
|
+
error=str(exc),
|
|
256
|
+
attempt=attempt,
|
|
257
|
+
)
|
|
258
|
+
logger.warning(
|
|
259
|
+
"Step '%s' timed out after %ds (attempt %d/%d)",
|
|
260
|
+
step.name, step.timeout, attempt, step.retries,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
except Exception as exc:
|
|
264
|
+
last_exception = exc
|
|
265
|
+
self._storage.fail_node(
|
|
266
|
+
flow_id=flow.id,
|
|
267
|
+
step_name=step.name,
|
|
268
|
+
error=str(exc),
|
|
269
|
+
attempt=attempt,
|
|
270
|
+
)
|
|
271
|
+
logger.warning(
|
|
272
|
+
"Step '%s' failed (attempt %d/%d): %s",
|
|
273
|
+
step.name, attempt, step.retries, exc,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
# Apply backoff before next attempt (not after last failure)
|
|
277
|
+
if attempt < step.retries:
|
|
278
|
+
delay = _calc_backoff(step, attempt)
|
|
279
|
+
if delay > 0:
|
|
280
|
+
logger.info(
|
|
281
|
+
"Step '%s' retrying in %.1fs (%s backoff)",
|
|
282
|
+
step.name, delay, step.backoff,
|
|
283
|
+
)
|
|
284
|
+
time.sleep(delay)
|
|
285
|
+
|
|
286
|
+
raise StepFailed(
|
|
287
|
+
step_name=step.name,
|
|
288
|
+
attempt=step.retries,
|
|
289
|
+
original=last_exception or Exception("Unknown error"),
|
|
290
|
+
)
|
|
291
|
+
|
flowsmith/flow.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from flowsmith.context import Context
|
|
6
|
+
from flowsmith.exceptions import FlowAlreadyCompleted
|
|
7
|
+
from flowsmith.executor import Executor
|
|
8
|
+
from flowsmith.step import ParallelGroup, Step
|
|
9
|
+
from flowsmith.storage.base import StorageBackend
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Flow:
|
|
13
|
+
"""
|
|
14
|
+
Defines a named workflow as an ordered sequence of steps.
|
|
15
|
+
|
|
16
|
+
Usage (production — uses global config):
|
|
17
|
+
flow = Flow("process_order")
|
|
18
|
+
flow.step("charge_payment", charge_payment, retries=3)
|
|
19
|
+
flow.step("create_order", create_order, retries=3)
|
|
20
|
+
flow.step("send_confirmation", send_confirmation, retries=2)
|
|
21
|
+
flow.run(ctx, tracking_id="order_abc123")
|
|
22
|
+
|
|
23
|
+
Usage (testing — local storage override):
|
|
24
|
+
flow = Flow("process_order", storage=InMemoryStorage())
|
|
25
|
+
...
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, name: str, storage: StorageBackend | None = None) -> None:
|
|
29
|
+
self.name = name
|
|
30
|
+
self._steps: list[Step | ParallelGroup] = []
|
|
31
|
+
self._storage_override = storage
|
|
32
|
+
self._active_parallel_group: ParallelGroup | None = None
|
|
33
|
+
|
|
34
|
+
@contextlib.contextmanager
|
|
35
|
+
def parallel(self) -> Any:
|
|
36
|
+
"""
|
|
37
|
+
Context manager to bundle subsequent step() calls into a ParallelGroup.
|
|
38
|
+
When executed, all steps in this group run concurrently.
|
|
39
|
+
"""
|
|
40
|
+
group = ParallelGroup(steps=[])
|
|
41
|
+
self._active_parallel_group = group
|
|
42
|
+
try:
|
|
43
|
+
yield
|
|
44
|
+
finally:
|
|
45
|
+
self._active_parallel_group = None
|
|
46
|
+
if group.steps:
|
|
47
|
+
self._steps.append(group)
|
|
48
|
+
def step(
|
|
49
|
+
self,
|
|
50
|
+
name: str,
|
|
51
|
+
fn: Callable[..., Any],
|
|
52
|
+
retries: int = 1,
|
|
53
|
+
backoff: str = "fixed",
|
|
54
|
+
backoff_base: float = 0.0,
|
|
55
|
+
timeout: int | None = None,
|
|
56
|
+
condition: Callable[..., Any] | None = None,
|
|
57
|
+
) -> "Flow":
|
|
58
|
+
"""
|
|
59
|
+
Register a step on this flow.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
name: Unique step identifier. Used as the DB key and ctx.data key.
|
|
63
|
+
fn: Callable with signature (ctx: Context) -> dict.
|
|
64
|
+
retries: Total attempts including the first. retries=3 means
|
|
65
|
+
the step will be tried up to 3 times before failing.
|
|
66
|
+
backoff: Delay strategy between retries.
|
|
67
|
+
"fixed" — constant backoff_base seconds
|
|
68
|
+
"exponential" — backoff_base * 2^(attempt-1), capped at 60s
|
|
69
|
+
"jitter" — exponential + random noise (avoids thundering herd)
|
|
70
|
+
backoff_base: Base delay in seconds. Default 0.0 (instant retry).
|
|
71
|
+
timeout: Max seconds a single attempt may run. None = no timeout.
|
|
72
|
+
On timeout: StepTimeoutError is raised and the attempt
|
|
73
|
+
counts as a failure — retried if attempts remain.
|
|
74
|
+
condition: Predicate func (ctx: Context) -> bool. If returns False,
|
|
75
|
+
the step is skipped during execution.
|
|
76
|
+
|
|
77
|
+
Returns self for optional chaining.
|
|
78
|
+
"""
|
|
79
|
+
step_obj = Step(
|
|
80
|
+
name=name,
|
|
81
|
+
fn=fn,
|
|
82
|
+
retries=retries,
|
|
83
|
+
backoff=backoff,
|
|
84
|
+
backoff_base=backoff_base,
|
|
85
|
+
timeout=timeout,
|
|
86
|
+
condition=condition,
|
|
87
|
+
)
|
|
88
|
+
if self._active_parallel_group is not None:
|
|
89
|
+
self._active_parallel_group.steps.append(step_obj)
|
|
90
|
+
else:
|
|
91
|
+
self._steps.append(step_obj)
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def subflow(
|
|
95
|
+
self,
|
|
96
|
+
name: str,
|
|
97
|
+
flow: "Flow",
|
|
98
|
+
tracking_id: str | Callable[[Context], str],
|
|
99
|
+
retries: int = 1,
|
|
100
|
+
backoff: str = "fixed",
|
|
101
|
+
backoff_base: float = 0.0,
|
|
102
|
+
timeout: int | None = None,
|
|
103
|
+
condition: Callable[..., Any] | None = None,
|
|
104
|
+
) -> "Flow":
|
|
105
|
+
"""
|
|
106
|
+
Formally register an embedded sub-flow as a step execution.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
flow: The Flow instance to trigger.
|
|
110
|
+
tracking_id: Either a static string or a callable (ctx) -> str
|
|
111
|
+
for dynamic tracking IDs based on runtime context.
|
|
112
|
+
"""
|
|
113
|
+
def _subflow_runner(ctx: Context) -> dict[str, Any]:
|
|
114
|
+
tid = tracking_id(ctx) if callable(tracking_id) else tracking_id
|
|
115
|
+
flow.run(ctx, tracking_id=tid)
|
|
116
|
+
return {"tracking_id": tid, "status": "COMPLETED"}
|
|
117
|
+
|
|
118
|
+
return self.step(
|
|
119
|
+
name=name,
|
|
120
|
+
fn=_subflow_runner,
|
|
121
|
+
retries=retries,
|
|
122
|
+
backoff=backoff,
|
|
123
|
+
backoff_base=backoff_base,
|
|
124
|
+
timeout=timeout,
|
|
125
|
+
condition=condition,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
def run(self, ctx: Context, tracking_id: str) -> None:
|
|
129
|
+
"""
|
|
130
|
+
Execute the flow.
|
|
131
|
+
|
|
132
|
+
If tracking_id already exists in the DB:
|
|
133
|
+
- COMPLETED → raises FlowAlreadyCompleted
|
|
134
|
+
- RUNNING / FAILED → resumes from last successful step
|
|
135
|
+
|
|
136
|
+
If tracking_id does not exist → starts a fresh execution.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
ctx: Context carrying the initial input data.
|
|
140
|
+
tracking_id: Caller-supplied idempotency key. Use a value that
|
|
141
|
+
is stable across retries, e.g. request.idempotency_key.
|
|
142
|
+
"""
|
|
143
|
+
storage = self._get_storage()
|
|
144
|
+
executor = Executor(storage)
|
|
145
|
+
|
|
146
|
+
flow = storage.get_flow(tracking_id)
|
|
147
|
+
|
|
148
|
+
if flow is None:
|
|
149
|
+
flow = storage.create_flow(
|
|
150
|
+
tracking_id=tracking_id,
|
|
151
|
+
name=self.name,
|
|
152
|
+
input_data=ctx.snapshot(),
|
|
153
|
+
)
|
|
154
|
+
elif flow.status == "COMPLETED":
|
|
155
|
+
raise FlowAlreadyCompleted(tracking_id)
|
|
156
|
+
# RUNNING or FAILED → resume (executor handles step-level skipping)
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
executor.run(flow, self._steps, ctx)
|
|
160
|
+
storage.complete_flow(
|
|
161
|
+
flow_id=flow.id,
|
|
162
|
+
output_data=ctx.snapshot(),
|
|
163
|
+
)
|
|
164
|
+
except Exception as exc:
|
|
165
|
+
storage.fail_flow(flow_id=flow.id, error=str(exc))
|
|
166
|
+
raise
|
|
167
|
+
|
|
168
|
+
def _get_storage(self) -> StorageBackend:
|
|
169
|
+
if self._storage_override is not None:
|
|
170
|
+
return self._storage_override
|
|
171
|
+
from flowsmith.config import get_storage
|
|
172
|
+
return get_storage()
|
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class FlowRecord:
|
|
8
|
+
"""
|
|
9
|
+
Represents one execution instance of a workflow.
|
|
10
|
+
Pure data — no DB logic here.
|
|
11
|
+
"""
|
|
12
|
+
id: str
|
|
13
|
+
name: str
|
|
14
|
+
status: str
|
|
15
|
+
input_data: dict[str, Any]
|
|
16
|
+
output_data: dict[str, Any] | None = None
|
|
17
|
+
error: str | None = None
|
|
18
|
+
created_at: datetime | None = None
|
|
19
|
+
updated_at: datetime | None = None
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class NodeRecord:
|
|
8
|
+
"""
|
|
9
|
+
Represents the execution record for a single step within a flow.
|
|
10
|
+
Pure data — no DB logic here.
|
|
11
|
+
"""
|
|
12
|
+
id: str
|
|
13
|
+
flow_id: str
|
|
14
|
+
step_name: str
|
|
15
|
+
status: str
|
|
16
|
+
input_data: dict[str, Any] | None = None
|
|
17
|
+
output_data: dict[str, Any] | None = None
|
|
18
|
+
error: str | None = None
|
|
19
|
+
attempt_count: int = 0
|
|
20
|
+
started_at: datetime | None = None
|
|
21
|
+
ended_at: datetime | None = None
|
flowsmith/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
flowsmith/step.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
BACKOFF_STRATEGIES = ("fixed", "exponential", "jitter")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Step:
|
|
10
|
+
"""
|
|
11
|
+
Represents a registered step within a Flow.
|
|
12
|
+
|
|
13
|
+
name: Unique identifier within the flow. Used as the DB key and
|
|
14
|
+
ctx.data key for the step's output.
|
|
15
|
+
fn: Callable with signature (ctx: Context) -> dict
|
|
16
|
+
retries: Total attempts including the first. retries=3 means the step
|
|
17
|
+
will be tried up to 3 times before raising StepFailed.
|
|
18
|
+
backoff: Delay strategy between retries.
|
|
19
|
+
"fixed" — constant delay of backoff_base seconds
|
|
20
|
+
"exponential" — backoff_base * 2^(attempt-1) seconds
|
|
21
|
+
"jitter" — exponential + random jitter (avoids thundering herd)
|
|
22
|
+
backoff_base: Base delay in seconds. Default 0.0 (no delay).
|
|
23
|
+
timeout: Max seconds a single attempt may run before StepTimeoutError
|
|
24
|
+
is raised. None means no timeout.
|
|
25
|
+
"""
|
|
26
|
+
name: str
|
|
27
|
+
fn: Callable[..., Any]
|
|
28
|
+
retries: int = 1
|
|
29
|
+
backoff: str = "fixed"
|
|
30
|
+
backoff_base: float = 0.0
|
|
31
|
+
timeout: int | None = None
|
|
32
|
+
condition: Callable[..., Any] | None = None
|
|
33
|
+
|
|
34
|
+
def __post_init__(self) -> None:
|
|
35
|
+
if self.retries < 1:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"Step '{self.name}': retries must be >= 1 (got {self.retries})"
|
|
38
|
+
)
|
|
39
|
+
if self.backoff not in BACKOFF_STRATEGIES:
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"Step '{self.name}': backoff must be one of {BACKOFF_STRATEGIES} "
|
|
42
|
+
f"(got '{self.backoff}')"
|
|
43
|
+
)
|
|
44
|
+
if self.backoff_base < 0:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"Step '{self.name}': backoff_base must be >= 0 (got {self.backoff_base})"
|
|
47
|
+
)
|
|
48
|
+
if self.timeout is not None and self.timeout < 1:
|
|
49
|
+
raise ValueError(
|
|
50
|
+
f"Step '{self.name}': timeout must be >= 1 second (got {self.timeout})"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class ParallelGroup:
|
|
56
|
+
"""
|
|
57
|
+
Represents a bundle of steps that should be executed concurrently.
|
|
58
|
+
"""
|
|
59
|
+
steps: list[Step]
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def name(self) -> str:
|
|
63
|
+
# Generate a distinct name based on the bundled steps
|
|
64
|
+
names = ",".join(s.name for s in self.steps)
|
|
65
|
+
return f"ParallelGroup({names})"
|
|
66
|
+
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from flowsmith.models import FlowRecord, NodeRecord
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class StorageBackend(ABC):
|
|
8
|
+
"""
|
|
9
|
+
Abstract interface for all FlowSmith storage backends.
|
|
10
|
+
Implement this to add a new backend (Redis, MongoDB, SQLite, etc.).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def get_flow(self, tracking_id: str) -> FlowRecord | None:
|
|
15
|
+
"""Return the FlowRecord for the given tracking_id, or None if not found."""
|
|
16
|
+
...
|
|
17
|
+
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def create_flow(
|
|
20
|
+
self,
|
|
21
|
+
tracking_id: str,
|
|
22
|
+
name: str,
|
|
23
|
+
input_data: dict[str, Any],
|
|
24
|
+
) -> FlowRecord:
|
|
25
|
+
"""Insert a new flow record with status=RUNNING and return it."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def complete_flow(self, flow_id: str, output_data: dict[str, Any]) -> None:
|
|
30
|
+
"""Mark a flow as COMPLETED and store its final output."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def fail_flow(self, flow_id: str, error: str) -> None:
|
|
35
|
+
"""Mark a flow as FAILED and store the error message."""
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def get_node(self, flow_id: str, step_name: str) -> NodeRecord | None:
|
|
40
|
+
"""Return the NodeRecord for (flow_id, step_name), or None if not found."""
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def start_node(
|
|
45
|
+
self,
|
|
46
|
+
flow_id: str,
|
|
47
|
+
step_name: str,
|
|
48
|
+
input_data: dict[str, Any],
|
|
49
|
+
) -> NodeRecord:
|
|
50
|
+
"""
|
|
51
|
+
Insert a new node record with status=RUNNING.
|
|
52
|
+
If a node already exists for (flow_id, step_name), upsert it
|
|
53
|
+
and increment attempt_count.
|
|
54
|
+
"""
|
|
55
|
+
...
|
|
56
|
+
|
|
57
|
+
@abstractmethod
|
|
58
|
+
def complete_node(
|
|
59
|
+
self,
|
|
60
|
+
flow_id: str,
|
|
61
|
+
step_name: str,
|
|
62
|
+
output_data: dict[str, Any],
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Mark a node as COMPLETED and store its output."""
|
|
65
|
+
...
|
|
66
|
+
|
|
67
|
+
@abstractmethod
|
|
68
|
+
def fail_node(
|
|
69
|
+
self,
|
|
70
|
+
flow_id: str,
|
|
71
|
+
step_name: str,
|
|
72
|
+
error: str,
|
|
73
|
+
attempt: int,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Mark a node as FAILED and store the error + attempt count."""
|
|
76
|
+
...
|
|
77
|
+
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def get_stuck_nodes(self, timeout_seconds: int) -> list[NodeRecord]:
|
|
80
|
+
"""
|
|
81
|
+
Return all NodeRecords that are:
|
|
82
|
+
- status = RUNNING
|
|
83
|
+
- started_at < now() - timeout_seconds
|
|
84
|
+
|
|
85
|
+
Used by the Watchdog to detect crashed processes.
|
|
86
|
+
"""
|
|
87
|
+
...
|