sfnkit 0.1.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 (72) hide show
  1. sfnkit-0.1.0/.gitignore +7 -0
  2. sfnkit-0.1.0/LICENSE +202 -0
  3. sfnkit-0.1.0/PKG-INFO +219 -0
  4. sfnkit-0.1.0/README.md +195 -0
  5. sfnkit-0.1.0/examples/__init__.py +0 -0
  6. sfnkit-0.1.0/examples/pipeline.py +247 -0
  7. sfnkit-0.1.0/isb.yaml +24 -0
  8. sfnkit-0.1.0/pyproject.toml +64 -0
  9. sfnkit-0.1.0/scripts/dump_asl.py +43 -0
  10. sfnkit-0.1.0/scripts/sandbox.sh +9 -0
  11. sfnkit-0.1.0/src/sfnkit/__init__.py +67 -0
  12. sfnkit-0.1.0/src/sfnkit/app.py +118 -0
  13. sfnkit-0.1.0/src/sfnkit/blocks.py +250 -0
  14. sfnkit-0.1.0/src/sfnkit/build/__init__.py +5 -0
  15. sfnkit-0.1.0/src/sfnkit/build/context.py +139 -0
  16. sfnkit-0.1.0/src/sfnkit/build/docker.py +75 -0
  17. sfnkit-0.1.0/src/sfnkit/build/dockerfile.py +56 -0
  18. sfnkit-0.1.0/src/sfnkit/cli.py +170 -0
  19. sfnkit-0.1.0/src/sfnkit/compile/__init__.py +1 -0
  20. sfnkit-0.1.0/src/sfnkit/compile/app.py +164 -0
  21. sfnkit-0.1.0/src/sfnkit/compile/asl.py +991 -0
  22. sfnkit-0.1.0/src/sfnkit/compile/cfn.py +302 -0
  23. sfnkit-0.1.0/src/sfnkit/compute/__init__.py +12 -0
  24. sfnkit-0.1.0/src/sfnkit/compute/base.py +113 -0
  25. sfnkit-0.1.0/src/sfnkit/compute/lambda_.py +125 -0
  26. sfnkit-0.1.0/src/sfnkit/deploy/__init__.py +14 -0
  27. sfnkit-0.1.0/src/sfnkit/deploy/client.py +81 -0
  28. sfnkit-0.1.0/src/sfnkit/deploy/deployer.py +251 -0
  29. sfnkit-0.1.0/src/sfnkit/errors.py +18 -0
  30. sfnkit-0.1.0/src/sfnkit/expr.py +492 -0
  31. sfnkit-0.1.0/src/sfnkit/iam.py +105 -0
  32. sfnkit-0.1.0/src/sfnkit/ir.py +241 -0
  33. sfnkit-0.1.0/src/sfnkit/local.py +220 -0
  34. sfnkit-0.1.0/src/sfnkit/runtime/__init__.py +1 -0
  35. sfnkit-0.1.0/src/sfnkit/runtime/container.py +50 -0
  36. sfnkit-0.1.0/src/sfnkit/runtime/execute.py +51 -0
  37. sfnkit-0.1.0/src/sfnkit/runtime/lambda_handler.py +11 -0
  38. sfnkit-0.1.0/src/sfnkit/runtime/protocol.py +68 -0
  39. sfnkit-0.1.0/src/sfnkit/runtime/results.py +268 -0
  40. sfnkit-0.1.0/src/sfnkit/step.py +185 -0
  41. sfnkit-0.1.0/src/sfnkit/trace/__init__.py +0 -0
  42. sfnkit-0.1.0/src/sfnkit/trace/lint.py +241 -0
  43. sfnkit-0.1.0/src/sfnkit/trace/merge.py +488 -0
  44. sfnkit-0.1.0/src/sfnkit/trace/tracer.py +395 -0
  45. sfnkit-0.1.0/src/sfnkit/workflow.py +146 -0
  46. sfnkit-0.1.0/tests/__init__.py +0 -0
  47. sfnkit-0.1.0/tests/core/__init__.py +0 -0
  48. sfnkit-0.1.0/tests/core/flows.py +236 -0
  49. sfnkit-0.1.0/tests/core/golden/block_attempt.json +135 -0
  50. sfnkit-0.1.0/tests/core/golden/branchy.json +172 -0
  51. sfnkit-0.1.0/tests/core/golden/catcher.json +234 -0
  52. sfnkit-0.1.0/tests/core/golden/mapper.json +495 -0
  53. sfnkit-0.1.0/tests/core/golden/matcher.json +173 -0
  54. sfnkit-0.1.0/tests/core/golden/narrow_catch.json +86 -0
  55. sfnkit-0.1.0/tests/core/golden/parent_wf.json +160 -0
  56. sfnkit-0.1.0/tests/core/golden/pipeline.json +766 -0
  57. sfnkit-0.1.0/tests/core/golden/simple.json +79 -0
  58. sfnkit-0.1.0/tests/core/test_compile.py +224 -0
  59. sfnkit-0.1.0/tests/core/test_trace.py +201 -0
  60. sfnkit-0.1.0/tests/infra/conftest.py +28 -0
  61. sfnkit-0.1.0/tests/infra/infra_app.py +97 -0
  62. sfnkit-0.1.0/tests/infra/infra_dummy_late.py +8 -0
  63. sfnkit-0.1.0/tests/infra/infra_dummy_steps.py +32 -0
  64. sfnkit-0.1.0/tests/infra/test_infra_build.py +191 -0
  65. sfnkit-0.1.0/tests/infra/test_infra_cfn.py +106 -0
  66. sfnkit-0.1.0/tests/infra/test_infra_cli.py +62 -0
  67. sfnkit-0.1.0/tests/infra/test_infra_container.py +50 -0
  68. sfnkit-0.1.0/tests/infra/test_infra_deploy.py +240 -0
  69. sfnkit-0.1.0/tests/infra/test_infra_runtime.py +223 -0
  70. sfnkit-0.1.0/tests/test_aws_validate.py +51 -0
  71. sfnkit-0.1.0/tests/test_e2e.py +142 -0
  72. sfnkit-0.1.0/uv.lock +924 -0
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ .sfnkit/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ dist/
sfnkit-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
sfnkit-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.5
2
+ Name: sfnkit
3
+ Version: 0.1.0
4
+ Summary: Author AWS Step Functions workflows as decorated Python functions
5
+ Project-URL: Homepage, https://github.com/execution-associates/sfnkit
6
+ Project-URL: Repository, https://github.com/execution-associates/sfnkit
7
+ Project-URL: Issues, https://github.com/execution-associates/sfnkit/issues
8
+ Author: Execution Associates
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: aws,lambda,orchestration,serverless,step-functions,workflow
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Topic :: System :: Distributed Computing
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: boto3>=1.35
23
+ Description-Content-Type: text/markdown
24
+
25
+ # sfnkit
26
+
27
+ Write AWS Step Functions workflows as plain Python. Steps are decorated functions that run as Lambda
28
+ container images. The workflow body is ordinary Python, including `match`, `if` and `with` blocks,
29
+ and is compiled into a state machine.
30
+
31
+ ```
32
+ pip install sfnkit
33
+ ```
34
+
35
+ Requires Python 3.12+. Deploying also needs Docker (to build the Lambda images) and AWS credentials
36
+ that can create IAM roles.
37
+
38
+ ```python
39
+ from sfnkit import step, workflow, attempt, Ok, Err, each, subworkflow, wait, fail, is_null
40
+ from sfnkit import Lambda, Retry, Allow, Policy
41
+
42
+ base = Policy(Allow("s3:GetObject", "arn:aws:s3:::data/*"))
43
+
44
+ @step(compute=Lambda(memory=1024, timeout=120), deps=["httpx>=0.27"])
45
+ def fetch(url: str) -> list[str]: ...
46
+
47
+ @step(deps=["pyyaml"], retry=Retry(on=[ValueError], max_attempts=3))
48
+ def parse(doc: str) -> dict: ...
49
+
50
+ @workflow(iam=base)
51
+ def pipeline(url: str, label: str = "run"):
52
+ docs = fetch(url)
53
+ rows = parse.map(docs, max_concurrency=10) # Map state
54
+
55
+ with subworkflow("scoring"): # child state machine
56
+ score = score_rows(rows)
57
+
58
+ match score["tier"]: # Choice state
59
+ case "gold" | "silver":
60
+ order = publish(rows)
61
+ case "review" if score["value"] > 0.5:
62
+ wait(seconds=300)
63
+ order = queue_for_review(rows)
64
+ case _:
65
+ fail("LowScore", "score below 0.5")
66
+
67
+ match attempt(charge, order): # Catch
68
+ case Ok(receipt):
69
+ pass
70
+ case Err("PaymentDeclined", cause):
71
+ receipt = refund(order, cause)
72
+
73
+ return {"receipt": receipt}
74
+ ```
75
+
76
+ ```
77
+ sfnkit local myapp.flows:pipeline --input '{"url": "https://..."}'
78
+ sfnkit synth myapp.flows:pipeline -o out/
79
+ sfnkit deploy myapp.flows:pipeline --region us-west-2
80
+ sfnkit run myapp.flows:pipeline --input '{"url": "https://..."}'
81
+ sfnkit destroy myapp.flows:pipeline
82
+ ```
83
+
84
+ ## How a workflow body becomes a state machine
85
+
86
+ A step called inside a `@workflow` doesn't run. It returns a *ref* to its future output, and the call
87
+ is recorded. Called anywhere else, a step is a normal Python function.
88
+
89
+ A condition on a ref (`==`, `<`, `in`, `and`, `if x:`) is a *decision*. The tracer runs the workflow
90
+ body once per combination of decisions and merges the runs into one graph:
91
+
92
+ - **Calls that don't depend on each other** run in one Parallel state.
93
+ - **Each decision** becomes a Choice state.
94
+ - **A variable assigned in several branches** is merged automatically, so it can be used after the
95
+ `if`/`match` like normal Python.
96
+
97
+ Because the body runs once per path, it must be deterministic and free of side effects. Paths are
98
+ capped at `max_paths` (default 1024). Each `@workflow` is traced on its own, so splitting a large
99
+ body into child workflows keeps the count down.
100
+
101
+ ## Control flow
102
+
103
+ | Python | Step Functions |
104
+ |---|---|
105
+ | independent step calls | Parallel |
106
+ | `if/elif/else`, `match` with literal, value and OR patterns and guards | Choice |
107
+ | `step.map(items, **kw)`, `with each(items) as it:` | Map (inline), or Distributed with `distributed=True` |
108
+ | `match attempt(fn, ...)` with `case Ok(v)` / `case Err(name, cause)` | Catch |
109
+ | `with subworkflow("name"):`, calling another `@workflow` | child state machine (`startExecution.sync:2`) |
110
+ | `wait(seconds=...)`, `wait(until=...)` | Wait. A barrier: everything before it runs first |
111
+ | `fail(error, cause)` | Fail |
112
+
113
+ **`attempt(fn, *args)`** runs a step, a workflow, or a plain function containing several steps.
114
+
115
+ - **It catches only the error names its `match` handles.** A Python exception's name is its class
116
+ name, so `Err(errors.PaymentDeclined, c)` and `Err("PaymentDeclined", c)` match the same error.
117
+ - **Errors no case handles fail the workflow,** just as they would without `attempt`.
118
+ - **`case Err(error, cause):` catches everything.** `cause` is Lambda's error object: `errorMessage`,
119
+ `errorType` and `stackTrace`.
120
+
121
+ **`each(items)`** takes items from a workflow input, a literal list, a step's output (or a field of
122
+ it), or another inline map's results. A Distributed Map can also read straight from S3 with
123
+ `S3Objects(bucket, prefix)` or `S3File(bucket, key, format="json"|"jsonl"|"csv")`. Inside the block,
124
+ `it.item` is the current item and `it.result(x)` sets that item's result. After the block, `it.value`
125
+ is the list of results.
126
+
127
+ **Checked when the decorator runs**, because tracing would silently take the wrong branch otherwise:
128
+
129
+ - `case None/True/False` and `is` compare by identity. Use `is_null(x)`.
130
+ - List and dict patterns aren't supported. Neither are class patterns other than `Ok`/`Err`.
131
+ - A bare exception name inside `Err(...)` captures every error instead of matching that exception.
132
+ Write the dotted name or a string.
133
+ - `try/except` isn't supported; use `attempt`. Neither is `while`.
134
+ - `return` must be the last statement of the workflow.
135
+
136
+ **Not supported** in a workflow body: arithmetic on refs, `len()` (use `length(x)`), and iterating a
137
+ ref (use `.map`/`each`). Do those in a step.
138
+
139
+ ## IAM
140
+
141
+ Every step's role gets three layers:
142
+
143
+ 1. **The runtime baseline.** This is added automatically: its own logs, plus read and write on the
144
+ artifacts bucket under `runs/`.
145
+ 2. **The workflow's base set**, from `@workflow(iam=base)` or `subworkflow(..., iam=base)`. Steps
146
+ with no `iam=` inherit the nearest one.
147
+ 3. **The step's own `iam=`, which replaces the base set.**
148
+ - Write `iam=base + Allow(...)` to keep the base set and add to it.
149
+ - Write `iam=Policy(Allow(...))` for granular permissions with none of the base set.
150
+
151
+ `Policy` objects compose with `+`, which takes their union and removes duplicates. A step that ends
152
+ up under two different policies is deployed as two functions. A reusable `@workflow` uses its own
153
+ `iam=`. Resources may be CloudFormation intrinsics, for example
154
+ `{"Fn::Sub": "arn:${AWS::Partition}:s3:::${ArtifactsBucket}/fixtures/*"}`.
155
+
156
+ ## Data between steps
157
+
158
+ Step arguments and results must be JSON-serializable. Step Functions caps each state's input and
159
+ output at 256 KiB, so any value over `offload_threshold` (default 32 KiB) goes to the artifacts
160
+ bucket. Step code only ever sees plain values.
161
+
162
+ A condition is evaluated inside Step Functions, which can't read S3. So the step that produces a
163
+ value also returns, inline, the specific fields conditions read (*facts*). Conditions can therefore
164
+ branch on a value even when the rest of it went to S3.
165
+
166
+ The wire format is in `src/sfnkit/runtime/protocol.py`.
167
+
168
+ ## Dependencies and images
169
+
170
+ A step's image is built from the workflow's `deps` + the step's `deps` (+ `system_packages`,
171
+ installed with `microdnf`), on `public.ecr.aws/lambda/python:<python>`. Steps with the same set
172
+ share an image. Tags are content hashes, so an unchanged image isn't rebuilt or pushed again. Build
173
+ contexts go in `<project>/.sfnkit/build/`.
174
+
175
+ ## Deploying
176
+
177
+ `deploy` creates two stacks:
178
+
179
+ - `<stack>-assets`: the ECR repository and the artifacts bucket.
180
+ - `<stack>`: the functions, their roles, log groups and state machines.
181
+
182
+ `destroy` deletes both, emptying the bucket first. The deploying credentials must be allowed to
183
+ create IAM roles. Credentials from `sts get-session-token` can't call IAM without MFA, so use
184
+ long-term or assumed-role credentials.
185
+
186
+ ## Adding a compute backend
187
+
188
+ Every step runs through one interface, `sfnkit.compute.base.ComputeBackend`. To add one:
189
+
190
+ 1. Subclass `ComputeSpec` for the user-facing settings, e.g. `Fargate(cpu=..., memory=...)`.
191
+ 2. Implement four methods on the backend:
192
+ - `resources(fn, ctx)`: the CloudFormation resources that run it.
193
+ - `baseline_statements(fn, ctx)`: IAM its own role needs.
194
+ - `task_state(fn)`: the Task state. Put `PAYLOAD` where the envelope goes.
195
+ - `state_machine_statements(fn)`: IAM the state machine needs to start it.
196
+ 3. Register it with `register_backend` or the `sfnkit.compute` entry point.
197
+
198
+ The compiler, CloudFormation assembly and deployer only call this interface. Containers can run the
199
+ same image with the entrypoint `python -m sfnkit.runtime.container`, which reads the envelope and
200
+ task token from the environment and reports the result with `SendTaskSuccess`/`SendTaskFailure`.
201
+ `tests/core/test_compile.py` registers a fake ECS backend to prove nothing else needs to change.
202
+
203
+ ## Development
204
+
205
+ Work happens in the isb sandbox described by `isb.yaml`:
206
+
207
+ ```
208
+ isb up -d
209
+ scripts/sandbox.sh -- 'uv sync && uv run pytest' # unit tests, no AWS
210
+ scripts/sandbox.sh -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION \
211
+ -- 'uv run pytest -m aws' # validate ASL with AWS
212
+ scripts/sandbox.sh -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION \
213
+ -- 'PYTHONPATH=. uv run pytest -m e2e -s' # deploy, run, destroy
214
+ ```
215
+
216
+ - **Golden ASL** lives in `tests/core/golden/`. Refresh it with `SFNKIT_UPDATE_GOLDEN=1` and
217
+ review the diff.
218
+ - **The e2e test** deploys `examples/pipeline.py` under a random `sfnkit-e2e-*` stack name, runs
219
+ every path, and always tears down.
sfnkit-0.1.0/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # sfnkit
2
+
3
+ Write AWS Step Functions workflows as plain Python. Steps are decorated functions that run as Lambda
4
+ container images. The workflow body is ordinary Python, including `match`, `if` and `with` blocks,
5
+ and is compiled into a state machine.
6
+
7
+ ```
8
+ pip install sfnkit
9
+ ```
10
+
11
+ Requires Python 3.12+. Deploying also needs Docker (to build the Lambda images) and AWS credentials
12
+ that can create IAM roles.
13
+
14
+ ```python
15
+ from sfnkit import step, workflow, attempt, Ok, Err, each, subworkflow, wait, fail, is_null
16
+ from sfnkit import Lambda, Retry, Allow, Policy
17
+
18
+ base = Policy(Allow("s3:GetObject", "arn:aws:s3:::data/*"))
19
+
20
+ @step(compute=Lambda(memory=1024, timeout=120), deps=["httpx>=0.27"])
21
+ def fetch(url: str) -> list[str]: ...
22
+
23
+ @step(deps=["pyyaml"], retry=Retry(on=[ValueError], max_attempts=3))
24
+ def parse(doc: str) -> dict: ...
25
+
26
+ @workflow(iam=base)
27
+ def pipeline(url: str, label: str = "run"):
28
+ docs = fetch(url)
29
+ rows = parse.map(docs, max_concurrency=10) # Map state
30
+
31
+ with subworkflow("scoring"): # child state machine
32
+ score = score_rows(rows)
33
+
34
+ match score["tier"]: # Choice state
35
+ case "gold" | "silver":
36
+ order = publish(rows)
37
+ case "review" if score["value"] > 0.5:
38
+ wait(seconds=300)
39
+ order = queue_for_review(rows)
40
+ case _:
41
+ fail("LowScore", "score below 0.5")
42
+
43
+ match attempt(charge, order): # Catch
44
+ case Ok(receipt):
45
+ pass
46
+ case Err("PaymentDeclined", cause):
47
+ receipt = refund(order, cause)
48
+
49
+ return {"receipt": receipt}
50
+ ```
51
+
52
+ ```
53
+ sfnkit local myapp.flows:pipeline --input '{"url": "https://..."}'
54
+ sfnkit synth myapp.flows:pipeline -o out/
55
+ sfnkit deploy myapp.flows:pipeline --region us-west-2
56
+ sfnkit run myapp.flows:pipeline --input '{"url": "https://..."}'
57
+ sfnkit destroy myapp.flows:pipeline
58
+ ```
59
+
60
+ ## How a workflow body becomes a state machine
61
+
62
+ A step called inside a `@workflow` doesn't run. It returns a *ref* to its future output, and the call
63
+ is recorded. Called anywhere else, a step is a normal Python function.
64
+
65
+ A condition on a ref (`==`, `<`, `in`, `and`, `if x:`) is a *decision*. The tracer runs the workflow
66
+ body once per combination of decisions and merges the runs into one graph:
67
+
68
+ - **Calls that don't depend on each other** run in one Parallel state.
69
+ - **Each decision** becomes a Choice state.
70
+ - **A variable assigned in several branches** is merged automatically, so it can be used after the
71
+ `if`/`match` like normal Python.
72
+
73
+ Because the body runs once per path, it must be deterministic and free of side effects. Paths are
74
+ capped at `max_paths` (default 1024). Each `@workflow` is traced on its own, so splitting a large
75
+ body into child workflows keeps the count down.
76
+
77
+ ## Control flow
78
+
79
+ | Python | Step Functions |
80
+ |---|---|
81
+ | independent step calls | Parallel |
82
+ | `if/elif/else`, `match` with literal, value and OR patterns and guards | Choice |
83
+ | `step.map(items, **kw)`, `with each(items) as it:` | Map (inline), or Distributed with `distributed=True` |
84
+ | `match attempt(fn, ...)` with `case Ok(v)` / `case Err(name, cause)` | Catch |
85
+ | `with subworkflow("name"):`, calling another `@workflow` | child state machine (`startExecution.sync:2`) |
86
+ | `wait(seconds=...)`, `wait(until=...)` | Wait. A barrier: everything before it runs first |
87
+ | `fail(error, cause)` | Fail |
88
+
89
+ **`attempt(fn, *args)`** runs a step, a workflow, or a plain function containing several steps.
90
+
91
+ - **It catches only the error names its `match` handles.** A Python exception's name is its class
92
+ name, so `Err(errors.PaymentDeclined, c)` and `Err("PaymentDeclined", c)` match the same error.
93
+ - **Errors no case handles fail the workflow,** just as they would without `attempt`.
94
+ - **`case Err(error, cause):` catches everything.** `cause` is Lambda's error object: `errorMessage`,
95
+ `errorType` and `stackTrace`.
96
+
97
+ **`each(items)`** takes items from a workflow input, a literal list, a step's output (or a field of
98
+ it), or another inline map's results. A Distributed Map can also read straight from S3 with
99
+ `S3Objects(bucket, prefix)` or `S3File(bucket, key, format="json"|"jsonl"|"csv")`. Inside the block,
100
+ `it.item` is the current item and `it.result(x)` sets that item's result. After the block, `it.value`
101
+ is the list of results.
102
+
103
+ **Checked when the decorator runs**, because tracing would silently take the wrong branch otherwise:
104
+
105
+ - `case None/True/False` and `is` compare by identity. Use `is_null(x)`.
106
+ - List and dict patterns aren't supported. Neither are class patterns other than `Ok`/`Err`.
107
+ - A bare exception name inside `Err(...)` captures every error instead of matching that exception.
108
+ Write the dotted name or a string.
109
+ - `try/except` isn't supported; use `attempt`. Neither is `while`.
110
+ - `return` must be the last statement of the workflow.
111
+
112
+ **Not supported** in a workflow body: arithmetic on refs, `len()` (use `length(x)`), and iterating a
113
+ ref (use `.map`/`each`). Do those in a step.
114
+
115
+ ## IAM
116
+
117
+ Every step's role gets three layers:
118
+
119
+ 1. **The runtime baseline.** This is added automatically: its own logs, plus read and write on the
120
+ artifacts bucket under `runs/`.
121
+ 2. **The workflow's base set**, from `@workflow(iam=base)` or `subworkflow(..., iam=base)`. Steps
122
+ with no `iam=` inherit the nearest one.
123
+ 3. **The step's own `iam=`, which replaces the base set.**
124
+ - Write `iam=base + Allow(...)` to keep the base set and add to it.
125
+ - Write `iam=Policy(Allow(...))` for granular permissions with none of the base set.
126
+
127
+ `Policy` objects compose with `+`, which takes their union and removes duplicates. A step that ends
128
+ up under two different policies is deployed as two functions. A reusable `@workflow` uses its own
129
+ `iam=`. Resources may be CloudFormation intrinsics, for example
130
+ `{"Fn::Sub": "arn:${AWS::Partition}:s3:::${ArtifactsBucket}/fixtures/*"}`.
131
+
132
+ ## Data between steps
133
+
134
+ Step arguments and results must be JSON-serializable. Step Functions caps each state's input and
135
+ output at 256 KiB, so any value over `offload_threshold` (default 32 KiB) goes to the artifacts
136
+ bucket. Step code only ever sees plain values.
137
+
138
+ A condition is evaluated inside Step Functions, which can't read S3. So the step that produces a
139
+ value also returns, inline, the specific fields conditions read (*facts*). Conditions can therefore
140
+ branch on a value even when the rest of it went to S3.
141
+
142
+ The wire format is in `src/sfnkit/runtime/protocol.py`.
143
+
144
+ ## Dependencies and images
145
+
146
+ A step's image is built from the workflow's `deps` + the step's `deps` (+ `system_packages`,
147
+ installed with `microdnf`), on `public.ecr.aws/lambda/python:<python>`. Steps with the same set
148
+ share an image. Tags are content hashes, so an unchanged image isn't rebuilt or pushed again. Build
149
+ contexts go in `<project>/.sfnkit/build/`.
150
+
151
+ ## Deploying
152
+
153
+ `deploy` creates two stacks:
154
+
155
+ - `<stack>-assets`: the ECR repository and the artifacts bucket.
156
+ - `<stack>`: the functions, their roles, log groups and state machines.
157
+
158
+ `destroy` deletes both, emptying the bucket first. The deploying credentials must be allowed to
159
+ create IAM roles. Credentials from `sts get-session-token` can't call IAM without MFA, so use
160
+ long-term or assumed-role credentials.
161
+
162
+ ## Adding a compute backend
163
+
164
+ Every step runs through one interface, `sfnkit.compute.base.ComputeBackend`. To add one:
165
+
166
+ 1. Subclass `ComputeSpec` for the user-facing settings, e.g. `Fargate(cpu=..., memory=...)`.
167
+ 2. Implement four methods on the backend:
168
+ - `resources(fn, ctx)`: the CloudFormation resources that run it.
169
+ - `baseline_statements(fn, ctx)`: IAM its own role needs.
170
+ - `task_state(fn)`: the Task state. Put `PAYLOAD` where the envelope goes.
171
+ - `state_machine_statements(fn)`: IAM the state machine needs to start it.
172
+ 3. Register it with `register_backend` or the `sfnkit.compute` entry point.
173
+
174
+ The compiler, CloudFormation assembly and deployer only call this interface. Containers can run the
175
+ same image with the entrypoint `python -m sfnkit.runtime.container`, which reads the envelope and
176
+ task token from the environment and reports the result with `SendTaskSuccess`/`SendTaskFailure`.
177
+ `tests/core/test_compile.py` registers a fake ECS backend to prove nothing else needs to change.
178
+
179
+ ## Development
180
+
181
+ Work happens in the isb sandbox described by `isb.yaml`:
182
+
183
+ ```
184
+ isb up -d
185
+ scripts/sandbox.sh -- 'uv sync && uv run pytest' # unit tests, no AWS
186
+ scripts/sandbox.sh -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION \
187
+ -- 'uv run pytest -m aws' # validate ASL with AWS
188
+ scripts/sandbox.sh -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_DEFAULT_REGION \
189
+ -- 'PYTHONPATH=. uv run pytest -m e2e -s' # deploy, run, destroy
190
+ ```
191
+
192
+ - **Golden ASL** lives in `tests/core/golden/`. Refresh it with `SFNKIT_UPDATE_GOLDEN=1` and
193
+ review the diff.
194
+ - **The e2e test** deploys `examples/pipeline.py` under a random `sfnkit-e2e-*` stack name, runs
195
+ every path, and always tears down.
File without changes