-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstream.go
More file actions
101 lines (83 loc) · 2.42 KB
/
Copy pathstream.go
File metadata and controls
101 lines (83 loc) · 2.42 KB
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
package protocol
import (
"errors"
"io"
pb "friendnet.org/protocol/pb/v1"
"github.com/quic-go/quic-go"
"google.golang.org/protobuf/proto"
)
// Stream is an interface that defines a pull-based stream for any type of value.
type Stream[T any] interface {
// ReadNext reads the next value from the stream.
// Returns io.EOF when the stream has ended.
// Any later calls to Read after the stream has ended will continue to return io.EOF.
ReadNext() (T, error)
// Close closes the stream and its underlying source.
Close() error
}
// TypedMsgStream is a stream that reads protocol messages of a specific type.
type TypedMsgStream[T proto.Message] struct {
typ pb.MsgType
bidi ProtoBidi
}
func NewTypedMsgStream[T proto.Message](reader ProtoBidi, typ pb.MsgType) TypedMsgStream[T] {
return TypedMsgStream[T]{
bidi: reader,
typ: typ,
}
}
// ReadNext reads the next message from the stream.
// If the stream has ended, returns io.EOF.
func (s TypedMsgStream[T]) ReadNext() (*TypedProtoMsg[T], error) {
msg, err := ReadExpect[T](s.bidi, s.typ)
if err != nil {
var streamErr *quic.StreamError
if errors.As(err, &streamErr) ||
errors.Is(err, quic.ErrServerClosed) ||
errors.Is(err, quic.ErrTransportClosed) {
_ = s.bidi.Close()
return nil, io.EOF
}
}
return msg, err
}
// Close closes the stream and the underlying bidi.
func (s TypedMsgStream[T]) Close() error {
return s.bidi.Close()
}
// TransformerStream wraps a stream and applies a transformation function to each value read from the stream.
type TransformerStream[T, R any] struct {
stream Stream[T]
fn func(T) R
}
func NewTransformerStream[T, R any](stream Stream[T], fn func(T) R) TransformerStream[T, R] {
return TransformerStream[T, R]{
stream: stream,
fn: fn,
}
}
func (s TransformerStream[T, R]) ReadNext() (R, error) {
val, err := s.stream.ReadNext()
if err != nil {
var empty R
return empty, err
}
return s.fn(val), nil
}
func (s TransformerStream[T, R]) Close() error {
return s.stream.Close()
}
// ReadCloserWithFunc wraps an io.Reader and a function to close it.
type ReadCloserWithFunc struct {
reader io.Reader
closer func() error
}
func NewReadCloserWithFunc(reader io.Reader, closer func() error) ReadCloserWithFunc {
return ReadCloserWithFunc{reader: reader, closer: closer}
}
func (r ReadCloserWithFunc) Read(p []byte) (int, error) {
return r.reader.Read(p)
}
func (r ReadCloserWithFunc) Close() error {
return r.closer()
}