pax_global_header00006660000000000000000000000064133353764200014520gustar00rootroot0000000000000052 comment=93e5576933fecb0d3fb25f2d2e50a012efd93ca0 throttler-1.1/000077500000000000000000000000001333537642000134105ustar00rootroot00000000000000throttler-1.1/.circleci/000077500000000000000000000000001333537642000152435ustar00rootroot00000000000000throttler-1.1/.circleci/config.yml000066400000000000000000000013031333537642000172300ustar00rootroot00000000000000# Golang CircleCI 2.0 configuration file # # Check https://circleci.com/docs/2.0/language-go/ for more details version: 2 jobs: build: docker: # specify the version - image: golang #### TEMPLATE_NOTE: go expects specific checkout path representing url #### expecting it in the form of #### /go/src/github.com/circleci/go-tool #### /go/src/bitbucket.org/circleci/go-tool working_directory: /go/src/github.com/nozzle/throttler steps: - checkout # specify any bash command here prefixed with `run: ` - run: go test -coverprofile=coverage.txt -covermode=atomic - run: bash <(curl -s https://codecov.io/bash) -t $CODECOV_TOKEN throttler-1.1/.gitignore000066400000000000000000000000631333537642000153770ustar00rootroot00000000000000.glue !empty .idea server.command *.bak *.out *.covthrottler-1.1/LICENSE000066400000000000000000000260751333537642000144270ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. throttler-1.1/README.md000066400000000000000000000063331333537642000146740ustar00rootroot00000000000000# Throttler - intelligent WaitGroups [![GoDoc](https://godoc.org/github.com/nozzle/throttler?status.svg)](http://godoc.org/github.com/nozzle/throttler) [![Coverage Status](https://coveralls.io/repos/nozzle/throttler/badge.svg?branch=master)](https://coveralls.io/r/nozzle/throttler?branch=master) [ ![Codeship Status for nozzle/throttler](https://codeship.com/projects/02d33900-a744-0132-4353-2eb3789e9959/status?branch=master)](https://codeship.com/projects/67187) Throttler fills the gap between sync.WaitGroup and manually monitoring your goroutines with channels. The API is almost identical to Wait Groups, but it allows you to set a max number of workers that can be running simultaneously. It uses channels internally to block until a job completes by calling Done() or until all jobs have been completed. It also provides a built in error channel that captures your goroutine errors and provides access to them as `[]error` after you exit the loop. See a fully functional example on the playground at http://bit.ly/throttler-v3 Compare the Throttler example to the sync.WaitGroup example from http://golang.org/pkg/sync/#example_WaitGroup *3/12 - Breaking change* Throttler handles errors by default now and `Done` requires an error to be passed into it. If your goroutine doesn't generate errors, just call `Done(nil)` and there won't be any performance impact. *3/13 - Breaking change* `Err()` now returns an error. To get the slice of errors caught by Throttler, use `Errs()`. *5/12 - Added Batching Feature* User can now use `NewBatchedThrottler` instead of `New` to access the new batching features. See `TestBatchedThrottler` in `throttler_test.go` for usage example. ### How to use Throttler ``` // This example fetches several URLs concurrently, // using a Throttler to block until all the fetches are complete. // Compare to http://golang.org/pkg/sync/#example_WaitGroup func ExampleThrottler() { var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } // Create a new Throttler that will get 2 urls at a time t := throttler.New(2, len(urls)) for _, url := range urls { // Launch a goroutine to fetch the URL. go func(url string) { // Fetch the URL. err := http.Get(url) // Let Throttler know when the goroutine completes // so it can dispatch another worker t.Done(err) }(url) // Pauses until a worker is available or all jobs have been completed // Returning the total number of goroutines that have errored // lets you choose to break out of the loop without starting any more errorCount := t.Throttle() } } ``` ### vs How to use a sync.WaitGroup ``` // This example fetches several URLs concurrently, // using a WaitGroup to block until all the fetches are complete. func ExampleWaitGroup() { var wg sync.WaitGroup var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. go func(url string) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. http.Get(url) }(url) } // Wait for all HTTP fetches to complete. wg.Wait() } ```throttler-1.1/example_test.go000066400000000000000000000037701333537642000164400ustar00rootroot00000000000000package throttler import "fmt" type httpPkg struct{} func (httpPkg) Get(url string) error { return nil } var http httpPkg // This example fetches several URLs concurrently, // using a Throttler to block until all the fetches are complete. // Compare to http://golang.org/pkg/sync/#example_WaitGroup func ExampleThrottler() { var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } // Create a new Throttler that will get 2 urls at a time t := New(2, len(urls)) for _, url := range urls { // Launch a goroutine to fetch the URL. go func(url string) { // Fetch the URL. err := http.Get(url) // Let Throttler know when the goroutine completes // so it can dispatch another worker t.Done(err) }(url) // Pauses until a worker is available or all jobs have been completed // Returning the total number of goroutines that have errored // lets you choose to break out of the loop without starting any more errorCount := t.Throttle() if errorCount > 0 { break } } } // This example fetches several URLs concurrently, // using a Throttler to block until all the fetches are complete // and checks the errors returned. // Compare to http://golang.org/pkg/sync/#example_WaitGroup func ExampleThrottler_errors() error { var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } // Create a new Throttler that will get 2 urls at a time t := New(2, len(urls)) for _, url := range urls { // Launch a goroutine to fetch the URL. go func(url string) { // Let Throttler know when the goroutine completes // so it can dispatch another worker defer t.Done(nil) // Fetch the URL. http.Get(url) }(url) // Pauses until a worker is available or all jobs have been completed t.Throttle() } if t.Err() != nil { // Loop through the errors to see the details for i, err := range t.Errs() { fmt.Printf("error #%d: %s", i, err) } return t.Err() } return nil } throttler-1.1/throttler.go000066400000000000000000000133231333537642000157700ustar00rootroot00000000000000// Package throttler fills the gap between sync.WaitGroup and manually monitoring your goroutines // with channels. The API is almost identical to Wait Groups, but it allows you to set // a max number of workers that can be running simultaneously. It uses channels internally // to block until a job completes by calling Done(err) or until all jobs have been completed. // // After exiting the loop where you are using Throttler, you can call the `Err` or `Errs` method to check // for errors. `Err` will return a single error representative of all the errors Throttler caught. The // `Errs` method will return all the errors as a slice of errors (`[]error`). // // Compare the Throttler example to the sync.WaitGroup example http://golang.org/pkg/sync/#example_WaitGroup // // See a fully functional example on the playground at http://bit.ly/throttler-v3 package throttler import ( "fmt" "math" "sync" "sync/atomic" ) // Throttler stores all the information about the number of workers, the active workers and error information type Throttler struct { maxWorkers int32 workerCount int32 batchingTotal int32 batchSize int32 totalJobs int32 jobsStarted int32 jobsCompleted int32 doneChan chan struct{} errsMutex *sync.Mutex errs []error errorCount int32 } // New returns a Throttler that will govern the max number of workers and will // work with the total number of jobs. It panics if maxWorkers < 1. func New(maxWorkers, totalJobs int) *Throttler { if maxWorkers < 1 { panic("maxWorkers has to be at least 1") } return &Throttler{ maxWorkers: int32(maxWorkers), batchSize: 1, totalJobs: int32(totalJobs), doneChan: make(chan struct{}, totalJobs), errsMutex: &sync.Mutex{}, } } // NewBatchedThrottler returns a Throttler (just like New), but also enables batching. func NewBatchedThrottler(maxWorkers, batchingTotal, batchSize int) *Throttler { totalJobs := int(math.Ceil(float64(batchingTotal) / float64(batchSize))) t := New(maxWorkers, totalJobs) t.batchSize = int32(batchSize) t.batchingTotal = int32(batchingTotal) return t } // SetMaxWorkers lets you change the total number of workers that can run concurrently. NOTE: If // all workers are currently running, this setting is not guaranteed to take effect until one of them // completes and Throttle() is called again func (t *Throttler) SetMaxWorkers(maxWorkers int) { if maxWorkers < 1 { panic("maxWorkers has to be at least 1") } atomic.StoreInt32(&t.maxWorkers, int32(maxWorkers)) } // Throttle works similarly to sync.WaitGroup, except inside your goroutine dispatch // loop rather than after. It will not block until the number of active workers // matches the max number of workers designated in the call to NewThrottler or // all of the jobs have been dispatched. It stops blocking when Done has been called // as many times as totalJobs. func (t *Throttler) Throttle() int { if atomic.LoadInt32(&t.totalJobs) < 1 { return int(atomic.LoadInt32(&t.errorCount)) } atomic.AddInt32(&t.jobsStarted, 1) atomic.AddInt32(&t.workerCount, 1) // check to see if the current number of workers equals the max number of workers // if they are equal, wait for one to finish before continuing if atomic.LoadInt32(&t.workerCount) == atomic.LoadInt32(&t.maxWorkers) { atomic.AddInt32(&t.jobsCompleted, 1) atomic.AddInt32(&t.workerCount, -1) <-t.doneChan } // check to see if all of the jobs have been started, and if so, wait until all // jobs have been completed before continuing if atomic.LoadInt32(&t.jobsStarted) == atomic.LoadInt32(&t.totalJobs) { for atomic.LoadInt32(&t.jobsCompleted) < atomic.LoadInt32(&t.totalJobs) { atomic.AddInt32(&t.jobsCompleted, 1) <-t.doneChan } } return int(atomic.LoadInt32(&t.errorCount)) } // Done lets Throttler know that a job has been completed so that another worker // can be activated. If Done is called less times than totalJobs, // Throttle will block forever func (t *Throttler) Done(err error) { if err != nil { t.errsMutex.Lock() t.errs = append(t.errs, err) atomic.AddInt32(&t.errorCount, 1) t.errsMutex.Unlock() } t.doneChan <- struct{}{} } // Err returns an error representative of all errors caught by throttler func (t *Throttler) Err() error { t.errsMutex.Lock() defer t.errsMutex.Unlock() if atomic.LoadInt32(&t.errorCount) == 0 { return nil } return multiError(t.errs) } // Errs returns a slice of any errors that were received from calling Done() func (t *Throttler) Errs() []error { t.errsMutex.Lock() defer t.errsMutex.Unlock() return t.errs } type multiError []error func (te multiError) Error() string { errString := te[0].Error() if len(te) > 1 { errString += fmt.Sprintf(" (and %d more errors)", len(te)-1) } return errString } // BatchStartIndex returns the starting index for the next batch. The job count isn't modified // until th.Throttle() is called, so if you don't call Throttle before executing this // again, it will return the same index as before func (t *Throttler) BatchStartIndex() int { return int(atomic.LoadInt32(&t.jobsStarted) * atomic.LoadInt32(&t.batchSize)) } // BatchEndIndex returns the ending index for the next batch. It either returns the full batch size // or the remaining amount of jobs. The job count isn't modified // until th.Throttle() is called, so if you don't call Throttle before executing this // again, it will return the same index as before. func (t *Throttler) BatchEndIndex() int { end := (atomic.LoadInt32(&t.jobsStarted) + 1) * atomic.LoadInt32(&t.batchSize) if end > atomic.LoadInt32(&t.batchingTotal) { end = atomic.LoadInt32(&t.batchingTotal) } return int(end) } // TotalJobs returns the total number of jobs throttler is performing func (t *Throttler) TotalJobs() int { return int(atomic.LoadInt32(&t.totalJobs)) } throttler-1.1/throttler_test.go000066400000000000000000000203271333537642000170310ustar00rootroot00000000000000package throttler import ( "fmt" "math/rand" "reflect" "strconv" "testing" "time" ) func TestThrottle(t *testing.T) { var tests = []struct { Desc string Jobs []string MaxWorkers int TotalJobs int }{ { "Standard implementation", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 5, -1, }, { "Incorrectly has 0 as TotalWorkers", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 5, 0, }, { "More workers than jobs", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 50000, -1, }, } for _, test := range tests { totalJobs := len(test.Jobs) if test.TotalJobs != -1 { totalJobs = test.TotalJobs } th := New(test.MaxWorkers, totalJobs) for _, job := range test.Jobs { go func(job string, th *Throttler) { defer th.Done(nil) time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond) }(job, th) th.Throttle() } if th.Err() != nil { fmt.Println("err:", th.Err()) } } } func TestThrottleWithErrors(t *testing.T) { var tests = []struct { Desc string Jobs []string MaxWorkers int TotalJobs int }{ { "Standard implementation", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 5, -1, }, { "Standard implementation", []string{"job01", "job02"}, 5, -1, }, } for _, test := range tests { totalJobs := len(test.Jobs) if test.TotalJobs != -1 { totalJobs = test.TotalJobs } th := New(test.MaxWorkers, totalJobs) for _, job := range test.Jobs { go func(job string, th *Throttler) { jobNum, _ := strconv.ParseInt(job[len(job)-2:], 10, 8) var err error if jobNum%2 != 0 { err = fmt.Errorf("Error on %s", job) } defer th.Done(err) time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond) }(job, th) th.Throttle() } if len(th.Errs()) != totalJobs/2 { t.Fatal("The wrong number of errors were returned") } if th.Err() != nil { fmt.Println("err:", th.Err()) } } } func TestThrottlePanic(t *testing.T) { defer func() { if r := recover(); r == nil { t.Fatal("Test failed to panic") } }() New(0, 100) } func TestBatchedThrottler(t *testing.T) { var tests = []struct { Desc string ToBeBatched []string MaxWorkers int BatchSize int ExpectedBatchedSlices [][]string }{ { "Standard implementation", []string{"item01", "item02", "item03", "item04", "item05", "item06", "item07", "item08", "item09", "item10", "item11", "item12", "item13", "item14", "item15", "item16", "item17", "item18", "item19", "item20", "item21", "item22", "item23", "item24", "item25", "item26", "item27", "item28", "item29", "item30", "item31", "item32", "item33", "item34", "item35", "item36", "item37", "item38", "item39", "item40", "item41", "item42", "item43", "item44", "item45", "item46", "item47", "item48", "item49", }, 10, 2, [][]string{ {"item01", "item02"}, {"item03", "item04"}, {"item05", "item06"}, {"item07", "item08"}, {"item09", "item10"}, {"item11", "item12"}, {"item13", "item14"}, {"item15", "item16"}, {"item17", "item18"}, {"item19", "item20"}, {"item21", "item22"}, {"item23", "item24"}, {"item25", "item26"}, {"item27", "item28"}, {"item29", "item30"}, {"item31", "item32"}, {"item33", "item34"}, {"item35", "item36"}, {"item37", "item38"}, {"item39", "item40"}, {"item41", "item42"}, {"item43", "item44"}, {"item45", "item46"}, {"item47", "item48"}, {"item49"}, }, }, } for _, test := range tests { th := NewBatchedThrottler(test.MaxWorkers, len(test.ToBeBatched), test.BatchSize) for i := 0; i < th.TotalJobs(); i++ { go func(tbbSlice []string, expectedSlice []string) { var err error if !reflect.DeepEqual(tbbSlice, expectedSlice) { err = fmt.Errorf("wanted: %#v | got: %#v", expectedSlice, tbbSlice) } th.Done(err) }(test.ToBeBatched[th.BatchStartIndex():th.BatchEndIndex()], test.ExpectedBatchedSlices[i]) if errCount := th.Throttle(); errCount > 0 { break } } if th.Err() != nil { t.Fatal(th.Err()) } } } func TestSetMaxWorkers(t *testing.T) { var tests = []struct { Desc string Jobs []string InitialMaxWorkers int EndMaxWorkers int TotalJobs int }{ { "Standard implementation", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 1, 5, -1, }, { "Incorrectly has 0 as TotalWorkers", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 1, 5, 0, }, { "More workers than jobs", []string{"job01", "job02", "job03", "job04", "job05", "job06", "job07", "job08", "job09", "job10", "job11", "job12", "job13", "job14", "job15", "job16", "job17", "job18", "job19", "job20", "job21", "job22", "job23", "job24", "job25", "job26", "job27", "job28", "job29", "job30", "job31", "job32", "job33", "job34", "job35", "job36", "job37", "job38", "job39", "job40", "job41", "job42", "job43", "job44", "job45", "job46", "job47", "job48", "job49", "job50"}, 1, 50000, -1, }, } for _, test := range tests { totalJobs := len(test.Jobs) if test.TotalJobs != -1 { totalJobs = test.TotalJobs } th := New(test.InitialMaxWorkers, totalJobs) for i, job := range test.Jobs { if i == test.InitialMaxWorkers+1 { th.SetMaxWorkers(test.EndMaxWorkers) } go func(job string, th *Throttler) { defer th.Done(nil) time.Sleep(time.Duration(rand.Intn(5)) * time.Millisecond) }(job, th) th.Throttle() } if th.Err() != nil { fmt.Println("err:", th.Err()) } } } func TestSetMaxWorkersPanic(t *testing.T) { defer func() { if r := recover(); r == nil { t.Fatal("Test failed to panic") } }() th := New(1, 10) th.SetMaxWorkers(-1) }