/
blocking.go
140 lines (126 loc) · 2.65 KB
/
blocking.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
130
131
132
133
134
135
136
137
138
139
140
package svc
import (
"context"
"sync"
)
// WrapBlocking transforms a blocking start func (like http.ListenAndServe)
// and returns a Service
func WrapBlocking(start LifecycleFn, stop LifecycleFn) Service {
b := &base{start: start, startBlocking: true, stop: stop, ch: make(chan op)}
go b.init()
return b
}
type op struct {
ctx context.Context
op string
ret chan error
fn func(string)
}
type base struct {
start LifecycleFn
stop LifecycleFn
startBlocking bool
mu sync.Mutex
ch chan op
state int
}
func (b *base) init() {
var (
state = StateEmpty
startCh = make(chan error)
startErr error
startCancel func()
stopErr error
tonotify = make([]chan error, 0)
)
for {
select {
case err := <-startCh:
startErr = err
state = StateStopped
for _, ch := range tonotify {
ch <- startErr
}
tonotify = make([]chan error, 0)
case op := <-b.ch:
switch op.op {
case "do":
op.fn(state)
op.ret <- nil
case "start":
switch state {
case StateEmpty:
state = StateStarted
var ctx context.Context
ctx, startCancel = context.WithCancel(op.ctx)
var err error
if b.start != nil {
if b.startBlocking {
go func(ctx context.Context) { startCh <- b.start(ctx) }(ctx)
} else {
err = b.start(ctx)
}
}
op.ret <- err
case StateStarted:
op.ret <- nil
default:
op.ret <- ErrStartInvalid
}
case "stop":
switch state {
case StateStarted:
state = StateStopped
if b.stop != nil {
stopErr = b.stop(op.ctx)
}
if startCancel != nil {
startCancel()
}
op.ret <- stopErr
for _, ch := range tonotify {
ch <- stopErr
}
tonotify = make([]chan error, 0)
case StateStopped:
op.ret <- stopErr
default:
op.ret <- ErrStopInvalid
}
case "wait":
switch state {
case StateStarted:
tonotify = append(tonotify, op.ret)
case StateStopped:
err := startErr
if err == nil {
err = stopErr
}
op.ret <- err
default:
op.ret <- ErrWaitInvalid
}
}
}
}
}
func (b *base) Start(ctx context.Context) error {
ch := make(chan error)
b.ch <- op{op: "start", ret: ch, ctx: ctx}
return <-ch
}
func (b *base) Stop(ctx context.Context) error {
ch := make(chan error)
b.ch <- op{op: "stop", ret: ch, ctx: ctx}
return <-ch
}
func (b *base) Wait(ctx context.Context) error {
ch := make(chan error)
b.ch <- op{op: "wait", ret: ch, ctx: ctx}
return <-ch
}
func (b *base) WithStatus(fn func(string)) {
ch := make(chan error)
b.ch <- op{op: "do", ret: ch, fn: fn, ctx: nil}
<-ch
}