-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrunners.go
110 lines (100 loc) · 2.03 KB
/
runners.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package gohalt
import (
"context"
"fmt"
"sync"
)
type Runner interface {
Run(Runnable)
Result() error
}
type rsync struct {
thr Throttler
ctx context.Context
err error
report func(error)
}
func NewRunnerSync(ctx context.Context, thr Throttler) *rsync {
ctx, cancel := context.WithCancel(ctx)
r := rsync{thr: thr, ctx: ctx}
r.report = func(err error) {
if r.err != nil {
r.err = err
cancel()
}
}
return &r
}
func (r *rsync) Run(run Runnable) {
defer func() {
if err := r.thr.Release(r.ctx); err != nil {
r.report(fmt.Errorf("throttler error has happened %w", err))
}
}()
if err := r.thr.Acquire(r.ctx); err != nil {
r.report(fmt.Errorf("throttler error has happened %w", err))
return
}
select {
case <-r.ctx.Done():
r.report(fmt.Errorf("context error has happened %w", r.ctx.Err()))
return
default:
}
if err := run(r.ctx); err != nil {
r.report(fmt.Errorf("function error has happened %w", err))
return
}
}
func (r *rsync) Result() error {
return r.err
}
type rasync struct {
thr Throttler
ctx context.Context
wg sync.WaitGroup
err error
report func(error)
}
func NewRunnerAsync(ctx context.Context, thr Throttler) *rasync {
ctx, cancel := context.WithCancel(ctx)
r := rasync{thr: thr, ctx: ctx}
var once sync.Once
r.report = func(err error) {
once.Do(func() {
r.err = err
cancel()
})
}
return &r
}
func (r *rasync) Run(run Runnable) {
r.wg.Add(1)
go func() {
defer func() {
if err := r.thr.Release(r.ctx); err != nil {
r.report(fmt.Errorf("throttler error has happened %w", err))
}
r.wg.Done()
}()
if err := r.thr.Acquire(r.ctx); err != nil {
r.report(fmt.Errorf("throttler error has happened %w", err))
return
}
select {
case <-r.ctx.Done():
r.report(fmt.Errorf("context error has happened %w", r.ctx.Err()))
return
default:
}
if err := run(r.ctx); err != nil {
r.report(fmt.Errorf("function error has happened %w", err))
return
}
}()
}
func (r *rasync) Result() error {
r.wg.Wait()
r.report(nil)
return r.err
}