flowsmith 0.6.0__tar.gz

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.
Files changed (32) hide show
  1. flowsmith-0.6.0/LICENSE +21 -0
  2. flowsmith-0.6.0/PKG-INFO +430 -0
  3. flowsmith-0.6.0/README.md +400 -0
  4. flowsmith-0.6.0/flowsmith/__init__.py +80 -0
  5. flowsmith-0.6.0/flowsmith/__main__.py +183 -0
  6. flowsmith-0.6.0/flowsmith/config.py +137 -0
  7. flowsmith-0.6.0/flowsmith/context.py +34 -0
  8. flowsmith-0.6.0/flowsmith/contrib/__init__.py +1 -0
  9. flowsmith-0.6.0/flowsmith/decorators.py +147 -0
  10. flowsmith-0.6.0/flowsmith/exceptions.py +52 -0
  11. flowsmith-0.6.0/flowsmith/executor.py +291 -0
  12. flowsmith-0.6.0/flowsmith/flow.py +172 -0
  13. flowsmith-0.6.0/flowsmith/migrations/__init__.py +0 -0
  14. flowsmith-0.6.0/flowsmith/models/__init__.py +4 -0
  15. flowsmith-0.6.0/flowsmith/models/flow_record.py +19 -0
  16. flowsmith-0.6.0/flowsmith/models/node_record.py +21 -0
  17. flowsmith-0.6.0/flowsmith/py.typed +1 -0
  18. flowsmith-0.6.0/flowsmith/step.py +66 -0
  19. flowsmith-0.6.0/flowsmith/storage/__init__.py +6 -0
  20. flowsmith-0.6.0/flowsmith/storage/base.py +87 -0
  21. flowsmith-0.6.0/flowsmith/storage/memory.py +127 -0
  22. flowsmith-0.6.0/flowsmith/storage/mysql.py +203 -0
  23. flowsmith-0.6.0/flowsmith/storage/postgres.py +194 -0
  24. flowsmith-0.6.0/flowsmith/watchdog.py +133 -0
  25. flowsmith-0.6.0/flowsmith.egg-info/PKG-INFO +430 -0
  26. flowsmith-0.6.0/flowsmith.egg-info/SOURCES.txt +30 -0
  27. flowsmith-0.6.0/flowsmith.egg-info/dependency_links.txt +1 -0
  28. flowsmith-0.6.0/flowsmith.egg-info/entry_points.txt +2 -0
  29. flowsmith-0.6.0/flowsmith.egg-info/requires.txt +17 -0
  30. flowsmith-0.6.0/flowsmith.egg-info/top_level.txt +1 -0
  31. flowsmith-0.6.0/pyproject.toml +81 -0
  32. flowsmith-0.6.0/setup.cfg +4 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RiteshRaoV
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,430 @@
1
+ Metadata-Version: 2.4
2
+ Name: flowsmith
3
+ Version: 0.6.0
4
+ Summary: Lightweight durable workflow execution for Python backends
5
+ License: MIT
6
+ Keywords: workflow,orchestration,durable,execution,backend
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: postgres
16
+ Requires-Dist: sqlalchemy>=2.0; extra == "postgres"
17
+ Requires-Dist: psycopg2-binary>=2.9; extra == "postgres"
18
+ Provides-Extra: mysql
19
+ Requires-Dist: sqlalchemy>=2.0; extra == "mysql"
20
+ Requires-Dist: mysql-connector-python>=8.0; extra == "mysql"
21
+ Provides-Extra: dev
22
+ Requires-Dist: sqlalchemy>=2.0; extra == "dev"
23
+ Requires-Dist: psycopg2-binary>=2.9; extra == "dev"
24
+ Requires-Dist: mysql-connector-python>=8.0; extra == "dev"
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
27
+ Requires-Dist: ruff>=0.4; extra == "dev"
28
+ Requires-Dist: mypy>=1.10; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # FlowSmith
32
+
33
+ Lightweight durable workflow execution for Python backends.
34
+
35
+ FlowSmith fills the gap between fragile custom scripts and heavyweight orchestration systems like Temporal or Airflow. Define backend workflows as code, execute them reliably, and resume them safely after crashes — with zero external infrastructure beyond your existing database.
36
+
37
+ ---
38
+
39
+ ## The problem
40
+
41
+ Modern backend systems require orchestrating multiple API calls in sequence:
42
+
43
+ ```python
44
+ product = call_products_api(product_id)
45
+ methods = call_payments_api(product["price"])
46
+ payment = create_payment(methods[0]["id"])
47
+ notify(user_id, payment["id"])
48
+ ```
49
+
50
+ Writing this is easy. Making it production-safe is not. What happens when:
51
+
52
+ - `create_payment` succeeds but the process crashes before `notify` runs?
53
+ - `call_payments_api` times out on attempt 1 but would succeed on attempt 2?
54
+ - You need to know exactly which step failed and why?
55
+
56
+ Without FlowSmith you write custom retry logic, track state manually, and hope nothing crashes mid-flow. With FlowSmith, every step is persisted, every failure is recoverable, and every execution is observable.
57
+
58
+ ---
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ # PostgreSQL
64
+ pip install flowsmith[postgres]
65
+
66
+ # MySQL
67
+ pip install flowsmith[mysql]
68
+
69
+ # Both
70
+ pip install flowsmith[postgres,mysql]
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Quickstart
76
+
77
+ **1. Configure once at server startup**
78
+
79
+ ```python
80
+ import flowsmith
81
+
82
+ flowsmith.configure(
83
+ database_url=os.environ["DATABASE_URL"],
84
+ pool_min=2, # always 2 connections alive
85
+ pool_max=10, # scales to 10 under load
86
+ pool_timeout=30, # wait 30s for a free connection before erroring
87
+ )
88
+
89
+ # Optional but recommended — detects crashed nodes automatically
90
+ flowsmith.start_watchdog(timeout_seconds=300, interval_seconds=60)
91
+ ```
92
+
93
+ Supports both PostgreSQL and MySQL — FlowSmith detects the right backend from the URL:
94
+
95
+ ```bash
96
+ DATABASE_URL=postgresql://user:password@host:5432/mydb
97
+ DATABASE_URL=mysql://user:password@host:3306/mydb
98
+ ```
99
+
100
+ **2. Run migrations**
101
+
102
+ ```bash
103
+ flowsmith migrate
104
+ # or explicitly
105
+ flowsmith migrate --url postgresql://user:pass@localhost/mydb
106
+ ```
107
+
108
+ This creates two tables in your database: `fs_flows` and `fs_nodes`.
109
+
110
+ **3. Define step functions**
111
+
112
+ Steps are plain Python functions. No base classes, no decorators, no magic.
113
+
114
+ ```python
115
+ def get_product(ctx):
116
+ product = products_api.get(ctx.data["product_id"])
117
+ return {
118
+ "name": product["name"],
119
+ "price": product["price"],
120
+ "currency": product["currency"],
121
+ }
122
+
123
+ def get_payment_methods(ctx):
124
+ product = ctx.data["get_product"] # output from step 1
125
+ methods = payments_api.list(
126
+ price=product["price"],
127
+ currency=product["currency"],
128
+ )
129
+ return {"methods": methods}
130
+
131
+ def create_payment(ctx):
132
+ product = ctx.data["get_product"] # output from step 1
133
+ methods = ctx.data["get_payment_methods"] # output from step 2
134
+ payment = payments_api.create(
135
+ method_id=methods["methods"][0]["id"],
136
+ amount=product["price"],
137
+ )
138
+ return {"payment_id": payment["id"]}
139
+
140
+ def send_notification(ctx):
141
+ product = ctx.data["get_product"] # output from step 1
142
+ payment = ctx.data["create_payment"] # output from step 3
143
+ user_id = ctx.data["user_id"] # original input
144
+ email_api.send_receipt(user_id, payment["payment_id"], product["name"])
145
+ return {"sent": True}
146
+ ```
147
+
148
+ Each step receives a `Context` object (`ctx`). The output of every completed step is available on `ctx.data` under the step's name. This is how data flows between steps — no argument passing, no globals.
149
+
150
+ **4. Wire up the flow and run it**
151
+
152
+ ```python
153
+ from flowsmith import Flow, Context
154
+
155
+ flow = Flow("create_order")
156
+ flow.step("get_product", get_product, retries=3)
157
+ flow.step("get_payment_methods", get_payment_methods, retries=3)
158
+ flow.step("create_payment", create_payment, retries=3)
159
+ flow.step("send_notification", send_notification, retries=2)
160
+
161
+ flow.run(
162
+ Context({"product_id": "prod_123", "user_id": "u_456"}),
163
+ tracking_id=request.idempotency_key,
164
+ )
165
+ ```
166
+
167
+ ---
168
+
169
+ ## The Decorator API (v0.4+)
170
+
171
+ FlowSmith supports a powerful Context-Aware Builder Pattern using decorators. This allows you to define workflows naturally and introduces built-in conditional branching.
172
+
173
+ ```python
174
+ from flowsmith.decorators import workflow, step
175
+
176
+ @workflow("checkout_process")
177
+ def process_order():
178
+
179
+ # Python evaluates this first, so it's Step 1
180
+ @step(retries=3)
181
+ def fetch_inventory(ctx):
182
+ return {"in_stock": True, "price": 100}
183
+
184
+ # Conditional Branching: This step is skipped if the lambda returns False
185
+ @step(condition=lambda ctx: ctx.data["fetch_inventory"]["in_stock"])
186
+ def reserve_items(ctx):
187
+ pass
188
+
189
+ # Triggering the nested workflow:
190
+ process_order(Context({"order_id": 999}), tracking_id="tr_abc123")
191
+ ```
192
+
193
+ The decorator natively handles retries, pausing on crashes, and skipped steps, exactly like the standard API, but keeps your code clean and composable.
194
+
195
+ ---
196
+
197
+ ## Parallel Execution & Subflows (v0.5+)
198
+
199
+ FlowSmith supports executing multiple independent steps concurrently utilizing a `ThreadPoolExecutor`, and formally supports isolated sub-workflows.
200
+
201
+ ```python
202
+ from flowsmith.decorators import workflow, step, parallel, subflow
203
+
204
+ @workflow("analytics_pipeline")
205
+ def process_data():
206
+
207
+ # 1. Parallel execution block
208
+ # Everything inside this block runs concurrently!
209
+ @parallel
210
+ def fetch_phase():
211
+ @step
212
+ def get_users(ctx): ...
213
+
214
+ @step
215
+ def get_products(ctx): ...
216
+
217
+ # 2. Sequential step
218
+ # Naturally waits for the entire fetch_phase to complete.
219
+ @step
220
+ def generate_report(ctx): ...
221
+
222
+ # 3. Trigger a formal sub-workflow
223
+ # Safely embeds a child flow process. Blocks parent until child is thoroughly DONE.
224
+ @subflow
225
+ def alert_email(ctx):
226
+ return {
227
+ "flow": send_email_flow,
228
+ "tracking_id": f"mail_{ctx.data['user_id']}"
229
+ }
230
+
231
+ ```
232
+
233
+ > For power users: `flow.parallel()` and `flow.subflow()` are fully available on the native builder API as well!
234
+ >
235
+ > ```python
236
+ > # 1. Parallel Execution
237
+ > with flow.parallel():
238
+ > flow.step("get_users", get_users)
239
+ > flow.step("get_products", get_products)
240
+ >
241
+ > flow.step("generate_report", generate_report)
242
+ >
243
+ > # 2. Subflow
244
+ > flow.subflow(
245
+ > "alert_email",
246
+ > send_email_flow,
247
+ > tracking_id=lambda ctx: f"mail_{ctx.data['user_id']}"
248
+ > )
249
+ > ```
250
+
251
+ ---
252
+
253
+ ## Core guarantees
254
+
255
+ | Guarantee | What it means |
256
+ | ---------------------------- | -------------------------------------------------------------------------- |
257
+ | Completed steps never re-run | If `get_product` succeeded, it is skipped on every subsequent retry |
258
+ | Resume from last success | A flow that failed on step 3 resumes at step 3, not step 1 |
259
+ | At-least-once execution | If a process crashes mid-step, that step will re-run on resume |
260
+ | Full execution trace | Every step's input, output, error, and attempt count is stored |
261
+ | Idempotent trigger | Calling `flow.run()` with the same `tracking_id` resumes, never duplicates |
262
+
263
+ > **Note on at-least-once:** FlowSmith guarantees completed steps are never re-run. Steps that were _in progress_ when a crash happened will be retried. Make your step functions idempotent (safe to run more than once) for full crash safety.
264
+
265
+ ---
266
+
267
+ ## The watchdog
268
+
269
+ The watchdog solves a subtle but critical problem: what happens when a process crashes _after_ a node is marked `RUNNING` but _before_ it is marked `COMPLETED`?
270
+
271
+ Without intervention, that node stays `RUNNING` in the database forever — the flow can never be resumed because FlowSmith sees it as still in progress.
272
+
273
+ The watchdog is a background thread that periodically scans for nodes that have been `RUNNING` longer than your configured timeout. When it finds one, it marks the node `FAILED` and the parent flow `FAILED`, so the next `flow.run()` call can resume correctly.
274
+
275
+ ```
276
+ 10:00:02 Node starts → status = RUNNING
277
+ 10:00:02 Server crashes → node frozen in RUNNING
278
+ ...5 minutes...
279
+ 10:05:00 Watchdog wakes → finds node RUNNING for > 5 min
280
+ 10:05:00 Watchdog marks → node = FAILED, flow = FAILED
281
+ 10:05:30 Server restarts → flow.run(tracking_id="same-id")
282
+ 10:05:30 FlowSmith sees → step 1 COMPLETED (skip)
283
+ 10:05:30 FlowSmith sees → step 2 FAILED (retry from here) ✓
284
+ ```
285
+
286
+ **Start it at server startup:**
287
+
288
+ ```python
289
+ flowsmith.configure(database_url=os.environ["DATABASE_URL"])
290
+ flowsmith.start_watchdog(
291
+ timeout_seconds=300, # how long before a RUNNING node is considered stuck
292
+ interval_seconds=60, # how often to scan
293
+ )
294
+ ```
295
+
296
+ Set `timeout_seconds` to at least 2x your slowest step's expected runtime. If your payment API can legitimately take 2 minutes, use a timeout of at least 5 minutes.
297
+
298
+ The watchdog runs as a daemon thread — it stops automatically when your process exits. No cleanup required.
299
+
300
+ ---
301
+
302
+ ## Resume behaviour
303
+
304
+ FlowSmith uses `tracking_id` to identify a flow execution. Pass the same `tracking_id` to resume:
305
+
306
+ ```python
307
+ # First run — crashes on step 3
308
+ flow.run(ctx, tracking_id="order_abc123")
309
+
310
+ # Resume — step 1 and 2 skipped automatically, resumes at step 3
311
+ flow.run(ctx, tracking_id="order_abc123")
312
+ ```
313
+
314
+ | Flow status on second call | Behaviour |
315
+ | -------------------------- | ------------------------------- |
316
+ | Not found | Fresh execution |
317
+ | `RUNNING` or `FAILED` | Resume from last completed step |
318
+ | `COMPLETED` | Raises `FlowAlreadyCompleted` |
319
+
320
+ ---
321
+
322
+ ## Database backends
323
+
324
+ FlowSmith supports PostgreSQL and MySQL via the same `StorageBackend` interface. The backend is selected automatically from your database URL.
325
+
326
+ | URL prefix | Backend |
327
+ | -------------------------------- | ----------------- |
328
+ | `postgresql://` or `postgres://` | `PostgresStorage` |
329
+ | `mysql://` | `MySQLStorage` |
330
+
331
+ For testing, use `InMemoryStorage` — no database required:
332
+
333
+ ```python
334
+ from flowsmith.storage import InMemoryStorage
335
+
336
+ flow = Flow("test_flow", storage=InMemoryStorage())
337
+ flow.step("my_step", my_fn)
338
+ flow.run(ctx, tracking_id="test-1")
339
+ ```
340
+
341
+ ---
342
+
343
+ ## Local development
344
+
345
+ **Note:**
346
+
347
+ - Requires Docker for integration tests
348
+ - Databases must be running before migrations/tests
349
+ - Uses PostgreSQL + MySQL via docker-compose
350
+ - CLI works on Windows, macOS, and Linux
351
+
352
+ ```bash
353
+ # Start both databases
354
+ make db-up
355
+
356
+ # Run migrations
357
+ make migrate-postgres
358
+ make migrate-mysql
359
+
360
+ # Install dev dependencies
361
+ make install
362
+
363
+ # Unit tests — no database needed, runs in milliseconds
364
+ make test-unit
365
+
366
+ # Integration tests — requires running databases
367
+ make test-integration
368
+
369
+ # All tests with coverage
370
+ make test
371
+
372
+ # Smoke tests — execute realistic end-to-end execution flow
373
+ python smoke_test.py
374
+
375
+ # Stop both databases
376
+ make db-down
377
+ ```
378
+
379
+ ---
380
+
381
+ ## Project structure
382
+
383
+ ```
384
+ flowsmith/
385
+ ├── flowsmith/
386
+ │ ├── __init__.py # public API: configure(), start_watchdog(), Flow, Context
387
+ │ ├── config.py # global configure(), start_watchdog(), get_storage()
388
+ │ ├── flow.py # Flow class — step registration and run()
389
+ │ ├── executor.py # step execution loop, retry, resume logic
390
+ │ ├── watchdog.py # background thread for stuck-node detection
391
+ │ ├── context.py # Context — shared state between steps
392
+ │ ├── step.py # Step dataclass
393
+ │ ├── exceptions.py # FlowSmithNotConfigured, StepFailed, FlowAlreadyCompleted
394
+ │ ├── storage/
395
+ │ │ ├── base.py # StorageBackend ABC — implement this to add a new backend
396
+ │ │ ├── postgres.py # PostgreSQL backend
397
+ │ │ ├── mysql.py # MySQL backend
398
+ │ │ └── memory.py # In-memory backend for tests
399
+ │ ├── models/
400
+ │ │ ├── flow_record.py # FlowRecord dataclass
401
+ │ │ └── node_record.py # NodeRecord dataclass
402
+ │ ├── migrations/
403
+ │ │ ├── postgres/ # PostgreSQL migration files
404
+ │ │ └── mysql/ # MySQL migration files
405
+ │ └── contrib/ # Optional integrations
406
+ └── tests/
407
+ ├── unit/ # Fast tests using InMemoryStorage — no infrastructure needed
408
+ └── integration/ # Real database tests — requires docker-compose
409
+ ```
410
+
411
+ ---
412
+
413
+ ## Roadmap
414
+
415
+ | Version | Scope |
416
+ | ---------- | ------------------------------------------------------------------------------------------------- |
417
+ | **v0.1.0** | Core engine, InMemoryStorage, sequential execution |
418
+ | **v0.2.0** | PostgresStorage, MySQLStorage, migrate CLI, watchdog |
419
+ | **v0.3.0** | Connection pooling, retry backoff strategies, per-step timeout |
420
+ | **v0.3.1** | Bugfixes: stuck-node SQL, cross-platform thread handling, CI on PRs, py.typed |
421
+ | **v0.4.0** | Decorator API builder pattern, conditional branching |
422
+ | **v0.5.0** | Parallel step execution, First-class blocking sub-flows |
423
+ | **v0.6.0** | PyPI Public Release, Community outreach, Strict Typing (mypy) ← current |
424
+ | v1.0.0 | Stable API, core feature completion, long-term stability |
425
+
426
+ ---
427
+
428
+ ## License
429
+
430
+ MIT