5
5
"fmt"
6
6
"os"
7
7
"path/filepath"
8
+ "time"
8
9
9
10
errorutils "github.com/sei-protocol/sei-db/common/errors"
10
11
"github.com/sei-protocol/sei-db/common/logger"
@@ -16,12 +17,14 @@ import (
16
17
var _ types.Stream [proto.ChangelogEntry ] = (* Stream )(nil )
17
18
18
19
type Stream struct {
20
+ dir string
19
21
log * wal.Log
20
22
config Config
21
23
logger logger.Logger
22
24
writeChannel chan * Message
23
25
errSignal chan error
24
26
nextOffset uint64
27
+ isClosed bool
25
28
}
26
29
27
30
type Message struct {
@@ -33,7 +36,8 @@ type Config struct {
33
36
DisableFsync bool
34
37
ZeroCopy bool
35
38
WriteBufferSize int
36
- KeepLast int
39
+ KeepRecent uint64
40
+ PruneInterval time.Duration
37
41
}
38
42
39
43
// NewStream creates a new changelog stream that persist the changesets in the log
@@ -45,20 +49,22 @@ func NewStream(logger logger.Logger, dir string, config Config) (*Stream, error)
45
49
if err != nil {
46
50
return nil , err
47
51
}
48
- firstEntry , err := log .FirstIndex ()
52
+ stream := & Stream {
53
+ dir : dir ,
54
+ log : log ,
55
+ config : config ,
56
+ logger : logger ,
57
+ isClosed : false ,
58
+ }
59
+ startIndex , err := log .FirstIndex ()
49
60
if err != nil {
50
61
return nil , err
51
62
}
52
- if firstEntry <= 0 {
53
- }
54
- if config .KeepLast > 0 {
55
-
63
+ stream .nextOffset = startIndex + 1
64
+ if config .KeepRecent > 0 {
65
+ go stream .StartPruning (config .KeepRecent , config .PruneInterval )
56
66
}
57
- return & Stream {
58
- log : log ,
59
- config : config ,
60
- logger : logger ,
61
- }, nil
67
+ return stream , nil
62
68
63
69
}
64
70
@@ -195,9 +201,17 @@ func (stream *Stream) Replay(start uint64, end uint64, processFn func(index uint
195
201
return nil
196
202
}
197
203
198
- //
199
- func (stream * Stream ) Pruning () {
200
-
204
+ func (stream * Stream ) StartPruning (keepRecent uint64 , pruneInterval time.Duration ) {
205
+ for ! stream .isClosed {
206
+ lastIndex , _ := stream .log .LastIndex ()
207
+ firstIndex , _ := stream .log .FirstIndex ()
208
+ if lastIndex > keepRecent && (lastIndex - keepRecent ) > firstIndex {
209
+ prunePos := lastIndex - keepRecent
210
+ err := stream .TruncateBefore (prunePos )
211
+ stream .logger .Error (fmt .Sprintf ("failed to prune changelog till index %d" , prunePos ), "err" , err )
212
+ }
213
+ time .Sleep (pruneInterval )
214
+ }
201
215
}
202
216
203
217
func (stream * Stream ) Close () error {
@@ -209,6 +223,7 @@ func (stream *Stream) Close() error {
209
223
stream .writeChannel = nil
210
224
stream .errSignal = nil
211
225
errClose := stream .log .Close ()
226
+ stream .isClosed = true
212
227
return errorutils .Join (err , errClose )
213
228
}
214
229
0 commit comments