-
Notifications
You must be signed in to change notification settings - Fork 11
/
pipeline.go
158 lines (124 loc) · 2.35 KB
/
pipeline.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package dns
import (
"io"
"sync"
"time"
)
type pipeline struct {
Conn
rmu, wmu sync.Mutex
mu sync.Mutex
inflight map[int]pipelineTx
readerr error
}
func (p *pipeline) alive() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.readerr == nil
}
func (p *pipeline) conn() Conn {
return &pipelineConn{
pipeline: p,
tx: pipelineTx{
msgerrc: make(chan msgerr),
abortc: make(chan struct{}),
},
}
}
func (p *pipeline) run() {
var err error
for {
var msg Message
p.rmu.Lock()
if err = p.Recv(&msg); err != nil {
break
}
p.rmu.Unlock()
p.mu.Lock()
tx, ok := p.inflight[msg.ID]
delete(p.inflight, msg.ID)
p.mu.Unlock()
if !ok {
continue
}
go tx.deliver(msgerr{msg: &msg})
}
p.rmu.Unlock()
p.mu.Lock()
p.readerr = err
txs := make([]pipelineTx, 0, len(p.inflight))
for _, tx := range p.inflight {
txs = append(txs, tx)
}
p.mu.Unlock()
for _, tx := range txs {
go tx.deliver(msgerr{err: err})
}
}
type pipelineConn struct {
*pipeline
aborto sync.Once
tx pipelineTx
readDeadline, writeDeadline time.Time
}
func (c *pipelineConn) Close() error {
c.aborto.Do(c.tx.abort)
return nil
}
func (c *pipelineConn) Recv(msg *Message) error {
var me msgerr
select {
case me = <-c.tx.msgerrc:
case <-c.tx.abortc:
return io.ErrUnexpectedEOF
}
if err := me.err; err != nil {
return err
}
*msg = *me.msg // shallow copy
return nil
}
func (c *pipelineConn) Send(msg *Message) error {
if err := c.register(msg); err != nil {
return err
}
c.wmu.Lock()
defer c.wmu.Unlock()
if err := c.Conn.SetWriteDeadline(c.writeDeadline); err != nil {
return err
}
return c.Conn.Send(msg)
}
func (c *pipelineConn) SetDeadline(t time.Time) error {
c.SetReadDeadline(t)
c.SetWriteDeadline(t)
return nil
}
func (c *pipelineConn) SetReadDeadline(t time.Time) error {
c.readDeadline = t
return nil
}
func (c *pipelineConn) SetWriteDeadline(t time.Time) error {
c.writeDeadline = t
return nil
}
func (c *pipelineConn) register(msg *Message) error {
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.inflight[msg.ID]; ok {
return ErrConflictingID
}
c.inflight[msg.ID] = c.tx
return nil
}
type pipelineTx struct {
msgerrc chan msgerr
abortc chan struct{}
}
func (p pipelineTx) abort() { close(p.abortc) }
func (p pipelineTx) deliver(me msgerr) {
select {
case p.msgerrc <- me:
case <-p.abortc:
}
}