-
Notifications
You must be signed in to change notification settings - Fork 18
Include task runner #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
package async | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
) | ||
|
||
type Runner struct { | ||
sync.Mutex | ||
tasks []Task | ||
errs []error | ||
limit int | ||
waitErrors bool | ||
} | ||
|
||
// NewRunner creates a new task manager to control async functions. | ||
func NewRunner(tasks ...Task) *Runner { | ||
return &Runner{ | ||
tasks: tasks, | ||
limit: len(tasks), | ||
} | ||
} | ||
|
||
// WaitErrors tells the runner to wait for the response from all functions instead of cancelling them all when the first error occurs. | ||
func (r *Runner) WaitErrors() *Runner { | ||
r.waitErrors = true | ||
return r | ||
} | ||
|
||
// WithLimit defines a limit for concurrent tasks execution | ||
func (r *Runner) WithLimit(limit int) *Runner { | ||
r.limit = limit | ||
return r | ||
} | ||
|
||
// AllErrors returns all errors reported by functions | ||
func (r *Runner) AllErrors() []error { | ||
return r.errs | ||
} | ||
|
||
// registerErr store an error to final report | ||
func (r *Runner) registerErr(err error) { | ||
r.Lock() | ||
defer r.Unlock() | ||
if err != nil { | ||
r.errs = append(r.errs, err) | ||
} | ||
} | ||
|
||
// wrapperChannel converts a given Task to a channel of errors | ||
func wrapperChannel(ctx context.Context, task Task) chan error { | ||
cerr := make(chan error, 1) | ||
go func() { | ||
cerr <- task(ctx) | ||
close(cerr) | ||
}() | ||
return cerr | ||
} | ||
|
||
// Run starts the task manager and returns the first error or nil if succeed | ||
func (r *Runner) Run(parentCtx context.Context) error { | ||
ctx, cancel := context.WithCancel(parentCtx) | ||
cerr := make(chan error, len(r.tasks)) | ||
queue := make(chan struct{}, r.limit) | ||
var wg sync.WaitGroup | ||
wg.Add(len(r.tasks)) | ||
for _, task := range r.tasks { | ||
queue <- struct{}{} | ||
go func(fn func(context.Context) error) { | ||
defer func() { | ||
<-queue | ||
wg.Done() | ||
safePanic(cerr) | ||
}() | ||
|
||
select { | ||
case <-parentCtx.Done(): | ||
rodrigo-brito marked this conversation as resolved.
Show resolved
Hide resolved
|
||
cerr <- parentCtx.Err() | ||
r.registerErr(parentCtx.Err()) | ||
case err := <-wrapperChannel(ctx, fn): | ||
cerr <- err | ||
r.registerErr(err) | ||
} | ||
}(task) | ||
} | ||
|
||
go func() { | ||
wg.Wait() | ||
cancel() | ||
close(cerr) | ||
}() | ||
|
||
var firstErr error | ||
for err := range cerr { | ||
if err != nil && firstErr == nil { | ||
firstErr = err | ||
if r.waitErrors { | ||
continue | ||
} | ||
cancel() | ||
return firstErr | ||
} | ||
} | ||
|
||
return firstErr | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
package async | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestRunner_AllErrors(t *testing.T) { | ||
expectErr := errors.New("fail") | ||
runner := NewRunner(func(context.Context) error { | ||
return expectErr | ||
}).WaitErrors() | ||
err := runner.Run(context.Background()) | ||
require.Equal(t, expectErr, err) | ||
require.Len(t, runner.AllErrors(), 1) | ||
require.Equal(t, expectErr, runner.AllErrors()[0]) | ||
} | ||
|
||
func TestRunner_WaitErrors(t *testing.T) { | ||
expectErrOne := errors.New("fail") | ||
expectErrTwo := errors.New("fail") | ||
runner := NewRunner(func(context.Context) error { | ||
return expectErrOne | ||
}, func(context.Context) error { | ||
return expectErrTwo | ||
}).WaitErrors() | ||
err := runner.Run(context.Background()) | ||
require.False(t, err != expectErrOne && err != expectErrTwo) | ||
require.Len(t, runner.AllErrors(), 2) | ||
} | ||
|
||
func TestRunner_Run(t *testing.T) { | ||
calledFist := false | ||
calledSecond := false | ||
runner := NewRunner(func(context.Context) error { | ||
calledFist = true | ||
return nil | ||
}, func(context.Context) error { | ||
calledSecond = true | ||
return nil | ||
}) | ||
err := runner.Run(context.Background()) | ||
require.Nil(t, err) | ||
require.True(t, calledFist) | ||
require.True(t, calledSecond) | ||
} | ||
|
||
func TestRunner_WithLimit(t *testing.T) { | ||
order := 1 | ||
runner := NewRunner(func(context.Context) error { | ||
require.Equal(t, 1, order) | ||
order++ | ||
return nil | ||
}, func(context.Context) error { | ||
require.Equal(t, 2, order) | ||
order++ | ||
return nil | ||
}).WithLimit(1) | ||
err := runner.Run(context.Background()) | ||
require.Nil(t, err) | ||
} | ||
|
||
func TestRunner_ContextCancelled(t *testing.T) { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
|
||
start := time.Now() | ||
runner := NewRunner(func(context.Context) error { | ||
cancel() | ||
time.Sleep(time.Minute) | ||
return nil | ||
}) | ||
err := runner.Run(ctx) | ||
require.True(t, time.Since(start) < time.Minute) | ||
require.Equal(t, context.Canceled, err) | ||
} | ||
|
||
func TestRunner_ContextTimeout(t *testing.T) { | ||
ctx, cancel := context.WithTimeout(context.Background(), time.Second) | ||
defer cancel() | ||
|
||
start := time.Now() | ||
runner := NewRunner(func(context.Context) error { | ||
time.Sleep(time.Minute) | ||
return nil | ||
}) | ||
err := runner.Run(ctx) | ||
require.True(t, time.Since(start) < time.Minute) | ||
require.Equal(t, context.DeadlineExceeded, err) | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Retornar todos os erros no mesmo obj que responda a interface de erro, e depois tratar usando
error.As
não seria mais idiomático?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ciceroverneck O comportamento atual retorna o primeiro erro que ocorrer sem alterar ele. Nesse formato o
err == ErrExample
não funcionaria mais. O usuário é obrigado a usar oerrors.Is
ouerrrors.As
. Vai quebrar muito código nosso, o que acha?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
esse
AllErrors
em tese seria apenas mais uma alternativa caso ele chamar o Runner com a opçãoWaitErrors
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
De boa.