├── go.sum ├── codecov.yml ├── go.mod ├── Makefile ├── .github └── workflows │ ├── go.yml │ └── codeql-analysis.yml ├── .gitignore ├── hunch_benchmark_test.go ├── example_test.go ├── README.md ├── hunch.go ├── LICENSE └── hunch_test.go /go.sum: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | fixes: 2 | - "/home/runner/work/Hunch/Hunch/::" -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/aaronjan/hunch 2 | 3 | go 1.12 4 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: test 2 | test: 3 | go test -v -race ./... 4 | 5 | .PHONY: test-bench 6 | test-bench: 7 | go test -bench=. 8 | 9 | .PHONY: test-cover 10 | test-cover: 11 | go test -coverprofile=coverage.out 12 | 13 | .PHONY: view-cover 14 | view-cover: 15 | go tool cover -html=coverage.out 16 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | steps: 15 | 16 | - name: Set up Go 1.x 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: ^1.13 20 | id: go 21 | 22 | - name: Check out code into the Go module directory 23 | uses: actions/checkout@v2 24 | 25 | - name: Get dependencies 26 | run: | 27 | go get -v -t -d ./... 28 | if [ -f Gopkg.toml ]; then 29 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 30 | dep ensure 31 | fi 32 | 33 | - name: Test 34 | run: | 35 | go test -v -race -count 20 ./... 36 | go test -coverprofile=coverage.out -covermode=set ./... 37 | pwd 38 | 39 | - name: Codecov 40 | uses: codecov/codecov-action@v1 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # General 15 | .DS_Store 16 | .AppleDouble 17 | .LSOverride 18 | 19 | # Icon must end with two \r 20 | Icon 21 | 22 | 23 | # Thumbnails 24 | ._* 25 | 26 | # Files that might appear in the root of a volume 27 | .DocumentRevisions-V100 28 | .fseventsd 29 | .Spotlight-V100 30 | .TemporaryItems 31 | .Trashes 32 | .VolumeIcon.icns 33 | .com.apple.timemachine.donotpresent 34 | 35 | # Directories potentially created on remote AFP share 36 | .AppleDB 37 | .AppleDesktop 38 | Network Trash Folder 39 | Temporary Items 40 | .apdisk 41 | 42 | # Windows thumbnail cache files 43 | Thumbs.db 44 | Thumbs.db:encryptable 45 | ehthumbs.db 46 | ehthumbs_vista.db 47 | 48 | # Dump file 49 | *.stackdump 50 | 51 | # Folder config file 52 | [Dd]esktop.ini 53 | 54 | # Recycle Bin used on file shares 55 | $RECYCLE.BIN/ 56 | 57 | # Windows Installer files 58 | *.cab 59 | *.msi 60 | *.msix 61 | *.msm 62 | *.msp 63 | 64 | # Windows shortcuts 65 | *.lnk 66 | 67 | # [Project] 68 | /coverage.txt 69 | /coverage.out 70 | -------------------------------------------------------------------------------- /hunch_benchmark_test.go: -------------------------------------------------------------------------------- 1 | package hunch 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | ) 7 | 8 | func BenchmarkTakeWithOnlyOne(b *testing.B) { 9 | rootCtx := context.Background() 10 | 11 | b.ResetTimer() 12 | for i := 0; i < b.N; i++ { 13 | Take( 14 | rootCtx, 15 | 1, 16 | func(ctx context.Context) (interface{}, error) { 17 | return 1, nil 18 | }, 19 | ) 20 | } 21 | } 22 | 23 | func BenchmarkTakeWithFiveExecsThatNeedsOne(b *testing.B) { 24 | rootCtx, cancel := context.WithCancel(context.Background()) 25 | defer cancel() 26 | 27 | b.ResetTimer() 28 | for i := 0; i < b.N; i++ { 29 | Take( 30 | rootCtx, 31 | 1, 32 | func(ctx context.Context) (interface{}, error) { 33 | return 1, nil 34 | }, 35 | func(ctx context.Context) (interface{}, error) { 36 | return 2, nil 37 | }, 38 | func(ctx context.Context) (interface{}, error) { 39 | return 3, nil 40 | }, 41 | func(ctx context.Context) (interface{}, error) { 42 | return 4, nil 43 | }, 44 | func(ctx context.Context) (interface{}, error) { 45 | return 5, nil 46 | }, 47 | ) 48 | } 49 | } 50 | 51 | func BenchmarkTakeWithFiveExecsThatNeedsFive(b *testing.B) { 52 | rootCtx, cancel := context.WithCancel(context.Background()) 53 | defer cancel() 54 | 55 | b.ResetTimer() 56 | for i := 0; i < b.N; i++ { 57 | Take( 58 | rootCtx, 59 | 5, 60 | func(ctx context.Context) (interface{}, error) { 61 | return 1, nil 62 | }, 63 | func(ctx context.Context) (interface{}, error) { 64 | return 2, nil 65 | }, 66 | func(ctx context.Context) (interface{}, error) { 67 | return 3, nil 68 | }, 69 | func(ctx context.Context) (interface{}, error) { 70 | return 4, nil 71 | }, 72 | func(ctx context.Context) (interface{}, error) { 73 | return 5, nil 74 | }, 75 | ) 76 | } 77 | } 78 | 79 | func BenchmarkAllWithFiveExecs(b *testing.B) { 80 | rootCtx, cancel := context.WithCancel(context.Background()) 81 | defer cancel() 82 | 83 | b.ResetTimer() 84 | for i := 0; i < b.N; i++ { 85 | All( 86 | rootCtx, 87 | func(ctx context.Context) (interface{}, error) { 88 | return 1, nil 89 | }, 90 | func(ctx context.Context) (interface{}, error) { 91 | return 2, nil 92 | }, 93 | func(ctx context.Context) (interface{}, error) { 94 | return 3, nil 95 | }, 96 | func(ctx context.Context) (interface{}, error) { 97 | return 4, nil 98 | }, 99 | func(ctx context.Context) (interface{}, error) { 100 | return 5, nil 101 | }, 102 | ) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 4 * * 4' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['go'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | with: 35 | # We must fetch at least the immediate parents so that if this is 36 | # a pull request then we can checkout the head. 37 | fetch-depth: 2 38 | 39 | # If this run was triggered by a pull request event, then checkout 40 | # the head of the pull request instead of the merge commit. 41 | - run: git checkout HEAD^2 42 | if: ${{ github.event_name == 'pull_request' }} 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package hunch_test 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/aaronjan/hunch" 9 | ) 10 | 11 | func ExampleAll() { 12 | ctx := context.Background() 13 | r, err := hunch.All( 14 | ctx, 15 | func(ctx context.Context) (interface{}, error) { 16 | time.Sleep(300 * time.Millisecond) 17 | return 1, nil 18 | }, 19 | func(ctx context.Context) (interface{}, error) { 20 | time.Sleep(200 * time.Millisecond) 21 | return 2, nil 22 | }, 23 | func(ctx context.Context) (interface{}, error) { 24 | time.Sleep(100 * time.Millisecond) 25 | return 3, nil 26 | }, 27 | ) 28 | 29 | fmt.Println(r, err) 30 | // Output: 31 | // [1 2 3] 32 | } 33 | 34 | func ExampleTake() { 35 | ctx := context.Background() 36 | r, err := hunch.Take( 37 | ctx, 38 | // Only need the first 2 values. 39 | 2, 40 | func(ctx context.Context) (interface{}, error) { 41 | time.Sleep(300 * time.Millisecond) 42 | return 1, nil 43 | }, 44 | func(ctx context.Context) (interface{}, error) { 45 | time.Sleep(200 * time.Millisecond) 46 | return 2, nil 47 | }, 48 | func(ctx context.Context) (interface{}, error) { 49 | time.Sleep(100 * time.Millisecond) 50 | return 3, nil 51 | }, 52 | ) 53 | 54 | fmt.Println(r, err) 55 | // Output: 56 | // [3 2] 57 | } 58 | 59 | func ExampleLast() { 60 | ctx := context.Background() 61 | r, err := hunch.Last( 62 | ctx, 63 | // Only need the last 2 values. 64 | 2, 65 | func(ctx context.Context) (interface{}, error) { 66 | time.Sleep(300 * time.Millisecond) 67 | return 1, nil 68 | }, 69 | func(ctx context.Context) (interface{}, error) { 70 | time.Sleep(200 * time.Millisecond) 71 | return 2, nil 72 | }, 73 | func(ctx context.Context) (interface{}, error) { 74 | time.Sleep(100 * time.Millisecond) 75 | return 3, nil 76 | }, 77 | ) 78 | 79 | fmt.Println(r, err) 80 | // Output: 81 | // [2 1] 82 | } 83 | 84 | func ExampleWaterfall() { 85 | ctx := context.Background() 86 | r, err := hunch.Waterfall( 87 | ctx, 88 | func(ctx context.Context, n interface{}) (interface{}, error) { 89 | return 1, nil 90 | }, 91 | func(ctx context.Context, n interface{}) (interface{}, error) { 92 | return n.(int) + 1, nil 93 | }, 94 | func(ctx context.Context, n interface{}) (interface{}, error) { 95 | return n.(int) + 1, nil 96 | }, 97 | ) 98 | 99 | fmt.Println(r, err) 100 | // Output: 101 | // 3 102 | } 103 | 104 | func ExampleRetry() { 105 | count := 0 106 | getStuffFromAPI := func() (int, error) { 107 | if count == 5 { 108 | return 1, nil 109 | } 110 | count++ 111 | 112 | return 0, fmt.Errorf("timeout") 113 | } 114 | 115 | ctx := context.Background() 116 | r, err := hunch.Retry( 117 | ctx, 118 | 10, 119 | func(ctx context.Context) (interface{}, error) { 120 | rs, err := getStuffFromAPI() 121 | 122 | return rs, err 123 | }, 124 | ) 125 | 126 | fmt.Println(r, err, count) 127 | // Output: 128 | // 1 5 129 | } 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Housekeeper 3 | 4 | 5 | ![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/aaronjan/hunch.svg) 6 | ![Build status](https://github.com/aaronjan/hunch/workflows/Go/badge.svg?branch=master) 7 | [![codecov](https://codecov.io/gh/AaronJan/Hunch/branch/master/graph/badge.svg)](https://codecov.io/gh/AaronJan/Hunch) 8 | [![Go Report Card](https://goreportcard.com/badge/github.com/aaronjan/hunch)](https://goreportcard.com/report/github.com/aaronjan/hunch) 9 | ![GitHub](https://img.shields.io/github/license/aaronjan/hunch.svg) 10 | [![GoDoc](https://godoc.org/github.com/aaronjan/hunch?status.svg)](https://godoc.org/github.com/aaronjan/hunch) 11 | 12 | # Hunch 13 | 14 | Hunch provides functions like: `All`, `First`, `Retry`, `Waterfall` etc., that makes asynchronous flow control more intuitive. 15 | 16 | ## About Hunch 17 | 18 | Go have several concurrency patterns, here're some articles: 19 | 20 | * https://blog.golang.org/pipelines 21 | * https://blog.golang.org/context 22 | * https://blog.golang.org/go-concurrency-patterns-timing-out-and 23 | * https://blog.golang.org/advanced-go-concurrency-patterns 24 | 25 | But nowadays, using the `context` package is the most powerful pattern. 26 | 27 | So base on `context`, Hunch provides functions that can help you deal with complex asynchronous logics with ease. 28 | 29 | ## Usage 30 | 31 | ### Installation 32 | 33 | #### `go get` 34 | 35 | ```shell 36 | $ go get -u -v github.com/aaronjan/hunch 37 | ``` 38 | 39 | #### `go mod` (Recommended) 40 | 41 | ```go 42 | import "github.com/aaronjan/hunch" 43 | ``` 44 | 45 | ```shell 46 | $ go mod tidy 47 | ``` 48 | 49 | ### Types 50 | 51 | ```go 52 | type Executable func(context.Context) (interface{}, error) 53 | 54 | type ExecutableInSequence func(context.Context, interface{}) (interface{}, error) 55 | ``` 56 | 57 | ### API 58 | 59 | #### All 60 | 61 | ```go 62 | func All(parentCtx context.Context, execs ...Executable) ([]interface{}, error) 63 | ``` 64 | 65 | All returns all the outputs from all Executables, order guaranteed. 66 | 67 | ##### Examples 68 | 69 | ```go 70 | ctx := context.Background() 71 | r, err := hunch.All( 72 | ctx, 73 | func(ctx context.Context) (interface{}, error) { 74 | time.Sleep(300 * time.Millisecond) 75 | return 1, nil 76 | }, 77 | func(ctx context.Context) (interface{}, error) { 78 | time.Sleep(200 * time.Millisecond) 79 | return 2, nil 80 | }, 81 | func(ctx context.Context) (interface{}, error) { 82 | time.Sleep(100 * time.Millisecond) 83 | return 3, nil 84 | }, 85 | ) 86 | 87 | fmt.Println(r, err) 88 | // Output: 89 | // [1 2 3] 90 | ``` 91 | 92 | #### Take 93 | 94 | ```go 95 | func Take(parentCtx context.Context, num int, execs ...Executable) ([]interface{}, error) 96 | ``` 97 | 98 | Take returns the first `num` values outputted by the Executables. 99 | 100 | ##### Examples 101 | 102 | ```go 103 | ctx := context.Background() 104 | r, err := hunch.Take( 105 | ctx, 106 | // Only need the first 2 values. 107 | 2, 108 | func(ctx context.Context) (interface{}, error) { 109 | time.Sleep(300 * time.Millisecond) 110 | return 1, nil 111 | }, 112 | func(ctx context.Context) (interface{}, error) { 113 | time.Sleep(200 * time.Millisecond) 114 | return 2, nil 115 | }, 116 | func(ctx context.Context) (interface{}, error) { 117 | time.Sleep(100 * time.Millisecond) 118 | return 3, nil 119 | }, 120 | ) 121 | 122 | fmt.Println(r, err) 123 | // Output: 124 | // [3 2] 125 | ``` 126 | 127 | #### Last 128 | 129 | ```go 130 | func Last(parentCtx context.Context, num int, execs ...Executable) ([]interface{}, error) 131 | ``` 132 | 133 | Last returns the last `num` values outputted by the Executables. 134 | 135 | ##### Examples 136 | 137 | ```go 138 | ctx := context.Background() 139 | r, err := hunch.Last( 140 | ctx, 141 | // Only need the last 2 values. 142 | 2, 143 | func(ctx context.Context) (interface{}, error) { 144 | time.Sleep(300 * time.Millisecond) 145 | return 1, nil 146 | }, 147 | func(ctx context.Context) (interface{}, error) { 148 | time.Sleep(200 * time.Millisecond) 149 | return 2, nil 150 | }, 151 | func(ctx context.Context) (interface{}, error) { 152 | time.Sleep(100 * time.Millisecond) 153 | return 3, nil 154 | }, 155 | ) 156 | 157 | fmt.Println(r, err) 158 | // Output: 159 | // [2 1] 160 | ``` 161 | 162 | #### Waterfall 163 | 164 | ```go 165 | func Waterfall(parentCtx context.Context, execs ...ExecutableInSequence) (interface{}, error) 166 | ``` 167 | 168 | Waterfall runs `ExecutableInSequence`s one by one, passing previous result to next Executable as input. When an error occurred, it stop the process then returns the error. When the parent Context canceled, it returns the `Err()` of it immediately. 169 | 170 | ##### Examples 171 | 172 | ```go 173 | ctx := context.Background() 174 | r, err := hunch.Waterfall( 175 | ctx, 176 | func(ctx context.Context, n interface{}) (interface{}, error) { 177 | return 1, nil 178 | }, 179 | func(ctx context.Context, n interface{}) (interface{}, error) { 180 | return n.(int) + 1, nil 181 | }, 182 | func(ctx context.Context, n interface{}) (interface{}, error) { 183 | return n.(int) + 1, nil 184 | }, 185 | ) 186 | 187 | fmt.Println(r, err) 188 | // Output: 189 | // 3 190 | ``` 191 | 192 | #### Retry 193 | 194 | ```go 195 | func Retry(parentCtx context.Context, retries int, fn Executable) (interface{}, error) 196 | ``` 197 | 198 | Retry attempts to get a value from an Executable instead of an Error. It will keeps re-running the Executable when failed no more than `retries` times. Also, when the parent Context canceled, it returns the `Err()` of it immediately. 199 | 200 | ##### Examples 201 | 202 | ```go 203 | count := 0 204 | getStuffFromAPI := func() (int, error) { 205 | if count == 5 { 206 | return 1, nil 207 | } 208 | count++ 209 | 210 | return 0, fmt.Errorf("timeout") 211 | } 212 | 213 | ctx := context.Background() 214 | r, err := hunch.Retry( 215 | ctx, 216 | 10, 217 | func(ctx context.Context) (interface{}, error) { 218 | rs, err := getStuffFromAPI() 219 | 220 | return rs, err 221 | }, 222 | ) 223 | 224 | fmt.Println(r, err, count) 225 | // Output: 226 | // 1 5 227 | ``` 228 | 229 | ## Credits 230 | 231 | Heavily inspired by [Async](https://github.com/caolan/async/) and [ReactiveX](http://reactivex.io/). 232 | 233 | ## Licence 234 | 235 | [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0) 236 | -------------------------------------------------------------------------------- /hunch.go: -------------------------------------------------------------------------------- 1 | // Package hunch provides functions like: `All`, `First`, `Retry`, `Waterfall` etc., that makes asynchronous flow control more intuitive. 2 | package hunch 3 | 4 | import ( 5 | "context" 6 | "fmt" 7 | "sort" 8 | "sync" 9 | ) 10 | 11 | // Executable represents a singular logic block. 12 | // It can be used with several functions. 13 | type Executable func(context.Context) (interface{}, error) 14 | 15 | // ExecutableInSequence represents one of a sequence of logic blocks. 16 | type ExecutableInSequence func(context.Context, interface{}) (interface{}, error) 17 | 18 | // IndexedValue stores the output of Executables, 19 | // along with the index of the source Executable for ordering. 20 | type IndexedValue struct { 21 | Index int 22 | Value interface{} 23 | } 24 | 25 | // IndexedExecutableOutput stores both output and error values from a Excetable. 26 | type IndexedExecutableOutput struct { 27 | Value IndexedValue 28 | Err error 29 | } 30 | 31 | func pluckVals(iVals []IndexedValue) []interface{} { 32 | vals := []interface{}{} 33 | for _, val := range iVals { 34 | vals = append(vals, val.Value) 35 | } 36 | 37 | return vals 38 | } 39 | 40 | func sortIdxVals(iVals []IndexedValue) []IndexedValue { 41 | sorted := make([]IndexedValue, len(iVals)) 42 | copy(sorted, iVals) 43 | sort.SliceStable( 44 | sorted, 45 | func(i, j int) bool { 46 | return sorted[i].Index < sorted[j].Index 47 | }, 48 | ) 49 | 50 | return sorted 51 | } 52 | 53 | // Take returns the first `num` values outputted by the Executables. 54 | func Take(parentCtx context.Context, num int, execs ...Executable) ([]interface{}, error) { 55 | execCount := len(execs) 56 | 57 | if num > execCount { 58 | num = execCount 59 | } 60 | 61 | // Create a new sub-context for possible cancelation. 62 | ctx, cancel := context.WithCancel(parentCtx) 63 | defer cancel() 64 | 65 | output := make(chan IndexedExecutableOutput, 1) 66 | go runExecs(ctx, output, execs) 67 | 68 | fail := make(chan error, 1) 69 | success := make(chan []IndexedValue, 1) 70 | go takeUntilEnough(fail, success, min(len(execs), num), output) 71 | 72 | select { 73 | 74 | case <-parentCtx.Done(): 75 | // Stub comment to fix a test coverage bug. 76 | return nil, parentCtx.Err() 77 | 78 | case err := <-fail: 79 | cancel() 80 | if parentCtxErr := parentCtx.Err(); parentCtxErr != nil { 81 | return nil, parentCtxErr 82 | } 83 | return nil, err 84 | 85 | case uVals := <-success: 86 | cancel() 87 | return pluckVals(uVals), nil 88 | } 89 | } 90 | 91 | func runExecs(ctx context.Context, output chan<- IndexedExecutableOutput, execs []Executable) { 92 | var wg sync.WaitGroup 93 | for i, exec := range execs { 94 | wg.Add(1) 95 | 96 | go func(i int, exec Executable) { 97 | val, err := exec(ctx) 98 | if err != nil { 99 | output <- IndexedExecutableOutput{ 100 | IndexedValue{i, nil}, 101 | err, 102 | } 103 | wg.Done() 104 | return 105 | } 106 | 107 | output <- IndexedExecutableOutput{ 108 | IndexedValue{i, val}, 109 | nil, 110 | } 111 | wg.Done() 112 | }(i, exec) 113 | } 114 | 115 | wg.Wait() 116 | close(output) 117 | } 118 | 119 | func takeUntilEnough(fail chan error, success chan []IndexedValue, num int, output chan IndexedExecutableOutput) { 120 | uVals := make([]IndexedValue, num) 121 | 122 | enough := false 123 | outputCount := 0 124 | for r := range output { 125 | if enough { 126 | continue 127 | } 128 | 129 | if r.Err != nil { 130 | enough = true 131 | fail <- r.Err 132 | continue 133 | } 134 | 135 | uVals[outputCount] = r.Value 136 | outputCount++ 137 | 138 | if outputCount == num { 139 | enough = true 140 | success <- uVals 141 | continue 142 | } 143 | } 144 | } 145 | 146 | // All returns all the outputs from all Executables, order guaranteed. 147 | func All(parentCtx context.Context, execs ...Executable) ([]interface{}, error) { 148 | // Create a new sub-context for possible cancelation. 149 | ctx, cancel := context.WithCancel(parentCtx) 150 | defer cancel() 151 | 152 | output := make(chan IndexedExecutableOutput, 1) 153 | go runExecs(ctx, output, execs) 154 | 155 | fail := make(chan error, 1) 156 | success := make(chan []IndexedValue, 1) 157 | go takeUntilEnough(fail, success, len(execs), output) 158 | 159 | select { 160 | 161 | case <-parentCtx.Done(): 162 | // Stub comment to fix a test coverage bug. 163 | return nil, parentCtx.Err() 164 | 165 | case err := <-fail: 166 | cancel() 167 | if parentCtxErr := parentCtx.Err(); parentCtxErr != nil { 168 | return nil, parentCtxErr 169 | } 170 | return nil, err 171 | 172 | case uVals := <-success: 173 | cancel() 174 | return pluckVals(sortIdxVals(uVals)), nil 175 | } 176 | } 177 | 178 | /* 179 | Last returns the last `num` values outputted by the Executables. 180 | */ 181 | func Last(parentCtx context.Context, num int, execs ...Executable) ([]interface{}, error) { 182 | execCount := len(execs) 183 | if num > execCount { 184 | num = execCount 185 | } 186 | start := execCount - num 187 | 188 | vals, err := Take(parentCtx, execCount, execs...) 189 | if err != nil { 190 | return nil, err 191 | } 192 | 193 | return vals[start:], err 194 | } 195 | 196 | // MaxRetriesExceededError stores how many times did an Execution run before exceeding the limit. 197 | // The retries field holds the value. 198 | type MaxRetriesExceededError struct { 199 | retries int 200 | } 201 | 202 | func (err MaxRetriesExceededError) Error() string { 203 | var word string 204 | switch err.retries { 205 | case 0: 206 | word = "infinity" 207 | case 1: 208 | word = "1 time" 209 | default: 210 | word = fmt.Sprintf("%v times", err.retries) 211 | } 212 | 213 | return fmt.Sprintf("Max retries exceeded (%v).\n", word) 214 | } 215 | 216 | // Retry attempts to get a value from an Executable instead of an Error. 217 | // It will keeps re-running the Executable when failed no more than `retries` times. 218 | // Also, when the parent Context canceled, it returns the `Err()` of it immediately. 219 | func Retry(parentCtx context.Context, retries int, fn Executable) (interface{}, error) { 220 | ctx, cancel := context.WithCancel(parentCtx) 221 | defer cancel() 222 | 223 | c := 0 224 | fail := make(chan error, 1) 225 | success := make(chan interface{}, 1) 226 | 227 | for { 228 | go func() { 229 | val, err := fn(ctx) 230 | if err != nil { 231 | fail <- err 232 | return 233 | } 234 | success <- val 235 | }() 236 | 237 | select { 238 | // 239 | case <-parentCtx.Done(): 240 | // Stub comment to fix a test coverage bug. 241 | return nil, parentCtx.Err() 242 | 243 | case <-fail: 244 | if parentCtxErr := parentCtx.Err(); parentCtxErr != nil { 245 | return nil, parentCtxErr 246 | } 247 | 248 | c++ 249 | if retries == 0 || c < retries { 250 | continue 251 | } 252 | return nil, MaxRetriesExceededError{c} 253 | 254 | case val := <-success: 255 | return val, nil 256 | } 257 | } 258 | } 259 | 260 | // Waterfall runs `ExecutableInSequence`s one by one, 261 | // passing previous result to next Executable as input. 262 | // When an error occurred, it stop the process then returns the error. 263 | // When the parent Context canceled, it returns the `Err()` of it immediately. 264 | func Waterfall(parentCtx context.Context, execs ...ExecutableInSequence) (interface{}, error) { 265 | ctx, cancel := context.WithCancel(parentCtx) 266 | defer cancel() 267 | 268 | var lastVal interface{} 269 | execCount := len(execs) 270 | i := 0 271 | fail := make(chan error, 1) 272 | success := make(chan interface{}, 1) 273 | 274 | for { 275 | go func() { 276 | val, err := execs[i](ctx, lastVal) 277 | if err != nil { 278 | fail <- err 279 | return 280 | } 281 | success <- val 282 | }() 283 | 284 | select { 285 | 286 | case <-parentCtx.Done(): 287 | // Stub comment to fix a test coverage bug. 288 | return nil, parentCtx.Err() 289 | 290 | case err := <-fail: 291 | if parentCtxErr := parentCtx.Err(); parentCtxErr != nil { 292 | return nil, parentCtxErr 293 | } 294 | 295 | return nil, err 296 | 297 | case val := <-success: 298 | lastVal = val 299 | i++ 300 | if i == execCount { 301 | return val, nil 302 | } 303 | 304 | continue 305 | } 306 | } 307 | } 308 | 309 | func min(x, y int) int { 310 | if x > y { 311 | return y 312 | } 313 | return x 314 | } 315 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /hunch_test.go: -------------------------------------------------------------------------------- 1 | package hunch 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "reflect" 7 | "sync/atomic" 8 | "testing" 9 | "time" 10 | ) 11 | 12 | type AppError struct { 13 | } 14 | 15 | func (err AppError) Error() string { 16 | return "app error!" 17 | } 18 | 19 | type MultiReturns struct { 20 | Val interface{} 21 | Err error 22 | } 23 | 24 | func isSlice(v interface{}) bool { 25 | rv := reflect.ValueOf(v) 26 | return rv.Kind() == reflect.Slice 27 | } 28 | 29 | func TestTake_ShouldWorksAsExpected(t *testing.T) { 30 | t.Parallel() 31 | 32 | rootCtx := context.Background() 33 | ch := make(chan MultiReturns) 34 | go func() { 35 | r, err := Take( 36 | rootCtx, 37 | 3, 38 | func(ctx context.Context) (interface{}, error) { 39 | time.Sleep(200 * time.Millisecond) 40 | return 1, nil 41 | }, 42 | func(ctx context.Context) (interface{}, error) { 43 | time.Sleep(100 * time.Millisecond) 44 | return 2, nil 45 | }, 46 | func(ctx context.Context) (interface{}, error) { 47 | <-time.After(300 * time.Millisecond) 48 | return 3, nil 49 | }, 50 | ) 51 | 52 | ch <- MultiReturns{r, err} 53 | close(ch) 54 | }() 55 | 56 | r := <-ch 57 | if r.Err != nil { 58 | t.Errorf("Gets an error: %v\n", r.Err) 59 | } 60 | 61 | rs := []int{} 62 | for _, v := range r.Val.([]interface{}) { 63 | rs = append(rs, v.(int)) 64 | } 65 | 66 | equal := reflect.DeepEqual([]int{2, 1, 3}, rs) 67 | if !equal { 68 | t.Errorf("Execution order is wrong, gets: %+v\n", rs) 69 | } 70 | } 71 | 72 | func TestTake_ShouldJustTakeAll(t *testing.T) { 73 | t.Parallel() 74 | 75 | rootCtx := context.Background() 76 | ch := make(chan MultiReturns) 77 | go func() { 78 | r, err := Take( 79 | rootCtx, 80 | 100, 81 | func(ctx context.Context) (interface{}, error) { 82 | return 1, nil 83 | }, 84 | func(ctx context.Context) (interface{}, error) { 85 | return 2, nil 86 | }, 87 | func(ctx context.Context) (interface{}, error) { 88 | return 3, nil 89 | }, 90 | ) 91 | 92 | ch <- MultiReturns{r, err} 93 | close(ch) 94 | }() 95 | 96 | r := <-ch 97 | if r.Err != nil { 98 | t.Errorf("Gets an error: %v\n", r.Err) 99 | } 100 | 101 | rs := []int{} 102 | for _, v := range r.Val.([]interface{}) { 103 | rs = append(rs, v.(int)) 104 | } 105 | 106 | if len(rs) != 3 { 107 | t.Errorf("Should return 3 results, but gets: %+v\n", rs) 108 | } 109 | } 110 | 111 | func TestTake_ShouldLimitResults(t *testing.T) { 112 | t.Parallel() 113 | 114 | rootCtx := context.Background() 115 | ch := make(chan MultiReturns) 116 | go func() { 117 | r, err := Take( 118 | rootCtx, 119 | 2, 120 | func(ctx context.Context) (interface{}, error) { 121 | time.Sleep(200 * time.Millisecond) 122 | return 1, nil 123 | }, 124 | func(ctx context.Context) (interface{}, error) { 125 | time.Sleep(100 * time.Millisecond) 126 | return 2, nil 127 | }, 128 | func(ctx context.Context) (interface{}, error) { 129 | <-time.After(300 * time.Millisecond) 130 | return 3, nil 131 | }, 132 | ) 133 | 134 | ch <- MultiReturns{r, err} 135 | close(ch) 136 | }() 137 | 138 | r := <-ch 139 | rs := []int{} 140 | for _, v := range r.Val.([]interface{}) { 141 | rs = append(rs, v.(int)) 142 | } 143 | 144 | equal := reflect.DeepEqual([]int{2, 1}, rs) 145 | if !equal { 146 | t.Errorf("Execution order is wrong, gets: %+v\n", rs) 147 | } 148 | } 149 | 150 | func TestTake_ShouldCancelWhenOneExecutableReturnedError(t *testing.T) { 151 | t.Parallel() 152 | 153 | rootCtx := context.Background() 154 | ch := make(chan MultiReturns) 155 | go func() { 156 | r, err := Take( 157 | rootCtx, 158 | 3, 159 | func(ctx context.Context) (interface{}, error) { 160 | time.Sleep(100 * time.Millisecond) 161 | return 1, nil 162 | }, 163 | func(ctx context.Context) (interface{}, error) { 164 | time.Sleep(200 * time.Millisecond) 165 | return 0, AppError{} 166 | }, 167 | func(ctx context.Context) (interface{}, error) { 168 | time.Sleep(200 * time.Millisecond) 169 | return 3, nil 170 | }, 171 | ) 172 | 173 | ch <- MultiReturns{r, err} 174 | close(ch) 175 | }() 176 | 177 | r := <-ch 178 | if !isSlice(r.Val) || len(r.Val.([]interface{})) != 0 { 179 | t.Errorf("Return Value should be default, gets: \"%v\"\n", r.Val) 180 | } 181 | if r.Err == nil { 182 | t.Errorf("Should returns an Error, gets `nil`\n") 183 | } 184 | } 185 | 186 | func TestTake_ShouldCancelWhenRootCanceled(t *testing.T) { 187 | t.Parallel() 188 | 189 | rootCtx, cancel := context.WithCancel(context.Background()) 190 | ch := make(chan MultiReturns) 191 | go func() { 192 | r, err := Take( 193 | rootCtx, 194 | 3, 195 | func(ctx context.Context) (interface{}, error) { 196 | time.Sleep(100 * time.Millisecond) 197 | return 1, nil 198 | }, 199 | func(ctx context.Context) (interface{}, error) { 200 | time.Sleep(200 * time.Millisecond) 201 | return 2, nil 202 | }, 203 | func(ctx context.Context) (interface{}, error) { 204 | select { 205 | case <-ctx.Done(): 206 | return nil, AppError{} 207 | case <-time.After(300 * time.Millisecond): 208 | return 3, nil 209 | } 210 | }, 211 | ) 212 | 213 | ch <- MultiReturns{r, err} 214 | close(ch) 215 | }() 216 | 217 | go func() { 218 | time.Sleep(150 * time.Millisecond) 219 | cancel() 220 | }() 221 | 222 | r := <-ch 223 | if !isSlice(r.Val) || len(r.Val.([]interface{})) != 0 { 224 | t.Errorf("Return Value should be default, gets: \"%v\"\n", r.Val) 225 | } 226 | if r.Err == nil { 227 | t.Errorf("Should returns an Error, gets `nil`\n") 228 | } 229 | } 230 | 231 | func TestAll_ShouldWorksAsExpected(t *testing.T) { 232 | t.Parallel() 233 | 234 | rootCtx := context.Background() 235 | ch := make(chan MultiReturns) 236 | go func() { 237 | r, err := All( 238 | rootCtx, 239 | func(ctx context.Context) (interface{}, error) { 240 | time.Sleep(200 * time.Millisecond) 241 | return 1, nil 242 | }, 243 | func(ctx context.Context) (interface{}, error) { 244 | time.Sleep(100 * time.Millisecond) 245 | return 2, nil 246 | }, 247 | func(ctx context.Context) (interface{}, error) { 248 | <-time.After(300 * time.Millisecond) 249 | return 3, nil 250 | }, 251 | ) 252 | 253 | ch <- MultiReturns{r, err} 254 | close(ch) 255 | }() 256 | 257 | r := <-ch 258 | if r.Err != nil { 259 | t.Errorf("Gets an error: %v\n", r.Err) 260 | } 261 | 262 | rs := []int{} 263 | for _, v := range r.Val.([]interface{}) { 264 | rs = append(rs, v.(int)) 265 | } 266 | 267 | equal := reflect.DeepEqual([]int{1, 2, 3}, rs) 268 | if !equal { 269 | t.Errorf("Execution order is wrong, gets: %+v\n", rs) 270 | } 271 | } 272 | 273 | func TestAll_WhenOutOfOrder(t *testing.T) { 274 | t.Parallel() 275 | 276 | rootCtx := context.Background() 277 | ch := make(chan MultiReturns) 278 | go func() { 279 | r, err := All( 280 | rootCtx, 281 | func(ctx context.Context) (interface{}, error) { 282 | time.Sleep(200 * time.Millisecond) 283 | return 1, nil 284 | }, 285 | func(ctx context.Context) (interface{}, error) { 286 | time.Sleep(300 * time.Millisecond) 287 | return 2, nil 288 | }, 289 | func(ctx context.Context) (interface{}, error) { 290 | <-time.After(100 * time.Millisecond) 291 | return 3, nil 292 | }, 293 | ) 294 | 295 | ch <- MultiReturns{r, err} 296 | close(ch) 297 | }() 298 | 299 | r := <-ch 300 | if r.Err != nil { 301 | t.Errorf("Gets an error: %v\n", r.Err) 302 | } 303 | 304 | rs := []int{} 305 | for _, v := range r.Val.([]interface{}) { 306 | rs = append(rs, v.(int)) 307 | } 308 | 309 | equal := reflect.DeepEqual([]int{1, 2, 3}, rs) 310 | if !equal { 311 | t.Errorf("Execution order is wrong, gets: %+v\n", rs) 312 | } 313 | } 314 | 315 | func TestAll_WhenRootCtxCanceled(t *testing.T) { 316 | t.Parallel() 317 | 318 | rootCtx, cancel := context.WithCancel(context.Background()) 319 | ch := make(chan MultiReturns) 320 | go func() { 321 | r, err := All( 322 | rootCtx, 323 | func(ctx context.Context) (interface{}, error) { 324 | time.Sleep(100 * time.Millisecond) 325 | return 1, nil 326 | }, 327 | func(ctx context.Context) (interface{}, error) { 328 | time.Sleep(200 * time.Millisecond) 329 | return 2, nil 330 | }, 331 | func(ctx context.Context) (interface{}, error) { 332 | select { 333 | case <-ctx.Done(): 334 | return nil, AppError{} 335 | case <-time.After(300 * time.Millisecond): 336 | return 3, nil 337 | } 338 | }, 339 | ) 340 | 341 | ch <- MultiReturns{r, err} 342 | close(ch) 343 | }() 344 | 345 | go func() { 346 | time.Sleep(150 * time.Millisecond) 347 | cancel() 348 | }() 349 | 350 | r := <-ch 351 | if !isSlice(r.Val) || len(r.Val.([]interface{})) != 0 { 352 | t.Errorf("Return Value should be default, gets: \"%v\"\n", r.Val) 353 | } 354 | if r.Err == nil { 355 | t.Errorf("Should returns an Error, gets `nil`\n") 356 | } 357 | } 358 | 359 | func TestAll_WhenAnySubFunctionFailed(t *testing.T) { 360 | t.Parallel() 361 | 362 | rootCtx, cancel := context.WithCancel(context.Background()) 363 | defer cancel() 364 | 365 | ch := make(chan MultiReturns) 366 | go func() { 367 | r, err := All( 368 | rootCtx, 369 | func(ctx context.Context) (interface{}, error) { 370 | time.Sleep(100 * time.Millisecond) 371 | return 1, nil 372 | }, 373 | func(ctx context.Context) (interface{}, error) { 374 | time.Sleep(200 * time.Millisecond) 375 | return 2, nil 376 | }, 377 | func(ctx context.Context) (interface{}, error) { 378 | time.Sleep(300 * time.Millisecond) 379 | return nil, AppError{} 380 | }, 381 | ) 382 | 383 | ch <- MultiReturns{r, err} 384 | close(ch) 385 | }() 386 | 387 | r := <-ch 388 | if !isSlice(r.Val) || len(r.Val.([]interface{})) != 0 { 389 | t.Errorf("Return Value should be default, gets: \"%v\"\n", r.Val) 390 | } 391 | if r.Err == nil { 392 | t.Errorf("Should returns an Error, gets `nil`\n") 393 | } 394 | if r.Err.Error() != "app error!" { 395 | t.Errorf("Should returns an AppError, gets \"%v\"\n", r.Err.Error()) 396 | } 397 | } 398 | 399 | func TestRetry_WithNoFailure(t *testing.T) { 400 | t.Parallel() 401 | 402 | times := 0 403 | expect := 1 404 | 405 | rootCtx, cancel := context.WithCancel(context.Background()) 406 | defer cancel() 407 | 408 | ch := make(chan MultiReturns) 409 | go func() { 410 | r, err := Retry( 411 | rootCtx, 412 | 10, 413 | func(ctx context.Context) (interface{}, error) { 414 | times++ 415 | 416 | time.Sleep(100 * time.Millisecond) 417 | return expect, nil 418 | }, 419 | ) 420 | 421 | ch <- MultiReturns{r, err} 422 | close(ch) 423 | }() 424 | 425 | r := <-ch 426 | if r.Err != nil { 427 | t.Errorf("Gets an error: %v\n", r.Err) 428 | } 429 | 430 | val, ok := r.Val.(int) 431 | if ok == false || val != expect { 432 | t.Errorf("Unmatched value: %v\n", r.Val) 433 | } 434 | if times != 1 { 435 | t.Errorf("Should execute only once, gets: %v\n", times) 436 | } 437 | } 438 | 439 | func TestLast_ShouldWorksAsExpected(t *testing.T) { 440 | t.Parallel() 441 | 442 | rootCtx := context.Background() 443 | ch := make(chan MultiReturns) 444 | go func() { 445 | r, err := Last( 446 | rootCtx, 447 | 2, 448 | func(ctx context.Context) (interface{}, error) { 449 | time.Sleep(200 * time.Millisecond) 450 | return 1, nil 451 | }, 452 | func(ctx context.Context) (interface{}, error) { 453 | time.Sleep(100 * time.Millisecond) 454 | return 2, nil 455 | }, 456 | func(ctx context.Context) (interface{}, error) { 457 | <-time.After(300 * time.Millisecond) 458 | return 3, nil 459 | }, 460 | ) 461 | 462 | ch <- MultiReturns{r, err} 463 | close(ch) 464 | }() 465 | 466 | r := <-ch 467 | if r.Err != nil { 468 | t.Errorf("Gets an error: %v\n", r.Err) 469 | } 470 | 471 | rs := []int{} 472 | for _, v := range r.Val.([]interface{}) { 473 | rs = append(rs, v.(int)) 474 | } 475 | 476 | equal := reflect.DeepEqual([]int{1, 3}, rs) 477 | if !equal { 478 | t.Errorf("Execution order is wrong, gets: %+v\n", rs) 479 | } 480 | } 481 | 482 | func TestWaterfall_ShouldWorksAsExpected(t *testing.T) { 483 | t.Parallel() 484 | 485 | rootCtx := context.Background() 486 | ch := make(chan MultiReturns) 487 | go func() { 488 | r, err := Waterfall( 489 | rootCtx, 490 | func(ctx context.Context, n interface{}) (interface{}, error) { 491 | time.Sleep(100 * time.Millisecond) 492 | return 1, nil 493 | }, 494 | func(ctx context.Context, n interface{}) (interface{}, error) { 495 | time.Sleep(100 * time.Millisecond) 496 | n = n.(int) + 1 497 | return n, nil 498 | }, 499 | func(ctx context.Context, n interface{}) (interface{}, error) { 500 | time.Sleep(100 * time.Millisecond) 501 | n = n.(int) + 1 502 | return n, nil 503 | }, 504 | ) 505 | 506 | ch <- MultiReturns{r, err} 507 | close(ch) 508 | }() 509 | 510 | r := <-ch 511 | if r.Err != nil { 512 | t.Errorf("Gets an error: %v\n", r.Err) 513 | } 514 | 515 | if r.Val.(int) != 3 { 516 | t.Errorf("Expect \"3\", but gets: \"%v\"\n", r.Val) 517 | } 518 | } 519 | 520 | func TestRetry_ShouldReturnsOnSuccess(t *testing.T) { 521 | t.Parallel() 522 | 523 | rootCtx := context.Background() 524 | ch := make(chan MultiReturns) 525 | go func() { 526 | r, err := Retry( 527 | rootCtx, 528 | 3, 529 | func(ctx context.Context) (interface{}, error) { 530 | time.Sleep(200 * time.Millisecond) 531 | return 1, nil 532 | }, 533 | ) 534 | 535 | ch <- MultiReturns{r, err} 536 | close(ch) 537 | }() 538 | 539 | r := <-ch 540 | if r.Err != nil { 541 | t.Errorf("Gets an error: %v\n", r.Err) 542 | } 543 | 544 | if r.Val != 1 { 545 | t.Errorf("Should gets `1`, gets: %+v instead\n", r.Val) 546 | } 547 | } 548 | 549 | func TestRetry_ShouldReturnsAfterFailingSeveralTimes(t *testing.T) { 550 | t.Parallel() 551 | 552 | var times int32 553 | rootCtx := context.Background() 554 | ch := make(chan MultiReturns) 555 | go func() { 556 | r, err := Retry( 557 | rootCtx, 558 | 3, 559 | func(ctx context.Context) (interface{}, error) { 560 | atomic.AddInt32(×, 1) 561 | if atomic.LoadInt32(×) >= 2 { 562 | return 1, nil 563 | } 564 | return nil, fmt.Errorf("err") 565 | }, 566 | ) 567 | 568 | ch <- MultiReturns{r, err} 569 | close(ch) 570 | }() 571 | 572 | r := <-ch 573 | if r.Err != nil { 574 | t.Errorf("Gets an error: %v\n", r.Err) 575 | } 576 | 577 | if times != 2 { 578 | t.Errorf("Should tried 2 times, instead of %v\n", times) 579 | } 580 | 581 | if r.Val != 1 { 582 | t.Errorf("Should gets `1`, gets: %+v instead\n", r.Val) 583 | } 584 | } 585 | 586 | func TestRetry_ShouldKeepRetrying(t *testing.T) { 587 | t.Parallel() 588 | 589 | var times int32 590 | rootCtx := context.Background() 591 | ch := make(chan MultiReturns) 592 | go func() { 593 | 594 | r, err := Retry( 595 | rootCtx, 596 | 3, 597 | func(ctx context.Context) (interface{}, error) { 598 | atomic.AddInt32(×, 1) 599 | return nil, fmt.Errorf("err") 600 | }, 601 | ) 602 | 603 | ch <- MultiReturns{r, err} 604 | close(ch) 605 | }() 606 | 607 | r := <-ch 608 | if r.Err == nil { 609 | t.Errorf("Should gets an error") 610 | } 611 | 612 | if times != 3 { 613 | t.Errorf("Should tried 3 times, instead of: %+v\n", times) 614 | } 615 | } 616 | 617 | func TestRetry_WhenRootCtxCanceled(t *testing.T) { 618 | t.Parallel() 619 | 620 | rootCtx, cancel := context.WithCancel(context.Background()) 621 | ch := make(chan MultiReturns) 622 | go func() { 623 | 624 | r, err := Retry( 625 | rootCtx, 626 | 3, 627 | func(ctx context.Context) (interface{}, error) { 628 | time.Sleep(50 * time.Millisecond) 629 | return nil, fmt.Errorf("err") 630 | }, 631 | ) 632 | 633 | ch <- MultiReturns{r, err} 634 | close(ch) 635 | }() 636 | go func() { 637 | time.Sleep(10 * time.Millisecond) 638 | cancel() 639 | }() 640 | 641 | r := <-ch 642 | if r.Err == nil { 643 | t.Errorf("Should gets an error") 644 | } 645 | } 646 | 647 | func TestMin(t *testing.T) { 648 | t.Parallel() 649 | 650 | if min(1, 2) != 1 { 651 | t.Errorf("Should returns 1") 652 | } 653 | if min(-1, 2) != -1 { 654 | t.Errorf("Should returns -1") 655 | } 656 | if min(54321, 12345) != 12345 { 657 | t.Errorf("Should returns 12345") 658 | } 659 | } 660 | --------------------------------------------------------------------------------