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 ADDED
@@ -0,0 +1,80 @@
1
+ """
2
+ FlowSmith — lightweight durable workflow execution for Python backends.
3
+
4
+ Quickstart:
5
+ import flowsmith
6
+
7
+ # 1. Configure once at server startup
8
+ flowsmith.configure(database_url=os.environ["DATABASE_URL"])
9
+ flowsmith.start_watchdog(timeout_seconds=300, interval_seconds=60)
10
+
11
+ # -------------------------------------------------------------------------
12
+ # Flavor 1: The Classic Builder API
13
+ # -------------------------------------------------------------------------
14
+ # Ideal for explicit control and dynamically generating workflows.
15
+ from flowsmith import Flow, Context
16
+
17
+ flow = Flow("process_order")
18
+ flow.step("charge", charge_fn, retries=3)
19
+ flow.step("notify", notify_fn, retries=2)
20
+
21
+ # Execute manually
22
+ flow.run(Context({"amount": 100}), tracking_id="order_123")
23
+
24
+ # -------------------------------------------------------------------------
25
+ # Flavor 2: The Decorator API (v0.4+)
26
+ # -------------------------------------------------------------------------
27
+ # Ideal for readable, declarative workflows with built-in branching.
28
+ from flowsmith import Context
29
+ from flowsmith.decorators import workflow, step
30
+
31
+ @workflow("process_order")
32
+ def order_flow():
33
+
34
+ @step(retries=3)
35
+ def charge_user(ctx):
36
+ return {"paid": True}
37
+
38
+ # Branching handles skipping inherently!
39
+ @step(condition=lambda ctx: ctx.data["charge_user"]["paid"])
40
+ def notify_user(ctx):
41
+ pass
42
+
43
+ # Trigger execution (resumes automatically if crashed before)
44
+ order_flow(Context({"amount": 100}), tracking_id="order_123")
45
+ """
46
+
47
+ from flowsmith.config import configure, reset, start_watchdog, stop_watchdog
48
+ from flowsmith.context import Context
49
+ from flowsmith.decorators import parallel, step, subflow, workflow
50
+ from flowsmith.exceptions import (
51
+ FlowAlreadyCompleted,
52
+ FlowSmithNotConfigured,
53
+ StepFailed,
54
+ StepTimeoutError,
55
+ )
56
+ from flowsmith.flow import Flow
57
+
58
+ __all__ = [
59
+ # Configuration
60
+ "configure",
61
+ "reset",
62
+ # Watchdog
63
+ "start_watchdog",
64
+ "stop_watchdog",
65
+ # Core API
66
+ "Flow",
67
+ "Context",
68
+ # Decorators
69
+ "workflow",
70
+ "subflow",
71
+ "parallel",
72
+ "step",
73
+ # Exceptions
74
+ "FlowSmithNotConfigured",
75
+ "StepFailed",
76
+ "StepTimeoutError",
77
+ "FlowAlreadyCompleted",
78
+ ]
79
+
80
+ __version__ = "0.5.0"
flowsmith/__main__.py ADDED
@@ -0,0 +1,183 @@
1
+ """
2
+ FlowSmith CLI
3
+ Usage:
4
+ flowsmith migrate --url postgresql://user:pass@localhost/db
5
+ flowsmith migrate --url mysql://user:pass@localhost/db
6
+ flowsmith migrate # reads DATABASE_URL from environment
7
+ flowsmith migrate # reads DATABASE_URL from environment
8
+ """
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ MIGRATIONS_DIR = Path(__file__).parent / "migrations"
16
+
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Helpers
20
+ # ---------------------------------------------------------------------------
21
+
22
+
23
+ def detect_dialect(url: str) -> str:
24
+ if url.startswith("postgresql://") or url.startswith("postgres://"):
25
+ return "postgres"
26
+ if url.startswith("mysql://"):
27
+ return "mysql"
28
+ raise ValueError(
29
+ f"Unsupported database URL scheme: '{url.split('://')[0]}'\n"
30
+ "Supported schemes: postgresql://, postgres://, mysql://"
31
+ )
32
+
33
+
34
+ def run_migrations_postgres(url: str) -> None:
35
+ try:
36
+ import psycopg2
37
+ except ImportError:
38
+ print("ERROR: psycopg2 is required for PostgreSQL.")
39
+ print("Install it with: pip install flowsmith[postgres]")
40
+ sys.exit(1)
41
+
42
+ migration_dir = MIGRATIONS_DIR / "postgres"
43
+ sql_files = sorted(migration_dir.glob("*.sql"))
44
+
45
+ conn = psycopg2.connect(url)
46
+ conn.autocommit = True
47
+ cur = conn.cursor()
48
+
49
+ for sql_file in sql_files:
50
+ print(f" -> {sql_file.name}")
51
+ cur.execute(sql_file.read_text())
52
+
53
+ cur.close()
54
+ conn.close()
55
+
56
+
57
+ def _split_mysql_statements(sql: str) -> list[str]:
58
+ """
59
+ Split a MySQL SQL file into individual executable statements.
60
+
61
+ Naive semicolon splitting breaks BEGIN...END blocks used in stored
62
+ procedures — each internal statement ends with a semicolon but must
63
+ be sent to MySQL as part of the whole CREATE PROCEDURE block.
64
+
65
+ This parser tracks BEGIN/END nesting depth and only splits on
66
+ semicolons that appear outside of a BEGIN...END block.
67
+ """
68
+ statements = []
69
+ current = []
70
+ depth = 0
71
+
72
+ for line in sql.splitlines():
73
+ stripped = line.strip().upper()
74
+
75
+ if stripped in ("BEGIN", "BEGIN;"):
76
+ depth += 1
77
+ elif stripped in ("END", "END;", "END;"):
78
+ depth -= 1
79
+
80
+ current.append(line)
81
+
82
+ if stripped.endswith(";") and depth == 0:
83
+ stmt = "\n".join(current).strip().rstrip(";")
84
+ if stmt:
85
+ statements.append(stmt)
86
+ current = []
87
+
88
+ remainder = "\n".join(current).strip()
89
+ if remainder:
90
+ statements.append(remainder)
91
+
92
+ return statements
93
+
94
+
95
+ def run_migrations_mysql(url: str) -> None:
96
+ try:
97
+ import mysql.connector
98
+ except ImportError:
99
+ print("ERROR: mysql-connector-python is required for MySQL.")
100
+ print("Install it with: pip install flowsmith[mysql]")
101
+ sys.exit(1)
102
+
103
+ from urllib.parse import urlparse
104
+ parsed = urlparse(url)
105
+
106
+ migration_dir = MIGRATIONS_DIR / "mysql"
107
+ sql_files = sorted(migration_dir.glob("*.sql"))
108
+
109
+ conn = mysql.connector.connect(
110
+ host=parsed.hostname,
111
+ port=parsed.port or 3306,
112
+ user=parsed.username,
113
+ password=parsed.password,
114
+ database=parsed.path.lstrip("/"),
115
+ )
116
+ cur = conn.cursor()
117
+
118
+ for sql_file in sql_files:
119
+ print(f" -> {sql_file.name}")
120
+ statements = _split_mysql_statements(sql_file.read_text())
121
+ for stmt in statements:
122
+ if stmt:
123
+ cur.execute(stmt)
124
+
125
+ conn.commit()
126
+ cur.close()
127
+ conn.close()
128
+
129
+
130
+ def cmd_migrate(args: argparse.Namespace) -> None:
131
+ url = args.url or os.environ.get("DATABASE_URL")
132
+
133
+ if not url:
134
+ print(
135
+ "ERROR: No database URL provided.\n"
136
+ "Pass --url or set the DATABASE_URL environment variable.\n\n"
137
+ "Examples:\n"
138
+ " flowsmith migrate --url postgresql://user:pass@localhost/mydb\n"
139
+ " flowsmith migrate --url mysql://user:pass@localhost/mydb\n"
140
+ )
141
+ sys.exit(1)
142
+
143
+ try:
144
+ dialect = detect_dialect(url)
145
+ except ValueError as e:
146
+ print(f"ERROR: {e}")
147
+ sys.exit(1)
148
+
149
+ print(f"Running FlowSmith migrations ({dialect})...")
150
+
151
+ try:
152
+ if dialect == "postgres":
153
+ run_migrations_postgres(url)
154
+ elif dialect == "mysql":
155
+ run_migrations_mysql(url)
156
+ except Exception as e:
157
+ print(f"\nERROR: Migration failed: {e}")
158
+ sys.exit(1)
159
+
160
+ print("Done. Tables fs_flows and fs_nodes are ready.")
161
+
162
+
163
+ def main() -> None:
164
+ parser = argparse.ArgumentParser(
165
+ prog="flowsmith",
166
+ description="FlowSmith CLI",
167
+ )
168
+ subparsers = parser.add_subparsers(dest="command")
169
+
170
+ # Core
171
+ migrate_parser = subparsers.add_parser("migrate", help="Run database migrations")
172
+ migrate_parser.add_argument("--url", help="Database URL", default=None)
173
+
174
+ args = parser.parse_args()
175
+
176
+ if args.command == "migrate":
177
+ cmd_migrate(args)
178
+ else:
179
+ parser.print_help()
180
+
181
+
182
+ if __name__ == "__main__":
183
+ main()
flowsmith/config.py ADDED
@@ -0,0 +1,137 @@
1
+ import threading
2
+ from typing import Any
3
+
4
+ from flowsmith.exceptions import FlowSmithNotConfigured
5
+ from flowsmith.storage.base import StorageBackend
6
+
7
+ _lock = threading.Lock()
8
+ _storage: StorageBackend | None = None
9
+ _watchdog: Any = None
10
+
11
+
12
+ def _make_storage(
13
+ database_url: str,
14
+ pool_min: int,
15
+ pool_max: int,
16
+ pool_timeout: int,
17
+ ) -> StorageBackend:
18
+ """
19
+ Instantiate the correct backend from the database URL scheme.
20
+ All pool params are passed through to the backend.
21
+ """
22
+ if database_url.startswith("postgresql://") or database_url.startswith("postgres://"):
23
+ from flowsmith.storage.postgres import PostgresStorage
24
+ return PostgresStorage(url=database_url, pool_min=pool_min, pool_max=pool_max, pool_timeout=pool_timeout)
25
+
26
+ if database_url.startswith("mysql://"):
27
+ from flowsmith.storage.mysql import MySQLStorage
28
+ return MySQLStorage(url=database_url, pool_min=pool_min, pool_max=pool_max, pool_timeout=pool_timeout)
29
+
30
+ raise ValueError(
31
+ f"Unsupported database URL scheme: '{database_url.split('://')[0]}'\n"
32
+ "Supported: postgresql://, postgres://, mysql://"
33
+ )
34
+
35
+
36
+ def configure(
37
+ database_url: str,
38
+ pool_min: int = 2,
39
+ pool_max: int = 10,
40
+ pool_timeout: int = 30,
41
+ ) -> None:
42
+ """
43
+ Initialise FlowSmith with a database URL and connection pool settings.
44
+ Call once at server startup.
45
+
46
+ Args:
47
+ database_url: PostgreSQL or MySQL connection string.
48
+ postgresql://user:password@host:port/dbname
49
+ mysql://user:password@host:port/dbname
50
+ pool_min: Minimum connections kept alive in the pool. Default 2.
51
+ pool_max: Maximum connections in the pool. Default 10.
52
+ pool_timeout: Seconds to wait for a connection before raising. Default 30.
53
+
54
+ Thread-safe and idempotent — calling again with the same URL is a no-op.
55
+ Raises ValueError if called again with a different URL.
56
+ """
57
+ global _storage
58
+
59
+ with _lock:
60
+ if _storage is not None:
61
+ existing_url = getattr(_storage, "_url", None)
62
+ if existing_url != database_url:
63
+ raise ValueError(
64
+ "flowsmith.configure() was already called with a different URL. "
65
+ "Call flowsmith.reset() first (test environments only)."
66
+ )
67
+ return
68
+
69
+ _storage = _make_storage(database_url, pool_min, pool_max, pool_timeout)
70
+
71
+
72
+ def start_watchdog(
73
+ timeout_seconds: int = 300,
74
+ interval_seconds: int = 60,
75
+ ) -> None:
76
+ """
77
+ Start the background watchdog that detects stuck nodes.
78
+
79
+ Call this after flowsmith.configure() at server startup.
80
+
81
+ Args:
82
+ timeout_seconds: How long a node can stay in RUNNING before it is
83
+ considered stuck. Default 300s (5 minutes).
84
+ interval_seconds: How often the watchdog scans for stuck nodes.
85
+ Default 60s (1 minute).
86
+
87
+ Example:
88
+ import flowsmith
89
+ flowsmith.configure(database_url=os.environ["DATABASE_URL"])
90
+ flowsmith.start_watchdog(timeout_seconds=300, interval_seconds=60)
91
+ """
92
+ global _watchdog
93
+
94
+ storage = get_storage() # raises FlowSmithNotConfigured if not configured
95
+
96
+ with _lock:
97
+ if _watchdog and _watchdog.is_running:
98
+ return # already running, no-op
99
+
100
+ from flowsmith.watchdog import Watchdog
101
+ _watchdog = Watchdog(
102
+ storage=storage,
103
+ timeout_seconds=timeout_seconds,
104
+ interval_seconds=interval_seconds,
105
+ )
106
+ _watchdog.start()
107
+
108
+
109
+ def stop_watchdog() -> None:
110
+ """
111
+ Stop the watchdog thread. Blocks until the thread exits.
112
+ Useful for clean shutdown in tests or long-running processes.
113
+ """
114
+ global _watchdog
115
+ if _watchdog and _watchdog.is_running:
116
+ _watchdog.stop()
117
+ _watchdog = None
118
+
119
+
120
+ def get_storage() -> StorageBackend:
121
+ """
122
+ Return the globally configured storage backend.
123
+ Raises FlowSmithNotConfigured if configure() has not been called.
124
+ """
125
+ if _storage is None:
126
+ raise FlowSmithNotConfigured()
127
+ return _storage
128
+
129
+
130
+ def reset() -> None:
131
+ """Reset global config and stop watchdog. FOR TESTING ONLY."""
132
+ global _storage, _watchdog
133
+ with _lock:
134
+ if _watchdog and _watchdog.is_running:
135
+ _watchdog.stop()
136
+ _watchdog = None
137
+ _storage = None
flowsmith/context.py ADDED
@@ -0,0 +1,34 @@
1
+ from copy import deepcopy
2
+ from typing import Any
3
+
4
+
5
+ class Context:
6
+ """
7
+ Carries shared state between steps within a single flow execution.
8
+
9
+ Step outputs are stored here automatically by the executor after
10
+ each successful step. Downstream steps access them via ctx.data.
11
+
12
+ Example:
13
+ def charge_payment(ctx):
14
+ return {"payment_id": "pay_123"}
15
+
16
+ def create_order(ctx):
17
+ pid = ctx.data["charge_payment"]["payment_id"] # set by executor
18
+ ...
19
+ """
20
+
21
+ def __init__(self, data: dict[str, Any] | None = None):
22
+ self.data: dict[str, Any] = deepcopy(data or {})
23
+
24
+ def store(self, step_name: str, output: dict[str, Any]) -> None:
25
+ """Called by the executor to store a step's output under its name."""
26
+ self.data[step_name] = deepcopy(output)
27
+
28
+ def snapshot(self) -> dict[str, Any]:
29
+ """Return a deep copy of the current data dict for persistence."""
30
+ return deepcopy(self.data)
31
+
32
+ def __repr__(self) -> str:
33
+ keys = list(self.data.keys())
34
+ return f"Context(keys={keys})"
@@ -0,0 +1 @@
1
+ # Optional integrations — not imported by default.
@@ -0,0 +1,147 @@
1
+ import contextvars
2
+ import functools
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ from flowsmith.flow import Flow
7
+
8
+ _current_flow: contextvars.ContextVar[Flow | None] = contextvars.ContextVar("_current_flow", default=None)
9
+
10
+
11
+ def step(
12
+ name: str | Callable[..., Any] | None = None,
13
+ *,
14
+ retries: int = 1,
15
+ backoff: str = "fixed",
16
+ backoff_base: float = 0.0,
17
+ timeout: int | None = None,
18
+ condition: Callable[..., Any] | None = None,
19
+ ) -> Any:
20
+ """
21
+ Decorator to register a function as a step within a workflow builder.
22
+
23
+ Can be used as:
24
+ @step
25
+ def my_step(ctx): ...
26
+
27
+ @step(retries=3, backoff="exponential")
28
+ def my_step(ctx): ...
29
+ """
30
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
31
+ step_name = name if isinstance(name, str) else fn.__name__
32
+ flow = _current_flow.get()
33
+
34
+ # If we are inside a @workflow builder context, register the step
35
+ if flow is not None:
36
+ flow.step(
37
+ name=step_name,
38
+ fn=fn,
39
+ retries=retries,
40
+ backoff=backoff,
41
+ backoff_base=backoff_base,
42
+ timeout=timeout,
43
+ condition=condition,
44
+ )
45
+ return fn
46
+
47
+ if callable(name):
48
+ # Used as @step without parentheses
49
+ return decorator(name)
50
+
51
+ return decorator
52
+
53
+
54
+ def workflow(name: str | Callable[..., Any] | None = None) -> Any:
55
+ """
56
+ Decorator to mark a function as a nested workflow builder.
57
+
58
+ When the decorated function is called with (ctx, tracking_id),
59
+ it evaluates the inner function definitions to build the flow
60
+ and then immediately executes the flow.
61
+ """
62
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
63
+ workflow_name = name if isinstance(name, str) else fn.__name__
64
+
65
+ @functools.wraps(fn)
66
+ def wrapper(ctx: Any, tracking_id: str) -> None:
67
+ flow = Flow(workflow_name)
68
+ token = _current_flow.set(flow)
69
+
70
+ try:
71
+ # Calling the builder function evaluates the inner
72
+ # def blocks, triggering @step decorators to register steps
73
+ fn()
74
+ finally:
75
+ _current_flow.reset(token)
76
+
77
+ # Now that all steps are registered, execute the flow!
78
+ flow.run(ctx, tracking_id=tracking_id)
79
+
80
+ return wrapper
81
+
82
+ if callable(name):
83
+ # Used as @workflow without parentheses
84
+ return decorator(name)
85
+
86
+ return decorator
87
+
88
+
89
+ def parallel(fn: Callable[..., Any]) -> Callable[..., Any]:
90
+ """
91
+ Decorator to mark a block of steps to be executed concurrently.
92
+ All @step definitions inside this function will be bundled into a ParallelGroup.
93
+ """
94
+ flow = _current_flow.get()
95
+ if flow is not None:
96
+ with flow.parallel():
97
+ fn()
98
+ return fn
99
+
100
+
101
+ def subflow(
102
+ name: str | Callable[..., Any] | None = None,
103
+ *,
104
+ retries: int = 1,
105
+ backoff: str = "fixed",
106
+ backoff_base: float = 0.0,
107
+ timeout: int | None = None,
108
+ condition: Callable[..., Any] | None = None,
109
+ ) -> Any:
110
+ """
111
+ Decorator to formally register a subflow execution.
112
+ The decorated function must return a dict containing {"flow": Flow, "tracking_id": str}.
113
+ """
114
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
115
+ step_name = name if isinstance(name, str) else fn.__name__
116
+ flow_builder = _current_flow.get()
117
+
118
+ if flow_builder is not None:
119
+ def _subflow_wrapper(ctx: Any) -> dict[str, Any]:
120
+ result = fn(ctx)
121
+ child_runner = result["flow"]
122
+ tid = result["tracking_id"]
123
+
124
+ from flowsmith.flow import Flow
125
+ if isinstance(child_runner, Flow):
126
+ child_runner.run(ctx, tracking_id=tid)
127
+ else:
128
+ # Assumes it's a @workflow decorated function
129
+ child_runner(ctx, tracking_id=tid)
130
+
131
+ return {"tracking_id": tid, "status": "COMPLETED"}
132
+
133
+ flow_builder.step(
134
+ name=step_name,
135
+ fn=_subflow_wrapper,
136
+ retries=retries,
137
+ backoff=backoff,
138
+ backoff_base=backoff_base,
139
+ timeout=timeout,
140
+ condition=condition,
141
+ )
142
+ return fn
143
+
144
+ if callable(name):
145
+ return decorator(name)
146
+
147
+ return decorator
@@ -0,0 +1,52 @@
1
+ class FlowSmithNotConfigured(Exception):
2
+ """
3
+ Raised when a Flow is created before flowsmith.configure() has been called.
4
+ """
5
+ def __init__(self) -> None:
6
+ super().__init__(
7
+ "FlowSmith is not configured. "
8
+ "Call flowsmith.configure(database_url=...) at server startup "
9
+ "before creating any Flow instances."
10
+ )
11
+
12
+
13
+ class StepFailed(Exception):
14
+ """
15
+ Raised when a step exhausts all retry attempts.
16
+ Wraps the original exception for inspection.
17
+ """
18
+ def __init__(self, step_name: str, attempt: int, original: Exception) -> None:
19
+ self.step_name = step_name
20
+ self.attempt = attempt
21
+ self.original = original
22
+ super().__init__(
23
+ f"Step '{step_name}' failed after {attempt} attempt(s): {original}"
24
+ )
25
+
26
+
27
+ class StepTimeoutError(Exception):
28
+ """
29
+ Raised when a step exceeds its configured timeout.
30
+ Treated as a retryable failure — the step will be retried
31
+ if attempts remain, with backoff applied.
32
+ """
33
+ def __init__(self, step_name: str, timeout: int, attempt: int) -> None:
34
+ self.step_name = step_name
35
+ self.timeout = timeout
36
+ self.attempt = attempt
37
+ super().__init__(
38
+ f"Step '{step_name}' timed out after {timeout}s "
39
+ f"(attempt {attempt})"
40
+ )
41
+
42
+
43
+ class FlowAlreadyCompleted(Exception):
44
+ """
45
+ Raised when flow.run() is called with a tracking_id that already
46
+ belongs to a COMPLETED flow.
47
+ """
48
+ def __init__(self, tracking_id: str) -> None:
49
+ super().__init__(
50
+ f"Flow with tracking_id='{tracking_id}' is already COMPLETED. "
51
+ "Use a new tracking_id to start a fresh execution."
52
+ )