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
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from copy import deepcopy
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from flowsmith.models import FlowRecord, NodeRecord
|
|
7
|
+
from flowsmith.storage.base import StorageBackend
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _now() -> datetime:
|
|
11
|
+
return datetime.now(UTC)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InMemoryStorage(StorageBackend):
|
|
15
|
+
"""
|
|
16
|
+
In-memory storage backend for unit tests.
|
|
17
|
+
|
|
18
|
+
Zero infrastructure required. Behaves identically to PostgresStorage
|
|
19
|
+
from the executor's perspective — same interface, same return types.
|
|
20
|
+
|
|
21
|
+
Not thread-safe. Use one instance per test.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
self._flows: dict[str, FlowRecord] = {}
|
|
26
|
+
self._nodes: dict[str, NodeRecord] = {}
|
|
27
|
+
|
|
28
|
+
def _node_key(self, flow_id: str, step_name: str) -> str:
|
|
29
|
+
return f"{flow_id}:{step_name}"
|
|
30
|
+
|
|
31
|
+
def get_flow(self, tracking_id: str) -> FlowRecord | None:
|
|
32
|
+
return deepcopy(self._flows.get(tracking_id))
|
|
33
|
+
|
|
34
|
+
def create_flow(
|
|
35
|
+
self,
|
|
36
|
+
tracking_id: str,
|
|
37
|
+
name: str,
|
|
38
|
+
input_data: dict[str, Any],
|
|
39
|
+
) -> FlowRecord:
|
|
40
|
+
now = _now()
|
|
41
|
+
record = FlowRecord(
|
|
42
|
+
id=tracking_id,
|
|
43
|
+
name=name,
|
|
44
|
+
status="RUNNING",
|
|
45
|
+
input_data=deepcopy(input_data),
|
|
46
|
+
created_at=now,
|
|
47
|
+
updated_at=now,
|
|
48
|
+
)
|
|
49
|
+
self._flows[tracking_id] = record
|
|
50
|
+
return deepcopy(record)
|
|
51
|
+
|
|
52
|
+
def complete_flow(self, flow_id: str, output_data: dict[str, Any]) -> None:
|
|
53
|
+
record = self._flows[flow_id]
|
|
54
|
+
record.status = "COMPLETED"
|
|
55
|
+
record.output_data = deepcopy(output_data)
|
|
56
|
+
record.updated_at = _now()
|
|
57
|
+
|
|
58
|
+
def fail_flow(self, flow_id: str, error: str) -> None:
|
|
59
|
+
record = self._flows[flow_id]
|
|
60
|
+
record.status = "FAILED"
|
|
61
|
+
record.error = error
|
|
62
|
+
record.updated_at = _now()
|
|
63
|
+
|
|
64
|
+
def get_node(self, flow_id: str, step_name: str) -> NodeRecord | None:
|
|
65
|
+
return deepcopy(self._nodes.get(self._node_key(flow_id, step_name)))
|
|
66
|
+
|
|
67
|
+
def start_node(
|
|
68
|
+
self,
|
|
69
|
+
flow_id: str,
|
|
70
|
+
step_name: str,
|
|
71
|
+
input_data: dict[str, Any],
|
|
72
|
+
) -> NodeRecord:
|
|
73
|
+
key = self._node_key(flow_id, step_name)
|
|
74
|
+
now = _now()
|
|
75
|
+
existing = self._nodes.get(key)
|
|
76
|
+
attempt = (existing.attempt_count + 1) if existing else 1
|
|
77
|
+
|
|
78
|
+
record = NodeRecord(
|
|
79
|
+
id=str(uuid.uuid4()),
|
|
80
|
+
flow_id=flow_id,
|
|
81
|
+
step_name=step_name,
|
|
82
|
+
status="RUNNING",
|
|
83
|
+
input_data=deepcopy(input_data),
|
|
84
|
+
attempt_count=attempt,
|
|
85
|
+
started_at=now,
|
|
86
|
+
)
|
|
87
|
+
self._nodes[key] = record
|
|
88
|
+
return deepcopy(record)
|
|
89
|
+
|
|
90
|
+
def complete_node(
|
|
91
|
+
self,
|
|
92
|
+
flow_id: str,
|
|
93
|
+
step_name: str,
|
|
94
|
+
output_data: dict[str, Any],
|
|
95
|
+
) -> None:
|
|
96
|
+
record = self._nodes[self._node_key(flow_id, step_name)]
|
|
97
|
+
record.status = "COMPLETED"
|
|
98
|
+
record.output_data = deepcopy(output_data)
|
|
99
|
+
record.ended_at = _now()
|
|
100
|
+
|
|
101
|
+
def fail_node(
|
|
102
|
+
self,
|
|
103
|
+
flow_id: str,
|
|
104
|
+
step_name: str,
|
|
105
|
+
error: str,
|
|
106
|
+
attempt: int,
|
|
107
|
+
) -> None:
|
|
108
|
+
record = self._nodes[self._node_key(flow_id, step_name)]
|
|
109
|
+
record.status = "FAILED"
|
|
110
|
+
record.error = error
|
|
111
|
+
record.attempt_count = attempt
|
|
112
|
+
record.ended_at = _now()
|
|
113
|
+
|
|
114
|
+
def get_stuck_nodes(self, timeout_seconds: int) -> list[NodeRecord]:
|
|
115
|
+
cutoff = datetime.now(UTC).timestamp() - timeout_seconds
|
|
116
|
+
stuck = []
|
|
117
|
+
for node in self._nodes.values():
|
|
118
|
+
if node.status == "RUNNING" and node.started_at:
|
|
119
|
+
started = node.started_at
|
|
120
|
+
started_ts = (
|
|
121
|
+
started.timestamp()
|
|
122
|
+
if started.tzinfo is None
|
|
123
|
+
else started.astimezone(UTC).timestamp()
|
|
124
|
+
)
|
|
125
|
+
if started_ts < cutoff:
|
|
126
|
+
stuck.append(node)
|
|
127
|
+
return stuck
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from flowsmith.models import FlowRecord, NodeRecord
|
|
7
|
+
from flowsmith.storage.base import StorageBackend
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _now() -> datetime:
|
|
11
|
+
"""Always return timezone-aware UTC datetime."""
|
|
12
|
+
return datetime.now(UTC)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _to_json(data: Any) -> str | None:
|
|
16
|
+
return json.dumps(data) if data is not None else None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _from_json(data: Any) -> Any:
|
|
20
|
+
if data is None:
|
|
21
|
+
return None
|
|
22
|
+
if isinstance(data, (dict, list)):
|
|
23
|
+
return data
|
|
24
|
+
return json.loads(data)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _mysql_url(url: str) -> str:
|
|
28
|
+
"""
|
|
29
|
+
Convert mysql:// URL to the SQLAlchemy mysql+mysqlconnector:// dialect.
|
|
30
|
+
SQLAlchemy needs the driver specified explicitly.
|
|
31
|
+
"""
|
|
32
|
+
if url.startswith("mysql://"):
|
|
33
|
+
return "mysql+mysqlconnector://" + url[len("mysql://"):]
|
|
34
|
+
return url
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MySQLStorage(StorageBackend):
|
|
38
|
+
"""
|
|
39
|
+
MySQL 8.0+ storage backend using SQLAlchemy connection pooling.
|
|
40
|
+
|
|
41
|
+
Requires: pip install flowsmith[mysql]
|
|
42
|
+
|
|
43
|
+
Uses SQLAlchemy's QueuePool — same pool implementation as PostgresStorage,
|
|
44
|
+
giving both backends identical pooling behaviour and configuration.
|
|
45
|
+
pool_pre_ping=True handles connections dropped after MySQL's wait_timeout.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
url: str,
|
|
51
|
+
pool_min: int = 2,
|
|
52
|
+
pool_max: int = 10,
|
|
53
|
+
pool_timeout: int = 30,
|
|
54
|
+
):
|
|
55
|
+
self._url = url
|
|
56
|
+
self._engine = self._create_engine(url, pool_min, pool_max, pool_timeout)
|
|
57
|
+
|
|
58
|
+
def _create_engine(self, url: str, pool_min: int, pool_max: int, pool_timeout: int) -> Any:
|
|
59
|
+
try:
|
|
60
|
+
from sqlalchemy import create_engine
|
|
61
|
+
except ImportError as err:
|
|
62
|
+
raise ImportError(
|
|
63
|
+
"sqlalchemy and mysql-connector-python are required for MySQLStorage.\n"
|
|
64
|
+
"Install with: pip install flowsmith[mysql]"
|
|
65
|
+
) from err
|
|
66
|
+
|
|
67
|
+
return create_engine(
|
|
68
|
+
_mysql_url(url),
|
|
69
|
+
pool_size=pool_min,
|
|
70
|
+
max_overflow=pool_max - pool_min,
|
|
71
|
+
pool_timeout=pool_timeout,
|
|
72
|
+
pool_pre_ping=True,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def _conn(self) -> Any:
|
|
76
|
+
return self._engine.connect()
|
|
77
|
+
|
|
78
|
+
# -------------------------------------------------------------------------
|
|
79
|
+
# Flow operations
|
|
80
|
+
# -------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
def get_flow(self, tracking_id: str) -> FlowRecord | None:
|
|
83
|
+
from sqlalchemy import text
|
|
84
|
+
with self._conn() as conn:
|
|
85
|
+
row = conn.execute(
|
|
86
|
+
text("SELECT * FROM fs_flows WHERE id = :id"),
|
|
87
|
+
{"id": tracking_id}
|
|
88
|
+
).mappings().fetchone()
|
|
89
|
+
return None if row is None else self._row_to_flow(row)
|
|
90
|
+
|
|
91
|
+
def create_flow(self, tracking_id: str, name: str, input_data: dict[str, Any]) -> FlowRecord:
|
|
92
|
+
from sqlalchemy import text
|
|
93
|
+
now = _now()
|
|
94
|
+
with self._conn() as conn:
|
|
95
|
+
conn.execute(text(
|
|
96
|
+
"INSERT INTO fs_flows (id, name, status, input_data, created_at, updated_at) "
|
|
97
|
+
"VALUES (:id, :name, 'RUNNING', :input_data, :created_at, :updated_at)"
|
|
98
|
+
), {"id": tracking_id, "name": name, "input_data": _to_json(input_data),
|
|
99
|
+
"created_at": now, "updated_at": now})
|
|
100
|
+
conn.commit()
|
|
101
|
+
return FlowRecord(id=tracking_id, name=name, status="RUNNING",
|
|
102
|
+
input_data=input_data, created_at=now, updated_at=now)
|
|
103
|
+
|
|
104
|
+
def complete_flow(self, flow_id: str, output_data: dict[str, Any]) -> None:
|
|
105
|
+
from sqlalchemy import text
|
|
106
|
+
with self._conn() as conn:
|
|
107
|
+
conn.execute(text(
|
|
108
|
+
"UPDATE fs_flows SET status='COMPLETED', output_data=:output_data, "
|
|
109
|
+
"updated_at=:updated_at WHERE id=:id"
|
|
110
|
+
), {"output_data": _to_json(output_data), "updated_at": _now(), "id": flow_id})
|
|
111
|
+
conn.commit()
|
|
112
|
+
|
|
113
|
+
def fail_flow(self, flow_id: str, error: str) -> None:
|
|
114
|
+
from sqlalchemy import text
|
|
115
|
+
with self._conn() as conn:
|
|
116
|
+
conn.execute(text(
|
|
117
|
+
"UPDATE fs_flows SET status='FAILED', error=:error, "
|
|
118
|
+
"updated_at=:updated_at WHERE id=:id"
|
|
119
|
+
), {"error": error, "updated_at": _now(), "id": flow_id})
|
|
120
|
+
conn.commit()
|
|
121
|
+
|
|
122
|
+
# -------------------------------------------------------------------------
|
|
123
|
+
# Node operations
|
|
124
|
+
# -------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def get_node(self, flow_id: str, step_name: str) -> NodeRecord | None:
|
|
127
|
+
from sqlalchemy import text
|
|
128
|
+
with self._conn() as conn:
|
|
129
|
+
row = conn.execute(text(
|
|
130
|
+
"SELECT * FROM fs_nodes WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
131
|
+
), {"flow_id": flow_id, "step_name": step_name}).mappings().fetchone()
|
|
132
|
+
return None if row is None else self._row_to_node(row)
|
|
133
|
+
|
|
134
|
+
def start_node(self, flow_id: str, step_name: str, input_data: dict[str, Any]) -> NodeRecord:
|
|
135
|
+
from sqlalchemy import text
|
|
136
|
+
now = _now()
|
|
137
|
+
node_id = str(uuid.uuid4())
|
|
138
|
+
with self._conn() as conn:
|
|
139
|
+
conn.execute(text("""
|
|
140
|
+
INSERT INTO fs_nodes (id, flow_id, step_name, status, input_data, attempt_count, started_at)
|
|
141
|
+
VALUES (:id, :flow_id, :step_name, 'RUNNING', :input_data, 1, :started_at)
|
|
142
|
+
ON DUPLICATE KEY UPDATE
|
|
143
|
+
status='RUNNING', input_data=VALUES(input_data),
|
|
144
|
+
attempt_count=attempt_count+1, started_at=VALUES(started_at),
|
|
145
|
+
output_data=NULL, error=NULL, ended_at=NULL
|
|
146
|
+
"""), {"id": node_id, "flow_id": flow_id, "step_name": step_name,
|
|
147
|
+
"input_data": _to_json(input_data), "started_at": now})
|
|
148
|
+
row = conn.execute(text(
|
|
149
|
+
"SELECT * FROM fs_nodes WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
150
|
+
), {"flow_id": flow_id, "step_name": step_name}).mappings().fetchone()
|
|
151
|
+
conn.commit()
|
|
152
|
+
return self._row_to_node(row)
|
|
153
|
+
|
|
154
|
+
def complete_node(self, flow_id: str, step_name: str, output_data: dict[str, Any]) -> None:
|
|
155
|
+
from sqlalchemy import text
|
|
156
|
+
with self._conn() as conn:
|
|
157
|
+
conn.execute(text(
|
|
158
|
+
"UPDATE fs_nodes SET status='COMPLETED', output_data=:output_data, ended_at=:ended_at "
|
|
159
|
+
"WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
160
|
+
), {"output_data": _to_json(output_data), "ended_at": _now(),
|
|
161
|
+
"flow_id": flow_id, "step_name": step_name})
|
|
162
|
+
conn.commit()
|
|
163
|
+
|
|
164
|
+
def fail_node(self, flow_id: str, step_name: str, error: str, attempt: int) -> None:
|
|
165
|
+
from sqlalchemy import text
|
|
166
|
+
with self._conn() as conn:
|
|
167
|
+
conn.execute(text(
|
|
168
|
+
"UPDATE fs_nodes SET status='FAILED', error=:error, "
|
|
169
|
+
"attempt_count=:attempt, ended_at=:ended_at "
|
|
170
|
+
"WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
171
|
+
), {"error": error, "attempt": attempt, "ended_at": _now(),
|
|
172
|
+
"flow_id": flow_id, "step_name": step_name})
|
|
173
|
+
conn.commit()
|
|
174
|
+
|
|
175
|
+
def get_stuck_nodes(self, timeout_seconds: int) -> list[NodeRecord]:
|
|
176
|
+
from sqlalchemy import text
|
|
177
|
+
with self._conn() as conn:
|
|
178
|
+
rows = conn.execute(text(
|
|
179
|
+
"SELECT * FROM fs_nodes WHERE status='RUNNING' "
|
|
180
|
+
"AND started_at < DATE_SUB(NOW(), INTERVAL :timeout SECOND)"
|
|
181
|
+
), {"timeout": timeout_seconds}).mappings().fetchall()
|
|
182
|
+
return [self._row_to_node(row) for row in rows]
|
|
183
|
+
|
|
184
|
+
# -------------------------------------------------------------------------
|
|
185
|
+
# Row mappers
|
|
186
|
+
# -------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
def _row_to_flow(self, row: Any) -> FlowRecord:
|
|
189
|
+
return FlowRecord(
|
|
190
|
+
id=row["id"], name=row["name"], status=row["status"],
|
|
191
|
+
input_data=_from_json(row["input_data"]),
|
|
192
|
+
output_data=_from_json(row["output_data"]),
|
|
193
|
+
error=row["error"], created_at=row["created_at"], updated_at=row["updated_at"],
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
def _row_to_node(self, row: Any) -> NodeRecord:
|
|
197
|
+
return NodeRecord(
|
|
198
|
+
id=row["id"], flow_id=row["flow_id"], step_name=row["step_name"],
|
|
199
|
+
status=row["status"], input_data=_from_json(row["input_data"]),
|
|
200
|
+
output_data=_from_json(row["output_data"]), error=row["error"],
|
|
201
|
+
attempt_count=row["attempt_count"], started_at=row["started_at"],
|
|
202
|
+
ended_at=row["ended_at"],
|
|
203
|
+
)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from flowsmith.models import FlowRecord, NodeRecord
|
|
7
|
+
from flowsmith.storage.base import StorageBackend
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _now() -> datetime:
|
|
11
|
+
"""Always return timezone-aware UTC datetime."""
|
|
12
|
+
return datetime.now(UTC)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _to_json(data: Any) -> str | None:
|
|
16
|
+
return json.dumps(data) if data is not None else None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _from_json(data: Any) -> Any:
|
|
20
|
+
if data is None:
|
|
21
|
+
return None
|
|
22
|
+
if isinstance(data, (dict, list)):
|
|
23
|
+
return data
|
|
24
|
+
return json.loads(data)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class PostgresStorage(StorageBackend):
|
|
28
|
+
"""
|
|
29
|
+
PostgreSQL storage backend using SQLAlchemy connection pooling.
|
|
30
|
+
|
|
31
|
+
Requires: pip install flowsmith[postgres]
|
|
32
|
+
|
|
33
|
+
Uses SQLAlchemy's QueuePool — a thread-safe pool that maintains
|
|
34
|
+
min connections alive and scales up to max under load.
|
|
35
|
+
pool_pre_ping=True verifies connections before use, automatically
|
|
36
|
+
handling connections dropped by the server after idle timeout.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
url: str,
|
|
42
|
+
pool_min: int = 2,
|
|
43
|
+
pool_max: int = 10,
|
|
44
|
+
pool_timeout: int = 30,
|
|
45
|
+
):
|
|
46
|
+
self._url = url
|
|
47
|
+
self._engine = self._create_engine(url, pool_min, pool_max, pool_timeout)
|
|
48
|
+
|
|
49
|
+
def _create_engine(self, url: str, pool_min: int, pool_max: int, pool_timeout: int) -> Any:
|
|
50
|
+
try:
|
|
51
|
+
from sqlalchemy import create_engine
|
|
52
|
+
except ImportError as err:
|
|
53
|
+
raise ImportError(
|
|
54
|
+
"sqlalchemy and psycopg2 are required for PostgresStorage.\n"
|
|
55
|
+
"Install with: pip install flowsmith[postgres]"
|
|
56
|
+
) from err
|
|
57
|
+
|
|
58
|
+
return create_engine(
|
|
59
|
+
url,
|
|
60
|
+
pool_size=pool_min,
|
|
61
|
+
max_overflow=pool_max - pool_min,
|
|
62
|
+
pool_timeout=pool_timeout,
|
|
63
|
+
pool_pre_ping=True, # validate connection before use
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def _conn(self) -> Any:
|
|
67
|
+
"""Return a context manager yielding a SQLAlchemy connection."""
|
|
68
|
+
return self._engine.connect()
|
|
69
|
+
|
|
70
|
+
# -------------------------------------------------------------------------
|
|
71
|
+
# Flow operations
|
|
72
|
+
# -------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
def get_flow(self, tracking_id: str) -> FlowRecord | None:
|
|
75
|
+
from sqlalchemy import text
|
|
76
|
+
with self._conn() as conn:
|
|
77
|
+
row = conn.execute(
|
|
78
|
+
text("SELECT * FROM fs_flows WHERE id = :id"),
|
|
79
|
+
{"id": tracking_id}
|
|
80
|
+
).mappings().fetchone()
|
|
81
|
+
return None if row is None else self._row_to_flow(row)
|
|
82
|
+
|
|
83
|
+
def create_flow(self, tracking_id: str, name: str, input_data: dict[str, Any]) -> FlowRecord:
|
|
84
|
+
from sqlalchemy import text
|
|
85
|
+
now = _now()
|
|
86
|
+
with self._conn() as conn:
|
|
87
|
+
conn.execute(text(
|
|
88
|
+
"INSERT INTO fs_flows (id, name, status, input_data, created_at, updated_at) "
|
|
89
|
+
"VALUES (:id, :name, 'RUNNING', :input_data, :created_at, :updated_at)"
|
|
90
|
+
), {"id": tracking_id, "name": name, "input_data": _to_json(input_data),
|
|
91
|
+
"created_at": now, "updated_at": now})
|
|
92
|
+
conn.commit()
|
|
93
|
+
return FlowRecord(id=tracking_id, name=name, status="RUNNING",
|
|
94
|
+
input_data=input_data, created_at=now, updated_at=now)
|
|
95
|
+
|
|
96
|
+
def complete_flow(self, flow_id: str, output_data: dict[str, Any]) -> None:
|
|
97
|
+
from sqlalchemy import text
|
|
98
|
+
with self._conn() as conn:
|
|
99
|
+
conn.execute(text(
|
|
100
|
+
"UPDATE fs_flows SET status='COMPLETED', output_data=:output_data, "
|
|
101
|
+
"updated_at=:updated_at WHERE id=:id"
|
|
102
|
+
), {"output_data": _to_json(output_data), "updated_at": _now(), "id": flow_id})
|
|
103
|
+
conn.commit()
|
|
104
|
+
|
|
105
|
+
def fail_flow(self, flow_id: str, error: str) -> None:
|
|
106
|
+
from sqlalchemy import text
|
|
107
|
+
with self._conn() as conn:
|
|
108
|
+
conn.execute(text(
|
|
109
|
+
"UPDATE fs_flows SET status='FAILED', error=:error, "
|
|
110
|
+
"updated_at=:updated_at WHERE id=:id"
|
|
111
|
+
), {"error": error, "updated_at": _now(), "id": flow_id})
|
|
112
|
+
conn.commit()
|
|
113
|
+
|
|
114
|
+
# -------------------------------------------------------------------------
|
|
115
|
+
# Node operations
|
|
116
|
+
# -------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def get_node(self, flow_id: str, step_name: str) -> NodeRecord | None:
|
|
119
|
+
from sqlalchemy import text
|
|
120
|
+
with self._conn() as conn:
|
|
121
|
+
row = conn.execute(text(
|
|
122
|
+
"SELECT * FROM fs_nodes WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
123
|
+
), {"flow_id": flow_id, "step_name": step_name}).mappings().fetchone()
|
|
124
|
+
return None if row is None else self._row_to_node(row)
|
|
125
|
+
|
|
126
|
+
def start_node(self, flow_id: str, step_name: str, input_data: dict[str, Any]) -> NodeRecord:
|
|
127
|
+
from sqlalchemy import text
|
|
128
|
+
now = _now()
|
|
129
|
+
node_id = str(uuid.uuid4())
|
|
130
|
+
with self._conn() as conn:
|
|
131
|
+
row = conn.execute(text("""
|
|
132
|
+
INSERT INTO fs_nodes (id, flow_id, step_name, status, input_data, attempt_count, started_at)
|
|
133
|
+
VALUES (:id, :flow_id, :step_name, 'RUNNING', :input_data, 1, :started_at)
|
|
134
|
+
ON CONFLICT (flow_id, step_name) DO UPDATE
|
|
135
|
+
SET status='RUNNING', input_data=EXCLUDED.input_data,
|
|
136
|
+
attempt_count=fs_nodes.attempt_count+1,
|
|
137
|
+
started_at=EXCLUDED.started_at,
|
|
138
|
+
output_data=NULL, error=NULL, ended_at=NULL
|
|
139
|
+
RETURNING *
|
|
140
|
+
"""), {"id": node_id, "flow_id": flow_id, "step_name": step_name,
|
|
141
|
+
"input_data": _to_json(input_data), "started_at": now}).mappings().fetchone()
|
|
142
|
+
conn.commit()
|
|
143
|
+
return self._row_to_node(row)
|
|
144
|
+
|
|
145
|
+
def complete_node(self, flow_id: str, step_name: str, output_data: dict[str, Any]) -> None:
|
|
146
|
+
from sqlalchemy import text
|
|
147
|
+
with self._conn() as conn:
|
|
148
|
+
conn.execute(text(
|
|
149
|
+
"UPDATE fs_nodes SET status='COMPLETED', output_data=:output_data, ended_at=:ended_at "
|
|
150
|
+
"WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
151
|
+
), {"output_data": _to_json(output_data), "ended_at": _now(),
|
|
152
|
+
"flow_id": flow_id, "step_name": step_name})
|
|
153
|
+
conn.commit()
|
|
154
|
+
|
|
155
|
+
def fail_node(self, flow_id: str, step_name: str, error: str, attempt: int) -> None:
|
|
156
|
+
from sqlalchemy import text
|
|
157
|
+
with self._conn() as conn:
|
|
158
|
+
conn.execute(text(
|
|
159
|
+
"UPDATE fs_nodes SET status='FAILED', error=:error, "
|
|
160
|
+
"attempt_count=:attempt, ended_at=:ended_at "
|
|
161
|
+
"WHERE flow_id=:flow_id AND step_name=:step_name"
|
|
162
|
+
), {"error": error, "attempt": attempt, "ended_at": _now(),
|
|
163
|
+
"flow_id": flow_id, "step_name": step_name})
|
|
164
|
+
conn.commit()
|
|
165
|
+
|
|
166
|
+
def get_stuck_nodes(self, timeout_seconds: int) -> list[NodeRecord]:
|
|
167
|
+
from sqlalchemy import text
|
|
168
|
+
with self._conn() as conn:
|
|
169
|
+
rows = conn.execute(text(
|
|
170
|
+
"SELECT * FROM fs_nodes WHERE status='RUNNING' "
|
|
171
|
+
"AND started_at < now() - INTERVAL '1 second' * :timeout"
|
|
172
|
+
), {"timeout": timeout_seconds}).mappings().fetchall()
|
|
173
|
+
return [self._row_to_node(row) for row in rows]
|
|
174
|
+
|
|
175
|
+
# -------------------------------------------------------------------------
|
|
176
|
+
# Row mappers
|
|
177
|
+
# -------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def _row_to_flow(self, row: Any) -> FlowRecord:
|
|
180
|
+
return FlowRecord(
|
|
181
|
+
id=row["id"], name=row["name"], status=row["status"],
|
|
182
|
+
input_data=_from_json(row["input_data"]),
|
|
183
|
+
output_data=_from_json(row["output_data"]),
|
|
184
|
+
error=row["error"], created_at=row["created_at"], updated_at=row["updated_at"],
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def _row_to_node(self, row: Any) -> NodeRecord:
|
|
188
|
+
return NodeRecord(
|
|
189
|
+
id=row["id"], flow_id=row["flow_id"], step_name=row["step_name"],
|
|
190
|
+
status=row["status"], input_data=_from_json(row["input_data"]),
|
|
191
|
+
output_data=_from_json(row["output_data"]), error=row["error"],
|
|
192
|
+
attempt_count=row["attempt_count"], started_at=row["started_at"],
|
|
193
|
+
ended_at=row["ended_at"],
|
|
194
|
+
)
|
flowsmith/watchdog.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FlowSmith Watchdog
|
|
3
|
+
|
|
4
|
+
Detects nodes stuck in RUNNING status after a process crash and
|
|
5
|
+
transitions them to FAILED so the flow can be resumed.
|
|
6
|
+
|
|
7
|
+
Usage:
|
|
8
|
+
import flowsmith
|
|
9
|
+
flowsmith.configure(database_url=os.environ["DATABASE_URL"])
|
|
10
|
+
flowsmith.start_watchdog(timeout_seconds=300, interval_seconds=60)
|
|
11
|
+
|
|
12
|
+
The watchdog runs in a daemon thread — it stops automatically when
|
|
13
|
+
the main process exits. No cleanup required.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import threading
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger("flowsmith.watchdog")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Watchdog:
|
|
24
|
+
"""
|
|
25
|
+
Background thread that periodically scans for stuck nodes.
|
|
26
|
+
|
|
27
|
+
A node is considered stuck if:
|
|
28
|
+
- status = RUNNING
|
|
29
|
+
- started_at < now() - timeout_seconds
|
|
30
|
+
|
|
31
|
+
On detection:
|
|
32
|
+
1. Node → FAILED (error = "Watchdog: node exceeded timeout")
|
|
33
|
+
2. Flow → FAILED (error = "Watchdog: flow has stuck nodes")
|
|
34
|
+
|
|
35
|
+
The flow can then be resumed by calling flow.run() with the same tracking_id.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
storage: Any,
|
|
41
|
+
timeout_seconds: int = 300,
|
|
42
|
+
interval_seconds: int = 60,
|
|
43
|
+
) -> None:
|
|
44
|
+
if timeout_seconds < 1:
|
|
45
|
+
raise ValueError("timeout_seconds must be >= 1")
|
|
46
|
+
if interval_seconds < 1:
|
|
47
|
+
raise ValueError("interval_seconds must be >= 1")
|
|
48
|
+
|
|
49
|
+
self._storage = storage
|
|
50
|
+
self._timeout_seconds = timeout_seconds
|
|
51
|
+
self._interval_seconds = interval_seconds
|
|
52
|
+
self._stop_event = threading.Event()
|
|
53
|
+
self._thread: threading.Thread | None = None
|
|
54
|
+
|
|
55
|
+
def start(self) -> None:
|
|
56
|
+
"""Start the watchdog background thread."""
|
|
57
|
+
if self._thread and self._thread.is_alive():
|
|
58
|
+
logger.warning("Watchdog is already running.")
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
self._stop_event.clear()
|
|
62
|
+
self._thread = threading.Thread(
|
|
63
|
+
target=self._loop,
|
|
64
|
+
name="flowsmith-watchdog",
|
|
65
|
+
daemon=True,
|
|
66
|
+
)
|
|
67
|
+
self._thread.start()
|
|
68
|
+
logger.info(
|
|
69
|
+
"Watchdog started — timeout=%ss, interval=%ss",
|
|
70
|
+
self._timeout_seconds,
|
|
71
|
+
self._interval_seconds,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def stop(self) -> None:
|
|
75
|
+
"""Signal the watchdog to stop. Blocks until the thread exits."""
|
|
76
|
+
self._stop_event.set()
|
|
77
|
+
if self._thread:
|
|
78
|
+
self._thread.join(timeout=self._interval_seconds + 2)
|
|
79
|
+
logger.info("Watchdog stopped.")
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def is_running(self) -> bool:
|
|
83
|
+
return self._thread is not None and self._thread.is_alive()
|
|
84
|
+
|
|
85
|
+
def _loop(self) -> None:
|
|
86
|
+
"""Main watchdog loop — runs until stop() is called."""
|
|
87
|
+
while not self._stop_event.is_set():
|
|
88
|
+
try:
|
|
89
|
+
self._scan()
|
|
90
|
+
except Exception as e:
|
|
91
|
+
# Never crash the watchdog — log and keep going
|
|
92
|
+
logger.error("Watchdog scan error: %s", e, exc_info=True)
|
|
93
|
+
# Sleep in small increments so stop() is responsive
|
|
94
|
+
self._stop_event.wait(timeout=self._interval_seconds)
|
|
95
|
+
|
|
96
|
+
def _scan(self) -> None:
|
|
97
|
+
"""Find stuck nodes and mark them failed."""
|
|
98
|
+
stuck = self._storage.get_stuck_nodes(timeout_seconds=self._timeout_seconds)
|
|
99
|
+
if not stuck:
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
logger.warning("Watchdog found %d stuck node(s)", len(stuck))
|
|
103
|
+
|
|
104
|
+
failed_flows = set()
|
|
105
|
+
|
|
106
|
+
for node in stuck:
|
|
107
|
+
logger.warning(
|
|
108
|
+
" Stuck node: flow_id=%s step=%s started_at=%s",
|
|
109
|
+
node.flow_id, node.step_name, node.started_at,
|
|
110
|
+
)
|
|
111
|
+
self._storage.fail_node(
|
|
112
|
+
flow_id=node.flow_id,
|
|
113
|
+
step_name=node.step_name,
|
|
114
|
+
error=(
|
|
115
|
+
f"Watchdog: node exceeded timeout of {self._timeout_seconds}s. "
|
|
116
|
+
"Process likely crashed. Resume the flow with the same tracking_id."
|
|
117
|
+
),
|
|
118
|
+
attempt=node.attempt_count,
|
|
119
|
+
)
|
|
120
|
+
failed_flows.add(node.flow_id)
|
|
121
|
+
|
|
122
|
+
for flow_id in failed_flows:
|
|
123
|
+
# Only fail the flow if it's still RUNNING
|
|
124
|
+
flow = self._storage.get_flow(flow_id)
|
|
125
|
+
if flow and flow.status == "RUNNING":
|
|
126
|
+
self._storage.fail_flow(
|
|
127
|
+
flow_id=flow_id,
|
|
128
|
+
error=(
|
|
129
|
+
"Watchdog: flow failed due to stuck node(s). "
|
|
130
|
+
"Resume with the same tracking_id."
|
|
131
|
+
),
|
|
132
|
+
)
|
|
133
|
+
logger.warning(" Flow %s marked FAILED by watchdog", flow_id)
|