-
Notifications
You must be signed in to change notification settings - Fork 11
/
state.go
74 lines (64 loc) · 1.29 KB
/
state.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
package j8a
import (
"fmt"
"github.com/rs/zerolog/log"
"math"
"time"
)
type State string
const (
Bootstrap State = "Bootstrap"
Daemon State = "Daemon"
Shutdown State = "Shutdown"
)
func (s State) Lesser(t State) bool {
if s == Bootstrap && (t == Daemon || t == Shutdown) {
return true
}
if s == Daemon && t == Shutdown {
return true
}
return false
}
type StateHandler struct {
Current State
Update chan State
}
func NewStateHandler() *StateHandler {
return &StateHandler{
Current: Bootstrap,
Update: make(chan State),
}
}
func (sh *StateHandler) waitState(s State, timeoutSeconds ...int) {
if s == sh.Current || s.Lesser(sh.Current) {
return
} else {
to := time.Duration(math.MaxInt64)
if len(timeoutSeconds) > 0 {
to = time.Second * time.Duration(timeoutSeconds[0])
}
for {
select {
case ev := <-sh.Update:
if s == ev || s.Lesser(ev) {
return
}
case <-time.After(to):
return
}
}
}
}
func (sh *StateHandler) setState(s State) {
// == matters because we may want to retrigger the state for waiting goroutines.
if sh.Current == s || sh.Current.Lesser(s) {
sh.Current = s
msg := fmt.Sprintf("server state now %v", sh.Current)
log.Info().Msg(msg)
//needs to be async else setState blocks
go func() {
sh.Update <- s
}()
}
}