/
async.go
86 lines (72 loc) · 1.81 KB
/
async.go
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
75
76
77
78
79
80
81
82
83
84
85
86
package optracker
import (
"context"
"sync"
"time"
"github.com/rs/zerolog/log"
)
type AsyncBuildJobs struct {
ctx context.Context
cancelCtx context.CancelFunc
m sync.Mutex
wait sync.WaitGroup
firstError error
tracker *OpTracker
start time.Time
appID string
}
func (a *AsyncBuildJobs) Tracker() *OpTracker {
return a.tracker
}
func NewAsyncBuildJobs(ctx context.Context, appID string, tracker *OpTracker) *AsyncBuildJobs {
ctx, cancelCtx := context.WithCancel(ctx)
return &AsyncBuildJobs{
ctx: ctx,
cancelCtx: cancelCtx,
appID: appID,
tracker: tracker,
start: time.Now(),
}
}
func (a *AsyncBuildJobs) Go(description string, track bool, minDuration time.Duration, f func(ctx context.Context) error) {
a.wait.Add(1)
trackerID := NoOperationID
if track && a.tracker != nil {
trackerID = a.tracker.Add(description, a.start)
}
go func() {
defer a.wait.Done()
log.Info().Str("app_id", a.appID).Str("job", description).Msg("starting build job")
if err := f(a.ctx); err != nil {
// If the context was canceled, it probably means the error was due to that.
if a.ctx.Err() != nil {
if a.tracker != nil {
a.tracker.Cancel(trackerID)
}
} else {
log.Err(err).Str("app_id", a.appID).Str("job", description).Msg("build job failed")
if a.tracker != nil {
a.tracker.Fail(trackerID, err)
}
a.recordError(err)
}
} else {
if a.tracker != nil {
a.tracker.Done(trackerID, minDuration)
}
log.Info().Str("app_id", a.appID).Str("job", description).Msg("build job finished")
}
}()
}
func (a *AsyncBuildJobs) Wait() error {
a.wait.Wait()
return a.firstError
}
func (a *AsyncBuildJobs) recordError(err error) {
a.m.Lock()
defer a.m.Unlock()
a.cancelCtx()
if a.firstError == nil {
a.firstError = err
}
}