├── .github ├── FUNDING.yml └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── bcast.go ├── bcast_test.go ├── data.go ├── fifo.go ├── fifo_test.go ├── go.mod ├── go.sum ├── parallel.go ├── parallel_test.go ├── pipeline.go ├── pipeline_test.go ├── pool.go ├── pool_test.go ├── sink.go ├── sink_test.go ├── source.go ├── source_test.go ├── stage.go ├── stage_test.go └── task.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [caffix] 2 | custom: ["https://www.buymeacoffee.com/caffix"] -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | 7 | jobs: 8 | test: 9 | name: Test 10 | strategy: 11 | matrix: 12 | os: [ "ubuntu-latest", "macos-latest", "windows-latest" ] 13 | go-version: [ "1.23.1" ] 14 | runs-on: ${{ matrix.os }} 15 | steps: 16 | - 17 | name: setup Go ${{ matrix.go-version }} 18 | uses: actions/setup-go@v3 19 | with: 20 | go-version: ${{ matrix.go-version }} 21 | - 22 | name: checkout 23 | uses: actions/checkout@v3 24 | - 25 | name: simple test 26 | run: go test -v 27 | - 28 | name: test with GC pressure 29 | run: go test -v 30 | env: 31 | GOGC: 1 32 | - 33 | name: test with race detector 34 | run: go test -v -race 35 | coverage: 36 | name: Coverage 37 | runs-on: ubuntu-latest 38 | steps: 39 | - name: setup Go 40 | uses: actions/setup-go@v3 41 | with: 42 | go-version: 1.23.1 43 | - name: checkout 44 | uses: actions/checkout@v3 45 | - name: measure coverage 46 | run: go test -v -coverprofile=coverage.out 47 | - name: report coverage 48 | run: | 49 | bash <(curl -s https://codecov.io/bash) 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 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 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Pipeline 2 | 3 | ![GitHub Test Status](https://github.com/caffix/pipeline/workflows/tests/badge.svg) 4 | [![GoDoc](https://img.shields.io/static/v1?label=godoc&message=reference&color=blue)](https://pkg.go.dev/github.com/caffix/pipeline?tab=overview) 5 | [![License](https://img.shields.io/github/license/caffix/pipeline)](https://www.apache.org/licenses/LICENSE-2.0) 6 | [![Go Report](https://goreportcard.com/badge/github.com/caffix/pipeline)](https://goreportcard.com/report/github.com/caffix/pipeline) 7 | [![CodeFactor](https://www.codefactor.io/repository/github/caffix/pipeline/badge)](https://www.codefactor.io/repository/github/caffix/pipeline) 8 | [![Codecov](https://codecov.io/gh/caffix/pipeline/branch/master/graph/badge.svg)](https://codecov.io/gh/caffix/pipeline) 9 | [![Follow on Twitter](https://img.shields.io/twitter/follow/jeff_foley.svg?logo=twitter)](https://twitter.com/jeff_foley) 10 | 11 | Simple asynchronous data pipeline written in Go with support for concurrent tasks at each stage. 12 | 13 | ## Installation [![Go Version](https://img.shields.io/github/go-mod/go-version/caffix/pipeline)](https://golang.org/dl/) 14 | 15 | ```bash 16 | go get -v -u github.com/caffix/pipeline 17 | ``` 18 | 19 | ## Usage 20 | 21 | The pipeline processes data provided by the input source through multiple stages and finally consumed by the output sink. All steps of the pipeline can be executing concurrently to maximize throughput. The pipeline can also be executed with buffering in-between each step in an attempt to minimize the impact of one stage taking longer than the others. Any error returned from a task being executed will terminate the pipeline. If a task returns `nil` data, the data is marked as processed and will not continue to the following stage. 22 | 23 | ### The Pipeline Data 24 | 25 | The pipeline `Data` implements the `Clone` and `MarkAsProcessed` methods that performs a deep copy and marks the data to prevent further movement down the pipeline, respectively. Below is a simple pipeline `Data` implementation: 26 | 27 | ```golang 28 | type stringData struct { 29 | processed bool 30 | val string 31 | } 32 | 33 | // Clone implements the pipeline Data interface. 34 | func (s *stringData) Clone() pipeline.Data { return &stringData{val: s.val} } 35 | 36 | // Clone implements the pipeline Data interface. 37 | func (s *stringData) MarkAsProcessed() { s.processed = true } 38 | 39 | // String implements the Stringer interface. 40 | func (s *stringData) String() string { return s.val } 41 | ``` 42 | 43 | ### The Input Source 44 | 45 | The `InputSource` is an iterator that feeds the pipeline with data. Once the `Next` method returns `false`, the pipeline prevents the following stage from receiving data and begins an avalanche affect stopping each stage and eventually terminating the pipeline. Below is a simple input source: 46 | 47 | ```golang 48 | type stringSource []pipeline.Data 49 | 50 | var source stringSource = []*stringData{ 51 | &stringData{val: "one"}, 52 | &stringData{val: "two"}, 53 | &stringData{val: "three"}, 54 | } 55 | 56 | // Next implements the pipeline InputSource interface. 57 | func (s stringSource) Next(context.Context) bool { return len(s) > 0 } 58 | 59 | // Data implements the pipeline InputSource interface. 60 | func (s stringSource) Data() pipeline.Data { 61 | defer func() { s = s[1:] } 62 | return s[0] 63 | } 64 | 65 | // Error implements the pipeline InputSource interface. 66 | func (s stringSource) Error() error { return nil } 67 | ``` 68 | 69 | ### The Output Sink 70 | 71 | The `OutputSink` serves as a final landing spot for the data after successfully traversing the entire pipeline. All data reaching the output sink is automatically marked as processed. Below is a simple output sink: 72 | 73 | ```golang 74 | type stringSink []string 75 | 76 | // Consume implements the pipeline OutputSink interface. 77 | func (s stringSink) Consume(ctx context.Context, data pipeline.Data) error { 78 | sd := data.(*stringData) 79 | 80 | s = append(s, sd.String()) 81 | return nil 82 | } 83 | ``` 84 | 85 | ### The Stages 86 | 87 | The pipeline steps are executed in sequential order by instances of `Stage`. The execution strategies implemented are `FIFO`, `FixedPool`, `DynamicPool`, `Broadcast`, and `Parallel`: 88 | 89 | * `FIFO` - Executes the single Task 90 | * `FixedPool` - Executes a fixed number of instances of the one specified Task 91 | * `DynamicPool` - Executes a dynamic number of instances of the one specified Task 92 | * `Broadcast` - Executes several unique Task instances concurrently moving Data ASAP 93 | * `Parallel` - Executes several unique Task instances concurrently and passing through the original Data only once all the tasks complete successfully 94 | 95 | The stage execution strategies can be combined to form desired pipelines. A Stage requires at least one Task to be executed at the step it represents in the pipeline. Each Task returns `Data` and an `error`. If the data returned is nil, it will not be sent to the following Stage. If the error is non-nil, the entire pipeline will be terminated. This allows users of the pipeline to have complete control over how failures impact the overall pipeline execution. A Task implements the `Process` method. 96 | 97 | ```golang 98 | // TaskFunc is defined as a function with a Process method that calls the function 99 | task := pipeline.TaskFunc(func(ctx context.Context, data pipeline.Data, tp pipeline.TaskParams) (pipeline.Data, error) { 100 | var val int 101 | s := data.(*stringData) 102 | 103 | switch s.String() { 104 | case "one": 105 | val = 1 106 | case "two": 107 | var = 2 108 | case "three": 109 | var = 3 110 | } 111 | 112 | data.val = fmt.Sprintf("%s - %d", s.String(), val) 113 | return data, nil 114 | }) 115 | 116 | stage := pipeline.FIFO("", task) 117 | ``` 118 | 119 | ### Executing the Pipeline 120 | 121 | The Pipeline continues executing until all the Data from the input source is processed, an error takes place, or the provided Context expires. At a minimum, the pipeline requires an input source, a pass through stage, and the output sink. 122 | 123 | ```golang 124 | p := NewPipeline(stage) 125 | 126 | if err := p.Execute(context.TODO(), source, sink); err != nil { 127 | fmt.Printf("Error executing the pipeline: %v\n", err) 128 | } 129 | ``` 130 | 131 | ## Future Features 132 | 133 | Some additional features would bring value to this data pipeline implementation. 134 | 135 | ### Logging 136 | 137 | No logging is built into this pipeline implementation and this could be quite useful to have. 138 | 139 | ### Metrics and Monitoring 140 | 141 | It would be helpful to have the ability to monitor stage and task performance such as how long each is taking to execute, the number of Data instances processes, the number of successes and failures, etc. 142 | 143 | ### Task Implementations for Common Use Cases 144 | 145 | This pipeline implementation is very abstract, which allows users to perform nearly any set of steps. Currently, users must implement their own tasks. Some tasks are very common and the project could build support for such activities. For example, executing a script pulled from a Git repo. 146 | 147 | ### Support for Configuration Files 148 | 149 | As the implementation becomes from complex, it could be helpful to support the use of configuration files and reduce the level of effort necessary to build a pipeline. For example, the configuration file could specify when tasks should be output to alternative stages. 150 | 151 | ### Develop Additional Stage Execution Strategies 152 | 153 | While the current execution strategies work for many use cases, there could be opportunities to develop additional stage types that ease pipeline development. 154 | 155 | ## Licensing [![License](https://img.shields.io/github/license/caffix/pipeline)](https://www.apache.org/licenses/LICENSE-2.0) 156 | 157 | This program is free software: you can redistribute it and/or modify it under the terms of the [Apache license](LICENSE). 158 | -------------------------------------------------------------------------------- /bcast.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | 7 | "github.com/caffix/queue" 8 | ) 9 | 10 | type broadcast struct { 11 | id string 12 | fifos []Stage 13 | inChs []chan Data 14 | } 15 | 16 | // Broadcast returns a Stage that passes a copy of each incoming data 17 | // to all specified tasks and emits their outputs to the next stage. 18 | func Broadcast(id string, tasks ...Task) Stage { 19 | if len(tasks) == 0 { 20 | return nil 21 | } 22 | 23 | fifos := make([]Stage, len(tasks)) 24 | for i, t := range tasks { 25 | fifos[i] = FIFO("", t) 26 | } 27 | 28 | return &broadcast{ 29 | id: id, 30 | fifos: fifos, 31 | inChs: make([]chan Data, len(fifos)), 32 | } 33 | } 34 | 35 | // ID implements Stage. 36 | func (b *broadcast) ID() string { 37 | return b.id 38 | } 39 | 40 | // Run implements Stage. 41 | func (b *broadcast) Run(ctx context.Context, sp StageParams) { 42 | var wg sync.WaitGroup 43 | // Start each FIFO in a goroutine. Each FIFO gets its own dedicated 44 | // input channel and the shared output channel passed to Run. 45 | for i := 0; i < len(b.fifos); i++ { 46 | wg.Add(1) 47 | b.inChs[i] = make(chan Data) 48 | go func(idx int) { 49 | b.fifos[idx].Run(ctx, ¶ms{ 50 | stage: sp.Position(), 51 | inCh: b.inChs[idx], 52 | outCh: sp.Output(), 53 | dataQueue: queue.NewQueue(), 54 | errQueue: sp.Error(), 55 | registry: sp.Registry(), 56 | }) 57 | wg.Done() 58 | }(i) 59 | } 60 | 61 | for { 62 | // Read incoming data and pass them to each FIFO 63 | if !processStageData(ctx, sp, b.executeTask) { 64 | break 65 | } 66 | } 67 | // Close input channels and wait for FIFOs to exit 68 | for _, ch := range b.inChs { 69 | close(ch) 70 | } 71 | wg.Wait() 72 | } 73 | 74 | func (b *broadcast) executeTask(ctx context.Context, data Data, sp StageParams) (Data, error) { 75 | select { 76 | case <-ctx.Done(): 77 | return nil, nil 78 | default: 79 | } 80 | 81 | for i := len(b.fifos) - 1; i >= 0; i-- { 82 | fifoData := data 83 | // As each FIFO might modify the data, to 84 | // avoid data races we need to make a copy 85 | // of the data for all FIFOs except the first. 86 | if i != 0 { 87 | fifoData = data.Clone() 88 | } 89 | 90 | select { 91 | case <-ctx.Done(): 92 | return nil, nil 93 | case b.inChs[i] <- fifoData: 94 | // data sent to i_th FIFO 95 | } 96 | } 97 | return data, nil 98 | } 99 | -------------------------------------------------------------------------------- /bcast_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "reflect" 7 | "sort" 8 | "testing" 9 | ) 10 | 11 | func TestBroadcast(t *testing.T) { 12 | num := 3 13 | tasks := make([]Task, num) 14 | for i := 0; i < num; i++ { 15 | tasks[i] = makeMutatingTask(i) 16 | } 17 | 18 | src := &sourceStub{data: stringDataValues(1)} 19 | sink := new(sinkStub) 20 | 21 | p := NewPipeline(Broadcast("", tasks...)) 22 | if err := p.Execute(context.TODO(), src, sink); err != nil { 23 | t.Errorf("Error executing the Pipeline: %v", err) 24 | } 25 | 26 | data := []Data{&stringData{val: "0_0"}, &stringData{val: "0_1"}, &stringData{val: "0_2"}} 27 | // Tasks run as goroutines so outputs will be shuffled. We need 28 | // to sort them first so we can check for equality. 29 | sort.Slice(data, func(i, j int) bool { 30 | return data[i].(*stringData).val < data[j].(*stringData).val 31 | }) 32 | sort.Slice(sink.data, func(i, j int) bool { 33 | return sink.data[i].(*stringData).val < sink.data[j].(*stringData).val 34 | }) 35 | if !reflect.DeepEqual(sink.data, data) { 36 | t.Errorf("Data does not match.\nWanted:%v\nGot:%v\n", data, sink.data) 37 | } 38 | } 39 | 40 | func BenchmarkBroadcast(b *testing.B) { 41 | for i := 0; i < b.N; i++ { 42 | p := NewPipeline(Broadcast("", makePassthroughTask())) 43 | src := &sourceStub{data: []Data{&stringData{val: "benchmark"}}} 44 | _ = p.Execute(context.TODO(), src, new(sinkStub)) 45 | } 46 | } 47 | 48 | func BenchmarkBroadcastDataElements(b *testing.B) { 49 | sink := new(sinkStub) 50 | src := &sourceStub{data: stringDataValues(b.N)} 51 | p := NewPipeline(Broadcast("", makePassthroughTask())) 52 | 53 | b.StartTimer() 54 | _ = p.Execute(context.TODO(), src, sink) 55 | b.StopTimer() 56 | } 57 | 58 | func makeMutatingTask(index int) Task { 59 | return TaskFunc(func(_ context.Context, d Data, _ TaskParams) (Data, error) { 60 | // Mutate data to check that each task got a copy 61 | sd := d.(*stringData) 62 | sd.val = fmt.Sprintf("%s_%d", sd.val, index) 63 | return d, nil 64 | }) 65 | } 66 | -------------------------------------------------------------------------------- /data.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | // Data is implemented by values that can be sent through a pipeline. 4 | type Data interface { 5 | // Clone returns a new Data that is a deep-copy of the original. 6 | Clone() Data 7 | } 8 | -------------------------------------------------------------------------------- /fifo.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | ) 7 | 8 | type fifo struct { 9 | id string 10 | task Task 11 | } 12 | 13 | // FIFO returns a Stage that processes incoming data in a first-in first-out 14 | // fashion. Each input is passed to the specified Task and its output 15 | // is emitted to the next Stage. 16 | func FIFO(id string, task Task) Stage { 17 | return &fifo{ 18 | id: id, 19 | task: task, 20 | } 21 | } 22 | 23 | // ID implements Stage. 24 | func (r *fifo) ID() string { 25 | return r.id 26 | } 27 | 28 | // Run implements Stage. 29 | func (r *fifo) Run(ctx context.Context, sp StageParams) { 30 | for { 31 | if !processStageData(ctx, sp, r.executeTask) { 32 | break 33 | } 34 | } 35 | } 36 | 37 | func (r *fifo) executeTask(ctx context.Context, data Data, sp StageParams) (Data, error) { 38 | select { 39 | case <-ctx.Done(): 40 | return nil, nil 41 | default: 42 | } 43 | 44 | dataOut, err := r.task.Process(ctx, data, &taskParams{ 45 | pipeline: sp.Pipeline(), 46 | registry: sp.Registry(), 47 | }) 48 | if err != nil { 49 | e := fmt.Errorf("pipeline stage %d: %v", sp.Position(), err) 50 | sp.Error().Append(e) 51 | return dataOut, e 52 | } 53 | // If the task did not output data for the 54 | // next stage there is nothing we need to do 55 | if dataOut == nil { 56 | return nil, nil 57 | } 58 | // Output processed data 59 | select { 60 | case <-ctx.Done(): 61 | case sp.Output() <- dataOut: 62 | } 63 | return dataOut, nil 64 | } 65 | -------------------------------------------------------------------------------- /fifo_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestFIFO(t *testing.T) { 10 | stages := make([]Stage, 10) 11 | for i := 0; i < len(stages); i++ { 12 | stages[i] = FIFO("", makePassthroughTask()) 13 | } 14 | 15 | src := &sourceStub{data: stringDataValues(3)} 16 | sink := new(sinkStub) 17 | 18 | p := NewPipeline(stages...) 19 | if err := p.Execute(context.TODO(), src, sink); err != nil { 20 | t.Errorf("Error executing the Pipeline: %v", err) 21 | } 22 | if !reflect.DeepEqual(sink.data, src.data) { 23 | t.Errorf("Data does not match.\nWanted:%v\nGot:%v\n", src.data, sink.data) 24 | } 25 | } 26 | 27 | func BenchmarkFIFO(b *testing.B) { 28 | for i := 0; i < b.N; i++ { 29 | p := NewPipeline(FIFO("", makePassthroughTask())) 30 | src := &sourceStub{data: []Data{&stringData{val: "benchmark"}}} 31 | _ = p.Execute(context.TODO(), src, new(sinkStub)) 32 | } 33 | } 34 | 35 | func BenchmarkFIFODataElements(b *testing.B) { 36 | sink := new(sinkStub) 37 | src := &sourceStub{data: stringDataValues(b.N)} 38 | p := NewPipeline(FIFO("", makePassthroughTask())) 39 | 40 | b.StartTimer() 41 | _ = p.Execute(context.TODO(), src, sink) 42 | b.StopTimer() 43 | } 44 | 45 | func makePassthroughTask() Task { 46 | return TaskFunc(func(_ context.Context, data Data, _ TaskParams) (Data, error) { 47 | return data, nil 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/caffix/pipeline 2 | 3 | go 1.23.1 4 | 5 | require ( 6 | github.com/caffix/queue v0.3.1 7 | github.com/caffix/stringset v0.2.0 8 | github.com/hashicorp/go-multierror v1.1.1 9 | ) 10 | 11 | require github.com/hashicorp/errwrap v1.1.0 // indirect 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/caffix/queue v0.3.1 h1:eg4V7cGomH76/Xq60MdEhSVZvO6E3iOPlacMwZOjiSA= 2 | github.com/caffix/queue v0.3.1/go.mod h1:AnCrUsy3cwDjLJvNv7FkQx/0Q9Hb7n7agRrUP0OiYl4= 3 | github.com/caffix/stringset v0.2.0 h1:kN6xnvL8jzx2YhQNOYr6A6hFzUK+iikt1JtJ2MS2LC8= 4 | github.com/caffix/stringset v0.2.0/go.mod h1:8PZ6GIPpMP5+r5hr790/05w3v9xI+gXRxRzJCZL57lQ= 5 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 6 | github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= 7 | github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 8 | github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= 9 | github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= 10 | -------------------------------------------------------------------------------- /parallel.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | ) 7 | 8 | type parallel struct { 9 | id string 10 | tasks []Task 11 | } 12 | 13 | // Parallel returns a Stage that passes a copy of each incoming Data 14 | // to all specified tasks, waits for all the tasks to finish before 15 | // sending data to the next stage, and only passes the original Data 16 | // through to the following stage. 17 | func Parallel(id string, tasks ...Task) Stage { 18 | if len(tasks) == 0 { 19 | return nil 20 | } 21 | 22 | return ¶llel{ 23 | id: id, 24 | tasks: tasks, 25 | } 26 | } 27 | 28 | // ID implements Stage. 29 | func (p *parallel) ID() string { 30 | return p.id 31 | } 32 | 33 | // Run implements Stage. 34 | func (p *parallel) Run(ctx context.Context, sp StageParams) { 35 | for { 36 | if !processStageData(ctx, sp, p.executeTask) { 37 | break 38 | } 39 | } 40 | } 41 | 42 | func (p *parallel) executeTask(ctx context.Context, data Data, sp StageParams) (Data, error) { 43 | select { 44 | case <-ctx.Done(): 45 | return nil, nil 46 | default: 47 | } 48 | 49 | done := make(chan Data, len(p.tasks)) 50 | for i := 0; i < len(p.tasks); i++ { 51 | go func(idx int, clone Data) { 52 | d, err := p.tasks[idx].Process(ctx, clone, &taskParams{ 53 | pipeline: sp.Pipeline(), 54 | registry: sp.Registry(), 55 | }) 56 | if err != nil { 57 | sp.Error().Append(fmt.Errorf("pipeline stage %d: %v", sp.Position(), err)) 58 | } 59 | done <- d 60 | }(i, data.Clone()) 61 | } 62 | 63 | var failed bool 64 | for i := 0; i < len(p.tasks); i++ { 65 | if d := <-done; d == nil { 66 | failed = true 67 | } 68 | } 69 | if failed { 70 | return nil, nil 71 | } 72 | 73 | select { 74 | case <-ctx.Done(): 75 | case sp.Output() <- data: 76 | } 77 | return data, nil 78 | } 79 | -------------------------------------------------------------------------------- /parallel_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "sync" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestParallel(t *testing.T) { 12 | num := 10 13 | var count int 14 | var m sync.Mutex 15 | tasks := make([]Task, num) 16 | for i := 0; i < num; i++ { 17 | tasks[i] = TaskFunc(func(_ context.Context, d Data, _ TaskParams) (Data, error) { 18 | time.Sleep(time.Second) 19 | m.Lock() 20 | count++ 21 | m.Unlock() 22 | return nil, nil 23 | }) 24 | } 25 | 26 | // Check that all previous tasks have completed 27 | checker := TaskFunc(func(_ context.Context, d Data, _ TaskParams) (Data, error) { 28 | var c int 29 | 30 | m.Lock() 31 | c = count 32 | m.Unlock() 33 | if c != num { 34 | return d, fmt.Errorf("Not all previous tasks have finished.\nWanted: %d\nGot: %d\n", num, c) 35 | } 36 | return d, nil 37 | }) 38 | 39 | src := &sourceStub{data: stringDataValues(1)} 40 | sink := new(sinkStub) 41 | 42 | p := NewPipeline(Parallel("", tasks...), FIFO("", checker)) 43 | if err := p.Execute(context.TODO(), src, sink); err != nil { 44 | t.Errorf("Error executing the Pipeline: %v", err) 45 | } 46 | } 47 | 48 | func BenchmarkParallel(b *testing.B) { 49 | for i := 0; i < b.N; i++ { 50 | p := NewPipeline(Parallel("", makePassthroughTask())) 51 | src := &sourceStub{data: []Data{&stringData{val: "benchmark"}}} 52 | _ = p.Execute(context.TODO(), src, new(sinkStub)) 53 | } 54 | } 55 | 56 | func BenchmarkParallelDataElements(b *testing.B) { 57 | sink := new(sinkStub) 58 | src := &sourceStub{data: stringDataValues(b.N)} 59 | p := NewPipeline(Parallel("", makePassthroughTask())) 60 | 61 | b.StartTimer() 62 | _ = p.Execute(context.TODO(), src, sink) 63 | b.StopTimer() 64 | } 65 | -------------------------------------------------------------------------------- /pipeline.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "sync" 7 | 8 | "github.com/caffix/queue" 9 | "github.com/caffix/stringset" 10 | multierror "github.com/hashicorp/go-multierror" 11 | ) 12 | 13 | type params struct { 14 | pipeline *Pipeline 15 | stage int 16 | inCh <-chan Data 17 | outCh chan<- Data 18 | dataQueue queue.Queue 19 | errQueue queue.Queue 20 | newdata chan<- Data 21 | processed chan<- Data 22 | registry StageRegistry 23 | } 24 | 25 | func (p *params) Pipeline() *Pipeline { return p.pipeline } 26 | func (p *params) Position() int { return p.stage } 27 | func (p *params) Input() <-chan Data { return p.inCh } 28 | func (p *params) Output() chan<- Data { return p.outCh } 29 | func (p *params) DataQueue() queue.Queue { return p.dataQueue } 30 | func (p *params) Error() queue.Queue { return p.errQueue } 31 | func (p *params) NewData() chan<- Data { return p.newdata } 32 | func (p *params) ProcessedData() chan<- Data { return p.processed } 33 | func (p *params) Registry() StageRegistry { return p.registry } 34 | 35 | // Pipeline is an abstract and extendable asynchronous data 36 | // pipeline with concurrent tasks at each stage. Each pipeline 37 | // is constructed from an InputSource, an OutputSink, and zero 38 | // or more Stage instances for processing. 39 | type Pipeline struct { 40 | sync.Mutex 41 | stages []Stage 42 | stageParams []*params 43 | } 44 | 45 | // NewPipeline returns a new data pipeline instance where input 46 | // traverse each of the provided Stage instances. 47 | func NewPipeline(stages ...Stage) *Pipeline { 48 | var count int 49 | set := stringset.New() 50 | defer set.Close() 51 | 52 | for _, stage := range stages { 53 | if id := stage.ID(); id != "" { 54 | set.Insert(id) 55 | count++ 56 | } 57 | } 58 | // Check that all stage identifiers are unique 59 | if count != set.Len() { 60 | return nil 61 | } 62 | return &Pipeline{stages: stages} 63 | } 64 | 65 | // Execute performs ExecuteBuffered with a bufsize parameter equal to 1. 66 | func (p *Pipeline) Execute(ctx context.Context, src InputSource, sink OutputSink) error { 67 | return p.ExecuteBuffered(ctx, src, sink, 1) 68 | } 69 | 70 | // ExecuteBuffered reads data from the InputSource, sends them through 71 | // each of the Stage instances, and finishes with the OutputSink. 72 | // All errors are returned that occurred during the execution. 73 | // ExecuteBuffered will block until all data from the InputSource has 74 | // been processed, or an error occurs, or the context expires. 75 | func (p *Pipeline) ExecuteBuffered(ctx context.Context, src InputSource, sink OutputSink, bufsize int) error { 76 | pCtx, cancel := context.WithCancel(ctx) 77 | defer cancel() 78 | 79 | var stageQueue []queue.Queue 80 | // Create the stage registry 81 | registry := make(StageRegistry, len(p.stages)+1) 82 | // Create channels for wiring together the InputSource, 83 | // the pipeline Stage instances, and the OutputSink 84 | stageCh := make([]chan Data, len(p.stages)+1) 85 | for i := 0; i < len(stageCh); i++ { 86 | stageCh[i] = make(chan Data, bufsize) 87 | stageQueue = append(stageQueue, queue.NewQueue()) 88 | 89 | id := "sink" 90 | if i != len(stageCh)-1 { 91 | id = p.stages[i].ID() 92 | } 93 | if id != "" { 94 | registry[id] = stageQueue[i] 95 | } 96 | } 97 | errQueue := queue.NewQueue() 98 | 99 | var wg sync.WaitGroup 100 | // Start a goroutine for each Stage 101 | for i := 0; i < len(p.stages); i++ { 102 | wg.Add(1) 103 | go func(idx int) { 104 | sparams := ¶ms{ 105 | pipeline: p, 106 | stage: idx + 1, 107 | inCh: stageCh[idx], 108 | outCh: stageCh[idx+1], 109 | dataQueue: stageQueue[idx], 110 | errQueue: errQueue, 111 | registry: registry, 112 | } 113 | p.Lock() 114 | p.stageParams = append(p.stageParams, sparams) 115 | p.Unlock() 116 | p.stages[idx].Run(pCtx, sparams) 117 | // Tell the next Stage that no more Data is available 118 | close(stageCh[idx+1]) 119 | wg.Done() 120 | }(i) 121 | } 122 | // Start goroutines for the InputSource and OutputSink 123 | wg.Add(2) 124 | go func() { 125 | p.inputSourceRunner(pCtx, src, stageCh[0], errQueue) 126 | // Tell the first Stage that no more Data is available 127 | close(stageCh[0]) 128 | wg.Done() 129 | }() 130 | go func() { 131 | p.outputSinkRunner(pCtx, sink, stageCh[len(stageCh)-1], errQueue) 132 | wg.Done() 133 | }() 134 | // Monitor for completion of the pipeline execution 135 | go func() { 136 | wg.Wait() 137 | cancel() 138 | }() 139 | 140 | var err error 141 | // Collect any emitted errors and wraps them in a multi-error 142 | select { 143 | case <-pCtx.Done(): 144 | case <-errQueue.Signal(): 145 | errQueue.Process(func(e interface{}) { 146 | if qErr, ok := e.(error); ok { 147 | err = multierror.Append(err, qErr) 148 | } 149 | }) 150 | } 151 | return err 152 | } 153 | 154 | // DataItemCount returns the number of data items currently on the pipeline. 155 | func (p *Pipeline) DataItemCount() int { 156 | p.Lock() 157 | defer p.Unlock() 158 | 159 | var count int 160 | for _, p := range p.stageParams { 161 | count += len(p.Input()) + p.DataQueue().Len() 162 | } 163 | return count 164 | } 165 | 166 | // inputSourceRunner drives the InputSource to continue providing 167 | // data to the first stage of the pipeline. 168 | func (p *Pipeline) inputSourceRunner(ctx context.Context, src InputSource, outCh chan<- Data, errQueue queue.Queue) { 169 | for src.Next(ctx) { 170 | data := src.Data() 171 | 172 | select { 173 | case <-ctx.Done(): 174 | return 175 | case outCh <- data: 176 | } 177 | } 178 | // Check for errors 179 | if err := src.Error(); err != nil { 180 | errQueue.Append(fmt.Errorf("pipeline input source: %v", err)) 181 | } 182 | } 183 | 184 | func (p *Pipeline) outputSinkRunner(ctx context.Context, sink OutputSink, inCh <-chan Data, errQueue queue.Queue) { 185 | for { 186 | select { 187 | case <-ctx.Done(): 188 | return 189 | case data, ok := <-inCh: 190 | if !ok { 191 | return 192 | } 193 | if err := sink.Consume(ctx, data); err != nil { 194 | errQueue.Append(fmt.Errorf("pipeline output sink: %v", err)) 195 | return 196 | } 197 | } 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /pipeline_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "math/rand" 8 | "reflect" 9 | "regexp" 10 | "testing" 11 | ) 12 | 13 | func TestDataFlow(t *testing.T) { 14 | stages := make([]Stage, 10) 15 | for i := 0; i < len(stages); i++ { 16 | stages[i] = testStage{t: t} 17 | } 18 | 19 | src := &sourceStub{data: stringDataValues(3)} 20 | sink := new(sinkStub) 21 | 22 | p := NewPipeline(stages...) 23 | if err := p.Execute(context.TODO(), src, sink); err != nil { 24 | t.Errorf("Error executing the Pipeline: %v", err) 25 | } 26 | if !reflect.DeepEqual(sink.data, src.data) { 27 | t.Errorf("Data does not match.\nWanted:%v\nGot:%v\n", src.data, sink.data) 28 | } 29 | } 30 | 31 | func TestTaskErrorHandling(t *testing.T) { 32 | err := errors.New("task error") 33 | stages := make([]Stage, 10) 34 | for i := 0; i < len(stages); i++ { 35 | var sErr error 36 | if i == 5 { 37 | sErr = err 38 | } 39 | 40 | stages[i] = testStage{ 41 | t: t, 42 | err: sErr, 43 | } 44 | } 45 | 46 | src := &sourceStub{data: stringDataValues(3)} 47 | sink := new(sinkStub) 48 | 49 | p := NewPipeline(stages...) 50 | re := regexp.MustCompile("(?s).*task error.*") 51 | if err := p.Execute(context.TODO(), src, sink); err == nil || !re.MatchString(err.Error()) { 52 | t.Errorf("Error did not match the expectation: %v", err) 53 | } 54 | } 55 | 56 | func TestDataItemCount(t *testing.T) { 57 | src := &sourceStub{data: stringDataValues(1000)} 58 | sink := new(sinkStub) 59 | 60 | p := NewPipeline(&randomStage{ 61 | id: "first", 62 | t: t, 63 | }) 64 | if err := p.Execute(context.TODO(), src, sink); err != nil { 65 | t.Errorf("Error executing the Pipeline: %v", err) 66 | } 67 | if num := p.DataItemCount(); num != 0 { 68 | t.Errorf("Pipeline execution finished with %d pending data items", num) 69 | } 70 | } 71 | 72 | type randomStage struct { 73 | id string 74 | t *testing.T 75 | err error 76 | } 77 | 78 | func (s randomStage) ID() string { 79 | return s.id 80 | } 81 | 82 | func (s randomStage) Run(ctx context.Context, sp StageParams) { 83 | // add data items to the stage queue 84 | for i := 0; i < 1000; i++ { 85 | SendData(ctx, "first", &stringData{val: fmt.Sprint(i)}, &taskParams{ 86 | pipeline: sp.Pipeline(), 87 | registry: sp.Registry(), 88 | }) 89 | } 90 | 91 | for { 92 | select { 93 | case <-ctx.Done(): 94 | return 95 | case <-sp.DataQueue().Signal(): 96 | if d, ok := sp.DataQueue().Next(); ok { 97 | if data, ok := d.(Data); ok { 98 | s.processData(ctx, data, sp) 99 | } 100 | } 101 | case d, ok := <-sp.Input(): 102 | if !ok { 103 | return 104 | } 105 | s.processData(ctx, d, sp) 106 | } 107 | } 108 | } 109 | 110 | func (s randomStage) processData(ctx context.Context, d Data, sp StageParams) { 111 | if s.err != nil { 112 | s.t.Logf("[stage %d] emit error: %v", sp.Position(), s.err) 113 | sp.Error().Append(s.err) 114 | return 115 | } 116 | 117 | if num := rand.Intn(2); num == 0 { 118 | return 119 | } 120 | 121 | select { 122 | case <-ctx.Done(): 123 | case sp.Output() <- d: 124 | } 125 | } 126 | 127 | type testStage struct { 128 | id string 129 | t *testing.T 130 | dropData bool 131 | err error 132 | } 133 | 134 | func (s testStage) ID() string { 135 | return s.id 136 | } 137 | 138 | func (s testStage) Run(ctx context.Context, sp StageParams) { 139 | for { 140 | select { 141 | case <-ctx.Done(): 142 | return 143 | case d, ok := <-sp.Input(): 144 | if !ok { 145 | return 146 | } 147 | if s.err != nil { 148 | sp.Error().Append(s.err) 149 | return 150 | } 151 | 152 | if s.dropData { 153 | continue 154 | } 155 | 156 | select { 157 | case <-ctx.Done(): 158 | return 159 | case sp.Output() <- d: 160 | } 161 | } 162 | } 163 | } 164 | 165 | type stringData struct { 166 | val string 167 | } 168 | 169 | func (s *stringData) Clone() Data { return &stringData{val: s.val} } 170 | func (s *stringData) String() string { return s.val } 171 | 172 | func stringDataValues(num int) []Data { 173 | out := make([]Data, num) 174 | 175 | for i := 0; i < len(out); i++ { 176 | out[i] = &stringData{val: fmt.Sprint(i)} 177 | } 178 | return out 179 | } 180 | -------------------------------------------------------------------------------- /pool.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "sync" 7 | ) 8 | 9 | type fixedPool struct { 10 | id string 11 | fifos []Stage 12 | } 13 | 14 | // FixedPool returns a Stage that spins up a pool containing numWorkers 15 | // to process incoming data in parallel and emit their outputs to the next stage. 16 | func FixedPool(id string, task Task, num int) Stage { 17 | if num <= 0 { 18 | return nil 19 | } 20 | 21 | fifos := make([]Stage, num) 22 | for i := 0; i < num; i++ { 23 | fifos[i] = FIFO("", task) 24 | } 25 | 26 | return &fixedPool{ 27 | id: id, 28 | fifos: fifos, 29 | } 30 | } 31 | 32 | // ID implements Stage. 33 | func (p *fixedPool) ID() string { 34 | return p.id 35 | } 36 | 37 | // Run implements Stage. 38 | func (p *fixedPool) Run(ctx context.Context, params StageParams) { 39 | var wg sync.WaitGroup 40 | // Spin up each task in the pool and wait for them to exit 41 | for i := 0; i < len(p.fifos); i++ { 42 | wg.Add(1) 43 | go func(idx int) { 44 | p.fifos[idx].Run(ctx, params) 45 | wg.Done() 46 | }(i) 47 | } 48 | wg.Wait() 49 | } 50 | 51 | type dynamicPool struct { 52 | id string 53 | task Task 54 | tokenPool chan struct{} 55 | } 56 | 57 | // DynamicPool returns a Stage that maintains a dynamic pool that can scale 58 | // up to max parallel tasks for processing incoming inputs in parallel and 59 | // emitting their outputs to the next stage. 60 | func DynamicPool(id string, task Task, max int) Stage { 61 | if max <= 0 { 62 | return nil 63 | } 64 | 65 | tp := make(chan struct{}, max) 66 | for i := 0; i < cap(tp); i++ { 67 | tp <- struct{}{} 68 | } 69 | 70 | return &dynamicPool{ 71 | id: id, 72 | task: task, 73 | tokenPool: tp, 74 | } 75 | } 76 | 77 | // ID implements Stage. 78 | func (p *dynamicPool) ID() string { 79 | return p.id 80 | } 81 | 82 | // Run implements Stage. 83 | func (p *dynamicPool) Run(ctx context.Context, sp StageParams) { 84 | for { 85 | if !processStageData(ctx, sp, p.executeTask) { 86 | break 87 | } 88 | } 89 | // Wait for all workers to exit by trying to empty the token pool 90 | for i := 0; i < cap(p.tokenPool); i++ { 91 | <-p.tokenPool 92 | } 93 | } 94 | 95 | func (p *dynamicPool) executeTask(ctx context.Context, data Data, sp StageParams) (Data, error) { 96 | select { 97 | case <-ctx.Done(): 98 | return nil, nil 99 | case <-p.tokenPool: 100 | } 101 | 102 | go func(dataIn Data) { 103 | defer func() { p.tokenPool <- struct{}{} }() 104 | 105 | dataOut, err := p.task.Process(ctx, dataIn, &taskParams{ 106 | pipeline: sp.Pipeline(), 107 | registry: sp.Registry(), 108 | }) 109 | 110 | if err != nil { 111 | sp.Error().Append(fmt.Errorf("pipeline stage %d: %v", sp.Position(), err)) 112 | return 113 | } 114 | // If the task did not output data for the 115 | // next stage there is nothing we need to do. 116 | if dataOut == nil { 117 | return 118 | } 119 | // Output processed data 120 | select { 121 | case <-ctx.Done(): 122 | case sp.Output() <- dataOut: 123 | } 124 | }(data) 125 | 126 | return data, nil 127 | } 128 | -------------------------------------------------------------------------------- /pool_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestFixedWorkerPool(t *testing.T) { 10 | num := 10 11 | syncCh := make(chan struct{}) 12 | rendezvousCh := make(chan struct{}) 13 | 14 | task := TaskFunc(func(_ context.Context, _ Data, _ TaskParams) (Data, error) { 15 | // Signal that we have reached the sync point and wait for the 16 | // green light to proceed by the test code 17 | syncCh <- struct{}{} 18 | <-rendezvousCh 19 | return nil, nil 20 | }) 21 | 22 | src := &sourceStub{data: stringDataValues(num)} 23 | 24 | p := NewPipeline(FixedPool("", task, num)) 25 | doneCh := make(chan struct{}) 26 | go func() { 27 | if err := p.Execute(context.TODO(), src, nil); err != nil { 28 | t.Errorf("Error executing the Pipeline: %v", err) 29 | } 30 | close(doneCh) 31 | }() 32 | 33 | // Wait for all workers to reach sync point. This means that each input 34 | // from the source is currently handled by a worker in parallel 35 | for i := 0; i < num; i++ { 36 | select { 37 | case <-syncCh: 38 | case <-time.After(10 * time.Second): 39 | t.Errorf("timed out waiting for worker %d to reach sync point", i) 40 | } 41 | } 42 | 43 | // Allow workers to proceed and wait for the pipeline to complete 44 | close(rendezvousCh) 45 | select { 46 | case <-doneCh: 47 | case <-time.After(10 * time.Second): 48 | t.Errorf("timed out waiting for pipeline to complete") 49 | } 50 | } 51 | 52 | func TestDynamicWorkerPool(t *testing.T) { 53 | num := 5 54 | syncCh := make(chan struct{}, num) 55 | rendezvousCh := make(chan struct{}) 56 | 57 | task := TaskFunc(func(_ context.Context, _ Data, _ TaskParams) (Data, error) { 58 | // Signal that we have reached the sync point and wait for the 59 | // green light to proceed by the test code 60 | syncCh <- struct{}{} 61 | <-rendezvousCh 62 | return nil, nil 63 | }) 64 | 65 | src := &sourceStub{data: stringDataValues(num * 2)} 66 | 67 | p := NewPipeline(DynamicPool("", task, num)) 68 | doneCh := make(chan struct{}) 69 | go func() { 70 | if err := p.Execute(context.TODO(), src, nil); err != nil { 71 | t.Errorf("Error executing the Pipeline: %v", err) 72 | } 73 | close(doneCh) 74 | }() 75 | 76 | // Wait for all workers to reach sync point. This means that the pool 77 | // has scaled up to the max number of workers 78 | for i := 0; i < num; i++ { 79 | select { 80 | case <-syncCh: 81 | case <-time.After(10 * time.Second): 82 | t.Errorf("timed out waiting for worker %d to reach sync point", i) 83 | } 84 | } 85 | 86 | // Allow workers to proceed and process the next batch of records 87 | close(rendezvousCh) 88 | select { 89 | case <-doneCh: 90 | case <-time.After(10 * time.Second): 91 | t.Errorf("timed out waiting for pipeline to complete") 92 | } 93 | } 94 | 95 | func BenchmarkFixedPool(b *testing.B) { 96 | for i := 0; i < b.N; i++ { 97 | p := NewPipeline(FixedPool("", makePassthroughTask(), 1)) 98 | src := &sourceStub{data: []Data{&stringData{val: "benchmark"}}} 99 | _ = p.Execute(context.TODO(), src, new(sinkStub)) 100 | } 101 | } 102 | 103 | func BenchmarkFixedPoolDataElements(b *testing.B) { 104 | sink := new(sinkStub) 105 | src := &sourceStub{data: stringDataValues(b.N)} 106 | p := NewPipeline(FixedPool("", makePassthroughTask(), 100)) 107 | 108 | b.StartTimer() 109 | _ = p.Execute(context.TODO(), src, sink) 110 | b.StopTimer() 111 | } 112 | 113 | func BenchmarkDynamicPool(b *testing.B) { 114 | for i := 0; i < b.N; i++ { 115 | p := NewPipeline(DynamicPool("", makePassthroughTask(), 1)) 116 | src := &sourceStub{data: []Data{&stringData{val: "benchmark"}}} 117 | _ = p.Execute(context.TODO(), src, new(sinkStub)) 118 | } 119 | } 120 | 121 | func BenchmarkDynamicPoolDataElements(b *testing.B) { 122 | sink := new(sinkStub) 123 | src := &sourceStub{data: stringDataValues(b.N)} 124 | p := NewPipeline(DynamicPool("", makePassthroughTask(), 1000)) 125 | 126 | b.StartTimer() 127 | _ = p.Execute(context.TODO(), src, sink) 128 | b.StopTimer() 129 | } 130 | -------------------------------------------------------------------------------- /sink.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import "context" 4 | 5 | // OutputSink is implemented by types that can operate as the tail of a pipeline. 6 | type OutputSink interface { 7 | // Consume processes a Data instance that has been emitted out of 8 | // a Pipeline instance. 9 | Consume(context.Context, Data) error 10 | } 11 | 12 | // SinkFunc is an adapter to allow the use of plain functions as OutputSink instances. 13 | type SinkFunc func(context.Context, Data) error 14 | 15 | // Consume calls f(ctx, data) 16 | func (f SinkFunc) Consume(ctx context.Context, data Data) error { 17 | return f(ctx, data) 18 | } 19 | -------------------------------------------------------------------------------- /sink_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "regexp" 7 | "testing" 8 | ) 9 | 10 | func TestSinkErrorHandling(t *testing.T) { 11 | src := &sourceStub{data: stringDataValues(3)} 12 | sink := &sinkStub{err: errors.New("sink error")} 13 | 14 | p := NewPipeline(testStage{t: t}) 15 | re := regexp.MustCompile("(?s).*pipeline output sink: sink error.*") 16 | if err := p.Execute(context.TODO(), src, sink); err == nil || !re.MatchString(err.Error()) { 17 | t.Errorf("Error did not match the expectation: %v", err) 18 | } 19 | } 20 | 21 | type sinkStub struct { 22 | data []Data 23 | err error 24 | } 25 | 26 | func (s *sinkStub) Consume(_ context.Context, d Data) error { 27 | s.data = append(s.data, d) 28 | return s.err 29 | } 30 | -------------------------------------------------------------------------------- /source.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import "context" 4 | 5 | // InputSource is implemented by types that generate Data instances which can be 6 | // used as inputs to a Pipeline instance. 7 | type InputSource interface { 8 | // Next fetches the next data element from the source. If no more items are 9 | // available or an error occurs, calls to Next return false. 10 | Next(context.Context) bool 11 | 12 | // Data returns the next data to be processed. 13 | Data() Data 14 | 15 | // Error return the last error observed by the source. 16 | Error() error 17 | } 18 | -------------------------------------------------------------------------------- /source_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "regexp" 7 | "testing" 8 | ) 9 | 10 | func TestSourceErrorHandling(t *testing.T) { 11 | src := &sourceStub{ 12 | data: stringDataValues(3), 13 | err: errors.New("source error"), 14 | } 15 | sink := new(sinkStub) 16 | 17 | p := NewPipeline(testStage{t: t}) 18 | re := regexp.MustCompile("(?s).*pipeline input source: source error.*") 19 | if err := p.Execute(context.TODO(), src, sink); err == nil || !re.MatchString(err.Error()) { 20 | t.Errorf("Error did not match the expectation: %v", err) 21 | } 22 | } 23 | 24 | type sourceStub struct { 25 | index int 26 | data []Data 27 | err error 28 | } 29 | 30 | func (s *sourceStub) Next(context.Context) bool { 31 | if s.err != nil || s.index == len(s.data) { 32 | return false 33 | } 34 | s.index++ 35 | return true 36 | } 37 | func (s *sourceStub) Error() error { return s.err } 38 | func (s *sourceStub) Data() Data { return s.data[s.index-1] } 39 | -------------------------------------------------------------------------------- /stage.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/caffix/queue" 7 | ) 8 | 9 | // StageRegistry is a map of stage identifiers to input channels. 10 | type StageRegistry map[string]queue.Queue 11 | 12 | // StageParams provides the information needed for executing a pipeline 13 | // Stage. The Pipeline passes a StageParams instance to the Run method 14 | // of each stage. 15 | type StageParams interface { 16 | // Pipeline returns the pipeline executing this stage. 17 | Pipeline() *Pipeline 18 | 19 | // Position returns the position of this stage in the pipeline. 20 | Position() int 21 | 22 | // Input returns the input channel for this stage. 23 | Input() <-chan Data 24 | 25 | // Output returns the output channel for this stage. 26 | Output() chan<- Data 27 | 28 | // DataQueue returns the alternative data queue for this stage. 29 | DataQueue() queue.Queue 30 | 31 | // Error returns the queue that reports errors encountered by the stage. 32 | Error() queue.Queue 33 | 34 | // Registry returns a map of stage names to stage input channels. 35 | Registry() StageRegistry 36 | } 37 | 38 | // Stage is designed to be executed in sequential order to 39 | // form a multi-stage data pipeline. 40 | type Stage interface { 41 | // ID returns the optional identifier assigned to this stage. 42 | ID() string 43 | 44 | // Run executes the processing logic for this stage by reading 45 | // data from the input channel, processing the data and sending 46 | // the results to the output channel. Run blocks until the stage 47 | // input channel is closed, the context expires, or an error occurs. 48 | Run(context.Context, StageParams) 49 | } 50 | 51 | type execTask func(context.Context, Data, StageParams) (Data, error) 52 | 53 | func processStageData(ctx context.Context, sp StageParams, task execTask) bool { 54 | cont := true 55 | // Processes data from the input channel and data queue 56 | select { 57 | case dataIn, ok := <-sp.Input(): 58 | if ok { 59 | _, _ = task(ctx, dataIn, sp) 60 | } else if sp.DataQueue().Len() == 0 { 61 | cont = false 62 | } 63 | case <-sp.DataQueue().Signal(): 64 | if d, ok := sp.DataQueue().Next(); ok { 65 | if data, ok := d.(Data); ok { 66 | _, _ = task(ctx, data, sp) 67 | } 68 | } 69 | } 70 | return cont 71 | } 72 | -------------------------------------------------------------------------------- /stage_test.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | ) 7 | 8 | func TestStageRegistry(t *testing.T) { 9 | src := &sourceStub{data: stringDataValues(1)} 10 | sink := &sinkStub{} 11 | 12 | max := 3 13 | var count int 14 | task := TaskFunc(func(ctx context.Context, data Data, tp TaskParams) (Data, error) { 15 | count++ 16 | if count > max { 17 | return data, nil 18 | } 19 | 20 | // Send data to an unnamed stage 21 | if count == 1 { 22 | SendData(ctx, "fake", data.Clone(), tp) 23 | } 24 | 25 | SendData(ctx, "counter", data.Clone(), tp) 26 | return data, nil 27 | }) 28 | 29 | p := NewPipeline(FIFO("counter", task)) 30 | if err := p.Execute(context.TODO(), src, sink); err != nil { 31 | t.Errorf("Error executing the Pipeline: %v", err) 32 | } 33 | if c := count - 1; c != max { 34 | t.Errorf("Retry count does not match expected value.\nWanted:%v\nGot:%v\n", max, c) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /task.go: -------------------------------------------------------------------------------- 1 | package pipeline 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | // TaskParams provides access to pipeline mechanisms needed by a Task. 8 | // The Stage passes a TaskParams instance to the Process method of 9 | // each task. 10 | type TaskParams interface { 11 | // Pipeline returns the pipeline executing this task. 12 | Pipeline() *Pipeline 13 | 14 | // Registry returns a map of stage names to stage input channels. 15 | Registry() StageRegistry 16 | } 17 | 18 | // Task is implemented by types that can process Data as part of a pipeline stage. 19 | type Task interface { 20 | // Process operates on the input data and returns back a new data to be 21 | // forwarded to the next pipeline stage. Task instances may also opt to 22 | // prevent the data from reaching the rest of the pipeline by returning 23 | // a nil data value instead. 24 | Process(context.Context, Data, TaskParams) (Data, error) 25 | } 26 | 27 | // TaskFunc is an adapter to allow the use of plain functions as Task instances. 28 | type TaskFunc func(context.Context, Data, TaskParams) (Data, error) 29 | 30 | // Process calls f(ctx, data) 31 | func (f TaskFunc) Process(ctx context.Context, data Data, params TaskParams) (Data, error) { 32 | return f(ctx, data, params) 33 | } 34 | 35 | // SendData marks the provided data as new to the pipeline and sends it to the 36 | // provided named stage. 37 | func SendData(ctx context.Context, stage string, data Data, tp TaskParams) { 38 | select { 39 | case <-ctx.Done(): 40 | return 41 | default: 42 | } 43 | 44 | if q, found := tp.Registry()[stage]; found { 45 | q.Append(data) 46 | } 47 | } 48 | 49 | type taskParams struct { 50 | pipeline *Pipeline 51 | registry StageRegistry 52 | } 53 | 54 | func (tp *taskParams) Pipeline() *Pipeline { return tp.pipeline } 55 | func (tp *taskParams) Registry() StageRegistry { return tp.registry } 56 | --------------------------------------------------------------------------------