/
stream.go
79 lines (65 loc) · 2.09 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
package streams
import (
"io"
"io/ioutil"
"time"
core "github.com/libp2p/go-libp2p-core"
"github.com/pkg/errors"
)
// Stream represents a stream in the system
type Stream interface {
// ID returns the id of the stream
ID() string
io.Closer
// CloseWrite closes the stream for writing but leaves it open for
// reading. It does not free the stream, a call Close or
// Reset is required.
CloseWrite() error
// ReadWithTimeout will read bytes from stream and return the result, will return error if timeout or error.
// does not close stream when returns
ReadWithTimeout(timeout time.Duration) ([]byte, error)
// WriteWithTimeout will write bytes to stream, will return error if timeout or error.
// does not close stream when returns
WriteWithTimeout(data []byte, timeout time.Duration) error
}
// streamWrapper is a wrapper struct for the core.Stream interface, implements Stream and network.SSVStream
type streamWrapper struct {
s core.Stream
}
// NewStream returns a new instance of stream
func NewStream(s core.Stream) Stream {
return &streamWrapper{
s: s,
}
}
// Close closes the stream
func (ts *streamWrapper) Close() error {
return ts.s.Close()
}
// CloseWrite closes write stream
func (ts *streamWrapper) CloseWrite() error {
return ts.s.CloseWrite()
}
// ReadWithTimeout reads with timeout
func (ts *streamWrapper) ReadWithTimeout(timeout time.Duration) ([]byte, error) {
if err := ts.s.SetReadDeadline(time.Now().Add(timeout)); err != nil {
return nil, errors.Wrap(err, "could not set read deadline")
}
return ioutil.ReadAll(ts.s)
}
// WriteWithTimeout reads next message with timeout
func (ts *streamWrapper) WriteWithTimeout(data []byte, timeout time.Duration) error {
if err := ts.s.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
return errors.Wrap(err, "could not set write deadline")
}
n := len(data)
bytsWrote, err := ts.s.Write(data)
if bytsWrote != n {
return errors.Errorf("written bytes (%d) to sync stream doesnt match input data (%d)", bytsWrote, n)
}
return err
}
// ID returns the id of the stream
func (ts *streamWrapper) ID() string {
return ts.s.ID()
}