-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
74 lines (62 loc) · 1.43 KB
/
loop.go
File metadata and controls
74 lines (62 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package triggerable
import (
"context"
"fmt"
"sync"
)
func (l *loopImpl) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
wg := &sync.WaitGroup{}
wg.Add(len(l.triggerable))
var err error
for _, t := range l.triggerable {
go func(t trigger) {
if err = l.listen(ctx, t.Triggered(ctx)); err != nil {
cancel()
}
wg.Done()
}(t)
}
wg.Wait()
return err
}
func Loop(logger logger, triggerable ...trigger) *loopImpl {
return &loopImpl{logger: logger, triggerable: triggerable}
}
type loopImpl struct {
logger logger
triggerable []trigger
}
func (l *loopImpl) listen(ctx context.Context, actions chan action) error {
for {
select {
case <-ctx.Done():
l.logger.Info(ctx, fmt.Sprintf("loop stopped"))
return nil
case a := <-actions:
l.logger.Debug(ctx, fmt.Sprintf("running action %q", a.Name()))
if err := a.Run(ctx); err != nil {
l.logger.Info(ctx, fmt.Sprintf("action %q failed with error: %s", a.Name(), err))
retry, retryFunc := a.RetryOnError(err)
if !retry {
return err
}
l.logger.Info(ctx, fmt.Sprintf("retrying action %q", a.Name()))
// retry function can contain time.Sleep call
// or something blocking,
// so we running it in separate goroutine
go func() {
if retryFunc != nil {
retryFunc(ctx)
}
select {
case <-ctx.Done():
return
case actions <- a:
}
}()
}
}
}
}