forked from libp2p/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_write.go
201 lines (179 loc) · 4.84 KB
/
stream_write.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
package libp2pwebrtc
import (
"errors"
"os"
"time"
"github.com/zbliujia/go-libp2p/core/network"
"github.com/zbliujia/go-libp2p/p2p/transport/webrtc/pb"
)
var errWriteAfterClose = errors.New("write after close")
// If we have less space than minMessageSize, we don't put a new message on the data channel.
// Instead, we wait until more space opens up.
const minMessageSize = 1 << 10
func (s *stream) Write(b []byte) (int, error) {
s.mx.Lock()
defer s.mx.Unlock()
if s.closeErr != nil {
return 0, s.closeErr
}
switch s.sendState {
case sendStateReset:
return 0, network.ErrReset
case sendStateDataSent:
return 0, errWriteAfterClose
}
// Check if there is any message on the wire. This is used for control
// messages only when the read side of the stream is closed
if s.receiveState != receiveStateReceiving {
s.readLoopOnce.Do(s.spawnControlMessageReader)
}
if !s.writeDeadline.IsZero() && time.Now().After(s.writeDeadline) {
return 0, os.ErrDeadlineExceeded
}
var writeDeadlineTimer *time.Timer
defer func() {
if writeDeadlineTimer != nil {
writeDeadlineTimer.Stop()
}
}()
var n int
for len(b) > 0 {
if s.closeErr != nil {
return n, s.closeErr
}
switch s.sendState {
case sendStateReset:
return n, network.ErrReset
case sendStateDataSent:
return n, errWriteAfterClose
}
writeDeadline := s.writeDeadline
// deadline deleted, stop and remove the timer
if writeDeadline.IsZero() && writeDeadlineTimer != nil {
writeDeadlineTimer.Stop()
writeDeadlineTimer = nil
}
var writeDeadlineChan <-chan time.Time
if !writeDeadline.IsZero() {
if writeDeadlineTimer == nil {
writeDeadlineTimer = time.NewTimer(time.Until(writeDeadline))
} else {
if !writeDeadlineTimer.Stop() {
<-writeDeadlineTimer.C
}
writeDeadlineTimer.Reset(time.Until(writeDeadline))
}
writeDeadlineChan = writeDeadlineTimer.C
}
availableSpace := s.availableSendSpace()
if availableSpace < minMessageSize {
s.mx.Unlock()
select {
case <-s.writeAvailable:
case <-writeDeadlineChan:
s.mx.Lock()
return n, os.ErrDeadlineExceeded
case <-s.sendStateChanged:
case <-s.writeDeadlineUpdated:
}
s.mx.Lock()
continue
}
end := maxMessageSize
if end > availableSpace {
end = availableSpace
}
end -= protoOverhead + varintOverhead
if end > len(b) {
end = len(b)
}
msg := &pb.Message{Message: b[:end]}
if err := s.writer.WriteMsg(msg); err != nil {
return n, err
}
n += end
b = b[end:]
}
return n, nil
}
// used for reading control messages while writing, in case the reader is closed,
// as to ensure we do still get control messages. This is important as according to the spec
// our data and control channels are intermixed on the same conn.
func (s *stream) spawnControlMessageReader() {
if s.nextMessage != nil {
s.processIncomingFlag(s.nextMessage.Flag)
s.nextMessage = nil
}
go func() {
// no deadline needed, Read will return once there's a new message, or an error occurred
_ = s.dataChannel.SetReadDeadline(time.Time{})
for {
var msg pb.Message
if err := s.reader.ReadMsg(&msg); err != nil {
return
}
s.mx.Lock()
s.processIncomingFlag(msg.Flag)
s.mx.Unlock()
}
}()
}
func (s *stream) SetWriteDeadline(t time.Time) error {
s.mx.Lock()
defer s.mx.Unlock()
s.writeDeadline = t
select {
case s.writeDeadlineUpdated <- struct{}{}:
default:
}
return nil
}
func (s *stream) availableSendSpace() int {
buffered := int(s.dataChannel.BufferedAmount())
availableSpace := maxBufferedAmount - buffered
if availableSpace < 0 { // this should never happen, but better check
log.Errorw("data channel buffered more data than the maximum amount", "max", maxBufferedAmount, "buffered", buffered)
}
return availableSpace
}
// There's no way to determine the size of a Protobuf message in the pbio package.
// Setting the size to 100 works as long as the control messages (incl. the varint prefix) are smaller than that value.
const controlMsgSize = 100
func (s *stream) sendControlMessage(msg *pb.Message) error {
available := s.availableSendSpace()
if controlMsgSize < available {
return s.writer.WriteMsg(msg)
}
s.controlMsgQueue = append(s.controlMsgQueue, msg)
return nil
}
func (s *stream) cancelWrite() error {
s.mx.Lock()
defer s.mx.Unlock()
if s.sendState != sendStateSending {
return nil
}
s.sendState = sendStateReset
select {
case s.sendStateChanged <- struct{}{}:
default:
}
if err := s.sendControlMessage(&pb.Message{Flag: pb.Message_RESET.Enum()}); err != nil {
return err
}
s.maybeDeclareStreamDone()
return nil
}
func (s *stream) CloseWrite() error {
s.mx.Lock()
defer s.mx.Unlock()
if s.sendState != sendStateSending {
return nil
}
s.sendState = sendStateDataSent
if err := s.sendControlMessage(&pb.Message{Flag: pb.Message_FIN.Enum()}); err != nil {
return err
}
s.maybeDeclareStreamDone()
return nil
}