-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvindicator.go
107 lines (89 loc) · 2.06 KB
/
vindicator.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
package vindicator
import (
"context"
"github.com/asaskevich/EventBus"
"sync"
"time"
)
type Worker interface {
Work(ctx context.Context) error // the worker() must be a blocking function
GetRunning() bool
SetRunning(bool)
}
type Vindicator struct {
interval int // check worker every Interval seconds
worker Worker
lock sync.Mutex
stopWorker func() // stop the worker
stopMonitor func() // stop the monitor
bus EventBus.Bus
}
type VindicatorFn func(v *Vindicator, args ...interface{})
func NewVindicator(worker Worker, interval int) *Vindicator {
return &Vindicator{
interval: interval,
worker: worker,
bus: EventBus.New(),
}
}
func (v *Vindicator) Start(ctx context.Context) error {
v.SetRunning()
defer v.SetStopped()
newCtx, cancel := context.WithCancel(ctx)
v.stopWorker = cancel
v.bus.Publish("worker:start", v)
defer v.bus.Publish("worker:stop", v)
if err := v.worker.Work(newCtx); err != nil {
v.bus.Publish("worker:error", v, err)
return err
}
return nil
}
func (v *Vindicator) Monitor(ctx context.Context) {
v.bus.Publish("monitor:start", v)
newCtx, cancel := context.WithCancel(ctx)
v.stopMonitor = cancel
timer := time.NewTicker(time.Duration(v.interval) * time.Second)
defer timer.Stop()
for {
select {
case <-newCtx.Done():
v.bus.Publish("monitor:stop", v)
return
case <-timer.C:
if !v.worker.GetRunning() {
v.bus.Publish("monitor:interrupt", v)
go func() {
_ = v.Start(ctx)
}()
} else {
v.bus.Publish("monitor:working", v)
}
}
}
}
func (v *Vindicator) Stop() {
if v.stopMonitor != nil {
v.stopMonitor()
}
if v.stopWorker != nil {
v.stopWorker()
// block the Stop function until the worker is stopped
v.Wait()
}
}
func (v *Vindicator) SetRunning() {
v.lock.Lock()
v.worker.SetRunning(true)
}
func (v *Vindicator) SetStopped() {
v.worker.SetRunning(false)
v.lock.Unlock()
}
func (v *Vindicator) Wait() {
v.lock.Lock()
v.lock.Unlock()
}
func (v *Vindicator) On(eventName string, callback VindicatorFn) {
_ = v.bus.Subscribe(eventName, callback)
}