Skip to content

Commit

Permalink
feat(executors): return all errors as wrapped error
Browse files Browse the repository at this point in the history
  • Loading branch information
lvlcn-t committed Jul 28, 2024
1 parent d1db56c commit dd2554b
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions executors/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,30 +74,46 @@ func (e Effector) WithFallback(fallback Effector) Effector {
}

// Concurrent returns an effector that runs the effectors concurrently and
// returns the first error that occurs.
// returns all errors that occurred as wrapped [errors.Join] error.
//
// Safe to use concurrently.
func Concurrent(effectors ...Effector) Effector {
return func(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
errs := make(chan error, len(effectors))
for _, effector := range effectors {
g.Go(func() error { return effector(ctx) })
effector := effector
g.Go(func() error {
err := effector(ctx)
errs <- err
return err
})
}
go func() {
// The returned error is ignored here on purpose,
// as we are interested in all errors and not just the first one.
_ = g.Wait()
close(errs)
}()

var err error
for e := range errs {
err = errors.Join(err, e)
}
return g.Wait()
return err
}
}

// Sequential returns an effector that runs the effectors sequentially and
// returns the first error that occurs.
// returns all errors that occurred as wrapped [errors.Join] error.
//
// Safe to use concurrently.
func Sequential(effectors ...Effector) Effector {
return func(ctx context.Context) error {
var errs []error
for _, effector := range effectors {
if err := effector(ctx); err != nil {
return err
}
errs = append(errs, effector(ctx))
}
return nil
return errors.Join(errs...)
}
}

0 comments on commit dd2554b

Please sign in to comment.