-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstream.go
118 lines (94 loc) · 2.24 KB
/
stream.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
package tomtp
import (
"errors"
"io"
"log/slog"
"sync"
)
type StreamState uint8
const (
StreamStarting StreamState = iota
StreamOpen
StreamEnding
StreamEnded
)
var (
ErrStreamClosed = errors.New("stream closed")
ErrWriteTooLarge = errors.New("write exceeds maximum size")
ErrTimeout = errors.New("operation timed out")
)
type Stream struct {
// Connection info
streamId uint32
streamSnNext uint64
conn *Connection
state StreamState
// Flow control
rcvWndSize uint64 // Receive window size
sndWndSize uint64 // Send window size
// Reliable delivery buffers
rbRcv *ReceiveBuffer // Receive buffer for incoming data
// Statistics
bytesRead uint64
lastWindowUpdate uint64
// Stream state
lastActive uint64 // Unix timestamp of last activity
closeTimeout uint64 // Unix timestamp for close timeout
closeInitiated bool
closePending bool
mu sync.Mutex
closeOnce sync.Once
cond *sync.Cond
}
func (s *Stream) Write(b []byte) (n int, err error) {
s.mu.Lock()
defer s.mu.Unlock()
slog.Debug("Write", debugGoroutineID(), s.debug(), slog.String("b...", string(b[:min(10, len(b))])))
return s.encode(b, n, err)
}
func (s *Stream) Read(b []byte) (n int, err error) {
s.mu.Lock()
defer s.mu.Unlock()
slog.Debug("read data start", debugGoroutineID(), s.debug())
segment := s.rbRcv.RemoveOldestInOrder()
if segment == nil {
if s.state >= StreamEnded {
return 0, io.EOF
}
return 0, nil
}
n = copy(b, segment.data)
slog.Debug("read Data done", debugGoroutineID(), s.debug(), slog.String("b...", string(b[:min(10, n)])))
s.bytesRead += uint64(n)
return n, nil
}
func (s *Stream) Update() error {
if s.state == StreamEnding || s.conn.state == ConnectionEnding || len(s.rbRcv.acks) > 0 {
_, err := s.Write([]byte{})
if err != nil {
return err
}
}
return nil
}
func (s *Stream) CloseAll() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.conn.state >= ConnectionEnding {
return nil
}
s.conn.state = ConnectionEnding
return nil
}
func (s *Stream) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.state >= StreamEnding {
return nil
}
s.state = StreamEnding
return nil
}
func (s *Stream) debug() slog.Attr {
return s.conn.listener.debug(s.conn.remoteAddr)
}