-
Notifications
You must be signed in to change notification settings - Fork 0
/
stupid.go
451 lines (363 loc) · 9.6 KB
/
stupid.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package stupid
import (
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/utkarsh-pro/use/pkg/id"
"github.com/utkarsh-pro/use/pkg/log"
"github.com/utkarsh-pro/use/pkg/storage/config"
"github.com/utkarsh-pro/use/pkg/storage/errors"
"github.com/utkarsh-pro/use/pkg/structures/bloom/dibf"
"github.com/utkarsh-pro/use/pkg/utils"
)
var (
// Storage Ops
SetOp = byte(1)
DelOp = byte(2)
)
// Storage is a stupid storage.
type Storage struct {
// file is path to the storage file.
file string
// rfd is the reading file descriptor.
rfd *os.File
// idgen is the id generator.
idgen id.Gen
// wmu is the write mutex.
wmu *sync.Mutex
// wfd is the writing file descriptor.
wfd *os.File
// lastSuccessWritePos is the last successful write position.
lastSuccessWritePos int64
// cfg is the storage config.
cfg config.Config
// bf is the bloom bf.
bf bf
}
// New returns a new Storage instance.
func New(dir string, cfg config.Config) *Storage {
return &Storage{
file: filepath.Join(dir, "stupid.db"),
wmu: &sync.Mutex{},
idgen: id.New(),
cfg: cfg,
bf: newBfSync(dibf.NewWithEstimates(1e6, 0.01, 1, nil)),
}
}
// Init configures the storage.
func (s *Storage) Init() error {
wfd, err := os.OpenFile(s.file, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("error opening file for write fd: %w", err)
}
// Move to the end of the file.
if pos, err := wfd.Seek(0, io.SeekEnd); err != nil {
return fmt.Errorf("error seeking to end of file: %w", err)
} else {
s.lastSuccessWritePos = pos
}
rfd, err := os.OpenFile(s.file, os.O_RDONLY, 0666)
if err != nil {
return fmt.Errorf("error opening file for read fd: %w", err)
}
s.rfd = rfd
s.wfd = wfd
// Don't perform any recovery if the storage is read-only.
if s.cfg.ReadOnly {
log.Infoln("storage is read-only, skipping recovery")
return nil
}
// Fix the corrupt data if there is any
if err := s.DetectAndFix(); err != nil {
return fmt.Errorf("%s: %w", errors.ErrCorruptStorage, err)
}
return nil
}
// Get returns the value for the given key.
func (s *Storage) Get(key []byte) ([]byte, error) {
if !s.isInit() {
return nil, errors.ErrStorageNotInitialized
}
if !s.bf.Contains(key) {
return nil, errors.ErrKeyNotFound
}
var candidate *Packet = nil
var pr *reader = nil
err := s.ForEach(func(r *reader, p *Packet, err error) error {
// get the reader
if pr == nil {
pr = r
}
if err != nil {
// Although this should NEVER happen. NEVER.
if err == io.EOF {
return nil
}
}
if utils.Equal(p.Key, key, func(a, b byte) bool { return a == b }) {
if p.Op == DelOp {
candidate = nil
return nil
}
if p.Op == SetOp {
candidate = p
return nil
}
}
return nil
})
if err != nil {
return nil, err
}
if candidate == nil {
return nil, errors.ErrKeyNotFound
}
if err := pr.fill(candidate); err != nil {
return nil, err
}
return candidate.Val, nil
}
// Set sets the value for the given key.
func (s *Storage) Set(key []byte, value []byte) error {
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
if s.cfg.ReadOnly {
return errors.ErrReadOnlyStorage
}
s.wmu.Lock()
defer s.wmu.Unlock()
pw := newwriter(s.wfd)
if err := pw.write(
&Packet{
ID: s.idgen.Next(),
Op: SetOp,
Key: key,
Val: value,
},
); err != nil {
return fmt.Errorf("error writing packet: %w", err)
}
if s.cfg.Sync == config.SyncTypeSync {
if err := s.wfd.Sync(); err != nil {
return fmt.Errorf("error syncing file: %w", err)
}
} else if s.cfg.Sync == config.SyncTypeAsync {
go s.wfd.Sync()
}
// record the last successful write position
pos, err := s.wfd.Seek(0, io.SeekCurrent)
if err != nil {
log.Warnln("failed to get current write position: ", err)
return nil
}
s.lastSuccessWritePos = pos
// add to bloom filter
s.bf.Add(key)
return nil
}
// Delete deletes the value for the given key.
func (s *Storage) Delete(key []byte) error {
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
if s.cfg.ReadOnly {
return errors.ErrReadOnlyStorage
}
if !s.bf.Contains(key) {
return nil
}
s.wmu.Lock()
defer s.wmu.Unlock()
pw := newwriter(s.wfd)
if err := pw.write(
&Packet{
ID: s.idgen.Next(),
Op: DelOp,
Key: key,
Val: nil,
},
); err != nil {
return fmt.Errorf("error writing packet: %w", err)
}
if s.cfg.Sync == config.SyncTypeSync {
if err := s.wfd.Sync(); err != nil {
return fmt.Errorf("error syncing file: %w", err)
}
} else if s.cfg.Sync == config.SyncTypeAsync {
go s.wfd.Sync()
}
// record the last successful write position
pos, err := s.wfd.Seek(0, io.SeekCurrent)
if err != nil {
log.Warnln("failed to get current write position: ", err)
return nil
}
s.lastSuccessWritePos = pos
// remove from bloom filter
s.bf.Delete(key)
return nil
}
// Exists returns true if the given key exists.
func (s *Storage) Exists(key []byte) (bool, error) {
if !s.isInit() {
return false, errors.ErrStorageNotInitialized
}
return s.bf.Contains(key), nil
}
// Len returns the number of keys in the storage.
func (s *Storage) Len() (int, error) {
if !s.isInit() {
return 0, errors.ErrStorageNotInitialized
}
set := make(map[string]struct{})
if err := s.ForEach(func(r *reader, p *Packet, err error) error {
if err != nil {
return err
}
set[string(p.Key)] = struct{}{}
return nil
}); err != nil {
return 0, err
}
return len(set), nil
}
// PhysicalSnapshot writes the current state of the storage to the given writer.
// The snapshot is written in a format that can be read by only by the storage.
//
// Note: The DB is locked for writes while the snapshot is being generated.
func (s *Storage) PhysicalSnapshot(w io.Writer) error {
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
// Get the last successful write position
lastSuccessWritePos := s.lastSuccessWritePos
// Create a new reader for the file.
tempfd, err := os.Open(s.file)
if err != nil {
return fmt.Errorf("error opening file for read fd: %w", err)
}
if _, err := io.CopyN(w, tempfd, lastSuccessWritePos); err != nil {
return fmt.Errorf("error generating snapshot: %w", err)
}
return nil
}
// ForEach goes through the entire store and executes the given function
// on each packet that it reads.
func (s *Storage) ForEach(fn func(*reader, *Packet, error) error) error {
// Fail silently if the storage hasn't been initialized yet
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
pr := newreader(s.rfd)
for {
// don't read beyond the last successful write position
if pr.pos() >= s.lastSuccessWritePos {
break
}
packet := &Packet{}
err := pr.lread(packet)
if err != nil {
// If we reach the end of the file, break.
//
// We don't call the function with the packet
// because we know that the packet has to be invalid.
//
// Due to the design of TLV, it is impossible to encounter
// EOF while reading a packet (even at the end).
if err == io.EOF {
break
}
}
if _err := fn(pr, packet, err); _err != nil {
return _err
}
}
return nil
}
// DetectAndFix detects corrupt data in the store and tries to fix it
//
// Note: DetectAndFix will remove the corrupt data from the store which means
// that some of the writes might vanish. But this is same because the storage engine
// provides guaranatees only in the cases when it is running in the sync mode and a
// response is sent back to the client indicating a success.
func (s *Storage) DetectAndFix() error {
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
lastSuccessRead := int64(0)
// Go through the entire store and try to see if we can get valid
// packet reads from the store
return s.ForEach(func(pr *reader, p *Packet, err error) error {
if err != nil {
if err == io.ErrUnexpectedEOF {
log.Warnln("Found corrupted data in the store. Trying to fix it...")
// Discard the rest of the file
if err := s.wfd.Truncate(lastSuccessRead); err != nil {
return fmt.Errorf("error truncating file: %w", err)
}
// No need to update the read position since we only rely on ReadAt
// and that doesn't changes os.File read position
// Move the write position to the last successful read position
s.wfd.Seek(lastSuccessRead, io.SeekStart)
// Update the last successful write position
s.lastSuccessWritePos = lastSuccessRead
log.Infoln("Successfully fixed the corrupted data in the store")
return nil
}
return err
}
// Update the last successful read position
lastSuccessRead = pr.pos()
// Insert the packet into the bloom filter
s.bf.Add(p.Key)
return nil
})
}
// Close closes the storage.
func (s *Storage) Close() error {
if !s.isInit() {
return errors.ErrStorageNotInitialized
}
if err := s.rfd.Close(); err != nil {
return fmt.Errorf("error closing read fd: %w", err)
}
s.rfd = nil
if err := s.wfd.Close(); err != nil {
return fmt.Errorf("error closing write fd: %w", err)
}
s.wfd = nil
return nil
}
// GetByID returns a packet corresponding to the given ID.
//
// This is a low level API and should not be used by the user.
func (s *Storage) GetByID(id uint64) (*Packet, error) {
if !s.isInit() {
return nil, errors.ErrStorageNotInitialized
}
var packet *Packet
desiredErr := fmt.Errorf("desired")
if err := s.ForEach(func(r *reader, p *Packet, err error) error {
if err != nil {
return err
}
if p.ID == id {
packet = p
return desiredErr
}
return nil
}); err != nil {
if err == desiredErr {
return packet, nil
}
return nil, err
}
return nil, errors.ErrKeyNotFound
}
// isInit returns true if the storage is initialized.
func (s *Storage) isInit() bool {
return s.rfd != nil && s.wfd != nil
}