This repository has been archived by the owner on May 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfiles.go
1033 lines (852 loc) · 23.5 KB
/
files.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
package gotinydb
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"time"
"github.com/alexandrestein/gotinydb/cipher"
"github.com/alexandrestein/gotinydb/transaction"
"github.com/dgraph-io/badger"
"golang.org/x/crypto/blake2b"
)
type (
// FileStore defines database file storage object
FileStore struct {
db *DB
}
// FileMeta defines some file metadata informations
FileMeta struct {
ID string
Name string
Size int64
LastModified time.Time
ChuckSize int
RelatedDocumentID string
RelatedDocumentCollection string
inWrite bool
}
readWriter struct {
deadLineTimer *time.Timer
meta *FileMeta
cache []byte
cachedChunk int
fs *FileStore
currentPosition int64
txn *badger.Txn
writer bool
}
// Reader define a simple object to read parts of the file.
// After 10 minutes (ReaderWriterTimeout variable) the reader
// is automatically closed.
Reader interface {
io.ReadCloser
io.Seeker
io.ReaderAt
GetMeta() *FileMeta
}
// Writer define a simple object to write parts of the file.
// After 10 minutes (ReaderWriterTimeout variable) the writer
// is automatically closed.
Writer interface {
Reader
io.Writer
io.WriterAt
}
)
// PutFile let caller insert large element into the database via a reader interface
func (fs *FileStore) PutFile(id string, name string, reader io.Reader) (n int, err error) {
return fs.PutFileRelated(id, name, reader, "", "")
}
// PutFileWithTTL let caller insert large element into the database via a reader interface
func (fs *FileStore) PutFileWithTTL(id string, name string, reader io.Reader, ttl time.Duration) (n int, err error) {
// Add the new file
n, err = fs.PutFileRelated(id, name, reader, "", "")
go fs.putFileTTL(id, ttl)
return n, err
}
func (fs *FileStore) putFileTTL(id string, ttl time.Duration) {
ttlObj := newTTL("", id, true, ttl)
ctx, cancel := context.WithTimeout(fs.db.ctx, time.Second*10)
defer cancel()
tx := transaction.New(ctx)
tx.AddOperation(
transaction.NewOperation(
"",
nil,
ttlObj.timeAsKey(),
ttlObj.exportAsBytes(),
false,
true,
),
)
// Do the writing:
select {
case fs.db.writeChan <- tx:
case <-fs.db.ctx.Done():
return
}
// Wait for the response
select {
case <-tx.ResponseChan:
case <-tx.Ctx.Done():
}
}
// PutFileRelated does the same as *DB.PutFile but the file is automatically removed
// when the related document is removed.
// The use case can be for blog post for example. You have posts which has images and medias in it.
// Ones the post is removed the images and the medias are not needed anymore.
// This provide a easy way remove files automatically based on collection documents.
func (fs *FileStore) PutFileRelated(id string, name string, reader io.Reader, colName, documentID string) (n int, err error) {
fs.DeleteFile(id)
meta := fs.buildMeta(id, name)
meta.inWrite = true
if colName != "" {
meta.RelatedDocumentCollection = colName
meta.RelatedDocumentID = documentID
// Save the related document
err = fs.addRelatedFileIDs(colName, documentID, id)
if err != nil {
return
}
}
// Set the meta
err = fs.putFileMeta(meta)
if err != nil {
return
}
// Track the numbers of chunks
nChunk := 1
// Open a loop
for true {
// Initialize the read buffer
buff := make([]byte, FileChuckSize)
var nWritten int
nWritten, err = reader.Read(buff)
// The read is done and it returns
if nWritten == 0 || err == io.EOF && nWritten == 0 {
break
}
// Return error if any
if err != nil && err != io.EOF {
return
}
// Clean the buffer
buff = buff[:nWritten]
n = n + nWritten
err = fs.writeFileChunk(id, nChunk, buff)
if err != nil {
return n, err
}
// Increment the chunk counter
nChunk++
}
meta.Size = int64(n)
meta.LastModified = time.Now()
meta.inWrite = false
err = fs.putFileMeta(meta)
if err != nil {
return
}
err = nil
return
}
func (fs *FileStore) writeFileChunk(id string, chunk int, content []byte) (err error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if FileChuckSize < len(content) {
return fmt.Errorf("the maximum chunk size is %d bytes long but the content to write is %d bytes long", FileChuckSize, len(content))
}
tx := transaction.New(ctx)
tx.AddOperation(
transaction.NewOperation("", nil, fs.buildFilePrefix(id, chunk), content, false, true),
)
// Run the insertion
select {
case fs.db.writeChan <- tx:
case <-fs.db.ctx.Done():
return fs.db.ctx.Err()
}
// And wait for the end of the insertion
select {
case err = <-tx.ResponseChan:
case <-tx.Ctx.Done():
err = tx.Ctx.Err()
}
return
}
func (fs *FileStore) getFileMetaWithTxn(txn *badger.Txn, id, name string) (meta *FileMeta, err error) {
metaID := fs.buildFilePrefix(id, 0)
var item *badger.Item
item, err = txn.Get(metaID)
if err != nil {
if err == badger.ErrKeyNotFound {
meta = fs.buildMeta(id, name)
return
}
return
}
var valAsEncryptedBytes []byte
valAsEncryptedBytes, err = item.ValueCopy(valAsEncryptedBytes)
if err != nil {
return
}
var valAsBytes []byte
valAsBytes, err = cipher.Decrypt(fs.db.privateKey, item.Key(), valAsEncryptedBytes)
if err != nil {
return
}
meta = new(FileMeta)
err = json.Unmarshal(valAsBytes, meta)
return meta, err
}
func (fs *FileStore) getFileMeta(id, name string) (meta *FileMeta, err error) {
err = fs.db.badger.View(func(txn *badger.Txn) (err error) {
meta, err = fs.getFileMetaWithTxn(txn, id, name)
return
})
if err != nil {
return
}
return
}
func (fs *FileStore) buildMeta(id, name string) (meta *FileMeta) {
meta = new(FileMeta)
meta.ID = id
meta.Name = name
meta.Size = 0
meta.LastModified = time.Time{}
meta.ChuckSize = FileChuckSize
return
}
func (fs *FileStore) putFileMeta(meta *FileMeta) (err error) {
metaID := fs.buildFilePrefix(meta.ID, 0)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var metaAsBytes []byte
metaAsBytes, err = json.Marshal(meta)
if err != nil {
return
}
tx := transaction.New(ctx)
tx.AddOperation(
transaction.NewOperation("", nil, metaID, metaAsBytes, false, true),
)
// Run the insertion
select {
case fs.db.writeChan <- tx:
case <-fs.db.ctx.Done():
return fs.db.ctx.Err()
}
// And wait for the end of the insertion
select {
case err = <-tx.ResponseChan:
case <-tx.Ctx.Done():
err = tx.Ctx.Err()
}
return
}
// buildRelatedFileID returns the id of the saved list of files related to the given document into the given collection
func (fs *FileStore) buildRelatedID(colName, documentID string) []byte {
col, err := fs.db.Use(colName)
if err != nil {
return nil
}
id := []byte{prefixFilesRelated}
id = append(id, col.prefix...)
id = append(id, []byte(documentID)...)
return id
}
func (fs *FileStore) getRelatedFileIDsInternal(colName, documentID string, txn *badger.Txn) (fileIDs []string, _ error) {
relatedID := fs.buildRelatedID(colName, documentID)
item, err := txn.Get(relatedID)
if err != nil {
if err == badger.ErrKeyNotFound {
return []string{}, nil
}
return nil, err
}
valAsEncryptedBytes := []byte{}
valAsEncryptedBytes, err = item.ValueCopy(valAsEncryptedBytes)
if err != nil {
return nil, err
}
var valAsBytes []byte
valAsBytes, err = cipher.Decrypt(fs.db.privateKey, item.Key(), valAsEncryptedBytes)
if err != nil {
return nil, err
}
fileIDs = []string{}
err = json.Unmarshal(valAsBytes, &fileIDs)
return fileIDs, err
}
func (fs *FileStore) getRelatedFileIDs(colName, documentID string) (fileIDs []string) {
fs.db.badger.View(func(txn *badger.Txn) (err error) {
fileIDs, err = fs.getRelatedFileIDsInternal(colName, documentID, txn)
return err
})
return
}
func (fs *FileStore) addRelatedFileIDs(colName, documentID string, fileIDsToAdd ...string) (err error) {
return fs.db.badger.View(func(txn *badger.Txn) error {
fileIDs, err := fs.getRelatedFileIDsInternal(colName, documentID, txn)
if err != nil {
return err
}
fileIDs = append(fileIDs, fileIDsToAdd...)
var retBytes []byte
retBytes, err = json.Marshal(fileIDs)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// And add it to the list of store IDs to delete
tx := transaction.New(ctx)
tx.AddOperation(
transaction.NewOperation("", fileIDs, fs.buildRelatedID(colName, documentID), retBytes, false, true),
)
// Send the write request
fs.db.writeChan <- tx
// Wait for the write response
select {
case err = <-tx.ResponseChan:
case <-tx.Ctx.Done():
err = tx.Ctx.Err()
}
return err
})
}
func (fs *FileStore) deleteRelatedFileIDs(colName, documentID string, fileIDsToDelete ...string) (err error) {
return fs.db.badger.View(func(txn *badger.Txn) error {
fileIDs, err := fs.getRelatedFileIDsInternal(colName, documentID, txn)
if err != nil {
return err
}
for i := len(fileIDs) - 1; i >= 0; i-- {
for _, idToDelete := range fileIDsToDelete {
if idToDelete == fileIDs[i] {
fileIDs = append(fileIDs[:i], fileIDs[i+1:]...)
}
}
}
var retBytes []byte
if len(fileIDs) != 0 {
retBytes, err = json.Marshal(fileIDs)
if err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// And add it to the list of store IDs to delete
tx := transaction.New(ctx)
if len(fileIDs) != 0 {
tx.AddOperation(
transaction.NewOperation("", fileIDs, fs.buildRelatedID(colName, documentID), retBytes, false, true),
)
} else {
tx.AddOperation(
transaction.NewOperation("", nil, fs.buildRelatedID(colName, documentID), nil, true, true),
)
}
// Send the write request
fs.db.writeChan <- tx
// Wait for the write response
select {
case err = <-tx.ResponseChan:
case <-tx.Ctx.Done():
err = tx.Ctx.Err()
}
if err != nil {
return err
}
return nil
})
}
// ReadFile write file content into the given writer
func (fs *FileStore) ReadFile(id string, writer io.Writer) error {
return fs.db.badger.View(func(txn *badger.Txn) error {
storeID := fs.buildFilePrefix(id, -1)
opt := badger.DefaultIteratorOptions
opt.PrefetchSize = 3
opt.PrefetchValues = true
it := txn.NewIterator(opt)
defer it.Close()
for it.Seek(fs.buildFilePrefix(id, 1)); it.ValidForPrefix(storeID); it.Next() {
var err error
var valAsEncryptedBytes []byte
valAsEncryptedBytes, err = it.Item().ValueCopy(valAsEncryptedBytes)
if err != nil {
return err
}
var valAsBytes []byte
valAsBytes, err = cipher.Decrypt(fs.db.privateKey, it.Item().Key(), valAsEncryptedBytes)
if err != nil {
return err
}
_, err = writer.Write(valAsBytes)
if err != nil {
return err
}
}
return nil
})
}
// GetFileReader returns a struct to provide simple reading partial of big files.
// The default position is at the begining of the file.
func (fs *FileStore) GetFileReader(id string) (Reader, error) {
rw, err := fs.newReadWriter(id, "", false, 0)
return Reader(rw), err
}
// GetFileWriter returns a struct to provide simple partial write of big files.
// The default position is at the end of the file.
func (fs *FileStore) GetFileWriter(id, name string) (Writer, error) {
return fs.GetFileWriterRelated(id, name, "", "")
}
// GetFileWriterWithTTL does the same as GetFileWriter but it's
// automatically removed after the given duration
func (fs *FileStore) GetFileWriterWithTTL(id, name string, ttl time.Duration) (Writer, error) {
w, err := fs.GetFileWriterRelated(id, name, "", "")
go fs.putFileTTL(id, ttl)
return w, err
}
// GetFileWriterRelated does the same as GetFileWriter but with related document
func (fs *FileStore) GetFileWriterRelated(id, name string, colName, documentID string) (Writer, error) {
rw, err := fs.newReadWriter(id, name, true, 0)
if err != nil {
return nil, err
}
if rw.meta.inWrite {
return nil, ErrFileInWrite
}
if colName != "" {
rw.meta.RelatedDocumentCollection = colName
rw.meta.RelatedDocumentID = documentID
// Save the related document
err = fs.addRelatedFileIDs(colName, documentID, id)
if err != nil {
return nil, err
}
}
rw.meta.inWrite = true
err = fs.putFileMeta(rw.meta)
if err != nil {
return nil, err
}
rw.currentPosition = rw.meta.Size
return Writer(rw), err
}
// DeleteFile deletes every chunks of the given file ID
func (fs *FileStore) DeleteFile(id string) (err error) {
listOfTx := []*transaction.Transaction{}
// Open a read transaction to get every IDs
return fs.db.badger.View(func(txn *badger.Txn) error {
// Build the file prefix
storeID := fs.buildFilePrefix(id, -1)
// Defines the iterator options to get only IDs
opt := badger.DefaultIteratorOptions
opt.PrefetchValues = false
opt.AllVersions = true
// Initialize the iterator
it := txn.NewIterator(opt)
defer it.Close()
// ctx, cancel := context.WithTimeout(context.Background(), time.Second)
ctx, cancel := context.WithCancel(fs.db.ctx)
defer cancel()
// Go the the first file chunk
for it.Seek(storeID); it.ValidForPrefix(storeID); it.Next() {
// Copy the store key
var key []byte
key = it.Item().KeyCopy(key)
// And add it to the list of store IDs to delete
tx := transaction.New(ctx)
tx.AddOperation(
transaction.NewOperation("", nil, key, nil, true, true),
)
listOfTx = append(listOfTx, tx)
fs.db.writeChan <- tx
}
for _, tx := range listOfTx {
select {
case err = <-tx.ResponseChan:
case <-tx.Ctx.Done():
err = tx.Ctx.Err()
}
if err != nil {
return err
}
}
var meta *FileMeta
meta, err = fs.getFileMetaWithTxn(txn, id, "")
fs.deleteRelatedFileIDs(meta.RelatedDocumentCollection, meta.RelatedDocumentID, id)
// Close the view transaction
return nil
})
}
func (fs *FileStore) buildFilePrefix(id string, chunkN int) []byte {
// Derive the ID to make sure no file ID overlap the other.
// Because the files are chunked it needs to have a stable prefix for reading
// and deletation.
derivedID := blake2b.Sum256([]byte(id))
// Build the prefix
prefixWithID := append([]byte{prefixFiles}, derivedID[:]...)
// Initialize the chunk part of the ID
chunkPart := []byte{}
// If less than zero it for deletation and only the prefix is returned
if chunkN < 0 {
return prefixWithID
}
// If it's the first chunk
if chunkN == 0 {
chunkPart = append(chunkPart, 0)
} else {
// Lockup the numbers of full bytes for the chunk ID
nbFull := chunkN / 256
restFull := chunkN % 256
for index := 0; index < nbFull; index++ {
chunkPart = append(chunkPart, 255)
}
chunkPart = append(chunkPart, uint8(restFull))
}
// Return the ID for the given file and ID
return append(prefixWithID, chunkPart...)
}
func (fs *FileStore) newReadWriter(id, name string, writer bool, timeOut time.Duration) (_ *readWriter, err error) {
rw := new(readWriter)
rw.writer = writer
if timeOut == 0 {
rw.deadLineTimer = time.AfterFunc(ReaderWriterTimeout, rw.mustClose)
} else {
rw.deadLineTimer = time.AfterFunc(timeOut, rw.mustClose)
}
rw.meta, err = fs.getFileMeta(id, name)
if err != nil {
if err == badger.ErrKeyNotFound && writer {
// not found but it's ok for writer
err = nil
} else {
// otherways the error is returned
return nil, err
}
}
rw.fs = fs
rw.txn = fs.db.badger.NewTransaction(false)
return rw, nil
}
// GetFileIterator returns a file iterator which help to list existing files
func (fs *FileStore) GetFileIterator() *FileIterator {
iterOptions := badger.DefaultIteratorOptions
iterOptions.PrefetchValues = true
iterOptions.PrefetchSize = 1
txn := fs.db.badger.NewTransaction(false)
badgerIter := txn.NewIterator(iterOptions)
badgerIter.Seek([]byte{prefixFiles})
return &FileIterator{
baseIterator: &baseIterator{
txn: txn,
badgerIter: badgerIter,
},
fs: fs,
}
}
// Read implements the io.Reader interface
func (r *readWriter) Read(dest []byte) (n int, err error) {
block, inside := r.getBlockAndInsidePosition(r.currentPosition)
opt := badger.DefaultIteratorOptions
opt.PrefetchSize = 3
opt.PrefetchValues = true
it := r.txn.NewIterator(opt)
defer it.Close()
buffer := bytes.NewBuffer(nil)
first := true
filePrefix := r.fs.buildFilePrefix(r.meta.ID, -1)
for it.Seek(r.fs.buildFilePrefix(r.meta.ID, block)); it.ValidForPrefix(filePrefix); it.Next() {
if it.Item().IsDeletedOrExpired() {
break
}
// they are a variable which is used later but because of the cache we declare it here
var err error
var valAsEncryptedBytes []byte
var valAsBytes []byte
if block == r.cachedChunk && r.cache != nil && first {
valAsBytes = make([]byte, len(r.cache))
copy(valAsBytes, r.cache)
goto useCache
}
valAsEncryptedBytes, err = it.Item().ValueCopy(valAsEncryptedBytes)
if err != nil {
return 0, err
}
valAsBytes, err = cipher.Decrypt(r.fs.db.privateKey, it.Item().Key(), valAsEncryptedBytes)
if err != nil {
return 0, err
}
// Save for caching
r.cache = make([]byte, len(valAsBytes))
copy(r.cache, valAsBytes)
r.cachedChunk = block
useCache:
var toAdd []byte
if first {
toAdd = valAsBytes[inside:]
} else {
toAdd = valAsBytes
}
buffer.Write(toAdd)
if buffer.Len() >= len(dest) {
copy(dest, buffer.Bytes()[:len(dest)])
r.currentPosition += int64(len(dest))
return len(dest), nil
}
first = false
}
copy(dest, buffer.Bytes())
r.currentPosition = 0
return buffer.Len(), io.EOF
}
func (r *readWriter) checkReadWriteAt(off int64) error {
if r.meta.Size <= off {
return fmt.Errorf("the offset can not be equal or bigger than the file")
}
return nil
}
// ReadAt implements the io.ReaderAt interface
func (r *readWriter) ReadAt(p []byte, off int64) (n int, err error) {
err = r.checkReadWriteAt(off)
if err != nil {
return 0, err
}
r.currentPosition = off
return r.Read(p)
}
func (r *readWriter) getExistingBlock(blockN int) (ret []byte, err error) {
chunkID := r.fs.buildFilePrefix(r.meta.ID, blockN)
var item *badger.Item
item, err = r.txn.Get(chunkID)
if err != nil {
if err == badger.ErrKeyNotFound {
return []byte{}, nil
}
return
}
var valAsEncryptedBytes []byte
valAsEncryptedBytes, err = item.ValueCopy(valAsEncryptedBytes)
if err != nil {
return nil, err
}
return cipher.Decrypt(r.fs.db.privateKey, item.Key(), valAsEncryptedBytes)
}
func (r *readWriter) Write(p []byte) (n int, err error) {
// Get a new transaction to be able to call write multiple times
defer r.afterWrite(len(p))
block, inside := r.getBlockAndInsidePosition(r.currentPosition)
var valAsBytes []byte
valAsBytes, err = r.getExistingBlock(block)
if err != nil {
return 0, err
}
freeToWriteInThisChunk := FileChuckSize - inside
if freeToWriteInThisChunk > len(p) {
toWrite := []byte{}
if inside <= len(valAsBytes) {
toWrite = valAsBytes[:inside]
}
toWrite = append(toWrite, p...)
// If the new content don't completely overwrite the previous content
if existingAfterNewWriteStartPosition := inside + len(p); existingAfterNewWriteStartPosition < len(valAsBytes) {
toWrite = append(toWrite, valAsBytes[existingAfterNewWriteStartPosition:]...)
}
return len(p), r.fs.writeFileChunk(r.meta.ID, block, toWrite)
}
toWriteInTheFirstChunk := valAsBytes[:inside]
toWriteInTheFirstChunk = append(toWriteInTheFirstChunk, p[n:freeToWriteInThisChunk]...)
err = r.fs.writeFileChunk(r.meta.ID, block, toWriteInTheFirstChunk)
if err != nil {
return n, err
}
n += freeToWriteInThisChunk
block++
done := false
newLoop:
newEnd := n + FileChuckSize
if newEnd > len(p) {
newEnd = len(p)
done = true
}
nextToWrite := p[n:newEnd]
if done {
valAsBytes, err = r.getExistingBlock(block)
if err != nil {
return 0, err
}
if len(valAsBytes) >= len(nextToWrite) {
nextToWrite = append(nextToWrite, valAsBytes[len(nextToWrite):]...)
}
}
err = r.fs.writeFileChunk(r.meta.ID, block, nextToWrite)
if err != nil {
return n, err
}
n += FileChuckSize
block++
if done {
n = len(p)
return
}
goto newLoop
}
func (r *readWriter) afterWrite(writtenLength int) {
// Refresh the transaction
r.txn.Discard()
r.txn = r.fs.db.badger.NewTransaction(false)
r.cachedChunk = 0
r.meta.Size += int64(writtenLength)
r.meta.LastModified = time.Now()
r.currentPosition += int64(writtenLength)
r.fs.putFileMeta(r.meta)
}
func (r *readWriter) getWrittenSize() (n int64) {
opt := badger.DefaultIteratorOptions
opt.PrefetchSize = 5
opt.PrefetchValues = false
it := r.txn.NewIterator(opt)
defer it.Close()
nbChunks := -1
blockesPrefix := r.fs.buildFilePrefix(r.meta.ID, -1)
var item *badger.Item
var lastBlockItem *badger.Item
for it.Seek(r.fs.buildFilePrefix(r.meta.ID, 1)); it.ValidForPrefix(blockesPrefix); it.Next() {
item = it.Item()
if item.IsDeletedOrExpired() {
break
}
lastBlockItem = item
nbChunks++
}
if lastBlockItem == nil {
return 0
}
var encryptedValue []byte
var err error
encryptedValue, err = lastBlockItem.ValueCopy(encryptedValue)
if err != nil {
return
}
var valAsBytes []byte
valAsBytes, err = cipher.Decrypt(r.fs.db.privateKey, item.Key(), encryptedValue)
if err != nil {
return
}
n = int64(nbChunks * r.meta.ChuckSize)
n += int64(len(valAsBytes))
return
}
func (r *readWriter) WriteAt(p []byte, off int64) (n int, err error) {
err = r.checkReadWriteAt(off)
if err != nil {
return 0, err
}
r.currentPosition = off
return r.Write(p)
}
// Seek implements the io.Seeker interface
func (r *readWriter) Seek(offset int64, whence int) (n int64, err error) {
switch whence {
case io.SeekStart:
n = offset
case io.SeekCurrent:
n = r.currentPosition + offset
case io.SeekEnd:
n = r.meta.Size - offset
default:
err = fmt.Errorf("whence not recognized")
}
if n > r.meta.Size || n < 0 {
err = fmt.Errorf("is out of the file")
}
r.currentPosition = n
return
}
// Close should be called when done with the Reader
func (r *readWriter) Close() (err error) {
if r.writer {
r.meta.inWrite = false
r.fs.putFileMeta(r.meta)
}
r.txn.Discard()
r.deadLineTimer.Stop()
return
}
func (r *readWriter) mustClose() {
r.Close()
}
func (r *readWriter) GetMeta() *FileMeta {
return r.meta
}
func (r *readWriter) getBlockAndInsidePosition(offset int64) (block, inside int) {
return int(offset/int64(r.meta.ChuckSize)) + 1, int(offset) % r.meta.ChuckSize
}
// GetMeta returns the metadata of the actual cursor position
func (i *FileIterator) GetMeta() *FileMeta {
return i.meta
}
// Next moves to the next valid metadata element
func (i *FileIterator) Next() error {
i.badgerIter.Next()
goToNext:
if !i.Valid() {
return ErrFileItemIteratorNotValid
}
isMeta, err := i.isMetaChunk()
if !isMeta || err != nil {
if err != nil {
return err
}
i.badgerIter.Next()
goto goToNext
}
return nil
}
// Seek moves to the meta coresponding to the given id
func (i *FileIterator) Seek(id string) {
i.badgerIter.Seek(i.fs.buildFilePrefix(id, 0))
}
// Valid checks if the cursor point a valid metadata document
func (i *FileIterator) Valid() bool {
valid := i.valid([]byte{prefixFiles})
if valid {
i.isMetaChunk()
}
return valid
}
func (i *FileIterator) isMetaChunk() (bool, error) {
dbKey := i.item.Key()
if len(dbKey) != 34 || dbKey[len(dbKey)-1] != 0 {