-
Notifications
You must be signed in to change notification settings - Fork 0
/
wal.go
57 lines (46 loc) · 823 Bytes
/
wal.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
package main
import (
"encoding/json"
"os"
"sync"
)
type WALEntry struct {
Operation string
RecordID uint64
Data []byte
}
type WAL struct {
path string
entries []*WALEntry
mutex sync.Mutex
}
func NewWAL(path string) *WAL {
return &WAL{
path: path,
entries: make([]*WALEntry, 0),
}
}
func (w *WAL) Log(entry *WALEntry) {
w.mutex.Lock()
defer w.mutex.Unlock()
w.entries = append(w.entries, entry)
}
func (w *WAL) Flush() error {
w.mutex.Lock()
defer w.mutex.Unlock()
file, err := os.Create(w.path)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
for _, entry := range w.entries {
err := encoder.Encode(entry)
if err != nil {
return err
}
}
// Clear the WAL entries after flushing
w.entries = make([]*WALEntry, 0)
return nil
}