├── .circleci
└── config.yml
├── .env
├── .gitignore
├── .golangci.yml
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── STATE_SPEC.md
├── bin
└── .keep
├── cmd
└── workflow
│ └── workflow.go
├── docker-compose.yaml
├── example.png
├── examples
└── choice.json
├── gen
└── .keep
├── go.mod
├── go.sum
├── internal
├── app
│ └── .keep
└── pkg
│ ├── .keep
│ └── common
│ ├── factory.go
│ └── helper.go
├── pkg
├── .keep
├── aslworkflow
│ ├── activity.go
│ ├── choice_state.go
│ ├── fail_state.go
│ ├── fail_state_test.go
│ ├── machine.go
│ ├── machine_test.go
│ ├── parallel_state.go
│ ├── parallel_state_test.go
│ ├── pass_state.go
│ ├── pass_state_test.go
│ ├── state.go
│ ├── succeed_state.go
│ ├── succeed_state_test.go
│ ├── task_state.go
│ ├── task_state_test.go
│ ├── wait_state.go
│ ├── wait_state_test.go
│ ├── workflow.go
│ └── workflow_test.go
└── jsonpath
│ └── jsonpath.go
├── scripts
└── .keep
└── vendor.tar.gz
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | test-unit:
4 | docker:
5 | - image: circleci/golang:1.13.1
6 | working_directory: /go/src/github.com/checkr/states-language-cadence
7 | steps:
8 | - checkout
9 | - run: "make mod-vendor-unpack test-unit"
10 | test-integration:
11 | docker:
12 | - image: circleci/golang:1.13.1
13 | - image: postgres:9.6
14 | environment:
15 | POSTGRES_PASSWORD: test
16 | POSTGRES_USER: test
17 | POSTGRES_DB: test
18 | working_directory: /go/src/github.com/checkr/states-language-cadence
19 | steps:
20 | - checkout
21 | - run: "make mod-vendor-unpack test-integration"
22 | test-lint:
23 | docker:
24 | - image: circleci/golang:1.13.1
25 | working_directory: /go/src/github.com/checkr/states-language-cadence
26 | steps:
27 | - checkout
28 | - run: "curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.19.1"
29 | - run: "make mod-vendor-unpack lint"
30 | build-docker:
31 | # Make sure the docker image is built properly.
32 | machine: true
33 | steps:
34 | - checkout
35 | - run: "make docker"
36 | workflows:
37 | version: 2
38 | test:
39 | jobs:
40 | - build-docker
41 | - test-unit
42 | - test-integration
43 | - test-lint
44 |
--------------------------------------------------------------------------------
/.env:
--------------------------------------------------------------------------------
1 | # Cadence Config
2 | CADENCE_DOMAIN=samples-domain
3 | CADENCE_SERVICE=cadence-frontend
4 | CADENCE_HOST=localhost:7933
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.so
3 | *.dylib
4 |
5 | .DS_Store
6 |
7 | # Test binary, build with `go test -c`
8 | *.test
9 |
10 | # Output of the go coverage tool, specifically when used with LiteIDE
11 | *.out
12 |
13 | /bin/[^.]*
14 | /gen/[^.]*
15 |
16 | /tmp
17 |
18 | /vendor
19 |
20 | /data
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | linters:
2 | disable-all: true
3 | enable:
4 | - gofmt
5 | - golint
6 | - goimports
7 | - govet
8 | - deadcode
9 | - errcheck
10 | - gosimple
11 | - ineffassign
12 | - staticcheck
13 | - structcheck
14 | - typecheck
15 | - unused
16 | - varcheck
17 | - goconst
18 | - unconvert
19 |
20 | run:
21 | modules-download-mode: vendor
22 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.13.1 as builder
2 |
3 | COPY . /build
4 | WORKDIR /build
5 |
6 | ENV GOOS=linux
7 | ENV CGO_ENABLED=0
8 | ENV GO_BUILD_OPTS="-a -installsuffix cgo"
9 |
10 | RUN make mod-vendor-unpack bin
11 |
12 | # ----
13 |
14 | FROM alpine:3.6
15 |
16 | RUN apk add --no-cache libc6-compat ca-certificates
17 |
18 | COPY --from=builder /build/bin/* /bgccore/bin/
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | GO=go
2 | GO_BUILD_OPTS?=
3 |
4 | # Test options. -count 1 disables test result caching.
5 | GO_TEST_OPTS?=-v --race -count 1
6 |
7 | BINDIR?=bin
8 | GENDIR?=gen
9 |
10 | .PHONY: all
11 | all: clean build lint test
12 |
13 | .PHONY: clean
14 | clean:
15 | rm -fR "$(BINDIR)/*"
16 | rm -fR "$(GENDIR)/*"
17 |
18 | # a rule to force phony pattern rules to build always.
19 | .PHONY: force
20 | force:
21 |
22 | .PHONY: build
23 | build: build-all bin
24 |
25 | .PHONY: build-all
26 | build-all:
27 | $(GO) build -mod vendor -o $(BINDIR) $(GO_BUILD_OPTS) ./...
28 |
29 | .PHONY: $(BINDIR)
30 | $(BINDIR): $(shell find cmd/* -type d | sed -e 's/^cmd/$(BINDIR)/')
31 |
32 | # Build a specific binary. Binaries are generated from ./cmd/ subdirs.
33 | $(BINDIR)/%: force
34 | $(GO) build -mod vendor -o $(BINDIR)/$* $(GO_BUILD_OPTS) ./cmd/$*
35 |
36 | .PHONY: test
37 | test: test-unit test-integration
38 |
39 | .PHONY: test-unit
40 | test-unit:
41 | $(GO) test -mod vendor -tags unit -coverprofile="$(GENDIR)/unit.cov" $(GO_TEST_OPTS) ./...
42 |
43 | .PHONY: test-integration
44 | test-integration: check-pg # remove check-pg if pq is not required.
45 | $(GO) test -mod vendor -tags integration -coverprofile="$(GENDIR)/int.cov" $(GO_TEST_OPTS) ./...
46 |
47 | # check for pg connection only if has pg_isready utility.
48 | # in ci probably doesn't have this installed.
49 | .PHONY: check-pg
50 | check-pg:
51 | @(! which pg_isready || pg_isready -h localhost -p 5432) 2>&1 >/dev/null || \
52 | (echo 'postgres not ready! run "docker-compose start" first.' && exit 1)
53 |
54 | # update all dependencies.
55 | .PHONY: mod-update
56 | mod-update:
57 | go get -u all
58 | make mod-vendor
59 |
60 | .PHONY: mod-vendor
61 | mod-vendor: mod-tidy
62 | rm -fR vendor
63 | $(GO) mod vendor
64 | make mod-vendor-pack
65 |
66 | .PHONY: mod-vendor-pack
67 | mod-vendor-pack:
68 | tar czf vendor.tar.gz vendor
69 |
70 | .PHONY: mod-vendor-unpack
71 | mod-vendor-unpack:
72 | rm -fR vendor
73 | tar xf vendor.tar.gz
74 |
75 | .PHONY: mod-tidy
76 | mod-tidy:
77 | $(GO) mod tidy
78 |
79 | .PHONY: lint
80 | lint:
81 | # see https://github.com/golangci/golangci-lint
82 | golangci-lint run ./...
83 |
84 | .PHONY: docker
85 | docker:
86 | docker build -t states-language-cadence -f Dockerfile .
87 |
88 | CADENCE_HOST := host.docker.internal:7933
89 |
90 | .PHONY: cadence-create-domain
91 | cadence-create-domain:
92 | docker run \
93 | --rm ubercadence/cli:master \
94 | --address ${CADENCE_HOST} \
95 | --domain samples-domain domain register \
96 | --global_domain false
97 |
98 | .PHONY: run-trigger
99 | run-trigger:
100 | docker run \
101 | --rm ubercadence/cli:master \
102 | --address ${CADENCE_HOST} \
103 | --domain samples-domain workflow run \
104 | --tl WorkflowDemo \
105 | --wt example:workflow:ExampleWorkflow \
106 | --et 60 \
107 | -i '{"example":"example"}'
108 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # States Language on Cadence
2 |
3 | This is an implementation of [States Language](https://states-language.net/spec.html) on top of the [Cadence Workflow](https://cadenceworkflow.io/) engine.
4 |
5 | #### Project Status
6 |
7 | :warning: **Note: This project is not production ready!** :warning:
8 |
9 | This project is still under development and isn't ready for use in production. Feedback is welcome from the Cadence community. The goal is to provide a plugable way to execute State Language workflows on top of Cadence.
10 |
11 | There a few States Language features still missing:
12 | - [ ] Error handling
13 | - [ ] Retry logic
14 | - [ ] JSON paths
15 | - [ ] Map task type
16 |
17 |
18 | #### About States Language
19 |
20 | Amazon States Language (ASL) is a JSON specification describing state machines and workflows. It is the description that powers AWS Step Functions. Cadence is a robust workflow engine created and open sourced by Uber.
21 | This project allows you to mimic Step Functions outside of AWS infrastructure on inside a Cadence workflow.
22 |
23 | - [Spec](./STATE_SPEC.md)
24 | - [Website](https://states-language.net/spec.html)
25 | - [Editor](https://github.com/checkr/states-language-editor)
26 |
27 | #### Running tests
28 |
29 | ```
30 | make test
31 | ```
32 |
33 | #### Updating vendors
34 |
35 | ```
36 | make mod-vendor
37 | ```
38 |
39 | #### Example
40 |
41 | An example command is provided in `cmd/workflow`. It should demenstrate how to use the framework and register workflows.
42 |
43 | #### Related projects
44 |
45 | Thanks to the folks at Amazon for designing the state machine spec, the folks at Coinbase for building an [implementation in Golang](https://github.com/coinbase/step) and the folks at Uber for building [Cadence](https://github.com/uber/cadence)
46 |
47 | ---
48 |
49 | #### What is States Language?
50 |
51 | The operation of a state machine is specified by states, which are represented by JSON objects, fields in the top-level
52 | `"States"` object. In this example, there is one state named `"FirstState"`.
53 |
54 | When this state machine is launched, the interpreter begins execution by identifying the Start State (`"StartAt"`). It
55 | executes that state, and then checks to see if the state is marked as an End State. If it is, the machine terminates
56 | and returns a result. If the state is not an End State, the interpreter looks for a `"Next"` field to determine what
57 | state to run next; it repeats this process until it reaches a Terminal State (Succeed, Fail, or an End State) or a
58 | runtime error occurs.
59 |
60 | 
61 |
62 | ```json
63 | {
64 | "Comment": "An example of the Amazon States Language using a choice state.",
65 | "StartAt": "FirstState",
66 | "States": {
67 | "FirstState": {
68 | "Type": "Task",
69 | "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
70 | "Next": "ChoiceState"
71 | },
72 | "ChoiceState": {
73 | "Type": "Choice",
74 | "Choices": [
75 | {
76 | "Variable": "$.foo",
77 | "NumericEquals": 1,
78 | "Next": "FirstMatchState"
79 | },
80 | {
81 | "Variable": "$.foo",
82 | "NumericEquals": 2,
83 | "Next": "SecondMatchState"
84 | }
85 | ],
86 | "Default": "DefaultState"
87 | },
88 | "FirstMatchState": {
89 | "Type": "Task",
90 | "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:OnFirstMatch",
91 | "Next": "NextState"
92 | },
93 | "SecondMatchState": {
94 | "Type": "Task",
95 | "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:OnSecondMatch",
96 | "Next": "NextState"
97 | },
98 | "DefaultState": {
99 | "Type": "Fail",
100 | "Error": "DefaultStateError",
101 | "Cause": "No Matches!"
102 | },
103 | "NextState": {
104 | "Type": "Task",
105 | "Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
106 | "End": true
107 | }
108 | }
109 | }
110 | ```
111 |
--------------------------------------------------------------------------------
/STATE_SPEC.md:
--------------------------------------------------------------------------------
1 | # Amazon States Language
2 |
3 | This document describes a [JSON](https://tools.ietf.org/html/rfc7159)-based language used to describe state machines declaratively. The state machines thus defined may be executed by software. In this document, the software is referred to as “the interpreter”.
4 |
5 | Copyright © 2016 Amazon.com Inc. or Affiliates.
6 |
7 | Permission is hereby granted, free of charge, to any person obtaining a copy of this specification and associated documentation files (the “specification”), to use, copy, publish, and/or distribute, the Specification) subject to the following conditions:
8 |
9 | The above copyright notice and this permission notice shall be included in all copies of the Specification.
10 |
11 | You may not modify, merge, sublicense, and/or sell copies of the Specification.
12 |
13 | THE SPECIFICATION IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SPECIFICATION OR THE USE OR OTHER DEALINGS IN THE SPECIFICATION.
14 |
15 | Any sample code included in the Specification, unless otherwise specified, is licensed under the Apache License, Version 2.0.
16 |
17 | ## Table of Contents
18 |
19 | * Structure of a State Machine
20 | * [Example: Hello World](#example)
21 | * [Top-level fields](#toplevelfields)
22 | * Concepts
23 | * [States](#states-fields)
24 | * [Transitions](#transition)
25 | * [Timestamps](#timestamps)
26 | * [Data](#data)
27 | * [Paths](#path)
28 | * [Reference Paths](#)
29 | * [Input and Output Processing](#filters)
30 | * [Errors](#errors)
31 | * State Types
32 | * [Table of State Types and Fields](#state-type-table)
33 | * [Pass State](#pass-state)
34 | * [Task State](#task-state)
35 | * [Choice State](#choice-state)
36 | * [Wait State](#wait-state)
37 | * [Succeed State](#succeed-state)
38 | * [Fail State](#fail-state)
39 | * [Parallel State](#parallel-state)
40 | * Appendices
41 | * [Appendix A: Predefined Error Codes](#appendix-a)
42 |
43 | ## Structure of a State Machine
44 |
45 | A State Machine is represented by a [JSON Object](https://tools.ietf.org/html/rfc7159#section-4).
46 |
47 | ### Example: Hello World
48 |
49 | The operation of a state machine is specified by states, which are represented by JSON objects, fields in the top-level “States” object. In this example, there is one state named “Hello World”.
50 |
51 | ```
52 | {
53 | "Comment": "A simple minimal example of the States language",
54 | "StartAt": "Hello World",
55 | "States": {
56 | "Hello World": {
57 | "Type": "Task",
58 | "Resource": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorld",
59 | "End": true
60 | }
61 | }
62 | }
63 | ```
64 |
65 | When this state machine is launched, the interpreter begins execution by identifying the Start State. It executes that state, and then checks to see if the state is marked as an End State. If it is, the machine terminates and returns a result. If the state is not an End State, the interpreter looks for a “Next” field to determine what state to run next; it repeats this process until it reaches a [Terminal State](#terminal-state) (Succeed, Fail, or an End State) or a runtime error occurs.
66 |
67 | In this example, the machine contains a single state named “Hello World”. Because “Hello World” is a Task State, the interpreter tries to execute it. Examining the value of the “Resource” field shows that it points to a Lambda function, so the interpreter attempts to invoke that function. Assuming the Lambda function executes successfully, the machine will terminate successfully.
68 |
69 | A State Machine is represented by a JSON object.
70 |
71 | ### Top-level fields
72 |
73 | A State Machine MUST have an object field named “States”, whose fields represent the states.
74 |
75 | A State Machine MUST have a string field named “StartAt”, whose value MUST exactly match one of names of the “States” fields. The interpreter starts running the the machine at the named state.
76 |
77 | A State Machine MAY have a string field named “Comment”, provided for human-readable description of the machine.
78 |
79 | A State Machine MAY have a string field named “Version”, which gives the version of the States language used in the machine. This document describes version 1.0, and if omitted, the default value of “Version” is the string “1.0”.
80 |
81 | A State Machine MAY have an integer field named “TimeoutSeconds”. If provided, it provides the maximum number of seconds the machine is allowed to run. If the machine runs longer than the specified time, then the interpreter fails the machine with a `States.Timeout` [Error Name](#error-names).
82 |
83 |
84 |
85 | ## Concepts
86 |
87 | ### States
88 |
89 | States are represented as fields of the top-level “States” object. The state name, whose length MUST BE less than or equal to 128 Unicode characters, is the field name; state names MUST be unique within the scope of the whole state machine. States describe tasks (units of work), or specify flow control (e.g. Choice).
90 |
91 | Here is an example state that executes a Lambda function:
92 |
93 | ```
94 | "HelloWorld": {
95 | "Type": "Task",
96 | "Resource": "arn:aws:lambda:us-east-1:123456789012:function:HelloWorld",
97 | "Next": "NextState",
98 | "Comment": "Executes the HelloWorld Lambda function"
99 | }
100 | ```
101 |
102 | Note that:
103 |
104 | 1. All states MUST have a “Type” field. This document refers to the values of this field as a state’s _type_, and to a state such as the one in the example above as a Task State.
105 |
106 | 2. Any state MAY have a “Comment” field, to hold a human-readable comment or description.
107 |
108 | 3. Most state types require additional fields as specified in this document.
109 |
110 | 4. Any state except for Choice, Succeed, and Fail MAY have a field named "End" whose value MUST be a boolean. The term “Terminal State” means a state with with `{ "End": true }`, or a state with `{ "Type": "Succeed" }`, or a state with `{ "Type": "Fail" }`.
111 |
112 | ### Transitions
113 |
114 | Transitions link states together, defining the control flow for the state machine. After executing a non-terminal state, the interpreter follows a transition to the next state. For most state types, transitions are unconditional and specified through the state's “Next” field.
115 |
116 | All non-terminal states MUST have a “Next” field, except for the Choice state. The value of the “Next” field MUST exactly and case-sensitively match the name of the another state.
117 |
118 | States can have multiple incoming transitions from other states.
119 |
120 | ### Timestamps
121 |
122 | The Choice and Wait states deal with JSON field values which represent timestamps. These are strings which MUST conform to the [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) profile of ISO 8601, with the further restrictions that an uppercase “T” character MUST be used to separate date and time, and an uppercase “Z” character MUST be present in the absence of a numeric time zone offset, for example “2016-03-14T01:59:00Z”.
123 |
124 | ### Data
125 |
126 | The interpreter passes data between states to perform calculations or to dynamically control the state machine’s flow. All such data MUST be expressed in JSON.
127 |
128 | When a state machine is started, the caller can provide an initial [JSON text](https://tools.ietf.org/html/rfc7159#section-2) as input, which is passed to the machine's start state as input. If no input is provided, the default is an empty JSON object, `{}`. As each state is executed, it receives a JSON text as input and can produce arbitrary output, which MUST be a JSON text. When two states are linked by a transition, the output from the first state is passed as input to the second state. The output from the machine's terminal state is treated as the its output.
129 |
130 | For example, consider a simple state machine that adds two numbers together:
131 | ```
132 | {
133 | "StartAt": "Add",
134 | "States": {
135 | "Add": {
136 | "Type": "Task",
137 | "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Add",
138 | "End": true
139 | }
140 | }
141 | }
142 | ```
143 | Suppose the “Add” Lambda function is defined as:
144 |
145 | ```
146 | exports.handler = function(event, context) {
147 | context.succeed(event.val1 + event.val2);
148 | };
149 | ```
150 |
151 | Then if this state machine was started with the input `{ "val1": 3, "val2": 4 }`, then the output would be the JSON text consisting of the number `7`.
152 |
153 | The usual constraints applying to JSON-encoded data apply. In particular, note that:
154 |
155 | 1. Numbers in JSON generally conform to JavaScript semantics, typically corresponding to double-precision IEEE-854 values. For this and other interoperability concerns, see [RFC 7159](https://tools.ietf.org/html/rfc7159).
156 |
157 | 2. Standalone "-delimited strings, booleans, and numbers are valid JSON texts.
158 |
159 | ### Paths
160 |
161 | A Path is a string, beginning with “$”, used to identify components with a JSON text. The syntax is that of [JsonPath](https://github.com/jayway/JsonPath).
162 |
163 | ### Reference Paths
164 |
165 | A Reference Path is a Path with syntax limited in such a way that it can only identify a single node in a JSON structure:
166 |
167 | 1. Object fields can only be accessed via the dot (“.”) notation.
168 |
169 | 2. The operators “@”, “..”, “,”, “:”, “?”, and "[]" are not supported - all Reference Paths MUST be unambiguous references to a single value, array, or object (subtree).
170 |
171 | For example, if state input data contained the values:
172 |
173 | ```
174 | {
175 | "foo": 123,
176 | "bar": ["a", "b", "c"],
177 | "car": {
178 | "cdr": true
179 | }
180 | }
181 | ```
182 |
183 | Then the following Reference Paths would return:
184 |
185 | ```
186 | $.foo => 123
187 | $.bar => ["a", "b", "c"]
188 | $.car.cdr => true
189 | ```
190 |
191 | Paths and Reference Paths are used by certain states, as specified later in this document, to control the flow of a state machine or to configure a state's settings or options.
192 |
193 | ### Input and Output Processing
194 |
195 | As described above, data is passed between states as JSON texts. However, a state - in particular, a Task State which sends the data to external code, and receives data back from that code - may want to send only a subset of the incoming data, and transmit only a subset of the data received back..
196 |
197 | In this discussion, “raw input” means the JSON text that is the input to a state. “Result” means the JSON text that a state generates, for example from external code invoked by a Task State, or the combined result of the branches in a Parallel State.
198 |
199 | Fields named “InputPath”, “OutputPath”, and “ResultPath” exist to support this. Any state except for a Fail State MAY have “InputPath” and “OutputPath”. States which potentially generate results MAY have “ResultPath”: Pass State, Task State, and Parallel State.
200 |
201 | 1. The value of “InputPath” MUST be a Path, which is applied to a State’s raw input to select some or all of it; that selection is used by the state, for example in passing to Resources in Task States and Choices selectors in Choice States.
202 |
203 | 2. The value of “ResultPath” MUST be a Reference Path, which specifies the combination with or replacement of the state’s result with its raw input.
204 |
205 | 3. The value of “OutputPath” MUST be a path, which is applied to the state’s output after the application of ResultPath, leading in the generation of the raw input for the next state.
206 |
207 | In this discussion, “effective input” means the input after the application of the InputPath, and “effective output” means the final state output after processing with ResultPath and OutputPath.
208 |
209 | Note that JsonPath can yield multiple values when applied to an input JSON text. For example, given the text:
210 |
211 | ```
212 | { "a": [1, 2, 3, 4] }
213 | ```
214 |
215 | Then if the JsonPath `$.a[0..1]` is appplied, the result will be two JSON texts, `1` and `2`. When this happens, to produce the effective input, the interpreter gathers the texts into an array, so in this example the state would see the input:
216 |
217 | ```
218 | [ 1, 2 ]
219 | ```
220 |
221 | The same rule applies to OutputPath processing; if the OutputPath result contains multiple values, the effective output is a JSON array containing all of them.
222 |
223 | The ResultPath field’s value is a Reference Path that specifies where to place the result, relative to the raw input. If the input has a field which matches the ResultPath value, then in the output, that field is discarded and overwritten by the state output. Otherwise, a new field is created in the state output.
224 |
225 | If the value of InputPath is `null`, that means that the raw input is discarded, and the effective input for the state is an empty JSON object, `{}`.
226 |
227 | If the value of of ResultPath is `null`, that means that the state’s own raw output is discarded and its raw input becomes its result.
228 |
229 | If the value of OutputPath is `null`, that means the input and result are discarded, and the effective output from the state is an empty JSON object, `{}`.
230 |
231 | #### Defaults
232 |
233 | Each of InputPath, ResultPath, and OutputPath are optional. The default value of InputPath is “$”, so by default the effective input is just the raw input. The default value of ResultPath is “$”, so by default a state’s result overwrites and replaces the raw input. The default value of OutputPath is “$”, so by default a state’s effective output is the result of processing ResultPath.
234 |
235 | Therefore, if none of InputPath, ResultPath, or OutputPath are supplied, a state consumes the raw input as provided and passes its result to the next state.
236 |
237 | #### Examples
238 |
239 | Consider the example given above, of a Lambda task that sums a pair of numbers. As presented, its input is: `{ "val1": 3, "val2": 4 }` and its output is: `7`.
240 |
241 | Suppose the input is little more complex:
242 |
243 | ```
244 | {
245 | "title": "Numbers to add",
246 | "numbers": { "val1": 3, "val2": 4 }
247 | }
248 | ```
249 |
250 | Then suppose we modify the state definition by adding:
251 |
252 | ```
253 | "InputPath": "$.numbers",
254 | "ResultPath": "$.sum"
255 | ```
256 |
257 | And finally,suppose we simplify Line 4 of the Lambda function to read as follows: `return JSON.stringify(total)`. This is probably a better form of the function, which should really only care about doing math and not care how its result is labeled.
258 |
259 | In this case, the output would be:
260 |
261 | ```
262 | {
263 | "title": "Numbers to add",
264 | "numbers": { "val1": 3, "val2": 4 },
265 | "sum": 7
266 | }
267 | ```
268 |
269 | The interpreter might need to construct multiple levels of JSON object to achieve the desired effect. Suppose the input to some Task state is:
270 |
271 | ```
272 | { "a": 1 }
273 | ```
274 |
275 | Suppose the output from the Task is “Hi!”, and the value of the “ResultPath” field is “$.b.greeting”. Then the output from the state would be:
276 |
277 | ```
278 | {
279 | "a": 1,
280 | "b": {
281 | "greeting": "Hi!"
282 | }
283 | }
284 | ```
285 |
286 | #### Runtime Errors
287 |
288 | Suppose a state’s input is the string `"foo"`, and its “ResultPath” field has the value “$.x”. Then ResultPath cannot apply and the Interpreter fails the machine with Error Name of “States.OutputMatchFailure”.
289 |
290 | ### Errors
291 |
292 | Any state can encounter runtime errors. Errors can arise because of state machine definition issues (e.g. the “ResultPath” problem discussed immediately above), task failures (e.g. an exception thrown by a Lambda function) or because of transient issues, such as network partition events.
293 |
294 | When a state reports an error, the default course of action for the interpreter is to fail the whole state machine.
295 |
296 | #### Error representation
297 |
298 | Errors are identified by case-sensitive strings, called Error Names. The States language defines a set of built-in strings naming well-known errors, all of which begin with the prefix “States.”; see [Appendix A](#appendix-a).
299 |
300 | States MAY report errors with other names, which MUST NOT begin with the prefix “States.”.
301 |
302 | #### Retrying after error
303 |
304 | Task States and Parallel States MAY have a field named “Retry”, whose value MUST be an array of objects, called Retriers.
305 |
306 | Each Retrier MUST contain a field named “ErrorEquals” whose value MUST be a non-empty array of Strings, which match [Error Names](#error-names).
307 |
308 | When a state reports an error, the interpreter scans through the Retriers and, when the Error Name appears in the value of of a Retrier’s “ErrorEquals” field, implements the retry policy described in that Retrier.
309 |
310 | An individual Retrier represents a certain number of retries, usually at increasing time intervals.
311 |
312 | A Retrier MAY contain a field named “IntervalSeconds”, whose value MUST be a positive integer, representing the number of seconds before the first retry attempt (default value: 1); a field named “MaxAttempts” whose value MUST be a non-negative integer, representing the maximum number of retry attempts (default: 3); and a field named “BackoffRate”, a number which is the multiplier that increases the retry interval on each attempt (default: 2.0). The value of BackoffRate MUST be greater than or equal to 1.0.
313 |
314 | Note that a “MaxAttempts” field whose value is 0 is legal, specifying that some error or errors should never be retried.
315 |
316 | Here is an example of a Retry field which will make 2 retry attempts after waits of 3 and 4.5 seconds:
317 |
318 | ```
319 | "Retry" : [
320 | {
321 | "ErrorEquals": [ "States.Timeout" ],
322 | "IntervalSeconds": 3,
323 | "MaxAttempts": 2,
324 | "BackoffRate": 1.5
325 | }
326 | ]
327 | ```
328 |
329 | The reserved name “States.ALL” in a Retrier’s “ErrorEquals” field is a wild-card and matches any Error Name. Such a value MUST appear alone in the “ErrorEquals” array and MUST appear in the last Retrier in the “Retry” array.
330 |
331 | Here is an example of a Retry field which will retry any error except for “States.Timeout”, using the default retry parameters.
332 |
333 | ```
334 | "Retry" : [
335 | {
336 | "ErrorEquals": [ "States.Timeout" ],
337 | "MaxAttempts": 0
338 | },
339 | {
340 | "ErrorEquals": [ "States.ALL" ]
341 | }
342 | ]
343 | ```
344 |
345 | If the error recurs more times than allowed for by the “MaxAttempts” field, retries cease and normal error handling resumes.
346 |
347 | #### Complex retry scenarios
348 |
349 | A Retrier’s parameters apply across all visits to that Retrier in the context of a single state execution. This is best illustrated by example; consider the following Task State:
350 |
351 | ```
352 | "X": {
353 | "Type": "Task",
354 | "Resource": "arn:aws:swf:us-east-1:123456789012:task:X",
355 | "Next": "Y",
356 | "Retry": [
357 | {
358 | "ErrorEquals": [ "ErrorA", "ErrorB" ],
359 | "IntervalSeconds": 1,
360 | "BackoffRate": 2,
361 | "MaxAttempts": 2
362 | },
363 | {
364 | "ErrorEquals": [ "ErrorC" ],
365 | "IntervalSeconds": 5
366 | }
367 | ],
368 | "Catch": [
369 | {
370 | "ErrorEquals": [ "States.ALL" ],
371 | "Next": "Z"
372 | }
373 | ]
374 | }
375 | ```
376 |
377 | Suppose that this task fails five successive times, throwing Error Names “ErrorA”, “ErrorB”, “ErrorC”, “ErrorB”, and “ErrorB”. The first two errors match the first retrier and cause waits of one and two seconds. The third error matches the second retrier and causes a wait of five seconds. The fourth error matches the first retrier and causes a wait of four seconds. The fifth also matches the first, but its “MaxAttempts” ceiling of two retries has already been reached, so that Retrier fails, and execution is redirected to the “Z” state via the “Catch” field.
378 |
379 | Note that once the interpreter transitions to another state in any way, all the Retrier parameters reset.
380 |
381 | #### Fallback states
382 |
383 | Task States and Parallel States MAY have a field named “Catch”, whose value MUST be an array of objects, called Catchers.
384 |
385 | Each Catcher MUST contain a field named “ErrorEquals”, specified exactly as with the Retrier “ErrorEquals” field, and a field named “Next” whose value MUST be a string exactly matching a State Name.
386 |
387 | When a state reports an error and either there is no Retry field, or retries have failed to resolve the error, the interpreter scans through the Catchers in array order, and when the [Error Name](#error-names) appears in the value of a Catcher’s “ErrorEquals” field, transitions the machine to the state named in the value of the “Next” field.
388 |
389 | The reserved name “States.ALL” appearing in a Retrier’s “ErrorEquals” field is a wild-card and matches any Error Name. Such a value MUST appear alone in the “ErrorEquals” array and MUST appear in the last Catcher in the “Catch” array.
390 |
391 | #### Error output
392 |
393 | When a state reports an error and it matches a Catcher, causing a transfer to another state, the state’s result (and thus the input to the state identified in the Catcher’s “Next” field) is a JSON object, called the Error Output. The Error Output MUST have a string-valued field named “Error”, containing the Error Name. It SHOULD have a string-valued field named “Cause”, containing human-readable text about the error.
394 |
395 | A Catcher MAY have an “ResultPath” field, which works exactly like [a state’s top-level “ResultPath”](#filters), and may be used to inject the Error Output into the state’s original input to create the input for the Catcher’s “Next” state. The default value, if the “ResultPath” field is not provided, is “$”, meaning that the output consists entirely of the Error Output.
396 |
397 | Here is an example of a Catch field that will transition to the state named “RecoveryState” when a Lambda function throws an unhandled Java Exception, and otherwise to the “EndMachine” state, which is presumably Terminal.
398 |
399 | Also in this example, if the first Catcher matches the Error Name, the input to “RecoveryState” will be the original state input, with the Error Output as the value of the top-level “error-info” field. For any other error, the input to “EndMachine” will just be the Error Output.
400 |
401 | ```
402 | "Catch": [
403 | {
404 | "ErrorEquals": [ "java.lang.Exception" ],
405 | "ResultPath": "$.error-info",
406 | "Next": "RecoveryState"
407 | },
408 | {
409 | "ErrorEquals": [ "States.ALL" ],
410 | "Next": "EndMachine"
411 | }
412 | ]
413 | ```
414 |
415 | Each Catcher can specifiy multiple errors to handle.
416 |
417 | When a state has both Retry and Catch fields, the interpreter uses any appropriate Retriers first and only applies the a matching Catcher transition if the retry policy fails to resove the error.
418 |
419 | ## State Types
420 |
421 | As a reminder, the state type is given by the value of the “Type” field, which MUST appear in every State object.
422 |
423 | ### Table of State Types and Fields
424 |
425 | Many fields can appear in more than one state type. The table below summarizes which fields can appear in which states. It excludes fields that are specific to one state type.
426 |
427 | (R for Required, A for Allowed)
428 |
429 | |States |Pass |Task |Choice |Wait |Succeed |Fail |Parallel |
430 | |--- |--- |--- |--- |--- |--- |--- |--- |
431 | |Type | R | R | R | R | R | R | R |
432 | |Comment | A | A | A | A | A | A | A |
433 | |InputPath OutputPath | A | A | A | A | A | | A |
434 | |ResultPath | A | A | | | | | A |
435 | |Next xor End | R | R | | R | | | R |
436 | |Retry, Catch | | A | | | | | A |
437 |
438 |
439 | ### Pass State
440 |
441 | The Pass State (identified by `"Type":"Pass"`) simply passes its input to its output, performing no work. Pass States are useful when constructing and debugging state machines.
442 |
443 | A Pass State MAY have a field named “Result”. If present, its value is treated as the output of a virtual task, and placed as prescribed by the “ResultPath” field, if any, to be passed on to the next state.
444 |
445 | Here is an example of a Pass State that injects some fixed data into the state machine, probably for testing purposes.
446 |
447 | ```
448 | "No-op": {
449 | "Type": "Pass",
450 | "Result": {
451 | "x-datum": 0.381018,
452 | "y-datum": 622.2269926397355
453 | },
454 | "ResultPath": "$.coords",
455 | "Next": "End"
456 | }
457 | ```
458 |
459 | Suppose the input to this state were as follows:
460 |
461 | ```
462 | {
463 | "georefOf": "Home"
464 | }
465 | ```
466 |
467 | Then the output would be:
468 |
469 | ```
470 | {
471 | "georefOf": "Home",
472 | "coords": {
473 | "x-datum": 0.381018,
474 | "y-datum": 622.2269926397355
475 | }
476 | }
477 | ```
478 |
479 | ### Task State
480 |
481 | The Task State (identified by `"Type":"Task"`) causes the interpreter to execute the work identified by the state’s “Resource” field.
482 |
483 | Here is an example:
484 |
485 | ```
486 | "TaskState": {
487 | "Comment": "Task State example",
488 | "Type": "Task",
489 | "Resource": "arn:aws:swf:us-east-1:123456789012:task:HelloWorld",
490 | "Next": "NextState",
491 | "TimeoutSeconds": 300,
492 | "HeartbeatSeconds": 60
493 | }
494 | ```
495 |
496 | A Task State MUST include a “Resource” field, whose value MUST be a URI that uniquely identifies the specific task to execute. The States language does not constrain the URI scheme nor any other part of the URI.
497 |
498 | Tasks can optionally specify timeouts. Timeouts (the “TimeoutSeconds” and “HeartbeatSeconds” fields) are specified in seconds and MUST be positive integers. If provided, the “HeartbeatSeconds” interval MUST be smaller than the “TimeoutSeconds” value.
499 |
500 | If not provided, the default value of “TimeoutSeconds” is 60.
501 |
502 | If the state runs longer than the specified timeout, or if more time than the specified heartbeat elapses between heartbeats from the task, then the interpreter fails the state with a `States.Timeout` Error Name.
503 |
504 | ### Choice State
505 |
506 | A Choice state (identified by `"Type":"Choice"`) adds branching logic to a state machine.
507 |
508 | A Choice state state MUST have a “Choices” field whose value is a non-empty array. Each element of the array is called a Choice Rule - an object containing a comparison operation and a “Next” field, whose value MUST match a state name.
509 |
510 | The interpreter attempts pattern-matches against the Choice Rules in array order and transitions to the state specified in the “Next” field on the first Choice Rule where there is an exact match between the input value and a member of the comparison-operator array.
511 |
512 | Here is an example of a Choice state, with some other states that it transitions to.
513 |
514 | ```
515 | "ChoiceStateX": {
516 | "Type" : "Choice",
517 | "Choices": [
518 | {
519 | "Not": {
520 | "Variable": "$.type",
521 | "StringEquals": "Private"
522 | },
523 | "Next": "Public"
524 | },
525 | {
526 | "And": [
527 | {
528 | "Variable": "$.value",
529 | "NumericGreaterThanEquals": 20
530 | },
531 | {
532 | "Variable": "$.value",
533 | "NumericLessThan": 30
534 | }
535 | ],
536 | "Next": "ValueInTwenties"
537 | }
538 | ],
539 | "Default": "DefaultState"
540 | },
541 |
542 | "Public": {
543 | "Type" : "Task",
544 | "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Foo",
545 | "Next": "NextState"
546 | },
547 |
548 | "ValueInTwenties": {
549 | "Type" : "Task",
550 | "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Bar",
551 | "Next": "NextState"
552 | },
553 |
554 | "DefaultState": {
555 | "Type": "Fail",
556 | "Cause": "No Matches!"
557 | }
558 | ```
559 |
560 | In this example, suppose the machine is started with an input value of:
561 |
562 | ```
563 | {
564 | "type": "private",
565 | "value": 22
566 | }
567 | ```
568 |
569 | Then the interpreter will transition to the “ValueInTwenties” state, based on the “value” field.
570 |
571 | Each choice rule MUST contain exactly one field containing a comparison operator. The following comparison operators are supported:
572 |
573 | 1. StringEquals
574 | 2. StringLessThan
575 | 3. StringGreaterThan
576 | 4. StringLessThanEquals
577 | 5. StringGreaterThanEquals
578 | 6. NumericEquals
579 | 7. NumericLessThan
580 | 8. NumericGreaterThan
581 | 9. NumericLessThanEquals
582 | 10. NumericGreaterThanEquals
583 | 11. BooleanEquals
584 | 12. TimestampEquals
585 | 13. TimestampLessThan
586 | 14. TimestampGreaterThan
587 | 15. TimestampLessThanEquals
588 | 16. TimestampGreaterThanEquals
589 | 17. And
590 | 18. Or
591 | 19. Not
592 |
593 | For each of these operators, the field’s value MUST be a value of the appropriate type: String, number, boolean, or [Timestamp](#timestamps).
594 |
595 | The interpreter scans through the Choice Rules in a type-sensitive way, and will not attempt to match a numeric field to a string value. However, since Timestamp fields are logically strings, it is possible that a field which is thought of as a time-stamp could be matched by a “StringEquals” comparator.
596 |
597 | Note that for interoperability, numeric comparisons should not be assumed to work with values outside the magnitude or precision representable using the IEEE 754-2008 “binary64” data type. In particular, integers outside of the range [-(253)+1, (253)-1] might fail to compare in the expected way.
598 |
599 | The values of the “And” and “Or” operators MUST be non-empty arrays of Choice Rules that MUST NOT contain “Next” fields; the “Next” field can only appear in a top-level Choice Rule.
600 |
601 | The value of a “Not” operator MUST be a single Choice Rule, that MUST NOT contain “Next” fields; the “Next” field can only appear in a top-level Choice Rule.
602 |
603 | Choice states MAY have a “Default” field, which will execute if none of the Choice Rules match. The interpreter will raise a run-time States.NoChoiceMatched error if a “Choice” state fails to match a Choice Rule and no “Default” transition was specified.
604 |
605 | Choice states MUST NOT be End states.
606 |
607 | ### Wait State
608 |
609 | A Wait state (identified by `"Type":"Wait"`) causes the interpreter to delay the machine from continuing for a specified time. The time can be specified as a wait duration, specified in seconds, or an absolute expiry time, specified as an ISO-8601 extended offset date-time format string.
610 |
611 | For example, the following Wait state introduces a ten-second delay into a state machine:
612 |
613 | ```
614 | "wait_ten_seconds" : {
615 | "Type" : "Wait",
616 | "Seconds" : 10,
617 | "Next": "NextState"
618 | }
619 | ```
620 |
621 | This waits until an absolute time:
622 |
623 | ```
624 | "wait_until" : {
625 | "Type": "Wait",
626 | "Timestamp": "2016-03-14T01:59:00Z",
627 | "Next": "NextState"
628 | }
629 | ```
630 |
631 | The wait duration does not need to be hardcoded. Here is the same example, reworked to look up the timestamp time using a Reference Path to the data, which might look like `{ "expirydate": "2016-03-14T01:59:00Z" }`:
632 |
633 | ```
634 | "wait_until" : {
635 | "Type": "Wait",
636 | "TimestampPath": "$.expirydate",
637 | "Next": "NextState"
638 | }
639 | ```
640 |
641 | A Wait state MUST contain exactly one of ”Seconds”, “SecondsPath”, “Timestamp”, or “TimestampPath”.
642 |
643 | ### Succeed State
644 |
645 | The Succeed State (identified by `"Type":"Succeed"`) terminates a state machine successfully. The Succeed State is a useful target for Choice-state branches that don't do anything but terminate the machine.
646 |
647 | Here is an example:
648 |
649 | ```
650 | "SuccessState": {
651 | "Type": "Succeed"
652 | }
653 | ```
654 |
655 | Because Succeed States are terminal states, they have no “Next” field.
656 |
657 | ### Fail State
658 |
659 | The Fail State (identified by `"Type":"Fail"`) terminates the machine and marks it as a failure.
660 |
661 | Here is an example:
662 |
663 | ```
664 | "FailState": {
665 | "Type": "Fail",
666 | "Error": "ErrorA",
667 | "Cause": "Kaiju attack"
668 | }
669 | ```
670 |
671 | A Fail State MUST have a string field named “Error”, used to provide an error name that can be used for error handling (Retry/Catch), operational, or diagnostic purposes. A Fail State MUST have a string field named “Cause”, used to provide a human-readable message.
672 |
673 | Because Fail States are terminal states, they have no “Next” field.
674 |
675 | ### Parallel State
676 |
677 | The Parallel State (identified by `"Type":"Parallel"`) causes parallel execution of "branches".
678 |
679 | Here is an example:
680 |
681 | ```
682 | "LookupCustomerInfo": {
683 | "Type": "Parallel",
684 | "Branches": [
685 | {
686 | "StartAt": "LookupAddress",
687 | "States": {
688 | "LookupAddress": {
689 | "Type": "Task",
690 | "Resource":
691 | "arn:aws:lambda:us-east-1:123456789012:function:AddressFinder",
692 | "End": true
693 | }
694 | }
695 | },
696 | {
697 | "StartAt": "LookupPhone",
698 | "States": {
699 | "LookupPhone": {
700 | "Type": "Task",
701 | "Resource":
702 | "arn:aws:lambda:us-east-1:123456789012:function:PhoneFinder",
703 | "End": true
704 | }
705 | }
706 | }
707 | ],
708 | "Next": "NextState"
709 | }
710 | ```
711 |
712 | A Parallel state causes the interpreter to execute each branch starting with the state named in its “StartAt” field, as concurrently as possible, and wait until each branch terminates (reaches a terminal state) before processing the Parallel state's “Next” field. In the above example, this means the interpreter waits for “LookupAddress” and “LookupPhoneNumber” to both finish before transitioning to “NextState”.
713 |
714 | In the example above, the LookupAddress and LookupPhoneNumber branches are executed in parallel.
715 |
716 | A Parallel State MUST contain a field named “Branches” which is an array whose elements MUST be objects. Each object MUST contain fields named “States” and “StartAt” whose meanings are exactly like those in the top level of a State Machine.
717 |
718 | A state in a Parallel state branch “States” field MUST NOT have a “Next” field that targets a field outside of that “States” field. A state MUST NOT have a “Next” field which matches a state name inside a Parallel state branch’s “States” field unless it is also inside the same “States” field.
719 |
720 | Put another way, states in a branch’s “States” field can transition only to each other, and no state outside of that “States” field can transition into it.
721 |
722 | If any branch fails, due to an unhandled error or by transitioning to a Fail state, the entire Parallel state is considered to have failed and all the branches are terminated. If the error is not handled by the Parallel State, the interpreter should terminate the machine execution with an error.
723 |
724 | The Parallel state passes its input (potentially as filtered by the “InputPath” field) as the input to each branch’s “StartAt” state. it generates output which is an array with one element for each branch containing the output from that branch. There is no requirement that all elements be of the same type.
725 |
726 | The output array can be inserted into the input data using the state’s “ResultPath” field in the usual way.
727 |
728 | For example, consider the following Parallel State:
729 |
730 | ```
731 | "FunWithMath": {
732 | "Type": "Parallel",
733 | "Branches": [
734 | {
735 | "StartAt": "Add",
736 | "States": {
737 | "Add": {
738 | "Type": "Task",
739 | "Resource": "arn:aws:swf:::task:Add",
740 | "End": true
741 | }
742 | }
743 | },
744 | {
745 | "StartAt": "Subtract",
746 | "States": {
747 | "Subtract": {
748 | "Type": "Task",
749 | "Resource": "arn:aws:swf:::task:Subtract",
750 | "End": true
751 | }
752 | }
753 | }
754 | ],
755 | "Next": "NextState"
756 | }
757 | ```
758 |
759 | If the “FunWithMath” state was given the JSON array `[3, 2]` as input, then both the “Add” and “Subtract” states would receive that array as input. The output of “Add” would be `5`, that of “Subtract” would be `1`, and the output of the Parallel State would be a JSON array:
760 |
761 | ```
762 | [ 5, 1 ]
763 | ```
764 |
765 | If any branch fails, due to an unhandled error or by transitioning to a Fail state, the entire Parallel state is considered to have failed and all the branches are terminated. If the error is not handled by the Parallel State, the interpreter should terminate the machine execution with an error.
766 |
767 |
768 |
769 | ## Appendices
770 |
771 | ### Appendix A: Predefined Error Codes
772 |
773 | | Code | Description |
774 | |--- |--- |
775 | |**States.ALL** | A wild-card which matches any Error Name.|
776 | |**States.Timeout** | A Task State either ran longer than the “TimeoutSeconds” value, or failed to heartbeat for a time longer than the “HeartbeatSeconds” value.|
777 | |**States.TaskFailed** | A Task State failed during the execution.|
778 | |**States.Permissions** | A Task State failed because it had insufficient privileges to execute the specified code.|
779 | |**States.ResultPathMatchFailure** | A Task State’s “ResultPath” field cannot be applied to the input the state received.|
780 | |**States.BranchFailed** | A branch of a Parallel state failed.|
781 | |**States.NoChoiceMatched** | A Choice state failed to find a match for the condition field extracted from its input.
782 |
783 |
--------------------------------------------------------------------------------
/bin/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/bin/.keep
--------------------------------------------------------------------------------
/cmd/workflow/workflow.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "fmt"
7 | "log"
8 | "strings"
9 |
10 | "github.com/checkr/states-language-cadence/internal/pkg/common"
11 | "github.com/checkr/states-language-cadence/pkg/aslworkflow"
12 | "github.com/joho/godotenv"
13 | "go.uber.org/cadence/activity"
14 | "go.uber.org/cadence/worker"
15 | "go.uber.org/cadence/workflow"
16 | "go.uber.org/zap"
17 | )
18 |
19 | var ApplicationName = "WorkflowDemo"
20 |
21 | type Example struct {
22 | name string
23 | json string
24 | }
25 |
26 | func getExamples() []Example {
27 | return []Example{
28 | {
29 | name: "example:workflow:ExampleWorkflow",
30 | json: `{
31 | "StartAt": "Example1",
32 | "States": {
33 | "Example1": {
34 | "Type": "Task",
35 | "Resource": "example:activity:ExampleActivity",
36 | "Next": "Example2"
37 | },
38 | "Example2": {
39 | "Type": "Task",
40 | "Resource": "example:workflow:ExampleSubworkflow",
41 | "End": true
42 | }
43 | }
44 | }`,
45 | },
46 | {
47 | name: "example:workflow:ExampleSubworkflow",
48 | json: `{
49 | "StartAt": "Example1",
50 | "States": {
51 | "Example1": {
52 | "Type": "Task",
53 | "Resource": "example:activity:ExampleActivity",
54 | "Next": "Wait"
55 | },
56 | "Wait": {
57 | "Type": "Wait",
58 | "Seconds": 3,
59 | "Next": "Result"
60 | },
61 | "Result": {
62 | "Type": "Pass",
63 | "Result": {
64 | "subworkflow": "example has been completed!"
65 | },
66 | "End": true
67 | }
68 | }
69 | }`,
70 | },
71 | }
72 | }
73 |
74 | func main() {
75 | err := godotenv.Load()
76 | if err != nil {
77 | log.Fatal("Error loading .env file")
78 | }
79 |
80 | for _, example := range getExamples() {
81 | sm, err := aslworkflow.FromJSON([]byte(example.json))
82 | if err != nil {
83 | panic(fmt.Errorf("error loading state machine %w", err))
84 | }
85 |
86 | sm.RegisterWorkflow(example.name)
87 | sm.RegisterActivities(ExampleActivity)
88 | }
89 |
90 | // Register the Global Task Handler
91 | aslworkflow.RegisterHandler(ExampleTaskHandler)
92 |
93 | var h common.CadenceHelper
94 | h.SetupServiceConfig()
95 |
96 | // Configure worker options.
97 | workerOptions := worker.Options{
98 | MetricsScope: h.Scope,
99 | Logger: h.Logger,
100 | }
101 | h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
102 |
103 | select {}
104 | }
105 |
106 | // ActivityPrefix is the prefix used for specifying activities to run (could also be something like `arn:aws:...`
107 | var ActivityPrefix = "example:activity:"
108 |
109 | // WorkflowPrefix is the prefix used for specifying subworkflow to run (could also be something like `arn:aws:...`
110 | var WorkflowPrefix = "example:workflow:"
111 |
112 | var ErrUnknownResource = errors.New("unknown resource")
113 |
114 | // ExampleTaskHandler is called for each task, it decides what to do. In this example it will execute and activity or subworkflow
115 | func ExampleTaskHandler(ctx workflow.Context, resource string, input interface{}) (interface{}, error) {
116 | var result interface{}
117 | var err error
118 |
119 | if strings.HasPrefix(resource, ActivityPrefix) {
120 | err = workflow.ExecuteActivity(ctx, resource, input).Get(ctx, &result)
121 | } else if strings.HasPrefix(resource, WorkflowPrefix) {
122 | err = workflow.ExecuteChildWorkflow(ctx, resource, input).Get(ctx, &result)
123 | } else {
124 | return nil, ErrUnknownResource
125 | }
126 |
127 | if err != nil {
128 | return nil, err
129 | }
130 |
131 | return result, nil
132 | }
133 |
134 | // ExampleActivity is the actual activity that is run by the handler, it could calla lambda function, http request, grpc, anything you'd like.
135 | // Noop for now, just passing input as output
136 | func ExampleActivity(ctx context.Context, input interface{}) (interface{}, error) {
137 | logger := activity.GetLogger(ctx)
138 |
139 | activityInfo := activity.GetInfo(ctx)
140 | taskToken := string(activityInfo.TaskToken)
141 | activityName := activityInfo.ActivityType.Name
142 |
143 | logger.Info("activity executed", zap.Any("input", input), zap.Any("taskToken", taskToken), zap.Any("activityName", activityName))
144 | return input, nil
145 | }
146 |
--------------------------------------------------------------------------------
/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | version: '3'
2 | services:
3 | mysql:
4 | image: mysql:5.7
5 | ports:
6 | - "3306:3306"
7 | environment:
8 | - "MYSQL_ROOT_PASSWORD=root"
9 | volumes:
10 | - ./data:/var/lib/mysql
11 | cadence:
12 | image: ubercadence/server:master-auto-setup
13 | ports:
14 | - "7933:7933"
15 | - "7934:7934"
16 | - "7935:7935"
17 | - "7939:7939"
18 | environment:
19 | - "DB=mysql"
20 | - "MYSQL_USER=root"
21 | - "MYSQL_PWD=root"
22 | - "MYSQL_SEEDS=mysql"
23 | - "DYNAMIC_CONFIG_FILE_PATH=config/dynamicconfig/development.yaml"
24 | depends_on:
25 | - mysql
26 | cadence-web:
27 | image: ubercadence/web:3.4.1
28 | environment:
29 | - "CADENCE_TCHANNEL_PEERS=cadence:7933"
30 | ports:
31 | - "8088:8088"
32 | depends_on:
33 | - cadence
34 |
--------------------------------------------------------------------------------
/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/example.png
--------------------------------------------------------------------------------
/examples/choice.json:
--------------------------------------------------------------------------------
1 | {
2 | "Comment": "Contrived Valid Example that should have all State types",
3 | "StartAt": "Pass",
4 | "States": {
5 | "SimpleTask": {
6 | "Comment": "This is a comment",
7 | "Type": "Task",
8 | "Resource": "asd",
9 | "End": true
10 | },
11 | "Task": {
12 | "Type": "Task",
13 | "Resource": "asd",
14 | "Catch": [
15 | {
16 | "ErrorEquals": [
17 | "CustomError1",
18 | "CustomError2"
19 | ],
20 | "ResultPath": "$.asd",
21 | "Next": "Pass"
22 | }
23 | ],
24 | "Retry": [
25 | {
26 | "ErrorEquals": [
27 | "CustomError1",
28 | "CustomError2"
29 | ],
30 | "IntervalSeconds": 3,
31 | "MaxAttempts": 10,
32 | "BackoffRate": 2.5
33 | }
34 | ],
35 | "End": true
36 | },
37 | "Pass": {
38 | "Type": "Pass",
39 | "Result": {
40 | "x": 0.1337,
41 | "y": 3.14159
42 | },
43 | "ResultPath": "$.coords",
44 | "End": true
45 | },
46 | "Choice": {
47 | "Type": "Choice",
48 | "Choices": [
49 | {
50 | "Not": {
51 | "Variable": "$.type.foo.bar",
52 | "StringEquals": "Private"
53 | },
54 | "Next": "Public"
55 | },
56 | {
57 | "Variable": "$.value",
58 | "NumericEquals": 0,
59 | "Next": "ValueIsZero"
60 | },
61 | {
62 | "And": [
63 | {
64 | "Variable": "$.value",
65 | "NumericGreaterThanEquals": 20.5
66 | },
67 | {
68 | "Variable": "$.value",
69 | "NumericLessThan": 30
70 | }
71 | ],
72 | "Next": "ValueInTwenties"
73 | }
74 | ],
75 | "Default": "DefaultState"
76 | },
77 | "Fail": {
78 | "Type": "Fail",
79 | "Error": "ERROR"
80 | },
81 | "Succeed": {
82 | "Type": "Succeed"
83 | },
84 | "Parallel": {
85 | "Type": "Parallel"
86 | },
87 | "Wait": {
88 | "Type": "Wait",
89 | "End": true,
90 | "Seconds": 10
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/gen/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/gen/.keep
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/checkr/states-language-cadence
2 |
3 | go 1.13.1
4 |
5 | require (
6 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 // indirect
7 | github.com/apache/thrift v0.12.0 // indirect
8 | github.com/bmizerany/perks v0.0.0-20141205001514-d9a9656a3a4b // indirect
9 | github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect
10 | github.com/coinbase/step v1.0.1-beta
11 | github.com/crossdock/crossdock-go v0.0.0-20160816171116-049aabb0122b // indirect
12 | github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a // indirect
13 | github.com/fatih/structtag v1.0.0 // indirect
14 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
15 | github.com/gogo/googleapis v1.3.0 // indirect
16 | github.com/gogo/status v1.1.0 // indirect
17 | github.com/golang/mock v1.3.1 // indirect
18 | github.com/jessevdk/go-flags v1.4.0 // indirect
19 | github.com/joho/godotenv v1.3.0
20 | github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
21 | github.com/opentracing/opentracing-go v1.1.0 // indirect
22 | github.com/pborman/uuid v1.2.0 // indirect
23 | github.com/pkg/errors v0.8.1
24 | github.com/prashantv/protectmem v0.0.0-20171002184600-e20412882b3a // indirect
25 | github.com/prometheus/client_golang v1.1.0 // indirect
26 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 // indirect
27 | github.com/prometheus/common v0.7.0 // indirect
28 | github.com/robfig/cron v1.2.0 // indirect
29 | github.com/samuel/go-thrift v0.0.0-20190219015601-e8b6b52668fe // indirect
30 | github.com/streadway/quantile v0.0.0-20150917103942-b0c588724d25 // indirect
31 | github.com/stretchr/testify v1.4.0
32 | github.com/uber-go/atomic v1.4.0 // indirect
33 | github.com/uber-go/mapdecode v1.0.0 // indirect
34 | github.com/uber-go/tally v3.3.12+incompatible
35 | github.com/uber/jaeger-client-go v2.19.0+incompatible // indirect
36 | github.com/uber/jaeger-lib v2.2.0+incompatible // indirect
37 | github.com/uber/tchannel-go v1.15.0 // indirect
38 | go.uber.org/atomic v1.4.0 // indirect
39 | go.uber.org/cadence v0.9.2
40 | go.uber.org/dig v1.7.0 // indirect
41 | go.uber.org/fx v1.9.0 // indirect
42 | go.uber.org/goleak v0.10.0 // indirect
43 | go.uber.org/multierr v1.2.0 // indirect
44 | go.uber.org/net/metrics v1.1.0 // indirect
45 | go.uber.org/thriftrw v1.20.0 // indirect
46 | go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee // indirect
47 | go.uber.org/yarpc v1.40.0
48 | go.uber.org/zap v1.10.0
49 | golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac // indirect
50 | golang.org/x/net v0.0.0-20191007182048-72f939374954 // indirect
51 | golang.org/x/sys v0.0.0-20191007154456-ef33b2fb2c41 // indirect
52 | golang.org/x/text v0.3.2 // indirect
53 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0 // indirect
54 | golang.org/x/tools v0.0.0-20190924170908-c006dc79eb54 // indirect
55 | google.golang.org/genproto v0.0.0-20191007204434-a023cd5227bd // indirect
56 | google.golang.org/grpc v1.24.0 // indirect
57 | gopkg.in/yaml.v2 v2.2.4 // indirect
58 | honnef.co/go/tools v0.0.1-2019.2.3 // indirect
59 | )
60 |
61 | replace github.com/apache/thrift => github.com/apache/thrift v0.0.0-20190309152529-a9b748bb0e02
62 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
3 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
4 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
5 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
6 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
7 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
8 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA=
9 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
10 | github.com/apache/thrift v0.0.0-20190309152529-a9b748bb0e02 h1:TSzEE99MqZxYJWTfzwTTvwigD8uTqgBLUxII35s3MwA=
11 | github.com/apache/thrift v0.0.0-20190309152529-a9b748bb0e02/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
12 | github.com/aws/aws-lambda-go v1.8.0 h1:YMCzi9FP7MNVVj9AkGpYyaqh/mvFOjhqiDtnNlWtKTg=
13 | github.com/aws/aws-lambda-go v1.8.0/go.mod h1:zUsUQhAUjYzR8AuduJPCfhBuKWUaDbQiPOG+ouzmE1A=
14 | github.com/aws/aws-sdk-go v1.16.3 h1:esEQzoR8SVXtwg42nRoR/YLftI4ktsZg6Qwr7jnDXy8=
15 | github.com/aws/aws-sdk-go v1.16.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
16 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0=
17 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
18 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
19 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
20 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
21 | github.com/bmizerany/perks v0.0.0-20141205001514-d9a9656a3a4b h1:AP/Y7sqYicnjGDfD5VcY4CIfh1hRXBUavxrvELjTiOE=
22 | github.com/bmizerany/perks v0.0.0-20141205001514-d9a9656a3a4b/go.mod h1:ac9efd0D1fsDb3EJvhqgXRbFx7bs2wqZ10HQPeU8U/Q=
23 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
24 | github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd h1:qMd81Ts1T2OTKmB4acZcyKaMtRnY5Y44NuXGX2GFJ1w=
25 | github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
26 | github.com/coinbase/step v1.0.1-beta h1:OX48iUl+qgVS7UO45fHJHn4nOJ9IOu15Z1W4Bb/ZBKM=
27 | github.com/coinbase/step v1.0.1-beta/go.mod h1:XU8bLMHgXSiQu4+RZ2Gcgq5dlfPDBYQK4gvKJKnff6k=
28 | github.com/crossdock/crossdock-go v0.0.0-20160816171116-049aabb0122b h1:WR1qVJzbvrVywhAk4kMQKRPx09AZVI0NdEdYs59iHcA=
29 | github.com/crossdock/crossdock-go v0.0.0-20160816171116-049aabb0122b/go.mod h1:v9FBN7gdVTpiD/+LZ7Po0UKvROyT87uLVxTHVky/dlQ=
30 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
31 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
32 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
33 | github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw=
34 | github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA=
35 | github.com/fatih/structtag v1.0.0 h1:pTHj65+u3RKWYPSGaU290FpI/dXxTaHdVwVwbcPKmEc=
36 | github.com/fatih/structtag v1.0.0/go.mod h1:IKitwq45uXL/yqi5mYghiD3w9H6eTOvI9vnk8tXMphA=
37 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
38 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
39 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
40 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
41 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
42 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
43 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
44 | github.com/gogo/googleapis v0.0.0-20180223154316-0cd9801be74a/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s=
45 | github.com/gogo/googleapis v1.3.0 h1:M695OaDJ5ipWvDPcoAg/YL9c3uORAegkEfBqTQF/fTQ=
46 | github.com/gogo/googleapis v1.3.0/go.mod h1:d+q1s/xVJxZGKWwC/6UfPIF33J+G1Tq4GYv9Y+Tg/EU=
47 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
48 | github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
49 | github.com/gogo/protobuf v1.3.0 h1:G8O7TerXerS4F6sx9OV7/nRfJdnXgHZu/S/7F2SN+UE=
50 | github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
51 | github.com/gogo/status v1.1.0 h1:+eIkrewn5q6b30y+g/BJINVVdi2xH7je5MPJ3ZPK3JA=
52 | github.com/gogo/status v1.1.0/go.mod h1:BFv9nrluPLmrS0EmGVvLaPNmRosr9KapBYd5/hpY1WM=
53 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
54 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
55 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
56 | github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s=
57 | github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
58 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
59 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
60 | github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
61 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
62 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
63 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
64 | github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI=
65 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
66 | github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
67 | github.com/google/uuid v1.0.0 h1:b4Gk+7WdP/d3HZH8EJsZpvV7EtDOgaZLtnaNGIu1adA=
68 | github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
69 | github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
70 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
71 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
72 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
73 | github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
74 | github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
75 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
76 | github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
77 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
78 | github.com/kisielk/errcheck v1.2.0 h1:reN85Pxc5larApoH1keMBiu2GWtPqXQ1nc9gx+jOU+E=
79 | github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
80 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
81 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
82 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
83 | github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s=
84 | github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
85 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
86 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
87 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
88 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
89 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
90 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
91 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
92 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
93 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
94 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
95 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
96 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
97 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
98 | github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
99 | github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
100 | github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g=
101 | github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k=
102 | github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
103 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
104 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
105 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
106 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
107 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
108 | github.com/prashantv/protectmem v0.0.0-20171002184600-e20412882b3a h1:AA9vgIBDjMHPC2McaGPojgV2dcI78ZC0TLNhYCXEKH8=
109 | github.com/prashantv/protectmem v0.0.0-20171002184600-e20412882b3a/go.mod h1:lzZQ3Noex5pfAy7mkAeCjcBDteYU85uWWnJ/y6gKU8k=
110 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
111 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
112 | github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8=
113 | github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g=
114 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
115 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
116 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4 h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=
117 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
118 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
119 | github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc=
120 | github.com/prometheus/common v0.7.0 h1:L+1lyG48J1zAQXA3RBX/nG/B3gjlHq0zTt2tlbJLyCY=
121 | github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA=
122 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
123 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
124 | github.com/prometheus/procfs v0.0.3 h1:CTwfnzjQ+8dS6MhHHu4YswVAD99sL2wjPqP+VkURmKE=
125 | github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ=
126 | github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
127 | github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
128 | github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
129 | github.com/samuel/go-thrift v0.0.0-20190219015601-e8b6b52668fe h1:gD4vkYmuoWVgdV6UwI3tPo9MtMfVoIRY+Xn9919SJBg=
130 | github.com/samuel/go-thrift v0.0.0-20190219015601-e8b6b52668fe/go.mod h1:Vrkh1pnjV9Bl8c3P9zH0/D4NlOHWP5d4/hF4YTULaec=
131 | github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
132 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
133 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
134 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
135 | github.com/streadway/quantile v0.0.0-20150917103942-b0c588724d25 h1:7z3LSn867ex6VSaahyKadf4WtSsJIgne6A1WLOAGM8A=
136 | github.com/streadway/quantile v0.0.0-20150917103942-b0c588724d25/go.mod h1:lbP8tGiBjZ5YWIc2fzuRpTaz0b/53vT6PEs3QuAWzuU=
137 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
138 | github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
139 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
140 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
141 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
142 | github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
143 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
144 | github.com/uber-go/atomic v1.4.0 h1:yOuPqEq4ovnhEjpHmfFwsqBXDYbQeT6Nb0bwD6XnD5o=
145 | github.com/uber-go/atomic v1.4.0/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g=
146 | github.com/uber-go/mapdecode v1.0.0 h1:euUEFM9KnuCa1OBixz1xM+FIXmpixyay5DLymceOVrU=
147 | github.com/uber-go/mapdecode v1.0.0/go.mod h1:b5nP15FwXTgpjTjeA9A2uTHXV5UJCl4arwKpP0FP1Hw=
148 | github.com/uber-go/tally v3.3.12+incompatible h1:Qa0XrHsKXclmhEpHmBHTTEZotwvQHAbm3lvtJ6RNn+0=
149 | github.com/uber-go/tally v3.3.12+incompatible/go.mod h1:YDTIBxdXyOU/sCWilKB4bgyufu1cEi0jdVnRdxvjnmU=
150 | github.com/uber/jaeger-client-go v2.19.0+incompatible h1:pbwbYfHUoaase0oPQOdZ1GcaUjImYGimUXSQ/+8+Z8Q=
151 | github.com/uber/jaeger-client-go v2.19.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
152 | github.com/uber/jaeger-lib v2.2.0+incompatible h1:MxZXOiR2JuoANZ3J6DE/U0kSFv/eJ/GfSYVCjK7dyaw=
153 | github.com/uber/jaeger-lib v2.2.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
154 | github.com/uber/tchannel-go v1.15.0 h1:Ert7x+68eiptx67DV5zx+gx0/lWDrg13xMw6KbEJndE=
155 | github.com/uber/tchannel-go v1.15.0/go.mod h1:Rrgz1eL8kMjW/nEzZos0t+Heq0O4LhnUJVA32OvWKHo=
156 | go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU=
157 | go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
158 | go.uber.org/cadence v0.9.2 h1:3d4MaqoRGL5yxFc6qJu8nPuYTy+tmK6vP3Ak12QQwO8=
159 | go.uber.org/cadence v0.9.2/go.mod h1:CQivfHCJ44B1kKL4LLtOhcepUwNoRodZceo/wU5Nthw=
160 | go.uber.org/dig v1.7.0 h1:E5/L92iQTNJTjfgJF2KgU+/JpMaiuvK2DHLBj0+kSZk=
161 | go.uber.org/dig v1.7.0/go.mod h1:z+dSd2TP9Usi48jL8M3v63iSBVkiwtVyMKxMZYYauPg=
162 | go.uber.org/fx v1.9.0 h1:7OAz8ucp35AU8eydejpYG7QrbE8rLKzGhHbZlJi5LYY=
163 | go.uber.org/fx v1.9.0/go.mod h1:mFdUyAUuJ3w4jAckiKSKbldsxy1ojpAMJ+dVZg5Y0Aw=
164 | go.uber.org/goleak v0.10.0 h1:G3eWbSNIskeRqtsN/1uI5B+eP73y3JUuBsv9AZjehb4=
165 | go.uber.org/goleak v0.10.0/go.mod h1:VCZuO8V8mFPlL0F5J5GK1rtHV3DrFcQ1R8ryq7FK0aI=
166 | go.uber.org/multierr v1.2.0 h1:6I+W7f5VwC5SV9dNrZ3qXrDB9mD0dyGOi/ZJmYw03T4=
167 | go.uber.org/multierr v1.2.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
168 | go.uber.org/net/metrics v1.1.0 h1:ijSZIk1Gl02eZP7tRf9MjbleJ45cuiosNlLpxT9ZCG4=
169 | go.uber.org/net/metrics v1.1.0/go.mod h1:cQvI3JawIRCZEgrpuF3rrV2OrQGLchMqJPyPAH7GUdo=
170 | go.uber.org/thriftrw v1.20.0 h1:KA0wLwXrF2YPy6ej9IOVwkZ3Gxnq3CoH4eIRtTzZ+Jo=
171 | go.uber.org/thriftrw v1.20.0/go.mod h1:a0+HZMaS9tmHDCPyrrx1GjYWFRK02xzxnrK1Nl9LiLU=
172 | go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4=
173 | go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
174 | go.uber.org/yarpc v1.40.0 h1:Gu+mpdQzP2h4bLj3O7jc6KqbgDvJ4f0EH+R7DTe0B80=
175 | go.uber.org/yarpc v1.40.0/go.mod h1:5wt+WtAfoQh3yGyup7479I35hUobLqCfb0oewxC58jE=
176 | go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM=
177 | go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
178 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
179 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
180 | golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
181 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
182 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
183 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
184 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0=
185 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
186 | golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac h1:8R1esu+8QioDxo4E4mX6bFztO+dMTM49DNAaWfO5OeY=
187 | golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
188 | golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
189 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
190 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
191 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
192 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
193 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
194 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
195 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
196 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
197 | golang.org/x/net v0.0.0-20191007182048-72f939374954 h1:JGZucVF/L/TotR719NbujzadOZ2AgnYlqphQGHDCKaU=
198 | golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
199 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
200 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
201 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
202 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
203 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
204 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
205 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
206 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
207 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
208 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
209 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
210 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
211 | golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
212 | golang.org/x/sys v0.0.0-20191007154456-ef33b2fb2c41 h1:OC2BiV9nQHWgVMNbxZ5/eZKWnnd3Z4H9W5zdNvC4EBc=
213 | golang.org/x/sys v0.0.0-20191007154456-ef33b2fb2c41/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
214 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
215 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
216 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
217 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
218 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0 h1:xQwXv67TxFo9nC1GJFyab5eq/5B590r6RlnL/G8Sz7w=
219 | golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
220 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
221 | golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
222 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
223 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
224 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
225 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
226 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A=
227 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
228 | golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
229 | golang.org/x/tools v0.0.0-20190924170908-c006dc79eb54 h1:XXQCxTBD6QmJueaLvsmOjHxQ9x6iAef/rPxMpmAhi/o=
230 | golang.org/x/tools v0.0.0-20190924170908-c006dc79eb54/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
231 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
232 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
233 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
234 | google.golang.org/genproto v0.0.0-20180518175338-11a468237815/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
235 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc=
236 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
237 | google.golang.org/genproto v0.0.0-20191007204434-a023cd5227bd h1:84VQPzup3IpKLxuIAZjHMhVjJ8fZ4/i3yUnj3k6fUdw=
238 | google.golang.org/genproto v0.0.0-20191007204434-a023cd5227bd/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
239 | google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
240 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
241 | google.golang.org/grpc v1.24.0 h1:vb/1TCsVn3DcJlQ0Gs1yB1pKI6Do2/QNwxdKqmc/b0s=
242 | google.golang.org/grpc v1.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA=
243 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
244 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
245 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
246 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
247 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
248 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
249 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
250 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
251 | gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
252 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
253 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
254 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=
255 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
256 | honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=
257 | honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
258 |
--------------------------------------------------------------------------------
/internal/app/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/internal/app/.keep
--------------------------------------------------------------------------------
/internal/pkg/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/internal/pkg/.keep
--------------------------------------------------------------------------------
/internal/pkg/common/factory.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "errors"
5 |
6 | "github.com/uber-go/tally"
7 | "go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
8 | "go.uber.org/cadence/client"
9 | "go.uber.org/cadence/encoded"
10 | "go.uber.org/cadence/workflow"
11 | "go.uber.org/yarpc"
12 | "go.uber.org/yarpc/transport/tchannel"
13 | "go.uber.org/zap"
14 | )
15 |
16 | const (
17 | _cadenceClientName = "cadence-client"
18 | _cadenceFrontendService = "cadence-frontend"
19 | )
20 |
21 | // WorkflowClientBuilder build client to cadence service
22 | type WorkflowClientBuilder struct {
23 | hostPort string
24 | dispatcher *yarpc.Dispatcher
25 | domain string
26 | clientIdentity string
27 | metricsScope tally.Scope
28 | Logger *zap.Logger
29 | ctxProps []workflow.ContextPropagator
30 | dataConverter encoded.DataConverter
31 | }
32 |
33 | // NewBuilder creates a new WorkflowClientBuilder
34 | func NewBuilder(logger *zap.Logger) *WorkflowClientBuilder {
35 | return &WorkflowClientBuilder{
36 | Logger: logger,
37 | }
38 | }
39 |
40 | // SetHostPort sets the hostport for the builder
41 | func (b *WorkflowClientBuilder) SetHostPort(hostport string) *WorkflowClientBuilder {
42 | b.hostPort = hostport
43 | return b
44 | }
45 |
46 | // SetDomain sets the domain for the builder
47 | func (b *WorkflowClientBuilder) SetDomain(domain string) *WorkflowClientBuilder {
48 | b.domain = domain
49 | return b
50 | }
51 |
52 | // SetClientIdentity sets the identity for the builder
53 | func (b *WorkflowClientBuilder) SetClientIdentity(identity string) *WorkflowClientBuilder {
54 | b.clientIdentity = identity
55 | return b
56 | }
57 |
58 | // SetMetricsScope sets the metrics scope for the builder
59 | func (b *WorkflowClientBuilder) SetMetricsScope(metricsScope tally.Scope) *WorkflowClientBuilder {
60 | b.metricsScope = metricsScope
61 | return b
62 | }
63 |
64 | // SetDispatcher sets the dispatcher for the builder
65 | func (b *WorkflowClientBuilder) SetDispatcher(dispatcher *yarpc.Dispatcher) *WorkflowClientBuilder {
66 | b.dispatcher = dispatcher
67 | return b
68 | }
69 |
70 | // SetContextPropagators sets the context propagators for the builder
71 | func (b *WorkflowClientBuilder) SetContextPropagators(ctxProps []workflow.ContextPropagator) *WorkflowClientBuilder {
72 | b.ctxProps = ctxProps
73 | return b
74 | }
75 |
76 | // SetDataConverter sets the data converter for the builder
77 | func (b *WorkflowClientBuilder) SetDataConverter(dataConverter encoded.DataConverter) *WorkflowClientBuilder {
78 | b.dataConverter = dataConverter
79 | return b
80 | }
81 |
82 | // BuildCadenceClient builds a client to cadence service
83 | func (b *WorkflowClientBuilder) BuildCadenceClient() (client.Client, error) {
84 | service, err := b.BuildServiceClient()
85 | if err != nil {
86 | return nil, err
87 | }
88 |
89 | return client.NewClient(
90 | service, b.domain, &client.Options{Identity: b.clientIdentity, MetricsScope: b.metricsScope, DataConverter: b.dataConverter, ContextPropagators: b.ctxProps}), nil
91 | }
92 |
93 | // BuildCadenceDomainClient builds a domain client to cadence service
94 | func (b *WorkflowClientBuilder) BuildCadenceDomainClient() (client.DomainClient, error) {
95 | service, err := b.BuildServiceClient()
96 | if err != nil {
97 | return nil, err
98 | }
99 |
100 | return client.NewDomainClient(
101 | service, &client.Options{Identity: b.clientIdentity, MetricsScope: b.metricsScope, ContextPropagators: b.ctxProps}), nil
102 | }
103 |
104 | // BuildServiceClient builds a rpc service client to cadence service
105 | func (b *WorkflowClientBuilder) BuildServiceClient() (workflowserviceclient.Interface, error) {
106 | if err := b.build(); err != nil {
107 | return nil, err
108 | }
109 |
110 | if b.dispatcher == nil {
111 | b.Logger.Fatal("No RPC dispatcher provided to create a connection to Cadence Service")
112 | }
113 |
114 | return workflowserviceclient.New(b.dispatcher.ClientConfig(_cadenceFrontendService)), nil
115 | }
116 |
117 | func (b *WorkflowClientBuilder) build() error {
118 | if b.dispatcher != nil {
119 | return nil
120 | }
121 |
122 | if len(b.hostPort) == 0 {
123 | return errors.New("HostPort is empty")
124 | }
125 |
126 | ch, err := tchannel.NewChannelTransport(
127 | tchannel.ServiceName(_cadenceClientName))
128 | if err != nil {
129 | b.Logger.Fatal("Failed to create transport channel", zap.Error(err))
130 | }
131 |
132 | b.Logger.Debug("Creating RPC dispatcher outbound",
133 | zap.String("ServiceName", _cadenceFrontendService),
134 | zap.String("HostPort", b.hostPort))
135 |
136 | b.dispatcher = yarpc.NewDispatcher(yarpc.Config{
137 | Name: _cadenceClientName,
138 | Outbounds: yarpc.Outbounds{
139 | _cadenceFrontendService: {Unary: ch.NewSingleOutbound(b.hostPort)},
140 | },
141 | })
142 |
143 | if b.dispatcher != nil {
144 | if err := b.dispatcher.Start(); err != nil {
145 | b.Logger.Fatal("Failed to create outbound transport channel: %v", zap.Error(err))
146 | }
147 | }
148 |
149 | return nil
150 | }
151 |
--------------------------------------------------------------------------------
/internal/pkg/common/helper.go:
--------------------------------------------------------------------------------
1 | package common
2 |
3 | import (
4 | "context"
5 | "os"
6 |
7 | "github.com/uber-go/tally"
8 | "go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
9 | "go.uber.org/cadence/client"
10 | "go.uber.org/cadence/encoded"
11 | "go.uber.org/cadence/worker"
12 | "go.uber.org/cadence/workflow"
13 | "go.uber.org/zap"
14 | )
15 |
16 | type (
17 | // CadenceHelper class for workflow sample helper.
18 | CadenceHelper struct {
19 | Service workflowserviceclient.Interface
20 | Scope tally.Scope
21 | Logger *zap.Logger
22 | Config Configuration
23 | Builder *WorkflowClientBuilder
24 | DataConverter encoded.DataConverter
25 | CtxPropagators []workflow.ContextPropagator
26 | }
27 |
28 | // Configuration for running samples.
29 | Configuration struct {
30 | DomainName string `yaml:"domain"`
31 | ServiceName string `yaml:"service"`
32 | HostNameAndPort string `yaml:"host"`
33 | }
34 | )
35 |
36 | // SetupServiceConfig setup the config for the sample code run
37 | func (h *CadenceHelper) SetupServiceConfig() {
38 | if h.Service != nil {
39 | return
40 | }
41 |
42 | h.Config.DomainName = os.Getenv("CADENCE_DOMAIN")
43 | h.Config.ServiceName = os.Getenv("CADENCE_SERVICE")
44 | h.Config.HostNameAndPort = os.Getenv("CADENCE_HOST")
45 |
46 | // Initialize logger for running samples
47 | logger, err := zap.NewDevelopment()
48 | if err != nil {
49 | panic(err)
50 | }
51 |
52 | logger.Info("Logger created.")
53 | h.Logger = logger
54 | h.Scope = tally.NoopScope
55 | h.Builder = NewBuilder(logger).
56 | SetHostPort(h.Config.HostNameAndPort).
57 | SetDomain(h.Config.DomainName).
58 | SetMetricsScope(h.Scope).
59 | SetDataConverter(h.DataConverter).
60 | SetContextPropagators(h.CtxPropagators)
61 | service, err := h.Builder.BuildServiceClient()
62 | if err != nil {
63 | panic(err)
64 | }
65 | h.Service = service
66 |
67 | domainClient, _ := h.Builder.BuildCadenceDomainClient()
68 | _, err = domainClient.Describe(context.Background(), h.Config.DomainName)
69 | if err != nil {
70 | logger.Info("Domain doesn't exist", zap.String("Domain", h.Config.DomainName), zap.Error(err))
71 | } else {
72 | logger.Info("Domain successfully registered.", zap.String("Domain", h.Config.DomainName))
73 | }
74 | }
75 |
76 | // StartWorkflow starts a workflow
77 | func (h *CadenceHelper) StartWorkflow(options client.StartWorkflowOptions, workflow interface{}, args ...interface{}) {
78 | h.StartWorkflowWithCtx(context.Background(), options, workflow, args...)
79 | }
80 |
81 | // StartWorkflowWithCtx starts a workflow with the provided context
82 | func (h *CadenceHelper) StartWorkflowWithCtx(ctx context.Context, options client.StartWorkflowOptions, workflow interface{}, args ...interface{}) {
83 | workflowClient, err := h.Builder.BuildCadenceClient()
84 | if err != nil {
85 | h.Logger.Error("Failed to build cadence client.", zap.Error(err))
86 | panic(err)
87 | }
88 |
89 | we, err := workflowClient.StartWorkflow(ctx, options, workflow, args...)
90 | if err != nil {
91 | h.Logger.Error("Failed to create workflow", zap.Error(err))
92 | panic("Failed to create workflow.")
93 |
94 | } else {
95 | h.Logger.Info("Started Workflow", zap.String("WorkflowID", we.ID), zap.String("RunID", we.RunID))
96 | }
97 | }
98 |
99 | // StartWorkers starts workflow worker and activity worker based on configured options.
100 | func (h *CadenceHelper) StartWorkers(domainName, groupName string, options worker.Options) {
101 | worker := worker.New(h.Service, domainName, groupName, options)
102 | err := worker.Start()
103 | if err != nil {
104 | h.Logger.Error("Failed to start workers.", zap.Error(err))
105 | panic("Failed to start workers")
106 | }
107 | }
108 |
109 | func (h *CadenceHelper) QueryWorkflow(workflowID, runID, queryType string, args ...interface{}) {
110 | workflowClient, err := h.Builder.BuildCadenceClient()
111 | if err != nil {
112 | h.Logger.Error("Failed to build cadence client.", zap.Error(err))
113 | panic(err)
114 | }
115 |
116 | resp, err := workflowClient.QueryWorkflow(context.Background(), workflowID, runID, queryType, args...)
117 | if err != nil {
118 | h.Logger.Error("Failed to query workflow", zap.Error(err))
119 | panic("Failed to query workflow.")
120 | }
121 | var result interface{}
122 | if err := resp.Get(&result); err != nil {
123 | h.Logger.Error("Failed to decode query result", zap.Error(err))
124 | }
125 | h.Logger.Info("Received query result", zap.Any("Result", result))
126 | }
127 |
128 | func (h *CadenceHelper) SignalWorkflow(workflowID, signal string, data interface{}) {
129 | workflowClient, err := h.Builder.BuildCadenceClient()
130 | if err != nil {
131 | h.Logger.Error("Failed to build cadence client.", zap.Error(err))
132 | panic(err)
133 | }
134 |
135 | err = workflowClient.SignalWorkflow(context.Background(), workflowID, "", signal, data)
136 | if err != nil {
137 | h.Logger.Error("Failed to signal workflow", zap.Error(err))
138 | panic("Failed to signal workflow.")
139 | }
140 | }
141 |
142 | func (h *CadenceHelper) CancelWorkflow(workflowID string) {
143 | workflowClient, err := h.Builder.BuildCadenceClient()
144 | if err != nil {
145 | h.Logger.Error("Failed to build cadence client.", zap.Error(err))
146 | panic(err)
147 | }
148 |
149 | err = workflowClient.CancelWorkflow(context.Background(), workflowID, "")
150 | if err != nil {
151 | h.Logger.Error("Failed to cancel workflow", zap.Error(err))
152 | panic("Failed to cancel workflow.")
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/pkg/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/pkg/.keep
--------------------------------------------------------------------------------
/pkg/aslworkflow/activity.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "context"
5 |
6 | "go.uber.org/cadence/activity"
7 | )
8 |
9 | type Activity func(ctx context.Context, input interface{}) (interface{}, error)
10 |
11 | func RegisterActivity(activityName string, activityFunc Activity) {
12 | activity.RegisterWithOptions(activityFunc, activity.RegisterOptions{Name: activityName})
13 | }
14 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/choice_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
8 | "github.com/coinbase/step/utils/to"
9 | "go.uber.org/cadence/workflow"
10 | )
11 |
12 | //
13 | // ChoiceState allows you to specify which state to go to next based on rules related to
14 | // this states inputs.
15 | //
16 | // "Choice": {
17 | // "Type": "Choice",
18 | // "Choices": [
19 | // {
20 | // "Variable": "$.value",
21 | // "NumericEquals": 0,
22 | // "Next": "ValueIsZero"
23 | // },
24 | // {
25 | // "And": [
26 | // {
27 | // "Variable": "$.value",
28 | // "NumericGreaterThanEquals": 20.5
29 | // },
30 | // {
31 | // "Variable": "$.value",
32 | // "NumericLessThan": 30
33 | // }
34 | // ],
35 | // "Next": "ValueInTwenties"
36 | // }
37 | // ],
38 | // "Default": "DefaultState"
39 | // }
40 |
41 | type ChoiceState struct {
42 | stateStr // Include Defaults
43 |
44 | Type *string
45 | Comment *string `json:",omitempty"`
46 |
47 | InputPath *jsonpath.Path `json:",omitempty"`
48 | OutputPath *jsonpath.Path `json:",omitempty"`
49 |
50 | Default *string `json:",omitempty"` // Default State if no choices match
51 |
52 | Choices []*Choice `json:",omitempty"`
53 | }
54 |
55 | type Choice struct {
56 | ChoiceRule
57 |
58 | Next *string `json:",omitempty"`
59 | }
60 |
61 | type ChoiceRule struct {
62 | Variable *jsonpath.Path `json:",omitempty"`
63 |
64 | StringEquals *string `json:",omitempty"`
65 | StringLessThan *string `json:",omitempty"`
66 | StringGreaterThan *string `json:",omitempty"`
67 | StringLessThanEquals *string `json:",omitempty"`
68 | StringGreaterThanEquals *string `json:",omitempty"`
69 |
70 | NumericEquals *float64 `json:",omitempty"`
71 | NumericLessThan *float64 `json:",omitempty"`
72 | NumericGreaterThan *float64 `json:",omitempty"`
73 | NumericLessThanEquals *float64 `json:",omitempty"`
74 | NumericGreaterThanEquals *float64 `json:",omitempty"`
75 |
76 | BooleanEquals *bool `json:",omitempty"`
77 |
78 | TimestampEquals *time.Time `json:",omitempty"`
79 | TimestampLessThan *time.Time `json:",omitempty"`
80 | TimestampGreaterThan *time.Time `json:",omitempty"`
81 | TimestampLessThanEquals *time.Time `json:",omitempty"`
82 | TimestampGreaterThanEquals *time.Time `json:",omitempty"`
83 |
84 | And []*ChoiceRule `json:",omitempty"`
85 | Or []*ChoiceRule `json:",omitempty"`
86 | Not *ChoiceRule `json:",omitempty"`
87 | }
88 |
89 | func (s *ChoiceState) process(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
90 | next := chooseNextState(input, s.Default, s.Choices)
91 | if next == nil {
92 | return nil, nil, fmt.Errorf("choice state error: no choice found")
93 | }
94 | return input, next, nil
95 | }
96 |
97 | func (s *ChoiceState) Execute(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
98 | return processError(
99 | s,
100 | processInputOutput(
101 | s.InputPath,
102 | s.OutputPath,
103 | s.process,
104 | ),
105 | )(ctx, input)
106 | }
107 |
108 | func chooseNextState(input interface{}, defaultChoice *string, choices []*Choice) *string {
109 | for _, choice := range choices {
110 | if choiceRulePositive(input, &choice.ChoiceRule) {
111 | return choice.Next
112 | }
113 | }
114 | return defaultChoice
115 | }
116 |
117 | func choiceRulePositive(input interface{}, cr *ChoiceRule) bool {
118 | if cr.And != nil {
119 | for _, a := range cr.And {
120 | // if any choices have false then return false
121 | if !choiceRulePositive(input, a) {
122 | return false
123 | }
124 | }
125 | return true
126 | }
127 |
128 | if cr.Or != nil {
129 | for _, a := range cr.Or {
130 | // if any choices have true then return true
131 | if choiceRulePositive(input, a) {
132 | return true
133 | }
134 | }
135 | return false
136 | }
137 |
138 | if cr.Not != nil {
139 | return !choiceRulePositive(input, cr.Not)
140 | }
141 |
142 | if cr.StringEquals != nil {
143 | vstr, err := cr.Variable.GetString(input)
144 | if err != nil {
145 | return false // either not found or bad type
146 | }
147 | return *vstr == *cr.StringEquals
148 | }
149 |
150 | if cr.StringLessThan != nil {
151 | vstr, err := cr.Variable.GetString(input)
152 | if err != nil {
153 | return false // either not found or bad type
154 | }
155 | return *vstr < *cr.StringLessThan
156 | }
157 |
158 | if cr.StringGreaterThan != nil {
159 | vstr, err := cr.Variable.GetString(input)
160 | if err != nil {
161 | return false // either not found or bad type
162 | }
163 | return *vstr > *cr.StringGreaterThan
164 | }
165 |
166 | if cr.StringLessThanEquals != nil {
167 | vstr, err := cr.Variable.GetString(input)
168 | if err != nil {
169 | return false // either not found or bad type
170 | }
171 | return *vstr <= *cr.StringLessThanEquals
172 | }
173 |
174 | if cr.StringGreaterThanEquals != nil {
175 | vstr, err := cr.Variable.GetString(input)
176 | if err != nil {
177 | return false // either not found or bad type
178 | }
179 | return *vstr >= *cr.StringGreaterThanEquals
180 | }
181 |
182 | // NUMBERs
183 | if cr.NumericEquals != nil {
184 | vnum, err := cr.Variable.GetNumber(input)
185 | if err != nil {
186 | return false
187 | }
188 | return *vnum == *cr.NumericEquals
189 | }
190 |
191 | if cr.NumericLessThan != nil {
192 | vnum, err := cr.Variable.GetNumber(input)
193 | if err != nil {
194 | return false
195 | }
196 | return *vnum < *cr.NumericLessThan
197 | }
198 |
199 | if cr.NumericGreaterThan != nil {
200 | vnum, err := cr.Variable.GetNumber(input)
201 | if err != nil {
202 | return false
203 | }
204 | return *vnum > *cr.NumericGreaterThan
205 | }
206 |
207 | if cr.NumericLessThanEquals != nil {
208 | vnum, err := cr.Variable.GetNumber(input)
209 | if err != nil {
210 | return false
211 | }
212 | return *vnum <= *cr.NumericLessThanEquals
213 | }
214 |
215 | if cr.NumericGreaterThanEquals != nil {
216 | vnum, err := cr.Variable.GetNumber(input)
217 | if err != nil {
218 | return false
219 | }
220 | return *vnum >= *cr.NumericGreaterThanEquals
221 | }
222 |
223 | if cr.BooleanEquals != nil {
224 | vbool, err := cr.Variable.GetBool(input)
225 | if err != nil {
226 | return false
227 | }
228 | return *vbool == *cr.BooleanEquals
229 | }
230 |
231 | if cr.TimestampEquals != nil {
232 | vtime, err := cr.Variable.GetTime(input)
233 | if err != nil {
234 | return false
235 | }
236 | return *vtime == *cr.TimestampEquals
237 | }
238 |
239 | if cr.TimestampLessThan != nil {
240 | vtime, err := cr.Variable.GetTime(input)
241 | if err != nil {
242 | return false
243 | }
244 | return vtime.Before(*cr.TimestampLessThan)
245 | }
246 |
247 | if cr.TimestampGreaterThan != nil {
248 | vtime, err := cr.Variable.GetTime(input)
249 | if err != nil {
250 | return false
251 | }
252 | return vtime.After(*cr.TimestampGreaterThan)
253 | }
254 |
255 | if cr.TimestampLessThanEquals != nil {
256 | vtime, err := cr.Variable.GetTime(input)
257 | if err != nil {
258 | return false
259 | }
260 | return *vtime == *cr.TimestampLessThanEquals || vtime.Before(*cr.TimestampLessThanEquals)
261 | }
262 |
263 | if cr.TimestampGreaterThanEquals != nil {
264 | vtime, err := cr.Variable.GetTime(input)
265 | if err != nil {
266 | return false
267 | }
268 | return *vtime == *cr.TimestampGreaterThanEquals || vtime.After(*cr.TimestampGreaterThanEquals)
269 | }
270 |
271 | return false
272 | }
273 |
274 | // VALIDATION LOGIC
275 |
276 | func (s *ChoiceState) Validate() error {
277 | s.SetType(to.Strp("Choice"))
278 |
279 | if err := ValidateNameAndType(s); err != nil {
280 | return fmt.Errorf("%v %w", errorPrefix(s), err)
281 | }
282 |
283 | if len(s.Choices) == 0 {
284 | return fmt.Errorf("%v must have Choices", errorPrefix(s))
285 | }
286 |
287 | for _, c := range s.Choices {
288 | err := validateChoice(c)
289 | if err != nil {
290 | return fmt.Errorf("%v %w", errorPrefix(s), err)
291 | }
292 | }
293 |
294 | return nil
295 | }
296 |
297 | func validateChoice(c *Choice) error {
298 | if c.Next == nil {
299 | return fmt.Errorf("Choice must have Next")
300 | }
301 |
302 | allChoiceRules := recursiveAllChoiceRule(&c.ChoiceRule)
303 |
304 | for _, cr := range allChoiceRules {
305 | if err := validateChoiceRule(cr); err != nil {
306 | return err
307 | }
308 | }
309 |
310 | return nil
311 | }
312 |
313 | func recursiveAllChoiceRule(c *ChoiceRule) []*ChoiceRule {
314 | if c == nil {
315 | return []*ChoiceRule{}
316 | }
317 |
318 | crs := []*ChoiceRule{c}
319 |
320 | if c.Not != nil {
321 | crs = append(crs, c.Not)
322 | }
323 |
324 | if c.And != nil {
325 | for _, cr := range c.And {
326 | crs = append(crs, recursiveAllChoiceRule(cr)...)
327 | }
328 | }
329 |
330 | if c.Or != nil {
331 | for _, cr := range c.Or {
332 | crs = append(crs, recursiveAllChoiceRule(cr)...)
333 | }
334 | }
335 |
336 | return crs
337 | }
338 |
339 | func validateChoiceRule(c *ChoiceRule) error {
340 | // Exactly One Comparison Operator
341 | allComparisonOperators := []bool{
342 | c.Not != nil,
343 | c.And != nil,
344 | c.Or != nil,
345 | c.StringEquals != nil,
346 | c.StringLessThan != nil,
347 | c.StringGreaterThan != nil,
348 | c.StringLessThanEquals != nil,
349 | c.StringGreaterThanEquals != nil,
350 | c.NumericEquals != nil,
351 | c.NumericLessThan != nil,
352 | c.NumericGreaterThan != nil,
353 | c.NumericLessThanEquals != nil,
354 | c.NumericGreaterThanEquals != nil,
355 | c.BooleanEquals != nil,
356 | c.TimestampEquals != nil,
357 | c.TimestampLessThan != nil,
358 | c.TimestampGreaterThan != nil,
359 | c.TimestampLessThanEquals != nil,
360 | c.TimestampGreaterThanEquals != nil,
361 | }
362 |
363 | count := 0
364 | for _, co := range allComparisonOperators {
365 | if co {
366 | count++
367 | }
368 | }
369 |
370 | if count != 1 {
371 | return fmt.Errorf("Not Exactly One comparison Operator")
372 | }
373 |
374 | // Variable must be defined, UNLESS AND NOT OR, in which case error if defined
375 | notAndOr := c.Not != nil || c.And != nil || c.Or != nil
376 |
377 | if notAndOr {
378 | if c.Variable != nil {
379 | return fmt.Errorf("Variable defined with Not And Or defined")
380 | }
381 | } else {
382 | if c.Variable == nil {
383 | return fmt.Errorf("Variable Not defined")
384 | }
385 | }
386 |
387 | if c.And != nil && len(c.And) == 0 {
388 | return fmt.Errorf("And Must have elements")
389 | }
390 |
391 | if c.Or != nil && len(c.Or) == 0 {
392 | return fmt.Errorf("Or Must have elements")
393 | }
394 |
395 | return nil
396 | }
397 |
398 | func (s *ChoiceState) SetType(t *string) {
399 | s.Type = t
400 | }
401 |
402 | func (s *ChoiceState) GetType() *string {
403 | return s.Type
404 | }
405 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/fail_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/coinbase/step/utils/is"
7 | "github.com/coinbase/step/utils/to"
8 | "go.uber.org/cadence"
9 | "go.uber.org/cadence/workflow"
10 | )
11 |
12 | type FailState struct {
13 | stateStr // Include Defaults
14 |
15 | Type *string
16 | Comment *string `json:",omitempty"`
17 |
18 | Error *string `json:",omitempty"`
19 | Cause *string `json:",omitempty"`
20 | }
21 |
22 | func (s *FailState) Execute(_ workflow.Context, input interface{}) (output interface{}, next *string, err error) {
23 | return nil, nil, cadence.NewCustomError(
24 | "Fail",
25 | errorOutput(s.Error, s.Cause))
26 | }
27 |
28 | func (s *FailState) Validate() error {
29 | s.SetType(to.Strp("Fail"))
30 |
31 | if err := ValidateNameAndType(s); err != nil {
32 | return fmt.Errorf("%v %v", errorPrefix(s), err)
33 | }
34 |
35 | if is.EmptyStr(s.Error) {
36 | return fmt.Errorf("%v %v", errorPrefix(s), "must contain Error")
37 | }
38 |
39 | return nil
40 | }
41 |
42 | func (s *FailState) SetType(t *string) {
43 | s.Type = t
44 | }
45 |
46 | func (s *FailState) GetType() *string {
47 | return s.Type
48 | }
49 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/fail_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "go.uber.org/cadence"
5 | )
6 |
7 | var failMachine = []byte(`
8 | {
9 | "StartAt": "Example1",
10 | "States": {
11 | "Example1": {
12 | "Type": "Fail",
13 | "Error": "ExampleError",
14 | "Cause": "This is an example error",
15 | "End": true
16 | }
17 | }
18 | }
19 | `)
20 |
21 | func (s *UnitTestSuite) Test_Workflow_Fail_State() {
22 | sm, err := FromJSON(failMachine)
23 | if err != nil {
24 | s.NoError(err)
25 | return
26 | }
27 |
28 | exampleInput := map[string]interface{}{"test": "example_input"}
29 |
30 | RegisterWorkflow("TestFailWorkflow", *sm)
31 |
32 | s.env.ExecuteWorkflow("TestFailWorkflow", exampleInput)
33 | s.True(s.env.IsWorkflowCompleted())
34 | err = s.env.GetWorkflowError()
35 | s.Error(err)
36 |
37 | var details map[string]interface{}
38 |
39 | switch err := err.(type) {
40 | case *cadence.CustomError:
41 | detailsErr := err.Details(&details)
42 |
43 | if detailsErr != nil {
44 | s.NoError(detailsErr)
45 | }
46 | }
47 |
48 | s.Equal("ExampleError", details["Error"])
49 | s.Equal("This is an example error", details["Cause"])
50 | }
51 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/machine.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 |
7 | "go.uber.org/cadence/workflow"
8 | )
9 |
10 | type StateMachine struct {
11 | States States
12 | StartAt string
13 | Comment string
14 | Version string
15 | TimeoutSeconds int32
16 | }
17 |
18 | // States is the collection of states
19 | type States map[string]State
20 |
21 | func FromJSON(raw []byte) (*StateMachine, error) {
22 | var sm StateMachine
23 | err := json.Unmarshal(raw, &sm)
24 | return &sm, err
25 | }
26 |
27 | func (sm *States) UnmarshalJSON(b []byte) error {
28 | // States
29 | var rawStates map[string]*json.RawMessage
30 | err := json.Unmarshal(b, &rawStates)
31 |
32 | if err != nil {
33 | return err
34 | }
35 |
36 | newStates := States{}
37 | for name, raw := range rawStates {
38 | states, err := unmarshallState(name, raw)
39 | if err != nil {
40 | return err
41 | }
42 |
43 | for _, s := range states {
44 | newStates[*s.Name()] = s
45 | }
46 | }
47 |
48 | *sm = newStates
49 | return nil
50 | }
51 |
52 | // Default State Methods
53 |
54 | func (s *stateStr) GetType() *string {
55 | return s.Type
56 | }
57 |
58 | func (s *stateStr) SetType(t *string) {
59 | s.Type = t
60 | }
61 |
62 | type stateType struct {
63 | Type string
64 | }
65 |
66 | func unmarshallState(name string, rawJSON *json.RawMessage) ([]State, error) {
67 | var err error
68 |
69 | // extract type (safer than regex)
70 | var stateType stateType
71 | if err = json.Unmarshal(*rawJSON, &stateType); err != nil {
72 | return nil, err
73 | }
74 |
75 | var newState State
76 |
77 | switch stateType.Type {
78 | case "Pass":
79 | var s PassState
80 | err = json.Unmarshal(*rawJSON, &s)
81 | newState = &s
82 | case "Task":
83 | var s TaskState
84 | err = json.Unmarshal(*rawJSON, &s)
85 | newState = &s
86 | case "Choice":
87 | var s ChoiceState
88 | err = json.Unmarshal(*rawJSON, &s)
89 | newState = &s
90 | case "Wait":
91 | var s WaitState
92 | err = json.Unmarshal(*rawJSON, &s)
93 | newState = &s
94 | case "Succeed":
95 | var s SucceedState
96 | err = json.Unmarshal(*rawJSON, &s)
97 | newState = &s
98 | case "Fail":
99 | var s FailState
100 | err = json.Unmarshal(*rawJSON, &s)
101 | newState = &s
102 | case "Parallel":
103 | var s ParallelState
104 | err = json.Unmarshal(*rawJSON, &s)
105 | newState = &s
106 | default:
107 | err = fmt.Errorf("unknown state %q", stateType.Type)
108 | }
109 |
110 | // End of loop return error
111 | if err != nil {
112 | return nil, err
113 | }
114 |
115 | // Set Name and Defaults
116 | newName := name
117 | newState.SetName(&newName) // Require New Variable Pointer
118 |
119 | return []State{newState}, nil
120 | }
121 |
122 | func (m *StateMachine) Execute(ctx workflow.Context, input interface{}) (interface{}, error) {
123 | nextState := &m.StartAt
124 |
125 | for {
126 | s := m.States[*nextState]
127 | if s == nil {
128 | return nil, fmt.Errorf("next state invalid (%v)", *nextState)
129 | }
130 |
131 | output, next, err := s.Execute(ctx, input)
132 |
133 | if err != nil {
134 | return nil, err
135 | }
136 |
137 | if next == nil {
138 | return output, nil
139 | }
140 |
141 | nextState = next
142 | input = output
143 | }
144 | }
145 |
146 | func tasksFromStates(states States) []*TaskState {
147 | var tasks []*TaskState
148 | for _, state := range states {
149 | switch typeState := state.(type) {
150 | case *TaskState:
151 | tasks = append(tasks, typeState)
152 | case *ParallelState:
153 | parallelState := state.(*ParallelState)
154 | for _, branch := range parallelState.Branches {
155 | tasks = append(tasks, branch.Tasks()...)
156 | }
157 | }
158 | }
159 | return tasks
160 | }
161 |
162 | func (m *StateMachine) Tasks() []*TaskState {
163 | var tasks []*TaskState
164 | tasks = append(tasks, tasksFromStates(m.States)...)
165 | return tasks
166 | }
167 |
168 | func (m *StateMachine) RegisterWorkflow(name string) {
169 | RegisterWorkflow(name, *m)
170 | }
171 |
172 | // Keep track of registered activities so we don't register the same activity more than once
173 | var registeredActivities = map[string]bool{}
174 |
175 | func (m *StateMachine) RegisterActivities(activityFunc Activity) {
176 | for _, task := range m.Tasks() {
177 | resourceName := *task.Resource
178 |
179 | // Check to see if this activity has already been registered, and skip if so
180 | if registeredActivities[resourceName] {
181 | continue
182 | }
183 |
184 | RegisterActivity(resourceName, activityFunc)
185 | registeredActivities[resourceName] = true
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/machine_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/assert"
7 | )
8 |
9 | func TestMachineGetTasks(t *testing.T) {
10 | sm, err := FromJSON([]byte(`
11 | {
12 | "StartAt": "Example1",
13 | "States": {
14 | "Example1": {
15 | "Type": "Task",
16 | "Resource": "arn:aws:resource:example",
17 | "Next": "Example2"
18 | },
19 | "Example2": {
20 | "Type": "Task",
21 | "Resource": "arn:aws:resource:example",
22 | "End": true
23 | }
24 | }
25 | }
26 | `))
27 | if err != nil {
28 | return
29 | }
30 |
31 | tasks := sm.Tasks()
32 |
33 | assert.Equal(t, 2, len(tasks))
34 | assert.Equal(t, "arn:aws:resource:example", *tasks[0].Resource)
35 | }
36 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/parallel_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
7 | "github.com/coinbase/step/utils/to"
8 | "go.uber.org/cadence/workflow"
9 | )
10 |
11 | type ParallelState struct {
12 | stateStr
13 |
14 | Branches []Branch
15 |
16 | InputPath *jsonpath.Path `json:",omitempty"`
17 | OutputPath *jsonpath.Path `json:",omitempty"`
18 | ResultPath *jsonpath.Path `json:",omitempty"`
19 | Parameters interface{} `json:",omitempty"`
20 |
21 | Catch []*Catcher `json:",omitempty"`
22 | Retry []*Retrier `json:",omitempty"`
23 |
24 | Next *string `json:",omitempty"`
25 | End *bool `json:",omitempty"`
26 | }
27 |
28 | type Branch struct {
29 | States States
30 | StartAt string
31 | }
32 |
33 | func (s *ParallelState) process(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
34 | // You can use the context passed in to activity as a way to cancel the activity like standard GO way.
35 | // Cancelling a parent context will cancel all the derived contexts as well.
36 | // In the parallel block, we want to execute all of them in parallel and wait for all of them.
37 | // if one activity fails then we want to cancel all the rest of them as well.
38 | childCtx, cancelHandler := workflow.WithCancel(ctx)
39 | selector := workflow.NewSelector(ctx)
40 | var activityErr error
41 |
42 | var resp []interface{}
43 |
44 | for _, branch := range s.Branches {
45 | f := executeAsync(s, branch, childCtx, input)
46 | selector.AddFuture(f, func(f workflow.Future) {
47 | var r interface{}
48 | err := f.Get(ctx, &r)
49 | if err != nil {
50 | // cancel all pending activities
51 | cancelHandler()
52 | activityErr = err
53 | }
54 | resp = append(resp, r)
55 | })
56 | }
57 |
58 | for i := 0; i < len(s.Branches); i++ {
59 | selector.Select(ctx) // this will wait for one branch
60 | if activityErr != nil {
61 | return nil, nil, activityErr
62 | }
63 | }
64 |
65 | return interface{}(resp), nextState(s.Next, s.End), nil
66 | }
67 |
68 | func (s *ParallelState) Execute(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
69 | return processError(s,
70 | processCatcher(s.Catch,
71 | processRetrier(s.Name(), s.Retry,
72 | processInputOutput(
73 | s.InputPath,
74 | s.OutputPath,
75 | processParams(
76 | s.Parameters,
77 | processResult(s.ResultPath, s.process),
78 | ),
79 | ),
80 | ),
81 | ),
82 | )(ctx, input)
83 | }
84 |
85 | func executeAsync(p *ParallelState, b Branch, ctx workflow.Context, input interface{}) workflow.Future {
86 | future, settable := workflow.NewFuture(ctx)
87 | workflow.Go(ctx, func(ctx workflow.Context) {
88 | output, _, err := b.Execute(ctx, *p, input)
89 | settable.Set(output, err)
90 | })
91 | return future
92 | }
93 |
94 | func (m *Branch) Execute(ctx workflow.Context, s ParallelState, input interface{}) (interface{}, *string, error) {
95 | nextState := &m.StartAt
96 |
97 | for {
98 | s := m.States[*nextState]
99 | if s == nil {
100 | return nil, nil, fmt.Errorf("next state invalid (%v)", *nextState)
101 | }
102 |
103 | output, next, err := s.Execute(ctx, input)
104 |
105 | if err != nil {
106 | return nil, nil, err
107 | }
108 |
109 | if next == nil || *next == "" {
110 | return output, nil, nil
111 | }
112 |
113 | nextState = next
114 | input = output
115 | }
116 | }
117 |
118 | func (m *Branch) Tasks() []*TaskState {
119 | var tasks []*TaskState
120 | tasks = append(tasks, tasksFromStates(m.States)...)
121 | return tasks
122 | }
123 |
124 | func (s *ParallelState) Validate() error {
125 | s.SetType(to.Strp("Parallel"))
126 |
127 | if err := ValidateNameAndType(s); err != nil {
128 | return fmt.Errorf("%v %v", errorPrefix(s), err)
129 | }
130 |
131 | return nil
132 | }
133 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/parallel_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | var parallelMachine = []byte(`
4 | {
5 | "StartAt": "Example1",
6 | "States": {
7 | "Example1": {
8 | "Type": "Parallel",
9 | "End": true,
10 | "Branches": [
11 | {
12 | "StartAt": "Branch1",
13 | "States": {
14 | "Branch1": {
15 | "Type": "Pass",
16 | "Result": {
17 | "branch1": true
18 | },
19 | "End": true
20 | }
21 | }
22 | },
23 | {
24 | "StartAt": "Branch2",
25 | "States": {
26 | "Branch2": {
27 | "Type": "Pass",
28 | "Result": {
29 | "branch2": true
30 | },
31 | "End": true
32 | }
33 | }
34 | }
35 | ]
36 | }
37 | }
38 | }
39 | `)
40 |
41 | func (s *UnitTestSuite) Test_Workflow_Parallel_State() {
42 | workflowName := "TestParallelWorkflow"
43 |
44 | sm, err := FromJSON(parallelMachine)
45 | if err != nil {
46 | s.NoError(err)
47 | return
48 | }
49 |
50 | exampleInput := map[string]interface{}{"example": "example"}
51 |
52 | RegisterWorkflow(workflowName, *sm)
53 | s.env.ExecuteWorkflow(workflowName, exampleInput)
54 |
55 | s.True(s.env.IsWorkflowCompleted())
56 | s.NoError(s.env.GetWorkflowError())
57 |
58 | var result []map[string]bool
59 | err = s.env.GetWorkflowResult(&result)
60 | s.NoError(err)
61 |
62 | s.True(result[0]["branch1"])
63 | s.True(result[1]["branch2"])
64 | }
65 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/pass_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
7 | "github.com/coinbase/step/utils/to"
8 | "go.uber.org/cadence/workflow"
9 | )
10 |
11 | type PassState struct {
12 | stateStr // Include Defaults
13 |
14 | Type *string
15 | Comment *string `json:",omitempty"`
16 |
17 | InputPath *jsonpath.Path `json:",omitempty"`
18 | OutputPath *jsonpath.Path `json:",omitempty"`
19 | ResultPath *jsonpath.Path `json:",omitempty"`
20 | Parameters interface{} `json:",omitempty"` // TODO: Create a struct for Parameters?
21 |
22 | Result interface{} `json:",omitempty"`
23 |
24 | Next *string `json:",omitempty"`
25 | End *bool `json:",omitempty"`
26 | }
27 |
28 | func (s *PassState) Execute(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
29 | return processError(s,
30 | processInputOutput(
31 | s.InputPath,
32 | s.OutputPath,
33 | processParams(
34 | s.Parameters,
35 | processResult(s.ResultPath, s.process),
36 | ),
37 | ),
38 | )(ctx, input)
39 | }
40 |
41 | func (s *PassState) process(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
42 | output = input
43 | if s.Result != nil {
44 | output = s.Result
45 | }
46 | return output, nextState(s.Next, s.End), nil
47 | }
48 |
49 | func (s *PassState) Validate() error {
50 | s.SetType(to.Strp("Pass"))
51 |
52 | if err := ValidateNameAndType(s); err != nil {
53 | return fmt.Errorf("%v %v", errorPrefix(s), err)
54 | }
55 |
56 | // Next xor End
57 | if err := isEndValid(s.Next, s.End); err != nil {
58 | return fmt.Errorf("%v %v", errorPrefix(s), err)
59 | }
60 |
61 | return nil
62 | }
63 |
64 | func (s *PassState) SetType(t *string) {
65 | s.Type = t
66 | }
67 |
68 | func (s *PassState) GetType() *string {
69 | return s.Type
70 | }
71 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/pass_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | var passMachine = []byte(`
4 | {
5 | "StartAt": "Example1",
6 | "States": {
7 | "Example1": {
8 | "Type": "Pass",
9 | "Next": "Example2"
10 | },
11 | "Example2": {
12 | "Type": "Pass",
13 | "Result": {
14 | "test": "example_output"
15 | },
16 | "End": true
17 | }
18 | }
19 | }
20 | `)
21 |
22 | func (s *UnitTestSuite) Test_Workflow_Pass_State() {
23 | sm, err := FromJSON(passMachine)
24 | if err != nil {
25 | s.NoError(err)
26 | return
27 | }
28 |
29 | exampleInput := map[string]interface{}{"test": "example_input"}
30 |
31 | RegisterWorkflow("TestPassWorkflow", *sm)
32 |
33 | s.env.ExecuteWorkflow("TestPassWorkflow", exampleInput)
34 |
35 | s.True(s.env.IsWorkflowCompleted())
36 | s.NoError(s.env.GetWorkflowError())
37 |
38 | var result map[string]interface{}
39 | err = s.env.GetWorkflowResult(&result)
40 | s.NoError(err)
41 |
42 | s.Equal("example_output", result["test"])
43 | }
44 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 |
7 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
8 | "github.com/coinbase/step/utils/is"
9 | "github.com/coinbase/step/utils/to"
10 | "github.com/pkg/errors"
11 | "go.uber.org/cadence/workflow"
12 | )
13 |
14 | type Execution func(workflow.Context, interface{}) (interface{}, *string, error)
15 |
16 | type State interface {
17 | Execute(workflow.Context, interface{}) (interface{}, *string, error)
18 | Validate() error
19 |
20 | SetName(*string)
21 | SetType(*string)
22 |
23 | Name() *string
24 | GetType() *string
25 | }
26 |
27 | type stateStr struct {
28 | name *string
29 |
30 | Type *string
31 | Comment *string `json:",omitempty"`
32 | }
33 |
34 | type Catcher struct {
35 | ErrorEquals []*string `json:",omitempty"`
36 | ResultPath *jsonpath.Path `json:",omitempty"`
37 | Next *string `json:",omitempty"`
38 | }
39 |
40 | type Retrier struct {
41 | ErrorEquals []*string `json:",omitempty"`
42 | IntervalSeconds *int `json:",omitempty"`
43 | MaxAttempts *int `json:",omitempty"`
44 | BackoffRate *float64 `json:",omitempty"`
45 | attempts int
46 | }
47 |
48 | func errorOutputFromError(err error) map[string]interface{} {
49 | return errorOutput(to.Strp(to.ErrorType(err)), to.Strp(err.Error()))
50 | }
51 |
52 | func errorOutput(err *string, cause *string) map[string]interface{} {
53 | errstr := ""
54 | causestr := ""
55 | if err != nil {
56 | errstr = *err
57 | }
58 | if cause != nil {
59 | causestr = *cause
60 | }
61 | return map[string]interface{}{
62 | "Error": errstr,
63 | "Cause": causestr,
64 | }
65 | }
66 |
67 | func errorIncluded(errorEquals []*string, err error) bool {
68 | errorType := to.ErrorType(err)
69 |
70 | for _, et := range errorEquals {
71 | if *et == StatesAll || *et == errorType {
72 | return true
73 | }
74 | }
75 |
76 | return false
77 | }
78 |
79 | // Default State Methods
80 |
81 | func (s *stateStr) Name() *string {
82 | return s.name
83 | }
84 |
85 | func (s *stateStr) SetName(name *string) {
86 | s.name = name
87 | }
88 |
89 | func nextState(next *string, end *bool) *string {
90 | if next != nil {
91 | return next
92 | }
93 | // If End is true then it should be nil
94 | // If End is false then Next must be defined so invalid
95 | // If End is nil then Next must be defined so invalid
96 | return nil
97 | }
98 |
99 | //////
100 | // Shared Methods
101 | //////
102 |
103 | func processRetrier(retryName *string, retriers []*Retrier, execution Execution) Execution {
104 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
105 | // Simulate Retry once, not actually waiting
106 | output, next, err := execution(ctx, input)
107 | if len(retriers) == 0 || err == nil {
108 | return output, next, err
109 | }
110 |
111 | // Is Error in a Retrier
112 | for _, retrier := range retriers {
113 | // If the error type is defined in the retrier AND we have not attempted the retry yet
114 | if retrier.MaxAttempts == nil {
115 | // Default retries is 3
116 | retrier.MaxAttempts = to.Intp(3)
117 | }
118 |
119 | // Match on first retrier
120 | if errorIncluded(retrier.ErrorEquals, err) {
121 | if retrier.attempts < *retrier.MaxAttempts {
122 | retrier.attempts++
123 | // Returns the name of the state to the state-machine to re-execute
124 | return input, retryName, nil
125 | }
126 | // Finished retrying so continue
127 | return output, next, err
128 | }
129 | }
130 |
131 | // Otherwise, just return
132 | return output, next, err
133 | }
134 | }
135 |
136 | func processCatcher(catchers []*Catcher, execution Execution) Execution {
137 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
138 | output, next, err := execution(ctx, input)
139 |
140 | if len(catchers) == 0 || err == nil {
141 | return output, next, err
142 | }
143 |
144 | for _, catcher := range catchers {
145 | if errorIncluded(catcher.ErrorEquals, err) {
146 |
147 | eo := errorOutputFromError(err)
148 | output, err := catcher.ResultPath.Set(input, eo)
149 |
150 | return output, catcher.Next, err
151 | }
152 | }
153 |
154 | // Otherwise continue
155 | return output, next, err
156 | }
157 | }
158 |
159 | func processError(s State, execution Execution) Execution {
160 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
161 | output, next, err := execution(ctx, input)
162 |
163 | if err != nil {
164 | return nil, nil, fmt.Errorf("%v %w", errorPrefix(s), err)
165 | }
166 | return output, next, nil
167 | }
168 | }
169 |
170 | func processInputOutput(inputPath *jsonpath.Path, outputPath *jsonpath.Path, execution Execution) Execution {
171 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
172 | input, err := inputPath.Get(input)
173 |
174 | if err != nil {
175 | return nil, nil, fmt.Errorf("Input Error: %v", err)
176 | }
177 |
178 | output, next, err := execution(ctx, input)
179 |
180 | if err != nil {
181 | return nil, nil, err
182 | }
183 |
184 | output, err = outputPath.Get(output)
185 |
186 | if err != nil {
187 | return nil, nil, fmt.Errorf("Output Error: %v", err)
188 | }
189 |
190 | return output, next, nil
191 | }
192 | }
193 |
194 | func processParams(params interface{}, execution Execution) Execution {
195 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
196 | if params == nil {
197 | return execution(ctx, input)
198 | }
199 | // Loop through the input replace values with JSON paths
200 | input, err := replaceParamsJSONPath(params, input)
201 | if err != nil {
202 | return nil, nil, err
203 | }
204 |
205 | return execution(ctx, input)
206 | }
207 | }
208 |
209 | func replaceParamsJSONPath(params interface{}, input interface{}) (interface{}, error) {
210 | switch params.(type) {
211 | case map[string]interface{}:
212 | newParams := map[string]interface{}{}
213 | // Recurse over params find keys to replace
214 | for key, value := range params.(map[string]interface{}) {
215 | if strings.HasSuffix(key, ".$") {
216 | key = key[:len(key)-len(".$")]
217 | // value must be a JSON path string!
218 | switch value.(type) {
219 | case string:
220 | default:
221 | return nil, fmt.Errorf("value to key %q is not string", key)
222 | }
223 | valueStr := value.(string)
224 | path, err := jsonpath.NewPath(valueStr)
225 | if err != nil {
226 | return nil, errors.Wrap(err, "failed parsing path")
227 | }
228 | newValue, err := path.Get(input)
229 | if err != nil {
230 | return nil, errors.Wrap(err, "failed getting path")
231 | }
232 | newParams[key] = newValue
233 | } else {
234 | newValue, err := replaceParamsJSONPath(value, input)
235 | if err != nil {
236 | return nil, errors.Wrap(err, "failed replacing path")
237 | }
238 | newParams[key] = newValue
239 | }
240 | }
241 | return newParams, nil
242 | }
243 | return params, nil
244 | }
245 |
246 | func processResult(resultPath *jsonpath.Path, execution Execution) Execution {
247 | return func(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
248 | result, next, err := execution(ctx, input)
249 |
250 | if err != nil {
251 | return nil, nil, err
252 | }
253 |
254 | if result != nil {
255 | input, err := resultPath.Set(input, result)
256 |
257 | if err != nil {
258 | return nil, nil, err
259 | }
260 |
261 | return input, next, nil
262 | }
263 |
264 | return input, next, nil
265 | }
266 | }
267 |
268 | //////
269 | // Shared Validity Methods
270 | //////
271 |
272 | func isEndValid(next *string, end *bool) error {
273 | if end == nil && next == nil {
274 | return fmt.Errorf("End and Next both undefined")
275 | }
276 |
277 | if end != nil && next != nil {
278 | return fmt.Errorf("End and Next both defined")
279 | }
280 |
281 | if end != nil && !*end {
282 | return fmt.Errorf("End can only be true or nil")
283 | }
284 |
285 | return nil
286 | }
287 |
288 | func errorPrefix(s State) string {
289 | if !is.EmptyStr(s.Name()) {
290 | return fmt.Sprintf("%vState(%v) Error:", *s.GetType(), *s.Name())
291 | }
292 |
293 | return fmt.Sprintf("%vState Error:", *s.GetType())
294 | }
295 |
296 | func ValidateNameAndType(s State) error {
297 | if is.EmptyStr(s.Name()) {
298 | return fmt.Errorf("Must have Name")
299 | }
300 |
301 | if is.EmptyStr(s.GetType()) {
302 | return fmt.Errorf("Must have Type")
303 | }
304 |
305 | return nil
306 | }
307 |
308 | func isRetryValid(retry []*Retrier) error {
309 | if retry == nil {
310 | return nil
311 | }
312 |
313 | for i, r := range retry {
314 | if err := isErrorEqualsValid(r.ErrorEquals, len(retry)-1 == i); err != nil {
315 | return err
316 | }
317 | }
318 |
319 | return nil
320 | }
321 |
322 | func isCatchValid(catch []*Catcher) error {
323 | if catch == nil {
324 | return nil
325 | }
326 |
327 | for i, c := range catch {
328 | if err := isErrorEqualsValid(c.ErrorEquals, len(catch)-1 == i); err != nil {
329 | return err
330 | }
331 |
332 | if is.EmptyStr(c.Next) {
333 | return fmt.Errorf("Catcher requires Next")
334 | }
335 | }
336 | return nil
337 | }
338 |
339 | const StatesAll = "States.ALL"
340 | const StatesTimeout = "States.Timeout"
341 | const StatesTaskFailed = "States.TaskFailed"
342 | const StatesPermissions = "States.Permissions"
343 | const StatesResultPathMatchFailure = "States.ResultPathMatchFailure"
344 | const StatesBranchFailed = "States.BranchFailed"
345 | const StatesNoChoiceMatched = "States.NoChoiceMatched"
346 |
347 | func isErrorEqualsValid(errorEquals []*string, last bool) error {
348 | if len(errorEquals) == 0 {
349 | return fmt.Errorf("Retrier requires ErrorEquals")
350 | }
351 |
352 | for _, e := range errorEquals {
353 | // If it is a States. Error, then must match one of the defined values
354 | if strings.HasPrefix(*e, "States.") {
355 | switch *e {
356 | case
357 | StatesAll,
358 | StatesTimeout,
359 | StatesTaskFailed,
360 | StatesPermissions,
361 | StatesResultPathMatchFailure,
362 | StatesBranchFailed,
363 | StatesNoChoiceMatched:
364 | default:
365 | return fmt.Errorf("Unknown States.* error found %q", *e)
366 | }
367 | }
368 |
369 | if *e == StatesAll {
370 | if len(errorEquals) != 1 {
371 | return fmt.Errorf(`"States.ALL" ErrorEquals must be only element in list`)
372 | }
373 |
374 | if !last {
375 | return fmt.Errorf(`"States.ALL" must be last Catcher/Retrier`)
376 | }
377 | }
378 | }
379 |
380 | return nil
381 | }
382 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/succeed_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
7 | "github.com/coinbase/step/utils/to"
8 | "go.uber.org/cadence/workflow"
9 | )
10 |
11 | type SucceedState struct {
12 | stateStr // Include Defaults
13 |
14 | Type *string
15 | Comment *string `json:",omitempty"`
16 |
17 | InputPath *jsonpath.Path `json:",omitempty"`
18 | OutputPath *jsonpath.Path `json:",omitempty"`
19 | }
20 |
21 | func (s *SucceedState) process(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
22 | return input, nil, nil
23 | }
24 |
25 | func (s *SucceedState) Execute(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
26 | return processError(s,
27 | processInputOutput(
28 | s.InputPath,
29 | s.OutputPath,
30 | s.process,
31 | ),
32 | )(ctx, input)
33 | }
34 |
35 | func (s *SucceedState) Validate() error {
36 | s.SetType(to.Strp("Succeed"))
37 |
38 | if err := ValidateNameAndType(s); err != nil {
39 | return fmt.Errorf("%v %v", errorPrefix(s), err)
40 | }
41 |
42 | return nil
43 | }
44 |
45 | func (s *SucceedState) SetType(t *string) {
46 | s.Type = t
47 | }
48 |
49 | func (s *SucceedState) GetType() *string {
50 | return s.Type
51 | }
52 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/succeed_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | var succeedMachine = []byte(`
4 | {
5 | "StartAt": "Example1",
6 | "States": {
7 | "Example1": {
8 | "Type": "Succeed"
9 | }
10 | }
11 | }
12 | `)
13 |
14 | func (s *UnitTestSuite) Test_Workflow_Succeed_State() {
15 | sm, err := FromJSON(succeedMachine)
16 | if err != nil {
17 | s.NoError(err)
18 | return
19 | }
20 |
21 | exampleInput := map[string]interface{}{"test": "example_input"}
22 |
23 | RegisterWorkflow("TestSucceedWorkflow", *sm)
24 |
25 | s.env.ExecuteWorkflow("TestSucceedWorkflow", exampleInput)
26 |
27 | s.True(s.env.IsWorkflowCompleted())
28 | s.NoError(s.env.GetWorkflowError())
29 |
30 | var result map[string]interface{}
31 | err = s.env.GetWorkflowResult(&result)
32 | s.NoError(err)
33 |
34 | s.Equal("example_input", result["test"])
35 | }
36 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/task_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 |
7 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
8 | "github.com/coinbase/step/utils/to"
9 | "go.uber.org/cadence/workflow"
10 | )
11 |
12 | type TaskState struct {
13 | stateStr // Include Defaults
14 |
15 | Type *string
16 | Comment *string `json:",omitempty"`
17 |
18 | InputPath *jsonpath.Path `json:",omitempty"`
19 | OutputPath *jsonpath.Path `json:",omitempty"`
20 | ResultPath *jsonpath.Path `json:",omitempty"`
21 | Parameters interface{} `json:",omitempty"`
22 |
23 | Resource *string `json:",omitempty"`
24 |
25 | Catch []*Catcher `json:",omitempty"`
26 | Retry []*Retrier `json:",omitempty"`
27 |
28 | Next *string `json:",omitempty"`
29 | End *bool `json:",omitempty"`
30 |
31 | TimeoutSeconds int `json:",omitempty"`
32 | HeartbeatSeconds int `json:",omitempty"`
33 | }
34 |
35 | var ErrTaskHandlerNotRegistered = errors.New("handler has not been registered")
36 |
37 | func (s *TaskState) process(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
38 | if globalTaskHandler != nil {
39 | result, err := globalTaskHandler(ctx, *s.Resource, input)
40 | if err != nil {
41 | return nil, nil, err
42 | }
43 | return result, nextState(s.Next, s.End), nil
44 | }
45 |
46 | return nil, nil, ErrTaskHandlerNotRegistered
47 | }
48 |
49 | // Input must include the Task name in $.Task
50 | func (s *TaskState) Execute(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
51 | return processError(s,
52 | processCatcher(s.Catch,
53 | processRetrier(s.Name(), s.Retry,
54 | processInputOutput(
55 | s.InputPath,
56 | s.OutputPath,
57 | processParams(
58 | s.Parameters,
59 | processResult(s.ResultPath, s.process),
60 | ),
61 | ),
62 | ),
63 | ),
64 | )(ctx, input)
65 | }
66 |
67 | func (s *TaskState) Validate() error {
68 | s.SetType(to.Strp("Task"))
69 |
70 | if err := ValidateNameAndType(s); err != nil {
71 | return fmt.Errorf("%v %w", errorPrefix(s), err)
72 | }
73 |
74 | if err := isEndValid(s.Next, s.End); err != nil {
75 | return fmt.Errorf("%v %w", errorPrefix(s), err)
76 | }
77 |
78 | if s.Resource == nil {
79 | return fmt.Errorf("%v Requires Resource", errorPrefix(s))
80 | }
81 |
82 | // TODO: implement custom handlers
83 | //if s.taskHandler != nil {
84 | //}
85 |
86 | if err := isCatchValid(s.Catch); err != nil {
87 | return err
88 | }
89 |
90 | if err := isRetryValid(s.Retry); err != nil {
91 | return err
92 | }
93 |
94 | return nil
95 | }
96 |
97 | func (s *TaskState) SetType(t *string) {
98 | s.Type = t
99 | }
100 |
101 | func (s *TaskState) GetType() *string {
102 | return s.Type
103 | }
104 |
105 | type TaskHandler func(ctx workflow.Context, resource string, input interface{}) (interface{}, error)
106 |
107 | var globalTaskHandler TaskHandler
108 |
109 | // RegisterHandler registers a global handler for tasks. The implementation is left up to importers of this package.
110 | func RegisterHandler(taskHandlerFunc TaskHandler) {
111 | globalTaskHandler = taskHandlerFunc
112 | }
113 |
114 | func DeregisterHandler() {
115 | globalTaskHandler = nil
116 | }
117 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/task_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "errors"
5 | "strings"
6 |
7 | "go.uber.org/cadence/workflow"
8 | )
9 |
10 | var taskMachine = []byte(`
11 | {
12 | "StartAt": "Example1",
13 | "States": {
14 | "Example1": {
15 | "Type": "Task",
16 | "Resource": "arn:aws:resource:example",
17 | "End": true
18 | }
19 | }
20 | }
21 | `)
22 |
23 | func (s *UnitTestSuite) Test_Workflow_Task_State() {
24 | sm, err := FromJSON(taskMachine)
25 | if err != nil {
26 | s.NoError(err)
27 | return
28 | }
29 |
30 | handler := func(ctx workflow.Context, resource string, input interface{}) (interface{}, error) {
31 | s.Equal("arn:aws:resource:example", resource)
32 | output := map[string]interface{}{"test": "example_output"}
33 | return output, nil
34 | }
35 | RegisterHandler(handler)
36 |
37 | exampleInput := map[string]interface{}{"test": "example_input"}
38 |
39 | RegisterWorkflow("TestTaskWorkflow", *sm)
40 |
41 | s.env.ExecuteWorkflow("TestTaskWorkflow", exampleInput)
42 |
43 | s.True(s.env.IsWorkflowCompleted())
44 | s.NoError(s.env.GetWorkflowError())
45 |
46 | var result map[string]interface{}
47 | err = s.env.GetWorkflowResult(&result)
48 | s.NoError(err)
49 |
50 | s.Equal("example_output", result["test"])
51 | }
52 |
53 | func (s *UnitTestSuite) Test_Workflow_Task_State_Error() {
54 | sm, err := FromJSON(taskMachine)
55 | if err != nil {
56 | s.NoError(err)
57 | return
58 | }
59 |
60 | handler := func(ctx workflow.Context, resource string, input interface{}) (interface{}, error) {
61 | s.Equal("arn:aws:resource:example", resource)
62 | return nil, errors.New("task error")
63 | }
64 | RegisterHandler(handler)
65 |
66 | exampleInput := map[string]interface{}{"test": "example_input"}
67 |
68 | RegisterWorkflow("TestTaskErrorWorkflow", *sm)
69 |
70 | s.env.ExecuteWorkflow("TestTaskWorkflow", exampleInput)
71 |
72 | s.True(s.env.IsWorkflowCompleted())
73 | s.Error(s.env.GetWorkflowError())
74 | }
75 |
76 | func (s *UnitTestSuite) Test_Workflow_Task_State_Missing() {
77 | sm, err := FromJSON(taskMachine)
78 | if err != nil {
79 | s.NoError(err)
80 | return
81 | }
82 |
83 | DeregisterHandler()
84 |
85 | exampleInput := map[string]interface{}{"test": "example_input"}
86 |
87 | RegisterWorkflow("TestTaskMissingWorkflow", *sm)
88 |
89 | s.env.ExecuteWorkflow("TestTaskWorkflow", exampleInput)
90 |
91 | s.True(s.env.IsWorkflowCompleted())
92 |
93 | err = s.env.GetWorkflowError()
94 | if s.Error(err) {
95 | s.True(strings.Contains(err.Error(), ErrTaskHandlerNotRegistered.Error()))
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/wait_state.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/checkr/states-language-cadence/pkg/jsonpath"
8 | "github.com/coinbase/step/utils/to"
9 | "go.uber.org/cadence/workflow"
10 | )
11 |
12 | type WaitState struct {
13 | stateStr // Include Defaults
14 |
15 | Type *string
16 | Comment *string `json:",omitempty"`
17 |
18 | InputPath *jsonpath.Path `json:",omitempty"`
19 | OutputPath *jsonpath.Path `json:",omitempty"`
20 |
21 | Seconds *float64 `json:",omitempty"`
22 | SecondsPath *jsonpath.Path `json:",omitempty"`
23 |
24 | Timestamp *time.Time `json:",omitempty"`
25 | TimestampPath *jsonpath.Path `json:",omitempty"`
26 |
27 | Next *string `json:",omitempty"`
28 | End *bool `json:",omitempty"`
29 | }
30 |
31 | func (s *WaitState) process(ctx workflow.Context, input interface{}) (interface{}, *string, error) {
32 | var duration time.Duration
33 |
34 | if s.SecondsPath != nil {
35 | // Validate the path exists
36 | secs, err := s.SecondsPath.GetNumber(input)
37 | if err != nil {
38 | return nil, nil, err
39 | }
40 | duration = time.Duration(*secs) * time.Second
41 |
42 | } else if s.Seconds != nil {
43 | duration = time.Duration(*s.Seconds) * time.Second
44 |
45 | } else if s.TimestampPath != nil {
46 | // Validate the path exists
47 | ts, err := s.TimestampPath.GetTime(input)
48 | if err != nil {
49 | return nil, nil, err
50 | }
51 | now := workflow.Now(ctx).UTC()
52 | duration = ts.Sub(now)
53 |
54 | } else if s.Timestamp != nil {
55 | now := workflow.Now(ctx).UTC()
56 | duration = s.Timestamp.Sub(now)
57 | }
58 |
59 | err := workflow.Sleep(ctx, duration)
60 | if err != nil {
61 | return nil, nil, err
62 | }
63 |
64 | return input, nextState(s.Next, s.End), nil
65 | }
66 |
67 | func (s *WaitState) Execute(ctx workflow.Context, input interface{}) (output interface{}, next *string, err error) {
68 | return processError(s,
69 | processInputOutput(
70 | s.InputPath,
71 | s.OutputPath,
72 | s.process,
73 | ),
74 | )(ctx, input)
75 | }
76 |
77 | func (s *WaitState) Validate() error {
78 | s.SetType(to.Strp("Wait"))
79 |
80 | if err := ValidateNameAndType(s); err != nil {
81 | return fmt.Errorf("%v %v", errorPrefix(s), err)
82 | }
83 |
84 | // Next xor End
85 | if err := isEndValid(s.Next, s.End); err != nil {
86 | return fmt.Errorf("%v %v", errorPrefix(s), err)
87 | }
88 |
89 | exactlyOne := []bool{
90 | s.Seconds != nil,
91 | s.SecondsPath != nil,
92 | s.Timestamp != nil,
93 | s.TimestampPath != nil,
94 | }
95 |
96 | count := 0
97 | for _, c := range exactlyOne {
98 | if c {
99 | count++
100 | }
101 | }
102 |
103 | if count != 1 {
104 | return fmt.Errorf("%v Exactly One (Seconds,SecondsPath,TimeStamp,TimeStampPath)", errorPrefix(s))
105 | }
106 |
107 | return nil
108 | }
109 |
110 | func (s *WaitState) SetType(t *string) {
111 | s.Type = t
112 | }
113 |
114 | func (s *WaitState) GetType() *string {
115 | return s.Type
116 | }
117 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/wait_state_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | var waitMachine = []byte(`
9 | {
10 | "StartAt": "Example1",
11 | "States": {
12 | "Example1": {
13 | "Type": "Wait",
14 | "Seconds" : 60,
15 | "Next": "Example2"
16 | },
17 | "Example2": {
18 | "Type": "Wait",
19 | "SecondsPath" : "$.input_seconds",
20 | "Next": "Example3"
21 | },
22 | "Example3": {
23 | "Type": "Wait",
24 | "Timestamp" : "%s",
25 | "Next": "Example4"
26 | },
27 | "Example4": {
28 | "Type": "Wait",
29 | "TimestampPath" : "$.input_timestamp",
30 | "End": true
31 | }
32 | }
33 | }
34 | `)
35 |
36 | func (s *UnitTestSuite) Test_Workflow_Wait_State() {
37 | workflowName := "TestWaitWorkflow"
38 |
39 | // Set the time to nearest minute. Timestamps only have seconds precision, so if you start the workflow not on a
40 | // minute interval the durations set in wait will chop off milliseconds. Probably fine in production, but makes
41 | // testing harder.
42 | s.env.SetStartTime(time.Now().UTC().Truncate(time.Minute))
43 |
44 | startTime := s.env.Now().UTC()
45 |
46 | inlineTime := startTime.Add(3 * time.Minute).Format(time.RFC3339)
47 | inputTime := startTime.Add(4 * time.Minute).Format(time.RFC3339)
48 |
49 | waitMachine = []byte(fmt.Sprintf(string(waitMachine), inlineTime))
50 |
51 | sm, err := FromJSON(waitMachine)
52 | if err != nil {
53 | s.NoError(err)
54 | return
55 | }
56 |
57 | exampleInput := map[string]interface{}{"input_seconds": 60, "input_timestamp": inputTime}
58 |
59 | // Expected timers
60 | timerCount := 0
61 | s.env.SetOnTimerScheduledListener(func(timerID string, d time.Duration) {
62 | secs := time.Minute
63 | diff := secs - d
64 | s.Equal(time.Duration(0), diff)
65 |
66 | timerCount++
67 | })
68 |
69 | RegisterWorkflow(workflowName, *sm)
70 | s.env.ExecuteWorkflow(workflowName, exampleInput)
71 |
72 | s.True(s.env.IsWorkflowCompleted())
73 | s.NoError(s.env.GetWorkflowError())
74 |
75 | endTime := s.env.Now().UTC()
76 |
77 | // Check that the workflow took 4 minutes
78 | s.Equal(4*time.Minute, endTime.Sub(startTime))
79 |
80 | // Check that the timer ran 4 times
81 | s.Equal(4, timerCount)
82 |
83 | var result map[string]interface{}
84 | err = s.env.GetWorkflowResult(&result)
85 | s.NoError(err)
86 |
87 | s.Equal(float64(60), result["input_seconds"])
88 | s.Equal(inputTime, result["input_timestamp"])
89 | }
90 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/workflow.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "go.uber.org/cadence/workflow"
8 | )
9 |
10 | func Workflow(ctx workflow.Context, sm StateMachine, input interface{}) (interface{}, error) {
11 | ao := workflow.ActivityOptions{
12 | ScheduleToStartTimeout: time.Minute,
13 | StartToCloseTimeout: time.Minute,
14 | HeartbeatTimeout: time.Second * 20,
15 | }
16 | ctx = workflow.WithActivityOptions(ctx, ao)
17 |
18 | output, err := sm.Execute(ctx, input)
19 | return output, err
20 | }
21 |
22 | func RegisterWorkflow(workflowName string, initStateMachine StateMachine) {
23 | workflowFunc := func(ctx workflow.Context, input interface{}) (interface{}, error) {
24 | // Create a local instance of state machine. Workflows that were started with a given machine
25 | // will continue using that machine.
26 | encodedStateMachine := workflow.SideEffect(ctx, func(ctx workflow.Context) interface{} {
27 | return initStateMachine
28 | })
29 |
30 | var sm StateMachine
31 | err := encodedStateMachine.Get(&sm)
32 | if err != nil {
33 | return nil, fmt.Errorf("failed to initialize the state machine: %w", err)
34 | }
35 |
36 | return Workflow(ctx, sm, input)
37 | }
38 | workflow.RegisterWithOptions(workflowFunc, workflow.RegisterOptions{Name: workflowName})
39 | }
40 |
--------------------------------------------------------------------------------
/pkg/aslworkflow/workflow_test.go:
--------------------------------------------------------------------------------
1 | package aslworkflow
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/stretchr/testify/suite"
7 | "go.uber.org/cadence/testsuite"
8 | )
9 |
10 | // This is used to set up a test suite for running workflow tests
11 |
12 | type UnitTestSuite struct {
13 | suite.Suite
14 | testsuite.WorkflowTestSuite
15 |
16 | env *testsuite.TestWorkflowEnvironment
17 | }
18 |
19 | func TestUnitTestSuite(t *testing.T) {
20 | suite.Run(t, new(UnitTestSuite))
21 | }
22 |
23 | func (s *UnitTestSuite) SetupTest() {
24 | s.env = s.NewTestWorkflowEnvironment()
25 | }
26 |
27 | func (s *UnitTestSuite) AfterTest(suiteName, testName string) {
28 | s.env.AssertExpectations(s.T())
29 | }
30 |
--------------------------------------------------------------------------------
/pkg/jsonpath/jsonpath.go:
--------------------------------------------------------------------------------
1 | // Simple Implementation of JSON Path for state machine
2 | package jsonpath
3 |
4 | import (
5 | "encoding/json"
6 | "errors"
7 | "fmt"
8 | "reflect"
9 | "strings"
10 | "time"
11 | )
12 |
13 | /*
14 | The `data` must be from JSON Unmarshal, that way we can guarantee the types:
15 |
16 | bool, for JSON booleans
17 | float64, for JSON numbers
18 | string, for JSON strings
19 | []interface{}, for JSON arrays
20 | map[string]interface{}, for JSON objects
21 | nil for JSON null
22 |
23 | */
24 |
25 | var ErrNotFoundError = errors.New("Not Found")
26 |
27 | type Path struct {
28 | path []string
29 | }
30 |
31 | // NewPath takes string returns JSONPath Object
32 | func NewPath(pathString string) (*Path, error) {
33 | path := Path{}
34 | pathArray, err := ParsePathString(pathString)
35 | path.path = pathArray
36 | return &path, err
37 | }
38 |
39 | // UnmarshalJSON makes a path out of a json string
40 | func (path *Path) UnmarshalJSON(b []byte) error {
41 | var pathString string
42 | err := json.Unmarshal(b, &pathString)
43 |
44 | if err != nil {
45 | return err
46 | }
47 |
48 | pathArray, err := ParsePathString(pathString)
49 |
50 | if err != nil {
51 | return err
52 | }
53 |
54 | path.path = pathArray
55 | return nil
56 | }
57 |
58 | // MarshalJSON converts path to json string
59 | func (path *Path) MarshalJSON() ([]byte, error) {
60 | if len(path.path) == 0 {
61 | return json.Marshal("$")
62 | }
63 | return json.Marshal(path.String())
64 | }
65 |
66 | func (path *Path) String() string {
67 | return fmt.Sprintf("$.%v", strings.Join(path.path[:], "."))
68 | }
69 |
70 | // ParsePathString parses a path string
71 | func ParsePathString(pathString string) ([]string, error) {
72 | // must start with $. otherwise empty path
73 | if pathString == "" || pathString[0:1] != "$" {
74 | return nil, fmt.Errorf("Bad JSON path: must start with $")
75 | }
76 |
77 | if pathString == "$" {
78 | // Default is no path
79 | return []string{}, nil
80 | }
81 |
82 | if len(pathString) < 2 {
83 | // This handles the case for $. or $* which are invalid
84 | return nil, fmt.Errorf("Bad JSON path: cannot not be 2 characters")
85 | }
86 |
87 | head := pathString[2:]
88 | pathArray := strings.Split(head, ".")
89 |
90 | // if path contains an "" error
91 | for _, p := range pathArray {
92 | if p == "" {
93 | return nil, fmt.Errorf("Bad JSON path: has empty element")
94 | }
95 | }
96 | // Simple Path Builder
97 | return pathArray, nil
98 | }
99 |
100 | // PUBLIC METHODS
101 |
102 | // GetTime returns Time from Path
103 | func (path *Path) GetTime(input interface{}) (*time.Time, error) {
104 | outputValue, err := path.Get(input)
105 |
106 | if err != nil {
107 | return nil, fmt.Errorf("GetTime Error %q", err)
108 | }
109 |
110 | var output time.Time
111 | switch outputValueCast := outputValue.(type) {
112 | case string:
113 | output, err = time.Parse(time.RFC3339, outputValueCast)
114 | if err != nil {
115 | return nil, fmt.Errorf("GetTime Error: time error %q", err)
116 | }
117 | default:
118 | return nil, fmt.Errorf("GetTime Error: time must be string")
119 | }
120 |
121 | return &output, nil
122 | }
123 |
124 | // GetBool returns Bool from Path
125 | func (path *Path) GetBool(input interface{}) (*bool, error) {
126 | outputValue, err := path.Get(input)
127 |
128 | if err != nil {
129 | return nil, fmt.Errorf("GetBool Error %q", err)
130 | }
131 |
132 | var output bool
133 | switch outputValueCast := outputValue.(type) {
134 | case bool:
135 | output = outputValueCast
136 | default:
137 | return nil, fmt.Errorf("GetBool Error: must return bool")
138 | }
139 |
140 | return &output, nil
141 | }
142 |
143 | // GetNumber returns Number from Path
144 | func (path *Path) GetNumber(input interface{}) (*float64, error) {
145 | outputValue, err := path.Get(input)
146 |
147 | if err != nil {
148 | return nil, fmt.Errorf("GetFloat Error %q", err)
149 | }
150 |
151 | var output float64
152 | switch outputValueCast := outputValue.(type) {
153 | case float64:
154 | output = outputValueCast
155 | case int:
156 | output = float64(outputValue.(int))
157 | default:
158 | return nil, fmt.Errorf("GetFloat Error: must return float")
159 | }
160 |
161 | return &output, nil
162 | }
163 |
164 | // GetString returns String from Path
165 | func (path *Path) GetString(input interface{}) (*string, error) {
166 | outputValue, err := path.Get(input)
167 |
168 | if err != nil {
169 | return nil, fmt.Errorf("GetString Error %q", err)
170 | }
171 |
172 | var output string
173 | switch outputValueCast := outputValue.(type) {
174 | case string:
175 | output = outputValueCast
176 | default:
177 | return nil, fmt.Errorf("GetString Error: must return string")
178 | }
179 |
180 | return &output, nil
181 | }
182 |
183 | // GetMap returns Map from Path
184 | func (path *Path) GetMap(input interface{}) (output map[string]interface{}, err error) {
185 | outputValue, err := path.Get(input)
186 |
187 | if err != nil {
188 | return nil, fmt.Errorf("GetMap Error %q", err)
189 | }
190 |
191 | switch outputValueCast := outputValue.(type) {
192 | case map[string]interface{}:
193 | output = outputValueCast
194 | default:
195 | return nil, fmt.Errorf("GetMap Error: must return map")
196 | }
197 |
198 | return output, nil
199 | }
200 |
201 | // Get returns interface from Path
202 | func (path *Path) Get(input interface{}) (value interface{}, err error) {
203 | if path == nil {
204 | return input, nil // Default is $
205 | }
206 | return recursiveGet(input, path.path)
207 | }
208 |
209 | // Set sets a Value in a map with Path
210 | func (path *Path) Set(input interface{}, value interface{}) (output interface{}, err error) {
211 | var setPath []string
212 | if path == nil {
213 | setPath = []string{} // default "$"
214 | } else {
215 | setPath = path.path
216 | }
217 |
218 | if len(setPath) == 0 {
219 | // The output is the value
220 | switch valueCast := value.(type) {
221 | case map[string]interface{}:
222 | output = valueCast
223 | return output, nil
224 | case []interface{}:
225 | output = value.([]interface{})
226 | return output, nil
227 | default:
228 | return nil, fmt.Errorf("Cannot Set value %q type %q in root JSON path $", value, reflect.TypeOf(value))
229 | }
230 | }
231 | return recursiveSet(input, value, setPath), nil
232 | }
233 |
234 | // PRIVATE METHODS
235 |
236 | func recursiveSet(data interface{}, value interface{}, path []string) (output interface{}) {
237 | var dataMap map[string]interface{}
238 |
239 | switch dataCast := data.(type) {
240 | case map[string]interface{}:
241 | dataMap = dataCast
242 | default:
243 | // Overwrite current data with new map
244 | // this will work for nil as well
245 | dataMap = make(map[string]interface{})
246 | }
247 |
248 | if len(path) == 1 {
249 | dataMap[path[0]] = value
250 | } else {
251 | dataMap[path[0]] = recursiveSet(dataMap[path[0]], value, path[1:])
252 | }
253 |
254 | return dataMap
255 | }
256 |
257 | func recursiveGet(data interface{}, path []string) (interface{}, error) {
258 | if len(path) == 0 {
259 | return data, nil
260 | }
261 |
262 | if data == nil {
263 | return nil, errors.New("Not Found")
264 | }
265 |
266 | switch dataCast := data.(type) {
267 | case map[string]interface{}:
268 | value, ok := dataCast[path[0]]
269 |
270 | if !ok {
271 | return data, ErrNotFoundError
272 | }
273 |
274 | return recursiveGet(value, path[1:])
275 |
276 | default:
277 | return data, ErrNotFoundError
278 | }
279 | }
280 |
--------------------------------------------------------------------------------
/scripts/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/scripts/.keep
--------------------------------------------------------------------------------
/vendor.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/checkr/states-language-cadence/a7130b9ce30ac0e42aebe39900d6a88bafb93a86/vendor.tar.gz
--------------------------------------------------------------------------------