-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdependency.go
129 lines (102 loc) · 2.09 KB
/
dependency.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package state
import (
"context"
"sync"
)
type dependState struct {
children *group
parent State
finished chan struct{}
ready chan struct{}
sync.RWMutex
}
// withDependency returns new state with merged parent and children
// with parent's dependency set on children.
func withDependency(parent State, children ...State) *dependState {
return &dependState{
children: merge(children...),
parent: parent,
finished: make(chan struct{}),
}
}
func (d *dependState) Shutdown(ctx context.Context) error {
return shutdown(ctx, d)
}
func (d *dependState) close() {
d.children.close()
<-d.children.finishSig()
d.parent.close()
<-d.parent.finishSig()
d.Done()
}
func (d *dependState) Done() {
d.Lock()
defer d.Unlock()
select {
case <-d.finished:
// Already closed
default:
close(d.finished)
}
}
func (d *dependState) Wait() {
d.children.Wait()
d.parent.Wait()
}
func (d *dependState) Ready() <-chan struct{} {
d.Lock()
defer d.Unlock()
if d.ready != nil {
// To avoid memory leaks - ready channel is created only once
return d.ready
}
d.ready = make(chan struct{})
go func() {
<-d.children.Ready()
<-d.parent.Ready()
close(d.ready)
}()
return d.ready
}
func (d *dependState) Err() (err error) {
if err = d.parent.Err(); err != nil {
return err
}
for _, states := range d.children.states {
if err = states.Err(); err != nil {
return err
}
}
return
}
func (d *dependState) Value(key interface{}) (value interface{}) {
if value = d.parent.Value(key); value != nil {
return value
}
for _, states := range d.children.states {
if value = states.Value(key); value != nil {
return value
}
}
return
}
func (d *dependState) DependsOn(children ...State) State {
return d.dependsOn(children...)
}
func (d *dependState) dependsOn(children ...State) *dependState {
return withDependency(d, children...)
}
func (d *dependState) finishSig() <-chan struct{} {
return d.finished
}
func (d *dependState) cause() error {
err := d.children.cause()
if err != nil {
return err
}
err = d.parent.cause()
if err != nil {
return err
}
return nil
}