-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathreadbuffer.go
126 lines (107 loc) · 2.41 KB
/
readbuffer.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
package remotedialer
import (
"bytes"
"errors"
"fmt"
"io"
"sync"
"time"
"github.com/sirupsen/logrus"
)
const (
MaxBuffer = 1 << 21
)
type readBuffer struct {
id, readCount, offerCount int64
cond sync.Cond
deadline time.Time
buf bytes.Buffer
err error
backPressure *backPressure
}
func newReadBuffer(id int64, backPressure *backPressure) *readBuffer {
return &readBuffer{
id: id,
backPressure: backPressure,
cond: sync.Cond{
L: &sync.Mutex{},
},
}
}
func (r *readBuffer) Status() string {
r.cond.L.Lock()
defer r.cond.L.Unlock()
return fmt.Sprintf("%d/%d", r.readCount, r.offerCount)
}
func (r *readBuffer) Offer(reader io.Reader) error {
r.cond.L.Lock()
defer r.cond.L.Unlock()
if r.err != nil {
return r.err
}
if n, err := io.Copy(&r.buf, reader); err != nil {
r.offerCount += n
return err
} else if n > 0 {
r.offerCount += n
r.cond.Broadcast()
}
if r.buf.Len() > MaxBuffer {
r.backPressure.Pause()
}
if r.buf.Len() > MaxBuffer*2 {
logrus.Debugf("remotedialer buffer exceeded id=%d, length: %d", r.id, r.buf.Len())
}
return nil
}
func (r *readBuffer) Read(b []byte) (int, error) {
r.cond.L.Lock()
defer r.cond.L.Unlock()
for {
if r.buf.Len() > 0 {
n, err := r.buf.Read(b)
if err != nil {
// The definition of bytes.Buffer is that this will always return nil because
// we first checked that bytes.Buffer.Len() > 0. We assume that fact so just assert
// that here.
panic("bytes.Buffer returned err=\"" + err.Error() + "\" when buffer length was > 0")
}
r.readCount += int64(n)
r.cond.Broadcast()
if r.buf.Len() < MaxBuffer/8 {
r.backPressure.Resume()
}
return n, nil
}
if r.buf.Cap() > MaxBuffer/8 {
logrus.Debugf("resetting remotedialer buffer id=%d to zero, old cap %d", r.id, r.buf.Cap())
r.buf = bytes.Buffer{}
}
if r.err != nil {
return 0, r.err
}
now := time.Now()
if !r.deadline.IsZero() {
if now.After(r.deadline) {
return 0, errors.New("deadline exceeded")
}
}
var t *time.Timer
if !r.deadline.IsZero() {
t = time.AfterFunc(r.deadline.Sub(now), func() { r.cond.Broadcast() })
}
r.cond.Wait()
if t != nil {
t.Stop()
}
}
}
func (r *readBuffer) Close(err error) error {
r.cond.L.Lock()
defer r.cond.L.Unlock()
if r.err == nil {
r.err = err
}
r.cond.Broadcast()
return nil
}