-
Notifications
You must be signed in to change notification settings - Fork 0
/
kvstore.go
545 lines (477 loc) · 12.1 KB
/
kvstore.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package main
import (
"io"
"encoding/gob"
"fmt"
"log"
"os"
"sync"
"time"
"strings"
"path"
"net"
"compress/zlib"
"bytes"
"bufio"
"github.com/golang/snappy"
)
// DB represents an embedded database.
type DB struct {
mu sync.RWMutex // Mutex for thread-safe operations
data map[string][]byte // In-memory data store
walLog *os.File // Write-Ahead Log file
snapshotDir string // Directory to store database snapshots
snapshotTTL time.Duration // Interval for saving snapshots
server *net.TCPListener // TCP/IP server for remote access (optional)
compressAlgo string // Compression algorithm (optional)
}
// WalEntry represents a log entry in the Write-Ahead Log.
type WalEntry struct {
Op string
Key string
Value []byte
}
// Open opens a new database instance.
func Open(path string, snapshotTTL time.Duration, remoteAccess bool, compressAlgo string) (*DB, error) {
walLog, err := os.OpenFile(path+".wal", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
var server *net.TCPListener
if remoteAccess {
// Start TCP/IP server for remote access
server, err = net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 8080})
if err != nil {
return nil, err
}
}
db := &DB{
data: make(map[string][]byte),
walLog: walLog,
snapshotDir: path,
snapshotTTL: snapshotTTL,
server: server,
compressAlgo: compressAlgo,
}
// Recover data from WAL log or snapshot
err = db.recover()
if err != nil {
return nil, err
}
// Start snapshot routine
go db.snapshotRoutine()
// Start TCP server
go db.handleRemoteRequests(server)
return db, nil
}
// Get retrieves the value for the given key.
func (db *DB) Get(key string) ([]byte, error) {
db.mu.RLock()
defer db.mu.RUnlock()
value, ok := db.data[key]
if !ok {
return nil, fmt.Errorf("key %s does not exist", key)
}
if db.compressAlgo == "zlib" {
value, _ = decompressZlib(value)
} else if db.compressAlgo == "snappy" {
value, _ = decompressSnappy(value)
}
return value, nil
}
// Put inserts or updates the value for the given key.
func (db *DB) Put(key string, value []byte) error {
db.mu.Lock()
defer db.mu.Unlock()
var err error
if db.compressAlgo == "zlib" {
value, err = compressZlib(value)
if err != nil {
return err
}
} else if db.compressAlgo == "snappy" {
value, err = compressSnappy(value)
if err != nil {
return err
}
}
// Write to WAL log
enc := gob.NewEncoder(db.walLog)
err = enc.Encode(&WalEntry{Op: "put", Key: key, Value: value})
if err != nil {
return err
}
// Update in-memory data
db.data[key] = value
return nil
}
// Delete removes the value for the given key.
func (db *DB) Delete(key string) error {
db.mu.Lock()
defer db.mu.Unlock()
// Write to WAL log
enc := gob.NewEncoder(db.walLog)
err := enc.Encode(&WalEntry{Op: "delete", Key: key})
if err != nil {
return err
}
if _, ok := mdb.data[key]; ok {
delete(db.data, key)
}
return nil
}
// Update modifies the value for the given key.
func (db *DB) Update(key string, newValue []byte) error {
db.mu.Lock()
defer db.mu.Unlock()
_, ok := db.data[key]
if !ok {
return fmt.Errorf("key %s does not exist", key)
}
var err error
if db.compressAlgo == "zlib" {
newValue, err = compressZlib(newValue)
if err != nil {
return err
}
} else if db.compressAlgo == "snappy" {
newValue, err = compressSnappy(newValue)
if err != nil {
return err
}
}
// Write to WAL log
enc := gob.NewEncoder(db.walLog)
err = enc.Encode(&WalEntry{Op: "put", Key: key, Value: newValue})
if err != nil {
return err
}
// Update in-memory data
db.data[key] = newValue
return nil
}
// IterKeys returns a slice of all keys in the database.
func (db *DB) IterKeys() []string {
db.mu.RLock()
defer db.mu.RUnlock()
keys := make([]string, 0, len(db.data))
for k := range db.data {
keys = append(keys, k)
}
return keys
}
// MultiGet retrieves the values for the given keys.
func (db *DB) MultiGet(keys []string) (map[string][]byte, error) {
db.mu.RLock()
defer db.mu.RUnlock()
values := make(map[string][]byte, len(keys))
for _, key := range keys {
value, ok := db.data[key]
if !ok {
return nil, fmt.Errorf("key %s does not exist", key)
}
if db.compressAlgo == "zlib" {
value, _ = decompressZlib(value)
} else if db.compressAlgo == "snappy" {
value, _ = decompressSnappy(value)
}
values[key] = value
}
return values, nil
}
// Close closes the database and underlying resources.
func (db *DB) Close() error {
if db.server != nil {
db.server.Close()
}
return db.walLog.Close()
}
func compressSnappy(data []byte) ([]byte, error) {
return snappy.Encode(nil, data), nil
}
func decompressSnappy(data []byte) ([]byte, error) {
decoded, err := snappy.Decode(nil, data)
if err != nil {
return nil, err
}
return decoded, nil
}
// Compression and decompression functions
func compressZlib(data []byte) ([]byte, error) {
var buf bytes.Buffer
writer := zlib.NewWriter(&buf)
_, err := writer.Write(data)
if err != nil {
return nil, err
}
err = writer.Close()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func decompressZlib(data []byte) ([]byte, error) {
reader, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
defer reader.Close()
buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, reader)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// RepairDB attempts to recover data from the WAL log in case of corruption.
func (db *DB) RepairDB() error {
return db.recover()
}
// recover reads the WAL log and the latest snapshot to restore the in-memory data.
func (db *DB) recover() error {
// Load data from the latest snapshot
snapshot, err := db.loadLatestSnapshot()
if err != nil {
return err
}
db.data = snapshot
// Apply changes from the WAL log
_, err = db.walLog.Seek(0, 0)
if err != nil {
return err
}
dec := gob.NewDecoder(db.walLog)
for {
var entry WalEntry
err := dec.Decode(&entry)
if err != nil {
if err == io.EOF {
break
}
return err
}
switch entry.Op {
case "put":
db.data[entry.Key] = entry.Value
case "delete":
delete(db.data, entry.Key)
}
}
return nil
}
// loadLatestSnapshot loads the latest database snapshot from disk.
func (db *DB) loadLatestSnapshot() (map[string][]byte, error) {
files, err := os.ReadDir(db.snapshotDir)
if err != nil {
return nil, err
}
var latestSnapshot map[string][]byte
var latestTime time.Time
for _, file := range files {
if file.IsDir() {
continue
}
if !strings.HasSuffix(file.Name(), ".snapshot") {
continue
}
fileInfo, err := file.Info()
if err != nil {
log.Printf("Failed to get file info for %s: %v", file.Name(), err)
continue
}
modTime := fileInfo.ModTime()
if modTime.After(latestTime) {
snapshot, err := db.loadSnapshot(file.Name())
if err != nil {
log.Printf("Failed to load snapshot %s: %v", file.Name(), err)
continue
}
latestSnapshot = snapshot
latestTime = modTime
}
}
return latestSnapshot, nil
}
// loadSnapshot loads a database snapshot from disk.
func (db *DB) loadSnapshot(filename string) (map[string][]byte, error) {
file, err := os.Open(path.Join(db.snapshotDir, filename))
if err != nil {
return nil, err
}
defer file.Close()
var snapshot map[string][]byte
dec := gob.NewDecoder(file)
err = dec.Decode(&snapshot)
if err != nil {
return nil, err
}
return snapshot, nil
}
// snapshotRoutine periodically saves a snapshot of the in-memory data to disk.
func (db *DB) snapshotRoutine() {
ticker := time.NewTicker(db.snapshotTTL)
defer ticker.Stop()
for {
<-ticker.C
db.saveSnapshot()
}
}
// saveSnapshot saves a snapshot of the in-memory data to disk and clears the WAL file.
func (db *DB) saveSnapshot() {
db.mu.RLock()
defer db.mu.RUnlock()
filename := fmt.Sprintf("%d.snapshot", time.Now().UnixNano())
file, err := os.Create(path.Join(db.snapshotDir, filename))
if err != nil {
log.Printf("Failed to create snapshot file %s: %v", filename, err)
return
}
defer file.Close()
enc := gob.NewEncoder(file)
err = enc.Encode(db.data)
if err != nil {
log.Printf("Failed to encode snapshot %s: %v", filename, err)
return
}
// Clean up old snapshots while holding the read lock
db.cleanupSnapshots()
// Clear the WAL file
db.mu.Lock()
defer db.mu.Unlock()
err = db.walLog.Truncate(0)
if err != nil {
log.Printf("Failed to truncate WAL file: %v", err)
return
}
_, err = db.walLog.Seek(0, 0)
if err != nil {
log.Printf("Failed to seek to the beginning of WAL file: %v", err)
return
}
}
// cleanupSnapshots removes old snapshots, keeping only the latest one.
func (db *DB) cleanupSnapshots() {
files, err := os.ReadDir(db.snapshotDir)
if err != nil {
log.Printf("Failed to read snapshot directory: %v", err)
return
}
var latestModTime time.Time
for _, file := range files {
if file.IsDir() {
continue
}
if !strings.HasSuffix(file.Name(), ".snapshot") {
continue
}
fileInfo, err := file.Info()
if err != nil {
log.Printf("Failed to get file info for %s: %v", file.Name(), err)
continue
}
modTime := fileInfo.ModTime()
if modTime.After(latestModTime) {
latestModTime = modTime
}
}
for _, file := range files {
if file.IsDir() {
continue
}
if !strings.HasSuffix(file.Name(), ".snapshot") {
continue
}
fileInfo, err := file.Info()
if err != nil {
log.Printf("Failed to get file info for %s: %v", file.Name(), err)
continue
}
modTime := fileInfo.ModTime()
if modTime.Before(latestModTime) {
os.Remove(path.Join(db.snapshotDir, file.Name()))
}
}
}
func (db *DB) handleRemoteRequests(listener *net.TCPListener) {
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept connection: %v", err)
continue
}
go db.handleConnection(conn)
}
}
func (db *DB) handleConnection(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
request, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
log.Printf("Failed to read request: %v", err)
return
}
// Parse the request and execute the corresponding database operation
parts := strings.Split(strings.TrimSpace(request), " ")
if len(parts) < 2 {
log.Printf("Invalid request format: %s", request)
continue
}
op, key, value := parts[0], parts[1], []byte(nil)
if len(parts) > 2 {
value = []byte(strings.Join(parts[2:], " "))
}
var response []byte
switch op {
case "GET":
value, err = db.Get(key)
if err != nil {
response = []byte(err.Error())
} else {
response = value
}
case "PUT":
err = db.Put(key, value)
if err != nil {
response = []byte(err.Error())
}
case "DELETE":
err = db.Delete(key)
if err != nil {
response = []byte(err.Error())
}
case "UPDATE":
err = db.Update(key, value)
if err != nil {
response = []byte(err.Error())
}
case "ITERKEYS":
keys := db.IterKeys()
response = []byte(strings.Join(keys, "\n"))
case "MULTIGET":
values, err := db.MultiGet(parts[1:])
if err != nil {
response = []byte(err.Error())
} else {
var sb strings.Builder
for k, v := range values {
sb.WriteString(k)
sb.WriteByte(' ')
sb.Write(v)
sb.WriteByte('\n')
}
response = []byte(sb.String())
}
default:
response = []byte("Invalid operation: " + op)
}
_, err = conn.Write(response)
if err != nil {
log.Printf("Failed to write response: %v", err)
return
}
}
}