-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
106 lines (97 loc) · 1.88 KB
/
store.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
101
102
103
104
105
106
package nodis
import (
"log"
"sync"
"time"
"github.com/diiyw/nodis/ds"
"github.com/diiyw/nodis/storage"
"github.com/diiyw/nodis/ds/list"
"github.com/diiyw/nodis/redis"
"github.com/tidwall/btree"
)
type store struct {
mu sync.RWMutex
metadata btree.Map[string, *metadata]
ss storage.Storage
closed bool
watchMu sync.RWMutex
watchedKeys btree.Map[string, *list.LinkedListG[*redis.Conn]]
}
func newStore(ss storage.Storage) *store {
s := &store{ss: ss}
err := s.ss.Init()
if err != nil {
log.Fatal(err)
}
s.ss.ScanKeys(func(key *ds.Key) bool {
var m = newMetadata()
m.key = key
m.state |= KeyStateNormal
s.metadata.Set(key.Name, m)
return true
})
return s
}
// flush changed keys to storage
func (s *store) flush() {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now().UnixMilli()
s.metadata.Scan(func(key string, m *metadata) bool {
m.Lock()
defer m.Unlock()
if !m.modified() || m.expired(now) || !m.isOk() {
return true
}
if m.value == nil {
return true
}
// save to storage
err := s.ss.Set(m.key, m.value)
if err != nil {
log.Println("Flush changes: ", err)
}
return true
})
}
// gc removes expired and unused keys
func (s *store) gc() {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
now := time.Now().UnixMilli()
s.metadata.Scan(func(key string, m *metadata) bool {
m.Lock()
defer m.Unlock()
if m.expired(now) || !m.isOk() {
s.metadata.Delete(key)
return true
}
if m.modified() {
err := s.ss.Set(m.key, m.value)
if err != nil {
log.Println("GC: ", err)
}
}
m.reset()
if m.count < 0 {
m.removeFromMemory()
}
return true
})
}
// close the store
func (s *store) close() error {
s.closed = true
s.flush()
return s.ss.Close()
}
// clear the store
func (s *store) clear() error {
s.mu.Lock()
defer s.mu.Unlock()
s.metadata.Clear()
return s.ss.Clear()
}