-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink.go
321 lines (252 loc) · 6.64 KB
/
link.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package link
import (
"bytes"
"context"
"encoding/binary"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"golang.org/x/xerrors"
)
const (
ackPayloadLength = 4
)
// Link impalement io.ReadWriteCloser.
type link struct {
ID uint32
ctx context.Context
ctxCloseFunc context.CancelFunc
manager *manager
buf *bytes.Buffer
readableBufSize int32 // add it to improve performance, by using atomic instead of read buf.Len() with bufLock
bufLock sync.Mutex
readEvent chan struct{} // notify Read link has some data to be read, manager.readLoop and Read may notify it by call readAvailable
// when writeWind < 0, Link.Write will be blocked
writeWind int32
writeEvent chan struct{}
// rst int32
eof sync.Once
readDeadline atomic.Value // time.Time
writeDeadline atomic.Value // time.Time
dialCtx context.Context
dialCtxFunc context.CancelFunc
closeOnce sync.Once
}
// newLink will create a Link, but the Link isn't created at other side,
// user should write some data to let other side create the link.
func newLink(id uint32, m *manager, mode mode) *link {
link := &link{
ID: id,
manager: m,
buf: bytes.NewBuffer(make([]byte, 0, m.cfg.ReadBufSize)),
readableBufSize: m.cfg.ReadBufSize,
readEvent: make(chan struct{}, 1),
writeEvent: make(chan struct{}, 1),
}
link.ctx, link.ctxCloseFunc = context.WithCancel(m.ctx)
link.readDeadline.Store(time.Time{})
link.writeDeadline.Store(time.Time{})
if mode == ClientMode {
link.dialCtx, link.dialCtxFunc = context.WithCancel(context.Background())
}
link.writeAvailable()
return link
}
// readAvailable notify link is readable
func (l *link) readAvailable() {
select {
case l.readEvent <- struct{}{}:
default:
}
}
// writeAvailable notify link is writable
func (l *link) writeAvailable() {
select {
case l.writeEvent <- struct{}{}:
default:
}
}
// pushBytes push some data to link.buf.
func (l *link) pushBytes(p []byte) {
if len(p) == 0 {
return
}
l.bufLock.Lock()
l.buf.Write(p)
l.bufLock.Unlock()
atomic.AddInt32(&l.readableBufSize, -int32(len(p)))
l.readAvailable()
}
// pushPacket when manager recv a packet about this link,
// manager calls pushPacket to let link handles that packet.
func (l *link) pushPacket(p *Packet) {
switch p.CMD {
case PSH:
l.pushBytes(p.Payload)
case NEW:
atomic.StoreInt32(&l.writeWind, int32(binary.BigEndian.Uint32(p.Payload[:4])))
l.pushBytes(p.Payload[4:])
case ACK:
atomic.StoreInt32(&l.writeWind, int32(binary.BigEndian.Uint32(p.Payload)))
if atomic.LoadInt32(&l.writeWind) > 0 {
l.writeAvailable()
}
case CLOSE:
l.closeByPeer()
case ACPT:
l.dialCtxFunc()
atomic.StoreInt32(&l.writeWind, int32(binary.BigEndian.Uint32(p.Payload)))
}
}
func (l *link) Read(p []byte) (n int, err error) {
readDeadline := l.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() && time.Now().After(readDeadline) {
return 0, xerrors.Errorf("link read failed: %w", ErrTimeout)
}
// we should not pass a 0 length buffer into Read(p []byte), if so will always return (0, nil)
if len(p) == 0 {
return 0, nil
}
for {
l.bufLock.Lock()
n, _ = l.buf.Read(p)
l.bufLock.Unlock()
if n > 0 {
atomic.AddInt32(&l.readableBufSize, int32(n))
select {
case <-l.ctx.Done():
// when link is closed, peer doesn't care about the ack because it won't send any packets again
default:
go l.sendACK()
}
return
}
timeoutCtx := context.Background()
readDeadline = l.readDeadline.Load().(time.Time)
if !readDeadline.IsZero() {
timeoutCtx, _ = context.WithTimeout(context.Background(), readDeadline.Sub(time.Now()))
}
select {
case <-l.ctx.Done():
err = xerrors.Errorf("link read failed: %w", io.ErrClosedPipe)
l.eof.Do(func() {
err = io.EOF
})
if err == io.EOF {
return
}
select {
case <-l.manager.ctx.Done():
return 0, xerrors.Errorf("link read failed: %w", ErrManagerClosed)
default:
}
return
case <-l.readEvent:
// wait for peer writing data
case <-timeoutCtx.Done():
return 0, xerrors.Errorf("link read failed: %w", ErrTimeout)
}
}
}
func (l *link) Write(p []byte) (int, error) {
writeDeadline := l.writeDeadline.Load().(time.Time)
if !writeDeadline.IsZero() && time.Now().After(writeDeadline) {
return 0, xerrors.Errorf("link write failed: %w", ErrTimeout)
}
// we should not pass a 0 length buffer into Write(p []byte), if so will always return (0, nil)
if len(p) == 0 {
return 0, nil
}
select {
case <-l.ctx.Done():
select {
case <-l.manager.ctx.Done():
return 0, xerrors.Errorf("link write failed: %w", ErrManagerClosed)
default:
}
return 0, xerrors.Errorf("link write failed: %w", io.ErrClosedPipe)
case <-l.writeEvent:
if err := l.manager.writePacket(newPacket(l.ID, PSH, p)); err != nil {
return 0, xerrors.Errorf("link write failed: %w", err)
}
if atomic.AddInt32(&l.writeWind, -int32(len(p))) > 0 {
l.writeAvailable()
}
return len(p), nil
}
}
// Close close the link.
func (l *link) Close() (err error) {
select {
case <-l.ctx.Done():
// fast path
return xerrors.Errorf("link closed failed: %w", ErrLinkClosed)
default:
}
err = ErrLinkClosed
l.closeOnce.Do(func() {
l.ctxCloseFunc()
l.manager.removeLink(l.ID)
err = l.manager.writePacket(newPacket(l.ID, CLOSE, nil))
})
if err != nil {
return xerrors.Errorf("link closed failed: %w", err)
}
return nil
}
// closeByPeer when link is closed by peer, closeByPeer will be called.
func (l *link) closeByPeer() {
l.ctxCloseFunc()
l.manager.removeLink(l.ID)
}
// sendACK check if n > 65535, if n > 65535 will send more then 1 ACK packet.
func (l *link) sendACK() {
buf := make([]byte, ackPayloadLength)
size := atomic.LoadInt32(&l.readableBufSize)
if size < 0 {
size = 0
}
binary.BigEndian.PutUint32(buf, uint32(size))
l.manager.writePacket(newPacket(l.ID, ACK, buf))
}
func (l *link) LocalAddr() net.Addr {
return Addr{
ID: strconv.Itoa(int(l.ID)),
}
}
func (l *link) RemoteAddr() net.Addr {
return Addr{
ID: strconv.Itoa(int(l.ID)),
}
}
func (l *link) SetDeadline(t time.Time) error {
select {
case <-l.ctx.Done():
return xerrors.Errorf("link set deadline failed: %w", ErrLinkClosed)
default:
}
l.readDeadline.Store(t)
l.writeDeadline.Store(t)
return nil
}
func (l *link) SetReadDeadline(t time.Time) error {
select {
case <-l.ctx.Done():
return xerrors.Errorf("link set read deadline failed: %w", ErrLinkClosed)
default:
}
l.readDeadline.Store(t)
return nil
}
func (l *link) SetWriteDeadline(t time.Time) error {
select {
case <-l.ctx.Done():
return xerrors.Errorf("link set write deadline failed: %w", ErrLinkClosed)
default:
}
l.writeDeadline.Store(t)
return nil
}