-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
100 lines (86 loc) · 1.53 KB
/
reader.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
package walx
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
"github.com/txix-open/wal"
)
const (
waitEntryTimeout = 500 * time.Millisecond
)
type ReadOnlyLog interface {
Read(index uint64) (data []byte, err error)
}
type Reader struct {
unsub func()
index *atomic.Uint64
log ReadOnlyLog
closed *atomic.Bool
readTime *time.Timer
ch chan struct{}
}
func NewReader(unsub func(), index uint64, log ReadOnlyLog) *Reader {
i := &atomic.Uint64{}
i.Store(index)
return &Reader{
unsub: unsub,
index: i,
log: log,
closed: &atomic.Bool{},
readTime: time.NewTimer(waitEntryTimeout),
ch: make(chan struct{}),
}
}
func (r *Reader) Read(ctx context.Context) (Entry, error) {
for {
if r.closed.Load() {
return Entry{}, ErrClosed
}
index := r.index.Load()
data, err := r.log.Read(index)
if errors.Is(err, wal.ErrNotFound) {
r.readTime.Reset(waitEntryTimeout)
select {
case <-r.ch:
case <-r.readTime.C:
case <-ctx.Done():
return Entry{}, ctx.Err()
}
continue
}
if err != nil {
return Entry{}, fmt.Errorf("wal read: %w", err)
}
r.index.Add(1)
return Entry{
Data: data,
Index: index,
}, nil
}
}
func (r *Reader) Close() {
if r.closed.Load() {
return
}
r.unsub()
r.close()
}
func (r *Reader) close() {
r.closed.Store(true)
close(r.ch)
r.readTime.Stop()
}
func (r *Reader) LastIndex() uint64 {
return r.index.Load() - 1
}
var (
signal = struct{}{}
)
func (r *Reader) notify() {
select {
case r.ch <- signal:
default:
}
}