-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtstorage.go
243 lines (209 loc) · 4.98 KB
/
mtstorage.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package memory_ttl_storage
import (
"encoding/gob"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
)
const (
defaultTickerTime = time.Second * 1
defaultTTL = int64(10)
defaultShowLogs = false
defaultBackupFile = "/opt/memory_ttl_storage/mtstorage.dat"
)
type Item struct {
Content interface{}
ExpireTimestamp int64
TTL int64
}
type MemoryTTLStorage struct {
mutext sync.RWMutex
useBackup bool
showLogs bool
items map[string]Item
defaultTTL int64
cleaningTicker time.Ticker
backupTicker time.Ticker
backup *StorageManager
onBackupProcess bool
}
type MemoryTTLStoreConfig struct {
TickerTime time.Duration
TTLValue int64
ShowLogs bool
UseBackup bool
BackupPath string
}
func New(cfg *MemoryTTLStoreConfig) *MemoryTTLStorage {
finalTickerTime := defaultTickerTime
finalTTLValue := defaultTTL
finalShowLogs := defaultShowLogs
if cfg != nil {
if cfg.TickerTime != 0 {
finalTickerTime = cfg.TickerTime
}
if cfg.TTLValue != 0 {
finalTTLValue = cfg.TTLValue
}
if cfg.UseBackup {
if cfg.BackupPath == "" {
cfg.BackupPath = defaultBackupFile
}
dir := filepath.Dir(cfg.BackupPath)
err := prepareBackupPath(dir)
if err != nil {
log.Println("unable to config backup path", cfg.BackupPath)
}
}
finalShowLogs = cfg.ShowLogs
}
rlc := MemoryTTLStorage{
showLogs: finalShowLogs,
defaultTTL: finalTTLValue,
useBackup: cfg.UseBackup,
items: make(map[string]Item),
}
if rlc.useBackup && cfg.BackupPath != "" {
rlc.backup = NewStorageManager(cfg.BackupPath)
err := rlc.backup.Restore(&rlc.items)
if err != nil {
rlc.log("unable to restore data from backup file: %s", cfg.BackupPath)
}
rlc.backupTicker = *rlc.NewBackupTicker()
}
rlc.log(fmt.Sprintf("creating a MemoryTTLStorage with tickerTime %d/s and default TTL %d/s", finalTickerTime/time.Second, finalTTLValue))
rlc.cleaningTicker = *rlc.NewCleanerTicker(finalTickerTime)
rlc.RegisterInterface(Item{})
return &rlc
}
func (mts *MemoryTTLStorage) NewCleanerTicker(tickerTime time.Duration) *time.Ticker {
t := time.NewTicker(tickerTime)
quit := make(chan struct{})
go func() {
for {
select {
case <-t.C:
mts.clearOldEntries()
case <-quit:
t.Stop()
return
}
}
}()
return t
}
func (mts *MemoryTTLStorage) NewBackupTicker() *time.Ticker {
t := time.NewTicker(time.Second * 5)
quit := make(chan struct{})
go func() {
for {
select {
case <-t.C:
if !mts.onBackupProcess {
mts.onBackupProcess = true
toStore := make(map[string]Item)
mts.mutext.Lock()
for k, v := range mts.items {
toStore[k] = v
}
mts.mutext.Unlock()
err := mts.backup.Store(mts.items)
if err != nil {
mts.log("unable create a timed backup", err)
}
mts.onBackupProcess = false
}
case <-quit:
t.Stop()
return
}
}
}()
return t
}
func (mts *MemoryTTLStorage) Stop() {
mts.cleaningTicker.Stop()
if mts.useBackup {
mts.mutext.Lock()
defer mts.mutext.Unlock()
defer mts.backupTicker.Stop()
err := mts.backup.Store(mts.items)
if err != nil {
mts.log("unable to store data", err)
}
}
}
func prepareBackupPath(folder string) error {
if _, err := os.Stat(folder); os.IsNotExist(err) {
err := os.Mkdir(folder, os.ModePerm)
if err != nil {
return err
}
}
return nil
}
func (mts *MemoryTTLStorage) clearOldEntries() {
mts.mutext.Lock()
defer mts.mutext.Unlock()
for k, v := range mts.items {
if v.ExpireTimestamp < time.Now().Unix() {
mts.log("deleting outdated item", k)
delete(mts.items, k)
}
}
}
func (mts *MemoryTTLStorage) log(v ...interface{}) {
if mts.showLogs {
data := v
log.Println(data)
}
}
func (mts *MemoryTTLStorage) RegisterInterface(i interface{}) {
gob.Register(i)
}
func (mts *MemoryTTLStorage) SetDefaultTTL(defaultTTL int64) {
mts.defaultTTL = defaultTTL
mts.log("defaultTTL updated", defaultTTL)
}
func (mts *MemoryTTLStorage) prepareItem(content interface{}, ttl *int64) Item {
finalTTL := mts.defaultTTL
if ttl != nil {
finalTTL = *ttl
}
expirationTS := time.Now().Unix() + finalTTL
item := Item{
Content: content,
ExpireTimestamp: expirationTS,
TTL: finalTTL,
}
return item
}
func (mts *MemoryTTLStorage) Add(key string, content interface{}, ttl *int64) {
mts.mutext.Lock()
defer mts.mutext.Unlock()
item := mts.prepareItem(content, ttl)
mts.items[key] = item
}
func (mts *MemoryTTLStorage) Get(key string) (interface{}, bool) {
mts.mutext.Lock()
defer mts.mutext.Unlock()
val, ok := mts.items[key]
return val.Content, ok
}
func (mts *MemoryTTLStorage) GetAndRefresh(key string) (interface{}, bool) {
mts.mutext.Lock()
defer mts.mutext.Unlock()
val, ok := mts.items[key]
item := mts.prepareItem(val.Content, &val.TTL)
mts.items[key] = item
return val.Content, ok
}
func (mts *MemoryTTLStorage) Delete(key string) {
mts.mutext.Lock()
defer mts.mutext.Unlock()
delete(mts.items, key)
mts.log("deleted element with key", key)
}