-
Notifications
You must be signed in to change notification settings - Fork 3
/
stream.go
78 lines (68 loc) · 1.78 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
package memlog
import (
"context"
"errors"
"time"
)
const (
streamBackoffInterval = time.Millisecond * 10
)
// Stream is an iterator to stream records in order from a log. It must only be
// used within the same goroutine.
type Stream struct {
ctx context.Context
log *Log
position Offset
done bool
err error
}
// Next blocks until the next Record is available. ok is true if the iterator
// has not stopped, otherwise ok is false and any subsequent calls return an
// invalid record and false.
//
// The caller must consult Err() which error caused stopping the error.
func (s *Stream) Next() (r Record, ok bool) {
for {
if s.done {
return Record{}, false
}
if s.ctx.Err() != nil {
s.err = s.ctx.Err()
s.done = true
return Record{}, false
}
r, err := s.log.Read(s.ctx, s.position)
if err != nil {
if errors.Is(err, ErrFutureOffset) {
// back off and continue polling
time.Sleep(streamBackoffInterval)
continue
}
s.err = err
s.done = true
return Record{}, false
}
s.position = r.Metadata.Offset + 1
return r, true
}
}
// Err returns the first error that has ocurred during streaming. This method
// should be called to inspect the error that caused stopping the iterator.
func (s *Stream) Err() error {
return s.err
}
// Stream returns a stream iterator to stream records, starting at the given
// start offset. If the start offset is in the future, stream will continuously
// poll until this offset is written.
//
// Use Stream.Next() to read from the stream. See the example for how to use
// this API.
//
// The returned stream iterator must only be used within the same goroutine.
func (l *Log) Stream(ctx context.Context, start Offset) Stream {
return Stream{
ctx: ctx,
log: l,
position: start,
}
}