# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pysfn']

package_data = \
{'': ['*']}

install_requires = \
['aws-cdk-lib>=2.55.1,<3.0.0',
 'constructs>=10.1.194,<11.0.0',
 'shortuuid>=1.0.11,<2.0.0']

setup_kwargs = {
    'name': 'pysfn',
    'version': '0.1.12',
    'description': 'Transpiler for AWS Step Functions',
    'long_description': '# PySFN\n*A Python to AWS Step Functions transpiler for the CDK*\n\nThis package is an initial experiment in exploring ways to make AWS Step Functions more useful by allowing\ndevelopers to build state machines in the same way they would write a Python function. Users can define\nstate machines in their CDK Stack as simple functions, then apply a `@state_machine` decorator to declare\na Construct in their stack.\n\nThis is very much an experiment, and I welcome feedback on the viability and utility of this approach. \n\nNote that because it\'s Python-based it will only work when used with Python CDK stacks, and not TypeScript or \nother languages. Of course, your Lambdas can be written in any language, but Python Lambdas can take advantage\nof some additional features.\n\n## Quick start\nThere is a lot of good information below, but if you want to get started quickly and experiment with the\nprototype app, clone the repo give it a shot. Assuming you have the AWS CDK installed, you should be able to\ndeploy the app by doing the following:\n\n```shell\npip install pysfn\ncd proto_app\ncdk deploy\n```\n\nOnce you\'ve deployed it, you can submit the *basic*, *simple*, and *larger* step functions that have been \ncreated with the following input.\n\n```json\n{\n  "str_value": "html",\n  "list_value": [100, 100],\n  "option": false\n}\n```\n\nReplacing `html` with `image`, `pdf`, or some other value will trigger the different paths in the function, \nand you can also test how default values are used by leaving off the `list_value` and `option` values.\n\n## Why Step Functions?\nAWS Step Functions (SFN) is a useful tool for orchestrating processing steps in a serverless fashion. By providing \nthe ability to invoke a range of AWS services such as Lambdas, DynamoDB, SNS, and many others, it\'s significantly\neasier to componentize an application into reusable pieces that can leverage a range of programming languages,\nlibraries, and utilities, while keeping compute requirements and complexity low.\n\nFor example, I\'ve built SFN applications that combine NodeJS lambdas, Python Lambdas using a range of \ndifferent libraries, the AWS Textract service and DynamoDB into a single app that can be used in multiple\ncontexts for data processing. Building this in SFN avoids the need to launch a hosted service to manage\nthe processing flow, and keeps each resource focused on the processing needs of that particular function.\n\n## States Language Hell\nThe biggest downside of SFN is the language that AWS developed to power it.  The\n[Amazon States Language](https://states-language.net/) makes it possible to develop processing flows in\na technology-agnostic way, but it can be clumsy to pick up and use efficiently. Data moves through a state\nmachine definition as a JSON object, and each processing step must manipulate it using jsonpath.\nTo do this well, a developer needs to be aware of the inputs and outputs of each stage and handle them appropriately.\nIn addition, the use of jsonpath operations limits how these values can be assigned to the payload object. As a \nresult it\'s common to follow each processing step with a Pass stage to restructure the results into the payload\nappropriately. The alternative is to make each processing stage take on this responsibility within the processing\nflow. This works, but forces a very tight connection between the SFN definition and the Lambda or other code, and\nremoves the ability to flexibly use that component in a different context.\n\n# A new approach\nPySFN allows you to define your state machines in the same way that you would define any other function in\nPython. Look at the following function which executes a series of steps. The steps (`step[1-4]`) each refer\nto a lambda operation that we want to execute. \n\n```python\n@state_machine(self, "pysfn-basic", locals())\ndef basic(str_value: str, list_value: List[int] = None, option: bool = False):\n    uri1: Union[str, None] = None\n    uri2: Union[str, None] = None\n    (\n        available,\n        mode,\n        option,\n        processing_seconds,\n        code_value,\n        type_value,\n    ) = step1(str_value, option)\n\n    if available:\n        if mode == "html":\n            (available, list_value, uri1) = step2(str_value, list_value)\n        else:\n            (available, uri2, uri1) = step3(str_value, mode, code_value)\n        if uri1:\n            uri2 = step4(uri1)\n    return (\n        mode,\n        code_value,\n        processing_seconds,\n        available,\n        uri1,\n        uri2,\n        option,\n    )\n```\n\nBy attaching the `@statemachine` decorator to the function, we instruct the CDK to generate a State Machine\nConstruct named *pysfn-basic* that has a definition aligned with the function contents. You can see the result\nin the **long** detail below.\n\n```json\n{\n  "StartAt": "Register Input [1:1]",\n  "States": {\n    "Register Input [1:1]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "Next": "Has list_value [1:2]"\n    },\n    "Has list_value [1:2]": {\n      "Type": "Choice",\n      "Choices": [\n        {\n          "Variable": "$.register.list_value",\n          "IsPresent": false,\n          "Next": "Assign list_value default [1:3]"\n        }\n      ],\n      "Default": "Has option [1:4]"\n    },\n    "Assign list_value default [1:3]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "list_value": "",\n        "str_value.$": "$.str_value"\n      },\n      "Next": "Has option [1:4]"\n    },\n    "Has option [1:4]": {\n      "Type": "Choice",\n      "Choices": [\n        {\n          "Variable": "$.register.option",\n          "IsPresent": false,\n          "Next": "Assign option default [1:5]"\n        }\n      ],\n      "Default": "Assign uri1 [1:6]"\n    },\n    "Assign option default [1:5]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "option": false,\n        "str_value.$": "$.str_value",\n        "list_value.$": "$.list_value"\n      },\n      "Next": "Assign uri1 [1:6]"\n    },\n    "Assign uri1 [1:6]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "uri1": "",\n        "option.$": "$.option",\n        "str_value.$": "$.str_value",\n        "list_value.$": "$.list_value"\n      },\n      "Next": "Assign uri2 [1:7]"\n    },\n    "Assign uri2 [1:7]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "uri2": "",\n        "option.$": "$.option",\n        "uri1.$": "$.uri1",\n        "str_value.$": "$.str_value",\n        "list_value.$": "$.list_value"\n      },\n      "Next": "Call step1 [1:8]"\n    },\n    "Call step1 [1:8]": {\n      "Next": "Register step1 [1:9]",\n      "Retry": [\n        {\n          "ErrorEquals": [\n            "Lambda.ServiceException",\n            "Lambda.AWSLambdaException",\n            "Lambda.SdkClientException"\n          ],\n          "IntervalSeconds": 2,\n          "MaxAttempts": 6,\n          "BackoffRate": 2\n        }\n      ],\n      "Type": "Task",\n      "ResultPath": "$.register.out",\n      "Resource": "arn:aws:states:::lambda:invoke",\n      "Parameters": {\n        "FunctionName": "arn:aws:lambda:us-west-2:999999999999:function:pysfn-base-python",\n        "Payload": {\n          "str_value.$": "$.register.str_value",\n          "bool_value.$": "$.register.option",\n          "launcher_target": "step1"\n        }\n      }\n    },\n    "Register step1 [1:9]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "available.$": "$.out.Payload.arg0",\n        "mode.$": "$.out.Payload.arg1",\n        "option.$": "$.out.Payload.arg2",\n        "processing_seconds.$": "$.out.Payload.arg3",\n        "code_value.$": "$.out.Payload.arg4",\n        "type_value.$": "$.out.Payload.arg5",\n        "list_value.$": "$.list_value",\n        "uri1.$": "$.uri1",\n        "uri2.$": "$.uri2",\n        "str_value.$": "$.str_value"\n      },\n      "Next": "If available [1:10]"\n    },\n    "If available [1:10]": {\n      "Type": "Choice",\n      "Choices": [\n        {\n          "And": [\n            {\n              "Variable": "$.register.available",\n              "IsPresent": true\n            },\n            {\n              "Or": [\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.available",\n                      "IsBoolean": true\n                    },\n                    {\n                      "Variable": "$.register.available",\n                      "BooleanEquals": true\n                    }\n                  ]\n                },\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.available",\n                      "IsString": true\n                    },\n                    {\n                      "Not": {\n                        "Variable": "$.register.available",\n                        "StringEquals": ""\n                      }\n                    }\n                  ]\n                },\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.available",\n                      "IsNumeric": true\n                    },\n                    {\n                      "Not": {\n                        "Variable": "$.register.available",\n                        "NumericEquals": 0\n                      }\n                    }\n                  ]\n                }\n              ]\n            }\n          ],\n          "Next": "If mode==\'html\' [1:11]"\n        }\n      ],\n      "Default": "Return [1:19]"\n    },\n    "If mode==\'html\' [1:11]": {\n      "Type": "Choice",\n      "Choices": [\n        {\n          "Variable": "$.register.mode",\n          "StringEquals": "html",\n          "Next": "Call step2 [1:12]"\n        }\n      ],\n      "Default": "Call step3 [1:14]"\n    },\n    "Call step2 [1:12]": {\n      "Next": "Register step2 [1:13]",\n      "Retry": [\n        {\n          "ErrorEquals": [\n            "Lambda.ServiceException",\n            "Lambda.AWSLambdaException",\n            "Lambda.SdkClientException"\n          ],\n          "IntervalSeconds": 2,\n          "MaxAttempts": 6,\n          "BackoffRate": 2\n        }\n      ],\n      "Type": "Task",\n      "ResultPath": "$.register.out",\n      "Resource": "arn:aws:states:::lambda:invoke",\n      "Parameters": {\n        "FunctionName": "arn:aws:lambda:us-west-2:999999999999:function:pysfn-js",\n        "Payload": {\n          "strValue.$": "$.register.str_value",\n          "optParam.$": "$.register.list_value"\n        }\n      }\n    },\n    "Register step2 [1:13]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "available.$": "$.out.Payload.available",\n        "list_value.$": "$.out.Payload.listValue",\n        "uri1.$": "$.out.Payload.resultURI",\n        "code_value.$": "$.code_value",\n        "mode.$": "$.mode",\n        "processing_seconds.$": "$.processing_seconds",\n        "option.$": "$.option",\n        "type_value.$": "$.type_value",\n        "uri2.$": "$.uri2",\n        "str_value.$": "$.str_value"\n      },\n      "Next": "If uri1 [1:16]"\n    },\n    "Call step3 [1:14]": {\n      "Next": "Register step3 [1:15]",\n      "Retry": [\n        {\n          "ErrorEquals": [\n            "Lambda.ServiceException",\n            "Lambda.AWSLambdaException",\n            "Lambda.SdkClientException"\n          ],\n          "IntervalSeconds": 2,\n          "MaxAttempts": 6,\n          "BackoffRate": 2\n        }\n      ],\n      "Type": "Task",\n      "ResultPath": "$.register.out",\n      "Resource": "arn:aws:states:::lambda:invoke",\n      "Parameters": {\n        "FunctionName": "arn:aws:lambda:us-west-2:999999999999:function:pysfn-highmemory-python",\n        "Payload": {\n          "str_value.$": "$.register.str_value",\n          "str_value2.$": "$.register.mode",\n          "str_value3.$": "$.register.code_value",\n          "launcher_target": "step3"\n        }\n      }\n    },\n    "Register step3 [1:15]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "available.$": "$.out.Payload.arg0",\n        "uri2.$": "$.out.Payload.arg1",\n        "uri1.$": "$.out.Payload.arg2",\n        "code_value.$": "$.code_value",\n        "mode.$": "$.mode",\n        "processing_seconds.$": "$.processing_seconds",\n        "list_value.$": "$.list_value",\n        "option.$": "$.option",\n        "type_value.$": "$.type_value",\n        "str_value.$": "$.str_value"\n      },\n      "Next": "If uri1 [1:16]"\n    },\n    "If uri1 [1:16]": {\n      "Type": "Choice",\n      "Choices": [\n        {\n          "And": [\n            {\n              "Variable": "$.register.uri1",\n              "IsPresent": true\n            },\n            {\n              "Or": [\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.uri1",\n                      "IsBoolean": true\n                    },\n                    {\n                      "Variable": "$.register.uri1",\n                      "BooleanEquals": true\n                    }\n                  ]\n                },\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.uri1",\n                      "IsString": true\n                    },\n                    {\n                      "Not": {\n                        "Variable": "$.register.uri1",\n                        "StringEquals": ""\n                      }\n                    }\n                  ]\n                },\n                {\n                  "And": [\n                    {\n                      "Variable": "$.register.uri1",\n                      "IsNumeric": true\n                    },\n                    {\n                      "Not": {\n                        "Variable": "$.register.uri1",\n                        "NumericEquals": 0\n                      }\n                    }\n                  ]\n                }\n              ]\n            }\n          ],\n          "Next": "Call step4 [1:17]"\n        }\n      ],\n      "Default": "Return [1:19]"\n    },\n    "Call step4 [1:17]": {\n      "Next": "Register step4 [1:18]",\n      "Retry": [\n        {\n          "ErrorEquals": [\n            "Lambda.ServiceException",\n            "Lambda.AWSLambdaException",\n            "Lambda.SdkClientException"\n          ],\n          "IntervalSeconds": 2,\n          "MaxAttempts": 6,\n          "BackoffRate": 2\n        }\n      ],\n      "Type": "Task",\n      "ResultPath": "$.register.out",\n      "Resource": "arn:aws:states:::lambda:invoke",\n      "Parameters": {\n        "FunctionName": "arn:aws:lambda:us-west-2:999999999999:function:pysfn-base-python",\n        "Payload": {\n          "str_value.$": "$.register.uri1",\n          "launcher_target": "step4"\n        }\n      }\n    },\n    "Register step4 [1:18]": {\n      "Type": "Pass",\n      "ResultPath": "$.register",\n      "InputPath": "$.register",\n      "Parameters": {\n        "uri2.$": "$.out.Payload.arg0",\n        "available.$": "$.available",\n        "code_value.$": "$.code_value",\n        "mode.$": "$.mode",\n        "processing_seconds.$": "$.processing_seconds",\n        "list_value.$": "$.list_value",\n        "option.$": "$.option",\n        "uri1.$": "$.uri1",\n        "type_value.$": "$.type_value",\n        "str_value.$": "$.str_value"\n      },\n      "Next": "Return [1:19]"\n    },\n    "Return [1:19]": {\n      "Type": "Pass",\n      "Parameters": {\n        "mode.$": "$.register.mode",\n        "code_value.$": "$.register.code_value",\n        "processing_seconds.$": "$.register.processing_seconds",\n        "available.$": "$.register.available",\n        "uri1.$": "$.register.uri1",\n        "uri2.$": "$.register.uri2",\n        "option.$": "$.register.option"\n      },\n      "End": true\n    }\n  }\n}\n```\n\nA few items to note with this result:\n* To avoid name conflicts when the CDK generates the constructs, I\'ve added an ID suffix to each stage.\n* I treat the `register` object within the payload as my version of `locals()` to maintain a clean\n  view of the current set of vars. The first step copies the inputs into the register.\n* After this, we address any optional parameters defined in the function signature. If they aren\'t present,\n  we set the default value.\n* This function sets defaults for two `uri` values which we set using Pass states.\n* The if operations are converted to Choice states with the appropriate conditions. Note that in the case\n  of the first and last Choice states, the logic inserts a complex condition to mimic Python boolean type coercion.\n* Each call to a Lambda function is followed by a generated Pass state to move the results into the register.\n\n## About Lambdas...\nOne of the goals of this project is to make working with Python lambdas more flexible so that you don\'t have\nto spend a lot of time writing code to parse the `event` object over and over. While it\'s not necessary to\nuse it to take advantage of the transpiler, most of the Lambda steps in the proto_app are based on \n**launcher** logic I\'ve included.\n\nThe `step1` function in the `operations.py` module is defined as shown below. Note that this looks like any other \npython function and could be referenced anywhere in your code. \n\n```python\ndef step1(str_value: str, bool_value: bool) -> (bool, str, bool, int, int, str):\n    return True, str_value, False, 4, 200, "text/html"\n```\n\nTo pull this into our stack we have to start by creating a Lambda that will hold the function. \nThis looks like this:\n\n```python\nbase_lambda = PythonLambda(\n    self,\n    "pysfn-base-python",\n    os.path.join(os.getcwd(), "python"),\n    role=self.lambda_role,\n    runtime=PythonLambda.PYTHON_3_9,\n    timeout_minutes=1,\n    memory_mb=1,\n    environment=None,\n)\n```\n\nThe `PythonLambda` class allows us to define a Lambda Construct that can contain multiple functions to be \nexecuted via a launcher that it will generate. Now that we\'ve defined the container, we can add our function\nto the launcher.\n\n```python\nstep1 = base_lambda.register(operations.step1)\n```\n\nThe new `step1` variable has the same function signature as the original function, but can now be used\nwithin our state machine function. The transpiler uses the details of this lambda to produce the following\nstate in our state machine. Note the `pysfn_operation` value that is included in the Payload.\n\n```json\n    "Call step1 [1:8]": {\n      "Next": "Register step1 [1:9]",\n      "Type": "Task",\n      "ResultPath": "$.register.out",\n      "Resource": "arn:aws:states:::lambda:invoke",\n      "Parameters": {\n        "FunctionName": "arn:aws:lambda:us-west-2:999999999999:function:pysfn-base-python",\n        "Payload": {\n          "str_value.$": "$.register.str_value",\n          "bool_value.$": "$.register.option",\n          "pysfn_operation": "step1"\n        }\n      }\n    }\n```\n\nOf course, existing Lambdas are also supported. For example, we can define a Lambda construct as we normally\nwould as shown below.\n\n```python\njs_lambda = lmbda.Function(\n    self,\n    "JSLambda",\n    function_name="pysfn-js",\n    code=lmbda.Code.from_asset(\n        os.path.join(os.getcwd(), "js"), exclude=["node_modules"]\n    ),\n    handler="app.handler",\n    runtime=lmbda.Runtime.NODEJS_14_X,\n    role=self.lambda_role,\n    timeout=Duration.minutes(10),\n    memory_size=2096,\n)\n```\n\nThen we can create a pysfn function from this construct as follows by declaring the input parameters and output \nvalues.\n\n```python\nstep2 = function_for_lambda(\n    js_lambda,\n    {"strValue": str, "optParam": bool},\n    {"available": bool, "listValue": List[int], "resultURI": str},\n)\n```\n\nBy specifying the output values in the function declaration, it allows PySFN to map the results from \na call like this to the appropriate variables.\n\n```python\n(available, list_value, uri1) = step2(str_value, list_value)\n```\n\nIn the step after the Lambda is invoked, a Pass state performs the mapping.\n\n```json\n"Register step2 [1:13]": {\n  "Type": "Pass",\n  "ResultPath": "$.register",\n  "InputPath": "$.register",\n  "Parameters": {\n    "available.$": "$.out.Payload.available",\n    "list_value.$": "$.out.Payload.listValue",\n    "uri1.$": "$.out.Payload.resultURI",\n    "code_value.$": "$.code_value",\n    "mode.$": "$.mode",\n    "processing_seconds.$": "$.processing_seconds",\n    "option.$": "$.option",\n    "type_value.$": "$.type_value",\n    "uri2.$": "$.uri2",\n    "str_value.$": "$.str_value"\n  },\n  "Next": "If uri1 [1:16]"\n}\n```\n\n# More to do!\nAfter a bunch of experiments and refactoring, I think I\'ve been able to prove the utility of this approach,\nat least for the range of projects I typically use SFN for. It\'s still undocumented and has a lot of\nrough edges, but overall I\'ve been thrilled at how easy it has been to iterate on new and existing SFNs\nusing this approach. It significantly reduces the cognitive load I felt when working with the stages language\nand makes it much easier to build stable and well-managed data flows.\n\nThat said, feedback and PRs are welcome. Over the next few months I\'ll hopefully be able to address the\nfollowing:\n1. Better support for `list`, `dict`, and `attribute` access\n2. List comprehensions\n3. Support for dataclasses\n4. Real documentation\n5. Take full advantage of Python type hints\n6. Support functions with kwonly or posonly args\n7. Add support for Parallel\n8. Support the full range of likely conditions\n9. Tree shaking to better handle if/elif/elif/else, as well as assigning multiple variables\n10. Support some common integrations such as reading from S3 or performing DynamoDB writes\n',
    'author': 'Dave Schultz',
    'author_email': 'dave@daveschultzconsulting.com',
    'maintainer': 'None',
    'maintainer_email': 'None',
    'url': 'None',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.9,<4.0',
}


setup(**setup_kwargs)
