-
Notifications
You must be signed in to change notification settings - Fork 0
/
anystore.go
1142 lines (1053 loc) · 27.2 KB
/
anystore.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
AnyStore is a thread-safe key/value store utilizing map[any]any in the
background with atomic.Value on read and mutex locks on write for
performance. The AnyStore map can optionally be persisted to disk as
an AES-128/192/256 encrypted GOB file with HMAC-SHA256 for
authentication and validation of the data. For access from multiple
instances sharing the same map, POSIX syscall.Flock is used to
exclusively lock a lockfile during save. There is no support for
Windows or other non-POSIX systems missing flock(2).
Example:
ephemeral, err := anystore.NewAnyStore(&anystore.Options{
EnablePersistence: false,
})
if err != nil {
log.Fatal(err)
}
// Store this key in a safe place, share between instances
encryptionKey := anystore.NewKey()
persisted, err := anystore.NewAnyStore(&anystore.Options{
EnablePersistence: true,
PersistenceFile: "~/.persisted-data.db",
EncryptionKey: encryptionKey,
})
if err != nil {
log.Fatal(err)
}
defer persisted.Close()
if err := ephemeral.Store("hello", "world"); err != nil {
log.Fatal(err)
}
value, err := ephemeral.Load("hello")
if err != nil {
log.Fatal(err)
}
v, ok := value.(string)
if !ok {
log.Fatalf("value %q is not a string", value)
}
log.Println(v)
// Persistence works just like a non-persisted store...
if err := persisted.Store("hello", "world"); err != nil {
log.Fatal(err)
}
value, err := persisted.Load("hello")
if err != nil {
log.Fatal(err)
}
v, ok := value.(string)
if !ok {
log.Fatalf("value %q is not a string", value)
}
log.Println(v)
AnyStore also feature a configuration mode with convenience-functions
Stash, Unstash and EditThing. Whether you choose to hard-code an
encryption key in the application or provide one via environment
variables, using Stash, Unstash and EditThing is simple...
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/sa6mwa/anystore"
)
// All fields need to be exported.
type MyConfig struct {
ListenAddress string
Username string
Token string
Endpoints []*Endpoint
}
type Endpoint struct {
ID int
Name string
URL string
}
func main() {
defaultConf := &MyConfig{
ListenAddress: "0.0.0.0:1234",
Username: "superuser",
Token: "abc123",
Endpoints: []*Endpoint{
{ID: 1, Name: "Endpoint 1", URL: "https://endpoint1.local"},
{ID: 2, Name: "Endpoint 2", URL: "https://endpoint2.local"},
},
}
file := "~/.myconfigfile.db"
var configuration MyConfig
if err := anystore.Unstash(&anystore.StashConfig{
File: file,
EncryptionKey: anystore.DefaultEncryptionKey,
Key: "configuration",
Thing: &configuration,
DefaultThing: defaultConf,
}); err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 && os.Args[1] == "edit" {
if err := anystore.EditThing(&anystore.StashConfig{
File: file,
EncryptionKey: anystore.DefaultEncryptionKey,
Key: "configuration",
Thing: &configuration,
// Editor: "/usr/bin/emacs",
}); err != nil {
log.Fatal(err)
}
}
j, err := json.MarshalIndent(configuration, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
}
*/
package anystore
import (
"bytes"
"compress/gzip"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
)
const DefaultEncryptionKey string = "cTAvflqncVmYD7bLM31fP3TVuwEoosMMwehpIwn1P84"
const DefaultPersistenceFile string = "~/.config/anystore/anystore.db"
var (
ErrKeyLength error = errors.New("key length must be 16, 24 or 32 (for AES-128, AES-192 or AES-256)")
ErrWroteTooLittle error = errors.New("wrote too few bytes")
ErrHMACValidationFailed error = errors.New("HMAC validation failed (corrupt data or wrong encryption key)")
)
// A thread-safe key/value store using string as key and interface{} (any) as
// values. Must be initialized using NewAnyStore.
//
// Solution/inspiration from https://pkg.go.dev/sync/atomic#example-Value-ReadMostly
type AnyStore interface {
SetPersistenceFile(file string) (AnyStore, error)
EnablePersistence() AnyStore
DisablePersistence() AnyStore
SetEncryptionKey(key string) (AnyStore, error)
// GetEncryptionKeyBytes returns a byte slice with the AES encryption key.
GetEncryptionKeyBytes() []byte
// HasKey tests if key exists in the store, returns true if it does, false if
// not. Retrieval is atomic.
HasKey(key any) bool
// Load atomically retrieves the value of key. Returns the value as an
// interface (any) and can therefore be casted into the correct type.
Load(key any) (any, error)
// Store adds or replaces a key/value pair in the store. Operation is locking
// and more costly than Load or HasKey.
Store(key any, value any) error
// Delete removes a key from the store. Operation uses sync.Mutex and is
// locking.
Delete(key any) error
// Len returns number of keys in the store.
Len() (int, error)
// Returns a slice with all keys in the store.
Keys() ([]any, error)
// Run executes function atomicOperation exclusively by locking the store.
// atomicOperation is intended to be an inline function running a set of
// operations on the store in an exclusive scope. BEWARE! You have to use the
// a AnyStore passed as argument to atomicOperation - it is not the same
// struct and methods underneath as Store, Delete and Run are now non-blocking
// ("unsafe") in "a". If you use the origin instance interface the Run
// receiver function is attached to Store, Delete and Run will cause a
// deadlock (these are overridden with non-locking versions in the interface
// passed to atomicOperation). Technically, you could use the original HasKey,
// Load and Len as they are non-locking and mere duplicates in the wrapped
// instance, but that could cause confusion. The error returned by the passed
// function is returned by Run.
Run(atomicOperation func(s AnyStore) error) error
// If persistence is enabled, Close removes the lockfile.
Close() error
load() error
loadStoreAndSave(key any, value any, remove bool) error
}
type Options struct {
// Store and load the AnyStore from file or io.ReadWriter? Set to true
EnablePersistence bool
// Can start with tilde for HOME resolution, will do os.MkdirAll on directory
// path. Omit to use DefaultPersistenceFile
PersistenceFile string
// 16, 24 or 32 byte base64-encoded string (omit to use the default key ==
// insecure)
EncryptionKey string
// If true, the serialized output (GOB) will be gzipped before encrypted and
// saved to disk and vice versa for loading from the persistence.
GZipPersistenceFile bool
}
type anyStore struct {
mutex sync.Mutex
kv atomic.Value
persist atomic.Bool
gzip atomic.Bool
key atomic.Value
savefile atomic.Value
}
// Implements AnyStore and "overrides" Store, Delete and Run.
type unsafeAnyStore struct {
*anyStore
}
// anyMap is a convenience-type.
type anyMap map[any]any
func init() {
gob.Register([]interface{}(nil))
gob.Register([]struct{}(nil))
gob.Register(struct{}{})
}
// NewAnyStore returns an initialized AnyStore.
func NewAnyStore(o *Options) (AnyStore, error) {
a := new(anyStore)
if o == nil {
o = &Options{}
}
if o.EnablePersistence {
if o.PersistenceFile != "" {
if _, err := a.SetPersistenceFile(o.PersistenceFile); err != nil {
return a, err
}
} else {
if _, err := a.SetPersistenceFile(DefaultPersistenceFile); err != nil {
return a, err
}
}
a.persist.Store(true)
} else {
a.persist.Store(false)
}
if o.GZipPersistenceFile {
a.gzip.Store(true)
} else {
a.gzip.Store(false)
}
if o.EncryptionKey != "" {
if _, err := a.SetEncryptionKey(o.EncryptionKey); err != nil {
return a, err
}
} else {
if _, err := a.SetEncryptionKey(DefaultEncryptionKey); err != nil {
return a, err
}
}
a.kv.Store(make(anyMap))
return a, nil
}
func (a *anyStore) SetPersistenceFile(file string) (AnyStore, error) {
// If persistence file starts with a tilde, resolve it to the user's home
// directory.
if strings.HasPrefix(file, "~/") {
dirname, err := os.UserHomeDir()
if err != nil {
return a, err
}
file = filepath.Join(dirname, file[2:])
}
dir, _ := filepath.Split(file)
if dir != "" && dir != "." && dir != ".." {
if _, err := os.Stat(dir); err != nil {
if errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(dir, 0777); err != nil {
return a, err
}
}
}
}
f, err := os.OpenFile(file, os.O_RDWR, 0666)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return a, err
}
} else {
f.Close()
}
a.savefile.Store(file)
return a, nil
}
func (a *anyStore) EnablePersistence() AnyStore {
a.persist.Store(true)
return a
}
func (a *anyStore) DisablePersistence() AnyStore {
a.persist.Store(false)
return a
}
func (a *anyStore) SetEncryptionKey(key string) (AnyStore, error) {
binkey, err := base64.RawStdEncoding.DecodeString(key)
if err != nil {
return a, err
}
switch len(binkey) {
case 16, 24, 32:
default:
return a, ErrKeyLength
}
a.key.Store(binkey)
return a, nil
}
func (a *anyStore) GetEncryptionKeyBytes() []byte {
return a.key.Load().([]byte)
}
func (a *anyStore) HasKey(key any) bool {
if a.persist.Load() {
a.mutex.Lock()
defer a.mutex.Unlock()
a.load()
}
kv := a.kv.Load().(anyMap)
_, ok := kv[key]
return ok
}
func (a *anyStore) Load(key any) (any, error) {
if a.persist.Load() {
a.mutex.Lock()
defer a.mutex.Unlock()
// File is our only source of truth, load file before loading key
if err := a.load(); err != nil {
return nil, err
}
}
kv := a.kv.Load().(anyMap)
return kv[key], nil
}
func (a *anyStore) Store(key any, value any) error {
a.mutex.Lock()
defer a.mutex.Unlock()
if a.persist.Load() {
return a.loadStoreAndSave(key, value, false)
}
kvO := a.kv.Load().(anyMap)
kvN := make(anyMap)
for k, v := range kvO {
kvN[k] = v
}
kvN[key] = value
a.kv.Store(kvN)
return nil
}
func (a *anyStore) Delete(key any) error {
a.mutex.Lock()
defer a.mutex.Unlock()
if a.persist.Load() {
return a.loadStoreAndSave(key, nil, true)
}
kvO := a.kv.Load().(anyMap)
kvN := make(anyMap)
for k, v := range kvO {
kvN[k] = v
}
delete(kvN, key)
a.kv.Store(kvN)
return nil
}
func (a *anyStore) Len() (int, error) {
if a.persist.Load() {
a.mutex.Lock()
defer a.mutex.Unlock()
if err := a.load(); err != nil {
return 0, err
}
}
return len(a.kv.Load().(anyMap)), nil
}
func (a *anyStore) Keys() ([]any, error) {
if a.persist.Load() {
a.mutex.Lock()
defer a.mutex.Unlock()
if err := a.load(); err != nil {
return nil, err
}
}
keys := make([]any, 0)
kv, ok := a.kv.Load().(anyMap)
if ok {
for k, _ := range kv {
keys = append(keys, k)
}
}
return keys, nil
}
func (a *anyStore) Run(atomicOperation func(s AnyStore) error) error {
a.mutex.Lock()
defer a.mutex.Unlock()
anyStoreOverride := &unsafeAnyStore{a}
return atomicOperation(anyStoreOverride)
}
func (a *anyStore) Close() error {
if a.persist.Load() {
// Lock the store
a.mutex.Lock()
defer a.mutex.Unlock()
file, ok := a.savefile.Load().(string)
if !ok {
return errors.New("persistence not set")
}
lockfile := file + ".lock"
_, err := os.Stat(lockfile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
if err := os.Remove(lockfile); err != nil {
return err
}
}
return nil
}
func (a *anyStore) load() error {
file, ok := a.savefile.Load().(string)
if !ok {
return errors.New("no persistence file set")
}
encryptionKey, ok := a.key.Load().([]byte)
if !ok {
return errors.New("encryption key not set")
}
// lockfile := file + ".lock"
// lockfd, err := syscall.Open(lockfile, syscall.O_CREAT|syscall.O_RDWR, 0666)
// if err != nil {
// return err
// }
// defer syscall.Close(lockfd)
// if err := syscall.Flock(lockfd, syscall.LOCK_EX); err != nil {
// return err
// }
data := []byte{}
f, err := os.OpenFile(file, os.O_RDONLY, 0666)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return err
}
} else {
data, err = io.ReadAll(f)
f.Close()
if err != nil {
return err
}
}
kvN := make(anyMap)
if len(data) > 0 {
decrypted, err := Decrypt(encryptionKey, data)
if err != nil {
return err
}
if len(decrypted) > 0 {
var in *gob.Decoder
if a.gzip.Load() {
gzipReader, err := gzip.NewReader(bytes.NewReader(decrypted))
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return fmt.Errorf("%w (perhaps persistence is not gzipped?)", err)
}
return err
}
in = gob.NewDecoder(gzipReader)
} else {
in = gob.NewDecoder(bytes.NewReader(decrypted))
}
if err := in.Decode(&kvN); err != nil {
if strings.Contains(err.Error(), "encoded unsigned integer out of range") && !a.gzip.Load() {
return fmt.Errorf("%w (perhaps persistence is gzipped?)", err)
}
return err
}
}
}
a.kv.Store(kvN)
return nil
}
func (a *anyStore) loadStoreAndSave(key any, value any, remove bool) error {
encryptionKey := a.key.Load().([]byte)
file, ok := a.savefile.Load().(string)
if !ok {
return errors.New("persistence file not set")
}
lockfile := file + ".lock"
unlink := true
var lockfd int
for {
var err error
lockfd, err = syscall.Open(lockfile, syscall.O_CREAT|syscall.O_RDWR, 0666)
if err != nil {
return err
}
if err := syscall.Flock(lockfd, syscall.LOCK_EX); err != nil {
syscall.Close(lockfd)
return err
}
var stat_t syscall.Stat_t
if err := syscall.Fstat(lockfd, &stat_t); err != nil {
syscall.Close(lockfd)
return err
}
if stat_t.Nlink == 0 {
// File deleted (no hard links), recreate it
syscall.Close(lockfd)
continue
}
// We should have a lockfd with an existing file at this point
defer syscall.Close(lockfd)
break
}
f, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return err
}
// Make a new KV map
kvN := make(anyMap)
if len(data) > 0 {
decrypted, err := Decrypt(encryptionKey, data)
if err != nil {
return err
}
if len(decrypted) > 0 {
var in *gob.Decoder
if a.gzip.Load() {
gzipReader, err := gzip.NewReader(bytes.NewReader(decrypted))
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return fmt.Errorf("%w (perhaps persistence is not gzipped?)", err)
}
return err
}
in = gob.NewDecoder(gzipReader)
} else {
in = gob.NewDecoder(bytes.NewReader(decrypted))
}
if err := in.Decode(&kvN); err != nil {
if strings.Contains(err.Error(), "encoded unsigned integer out of range") && !a.gzip.Load() {
return fmt.Errorf("%w (perhaps persistence is gzipped?)", err)
}
return err
}
}
}
// Set our key/value on top of incoming KV pairs, or delete the key
if remove {
delete(kvN, key)
} else {
kvN[key] = value
}
// Store map
a.kv.Store(kvN)
// Store as GOB, encrypt it and save as temporary file along-side the original
// and replace the main file via rename (as rename is atomic, it will not
// corrupt the main file in the event of a crash).
var output bytes.Buffer
var out *gob.Encoder
var gzipWriter *gzip.Writer
if a.gzip.Load() {
gzipWriter = gzip.NewWriter(&output)
out = gob.NewEncoder(gzipWriter)
} else {
out = gob.NewEncoder(&output)
}
if err := out.Encode(kvN); err != nil {
if gzipWriter != nil {
gzipWriter.Close()
}
return err
}
if gzipWriter != nil {
gzipWriter.Close()
}
encryptedOutput, err := Encrypt(encryptionKey, output.Bytes())
if err != nil {
return err
}
newFilename := file + "." + rndstr(10)
tmpf, err := os.OpenFile(newFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer func() {
if unlink {
os.Remove(newFilename)
}
}()
if n, err := tmpf.Write(encryptedOutput); err != nil {
tmpf.Close()
return err
} else if n != len(encryptedOutput) {
tmpf.Close()
return ErrWroteTooLittle
}
tmpf.Sync()
tmpf.Close()
if err := os.Rename(newFilename, file); err != nil {
return err
}
unlink = false
return nil
}
// unsafeAnyStore implements AnyStore, but in an unlocked state (where Store,
// Delete and Run have been modified not to lock) to be used in the Run
// function. All functions need to defined to implement the AnyStore interface.
func (u *unsafeAnyStore) SetPersistenceFile(file string) (AnyStore, error) {
// If persistence file starts with a tilde, resolve it to the user's home
// directory.
if strings.HasPrefix(file, "~/") {
dirname, err := os.UserHomeDir()
if err != nil {
return u, err
}
file = filepath.Join(dirname, file[2:])
}
dir, _ := filepath.Split(file)
if _, err := os.Stat(file); err != nil {
if errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(dir, 0777); err != nil {
return u, err
}
} else {
return u, err
}
}
f, err := os.OpenFile(file, os.O_RDWR, 0666)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return u, err
}
} else {
f.Close()
}
u.savefile.Store(file)
return u, nil
}
func (u *unsafeAnyStore) EnablePersistence() AnyStore {
u.persist.Store(true)
return u
}
func (u *unsafeAnyStore) DisablePersistence() AnyStore {
u.persist.Store(false)
return u
}
func (u *unsafeAnyStore) SetEncryptionKey(key string) (AnyStore, error) {
binkey, err := base64.RawStdEncoding.DecodeString(key)
if err != nil {
return u, err
}
switch len(binkey) {
case 16, 24, 32:
default:
return u, ErrKeyLength
}
u.key.Store(binkey)
return u, nil
}
func (u *unsafeAnyStore) GetEncryptionKeyBytes() []byte {
return u.key.Load().([]byte)
}
func (u *unsafeAnyStore) HasKey(key any) bool {
if u.persist.Load() {
u.load()
}
kv := u.kv.Load().(anyMap)
_, ok := kv[key]
return ok
}
func (u *unsafeAnyStore) Load(key any) (any, error) {
if u.persist.Load() {
// File is our only source of truth, load file before loading key
if err := u.load(); err != nil {
return nil, err
}
}
kv := u.kv.Load().(anyMap)
return kv[key], nil
}
func (u *unsafeAnyStore) Store(key any, value any) error {
if u.persist.Load() {
return u.loadStoreAndSave(key, value, false)
}
kvO := u.kv.Load().(anyMap)
kvN := make(anyMap)
for k, v := range kvO {
kvN[k] = v
}
kvN[key] = value
u.kv.Store(kvN)
return nil
}
func (u *unsafeAnyStore) Delete(key any) error {
if u.persist.Load() {
return u.loadStoreAndSave(key, nil, true)
}
kvO := u.kv.Load().(anyMap)
kvN := make(anyMap)
for k, v := range kvO {
kvN[k] = v
}
delete(kvN, key)
u.kv.Store(kvN)
return nil
}
func (u *unsafeAnyStore) Len() (int, error) {
if u.persist.Load() {
if err := u.load(); err != nil {
return 0, err
}
}
return len(u.kv.Load().(anyMap)), nil
}
func (u *unsafeAnyStore) Keys() ([]any, error) {
if u.persist.Load() {
if err := u.load(); err != nil {
return nil, err
}
}
keys := make([]any, 0)
kv, ok := u.kv.Load().(anyMap)
if ok {
for k, _ := range kv {
keys = append(keys, k)
}
}
return keys, nil
}
func (u *unsafeAnyStore) Run(atomicOperation func(s AnyStore) error) error {
return atomicOperation(u)
}
func (u *unsafeAnyStore) Close() error {
if u.persist.Load() {
file, ok := u.savefile.Load().(string)
if !ok {
return errors.New("persistence not set")
}
lockfile := file + ".lock"
_, err := os.Stat(lockfile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
if err := os.Remove(lockfile); err != nil {
return err
}
}
return nil
}
func (u *unsafeAnyStore) load() error {
file, ok := u.savefile.Load().(string)
if !ok {
return errors.New("no persistence file set")
}
encryptionKey, ok := u.key.Load().([]byte)
if !ok {
return errors.New("encryption key not set")
}
// lockfile := file + ".lock"
// lockfd, err := syscall.Open(lockfile, syscall.O_CREAT|syscall.O_RDWR, 0666)
// if err != nil {
// return err
// }
// defer syscall.Close(lockfd)
// if err := syscall.Flock(lockfd, syscall.LOCK_EX); err != nil {
// return err
// }
data := []byte{}
f, err := os.OpenFile(file, os.O_RDONLY, 0666)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return err
}
} else {
data, err = io.ReadAll(f)
f.Close()
if err != nil {
return err
}
}
kvN := make(anyMap)
if len(data) > 0 {
decrypted, err := Decrypt(encryptionKey, data)
if err != nil {
return err
}
if len(decrypted) > 0 {
var in *gob.Decoder
if u.gzip.Load() {
gzipReader, err := gzip.NewReader(bytes.NewReader(decrypted))
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return fmt.Errorf("%w (perhaps persistence is not gzipped?)", err)
}
return err
}
in = gob.NewDecoder(gzipReader)
} else {
in = gob.NewDecoder(bytes.NewReader(decrypted))
}
if err := in.Decode(&kvN); err != nil {
if strings.Contains(err.Error(), "encoded unsigned integer out of range") && !u.gzip.Load() {
return fmt.Errorf("%w (perhaps persistence is gzipped?)", err)
}
return err
}
}
}
u.kv.Store(kvN)
return nil
}
func (u *unsafeAnyStore) loadStoreAndSave(key any, value any, remove bool) error {
encryptionKey := u.key.Load().([]byte)
file, ok := u.savefile.Load().(string)
if !ok {
return errors.New("persistence file not set")
}
lockfile := file + ".lock"
unlink := true
var lockfd int
for {
var err error
lockfd, err = syscall.Open(lockfile, syscall.O_CREAT|syscall.O_RDWR, 0666)
if err != nil {
return err
}
if err := syscall.Flock(lockfd, syscall.LOCK_EX); err != nil {
syscall.Close(lockfd)
return err
}
var stat_t syscall.Stat_t
if err := syscall.Fstat(lockfd, &stat_t); err != nil {
syscall.Close(lockfd)
return err
}
if stat_t.Nlink == 0 {
// File deleted (no hard links), recreate it
syscall.Close(lockfd)
continue
}
// We should have a lockfd with an existing file at this point
defer syscall.Close(lockfd)
break
}
f, err := os.OpenFile(file, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
return err
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return err
}
// Make a new KV map
kvN := make(anyMap)
if len(data) > 0 {
decrypted, err := Decrypt(encryptionKey, data)
if err != nil {
return err
}
if len(decrypted) > 0 {
var in *gob.Decoder
if u.gzip.Load() {
gzipReader, err := gzip.NewReader(bytes.NewReader(decrypted))
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return fmt.Errorf("%w (perhaps persistence is not gzipped?)", err)
}
return err
}
in = gob.NewDecoder(gzipReader)
} else {
in = gob.NewDecoder(bytes.NewReader(decrypted))
}
if err := in.Decode(&kvN); err != nil {
if strings.Contains(err.Error(), "encoded unsigned integer out of range") && !u.gzip.Load() {
return fmt.Errorf("%w (perhaps persistence is gzipped?)", err)
}
return err
}
}
}
// Set our key/value on top of incoming KV pairs, or delete the key
if remove {
delete(kvN, key)
} else {
kvN[key] = value
}
// Store map
u.kv.Store(kvN)
// Store as GOB, encrypt it and save as temporary file along-side the original
// and replace the main file via rename (as rename is atomic, it will not
// corrupt the main file in the event of a crash).
var output bytes.Buffer
var out *gob.Encoder
var gzipWriter *gzip.Writer
if u.gzip.Load() {
gzipWriter = gzip.NewWriter(&output)
out = gob.NewEncoder(gzipWriter)
} else {
out = gob.NewEncoder(&output)
}
if err := out.Encode(kvN); err != nil {
if gzipWriter != nil {
gzipWriter.Close()
}
return err
}
if gzipWriter != nil {
gzipWriter.Close()
}
encryptedOutput, err := Encrypt(encryptionKey, output.Bytes())
if err != nil {