File tree Expand file tree Collapse file tree 3 files changed +38
-2
lines changed
Expand file tree Collapse file tree 3 files changed +38
-2
lines changed Original file line number Diff line number Diff line change 11package wal
22
3- import "os"
3+ import (
4+ "os"
5+ "time"
6+ )
47
58// Options represents the configuration options for a Write-Ahead Log (WAL).
69type Options struct {
@@ -29,6 +32,10 @@ type Options struct {
2932
3033 // BytesPerSync specifies the number of bytes to write before calling fsync.
3134 BytesPerSync uint32
35+
36+ // SyncInterval is the time duration in which explicit synchronization is performed.
37+ // If SyncInterval is zero, no periodic synchronization is performed.
38+ SyncInterval time.Duration
3239}
3340
3441const (
@@ -44,4 +51,5 @@ var DefaultOptions = Options{
4451 SegmentFileExt : ".SEG" ,
4552 Sync : false ,
4653 BytesPerSync : 0 ,
54+ SyncInterval : 0 ,
4755}
Original file line number Diff line number Diff line change 99 "sort"
1010 "strings"
1111 "sync"
12+ "time"
1213)
1314
1415const (
@@ -40,6 +41,8 @@ type WAL struct {
4041 pendingWrites [][]byte
4142 pendingSize int64
4243 pendingWritesLock sync.Mutex
44+ closeC chan struct {}
45+ syncTicker * time.Ticker
4346}
4447
4548// Reader represents a reader for the WAL.
@@ -64,6 +67,7 @@ func Open(options Options) (*WAL, error) {
6467 options : options ,
6568 olderSegments : make (map [SegmentID ]* segment ),
6669 pendingWrites : make ([][]byte , 0 ),
70+ closeC : make (chan struct {}),
6771 }
6872
6973 // create the directory if not exists.
@@ -117,6 +121,22 @@ func Open(options Options) (*WAL, error) {
117121 }
118122 }
119123
124+ // only start the sync operation if the SyncInterval is greater than 0.
125+ if wal .options .SyncInterval > 0 {
126+ wal .syncTicker = time .NewTicker (wal .options .SyncInterval )
127+ go func () {
128+ for {
129+ select {
130+ case <- wal .syncTicker .C :
131+ _ = wal .Sync ()
132+ case <- wal .closeC :
133+ wal .syncTicker .Stop ()
134+ return
135+ }
136+ }
137+ }()
138+ }
139+
120140 return wal , nil
121141}
122142
@@ -428,6 +448,13 @@ func (wal *WAL) Close() error {
428448 wal .mu .Lock ()
429449 defer wal .mu .Unlock ()
430450
451+ select {
452+ case <- wal .closeC :
453+ // channel is already closed
454+ default :
455+ close (wal .closeC )
456+ }
457+
431458 // close all segment files.
432459 for _ , segment := range wal .olderSegments {
433460 if err := segment .Close (); err != nil {
Original file line number Diff line number Diff line change 11package wal
22
33import (
4- "github.com/stretchr/testify/assert"
54 "io"
65 "os"
76 "strings"
87 "testing"
8+
9+ "github.com/stretchr/testify/assert"
910)
1011
1112func destroyWAL (wal * WAL ) {
You can’t perform that action at this time.
0 commit comments