-
Notifications
You must be signed in to change notification settings - Fork 45
/
db.go
339 lines (271 loc) · 5.83 KB
/
db.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package gcse
import (
"encoding/gob"
"io"
"log"
"os"
"reflect"
"sync"
"time"
"github.com/golangplus/strings"
"github.com/daviddengcn/go-index"
"github.com/daviddengcn/go-villa"
)
type MemDB struct {
db map[string]interface{}
fn villa.Path
sync.RWMutex
syncMutex sync.Mutex // if lock both mutexes, lock RWMutex first
lastModified time.Time
modified bool
}
func NewMemDB(root villa.Path, kind string) *MemDB {
mdb := &MemDB{
db: make(map[string]interface{}),
}
if root != "" {
if err := root.MkdirAll(0755); err != nil {
log.Printf("MkdirAll failed: %v", err)
}
mdb.fn = root.Join(kind + ".gob")
if err := mdb.Load(); err != nil {
log.Printf("Load MemDB %s failed: %v", kind, err)
}
}
return mdb
}
func (mdb *MemDB) Modified() bool {
return mdb.modified
}
func (mdb *MemDB) LastModified() time.Time {
return mdb.lastModified
}
func (mdb *MemDB) Load() error {
if mdb.fn == "" {
return nil
}
mdb.Lock()
defer mdb.Unlock()
lastModified := time.Now()
if st, err := mdb.fn.Stat(); err == nil {
lastModified = st.ModTime()
}
if f, err := mdb.fn.Open(); err == nil {
defer f.Close()
dec := gob.NewDecoder(f)
if err := dec.Decode(&mdb.db); err != nil {
return err
}
} else if os.IsNotExist(err) {
// try recover from fn.new
if f, err := (mdb.fn + ".new").Open(); err == nil {
defer f.Close()
dec := gob.NewDecoder(f)
if err := dec.Decode(&mdb.db); err != nil {
return err
}
} else if os.IsNotExist(err) {
// just an empty db
mdb.db = make(map[string]interface{})
} else {
return err
}
} else {
return err
}
mdb.lastModified = lastModified
mdb.modified = false
return nil
}
// 1) save to fn.new; 2) remove fn; 3) rename fn.new to fn.
func safeSave(fn villa.Path, doSave func(w io.Writer) error) error {
tmpFn := fn + ".new"
if err := func() error {
f, err := tmpFn.Create()
if err != nil {
return err
}
defer f.Close()
return doSave(f)
}(); err != nil {
return err
}
if err := fn.Remove(); err != nil && !os.IsNotExist(err) {
return err
}
if err := tmpFn.Rename(fn); err != nil {
return err
}
return nil
}
func (mdb *MemDB) Sync() error {
if mdb.fn == "" {
// this db is not for syncing
return nil
}
mdb.RLock()
defer mdb.RUnlock()
if !mdb.modified {
return nil
}
mdb.syncMutex.Lock()
defer mdb.syncMutex.Unlock()
if err := safeSave(mdb.fn, func(w io.Writer) error {
enc := gob.NewEncoder(w)
return enc.Encode(mdb.db)
}); err != nil {
return err
}
mdb.modified = false
return nil
}
/*
Export saves the data to some space, but not affecting the modified property.
*/
func (mdb *MemDB) Export(root villa.Path, kind string) error {
mdb.RLock()
defer mdb.RUnlock()
fn := root.Join(kind + ".gob")
f, err := fn.Create()
if err != nil {
return err
}
defer f.Close()
enc := gob.NewEncoder(f)
return enc.Encode(mdb.db)
}
// Get fetches an entry of specified key. data is a pointer. Return false if not exists
func (mdb *MemDB) Get(key string, data interface{}) bool {
mdb.RLock()
defer mdb.RUnlock()
vl, ok := mdb.db[key]
if !ok {
return false
}
reflect.ValueOf(data).Elem().Set(reflect.ValueOf(vl))
return true
}
func (mdb *MemDB) Put(key string, data interface{}) {
mdb.Lock()
defer mdb.Unlock()
mdb.db[key] = data
mdb.lastModified = time.Now()
mdb.modified = true
}
func (mdb *MemDB) Delete(key string) {
mdb.Lock()
defer mdb.Unlock()
delete(mdb.db, key)
mdb.lastModified = time.Now()
mdb.modified = true
}
func (mdb *MemDB) Iterate(output func(key string, val interface{}) error) error {
mdb.RLock()
defer mdb.RUnlock()
for k, v := range mdb.db {
if err := output(k, v); err != nil {
return err
}
}
return nil
}
// Count returns the number of entries in the DB
func (mdb *MemDB) Count() int {
mdb.RLock()
defer mdb.RUnlock()
return len(mdb.db)
}
// TokenIndexer is thread-safe.
type TokenIndexer struct {
index.TokenIndexer
fn villa.Path
sync.RWMutex
syncMutex sync.Mutex
lastModified time.Time
modified bool
}
func NewTokenIndexer(root villa.Path, kind string) *TokenIndexer {
ti := &TokenIndexer{}
if root != "" {
if err := root.MkdirAll(0755); err != nil {
log.Printf("MkdirAll failed: %v", err)
}
ti.fn = root.Join(kind + ".gob")
if err := ti.Load(); err != nil {
log.Printf("Load MemDB failed: %v", err)
// its ok loading failed
}
}
return ti
}
func (ti *TokenIndexer) Modified() bool {
return ti.modified
}
func (ti *TokenIndexer) LastModified() time.Time {
return ti.lastModified
}
func (ti *TokenIndexer) Load() error {
ti.Lock()
defer ti.Unlock()
lastModified := time.Now()
st, err := ti.fn.Stat()
if err == nil {
lastModified = st.ModTime()
}
f, err := ti.fn.Open()
if err == os.ErrNotExist {
return nil
}
if err != nil {
return err
}
defer f.Close()
if err := ti.TokenIndexer.Load(f); err != nil {
return err
}
ti.lastModified = lastModified
ti.modified = false
return nil
}
func (ti *TokenIndexer) Sync() error {
ti.RLock()
defer ti.RUnlock()
ti.syncMutex.Lock()
defer ti.syncMutex.Unlock()
if !ti.modified {
return nil
}
if err := safeSave(ti.fn, ti.TokenIndexer.Save); err != nil {
return err
}
ti.modified = false
return nil
}
func (ti *TokenIndexer) Export(root villa.Path, kind string) error {
fn := root.Join(kind + ".gob")
ti.RLock()
defer ti.RUnlock()
f, err := fn.Create()
if err != nil {
return err
}
defer f.Close()
return ti.TokenIndexer.Save(f)
}
func (ti *TokenIndexer) Put(id string, tokens stringsp.Set) {
ti.Lock()
defer ti.Unlock()
ti.TokenIndexer.PutTokens(id, tokens)
ti.lastModified = time.Now()
ti.modified = true
}
func (ti *TokenIndexer) IdsOfToken(token string) []string {
ti.RLock()
defer ti.RUnlock()
return ti.TokenIndexer.IdsOfToken(token)
}
func (ti *TokenIndexer) TokensOfId(id string) []string {
ti.RLock()
defer ti.RUnlock()
return ti.TokenIndexer.TokensOfId(id)
}