-
Notifications
You must be signed in to change notification settings - Fork 15
/
bucket.go
1365 lines (1151 loc) · 29.3 KB
/
bucket.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 lungo
import (
"context"
"errors"
"fmt"
"io"
"sync"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/gridfs"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"github.com/256dpi/lungo/bsonkit"
)
// ErrFileNotFound is returned if the specified file was not found in the bucket.
// The value is the same as gridfs.ErrFileNotFound and can be used interchangeably.
var ErrFileNotFound = gridfs.ErrFileNotFound
// ErrNegativePosition is returned if the resulting position after a seek
// operation is negative.
var ErrNegativePosition = errors.New("negative position")
// The bucket marker states.
const (
BucketMarkerStateUploading = "uploading"
BucketMarkerStateUploaded = "uploaded"
BucketMarkerStateDeleted = "deleted"
)
// BucketMarker represents a document stored in the bucket "markers" collection.
type BucketMarker struct {
ID primitive.ObjectID `bson:"_id"`
File interface{} `bson:"files_id"`
State string `bson:"state"`
Timestamp time.Time `bson:"timestamp"`
Length int `bson:"length"`
ChunkSize int `bson:"chunkSize"`
Filename string `bson:"filename"`
Metadata interface{} `bson:"metadata,omitempty"`
}
// BucketFile represents a document stored in the bucket "files" collection.
type BucketFile struct {
ID interface{} `bson:"_id"`
Length int `bson:"length"`
ChunkSize int `bson:"chunkSize"`
UploadDate time.Time `bson:"uploadDate"`
Filename string `bson:"filename"`
Metadata interface{} `bson:"metadata,omitempty"`
}
// BucketChunk represents a document stored in the bucket "chunks" collection.
type BucketChunk struct {
ID primitive.ObjectID `bson:"_id"`
File interface{} `bson:"files_id"`
Num int `bson:"n"`
Data []byte `bson:"data"`
}
// Bucket provides access to a GridFS bucket. The type is generally compatible
// with gridfs.Bucket from the official driver but allows the passing in of a
// context on all methods. This way the bucket theoretically supports multi-
// document transactions. However, it is not recommended to use transactions for
// large uploads and instead enable the tracking mode and claim the uploads
// to ensure operational safety.
type Bucket struct {
tracked bool
files ICollection
chunks ICollection
markers ICollection
chunkSize int
indexMutex sync.Mutex
indexEnsured bool
}
// NewBucket creates a bucket using the provided database and options.
func NewBucket(db IDatabase, opts ...*options.BucketOptions) *Bucket {
// merge options
opt := options.MergeBucketOptions(opts...)
// assert supported options
assertOptions(opt, map[string]string{
"Name": supported,
"ChunkSizeBytes": supported,
"WriteConcern": supported,
"ReadConcern": supported,
"ReadPreference": supported,
})
// get name
name := options.DefaultName
if opt.Name != nil {
name = *opt.Name
}
// get chunk size
var chunkSize = int(options.DefaultChunkSize)
if opt.ChunkSizeBytes != nil {
chunkSize = int(*opt.ChunkSizeBytes)
}
// prepare collection options
var collOpt = options.Collection().
SetWriteConcern(opt.WriteConcern).
SetReadConcern(opt.ReadConcern).
SetReadPreference(opt.ReadPreference)
return &Bucket{
files: db.Collection(name+".files", collOpt),
chunks: db.Collection(name+".chunks", collOpt),
markers: db.Collection(name+".markers", collOpt),
chunkSize: chunkSize,
}
}
// GetFilesCollection returns the collection used for storing files.
func (b *Bucket) GetFilesCollection(_ context.Context) ICollection {
return b.files
}
// GetChunksCollection returns the collection used for storing chunks.
func (b *Bucket) GetChunksCollection(_ context.Context) ICollection {
return b.chunks
}
// GetMarkersCollection returns the collection used for storing markers.
func (b *Bucket) GetMarkersCollection(_ context.Context) ICollection {
return b.markers
}
// EnableTracking will enable a non-standard mode in which in-progress uploads
// and deletions are tracked by storing a document in an additional "markers"
// collection. If enabled, uploads can be suspended and resumed later and must
// be explicitly claimed. All unclaimed uploads and not fully deleted files
// can be cleaned up.
func (b *Bucket) EnableTracking() {
b.tracked = true
}
// Delete will remove the specified file from the bucket. If the bucket is
// tracked, only a marker is inserted that will ensure the file and its chunks
// are deleted during the next cleanup.
func (b *Bucket) Delete(ctx context.Context, id interface{}) error {
// just ensure marker if tracked
if b.tracked {
_, err := b.markers.ReplaceOne(ctx, &BucketMarker{
File: id,
State: BucketMarkerStateDeleted,
Timestamp: time.Now(),
}, options.Replace().SetUpsert(true))
if err != nil {
return err
}
return nil
}
// delete file
res1, err := b.files.DeleteOne(ctx, bson.M{
"_id": id,
})
if err != nil {
return err
}
// delete chunks, even if file is missing
res2, err := b.chunks.DeleteMany(ctx, bson.M{
"files_id": id,
})
if err != nil {
return err
}
// return error if no chunks or files have been deleted
if res1.DeletedCount == 0 && res2.DeletedCount == 0 {
return ErrFileNotFound
}
return nil
}
// DownloadToStream will download the file with the specified id and write its
// contents to the provided writer.
func (b *Bucket) DownloadToStream(ctx context.Context, id interface{}, w io.Writer) (int64, error) {
// open stream
stream, err := b.OpenDownloadStream(ctx, id)
if err != nil {
return 0, err
}
// copy data
n, err := io.Copy(w, stream)
if err != nil {
return 0, err
}
return n, nil
}
// DownloadToStreamByName will download the file with the specified name and
// write its contents to the provided writer.
func (b *Bucket) DownloadToStreamByName(ctx context.Context, name string, w io.Writer, opts ...*options.NameOptions) (int64, error) {
// open stream
stream, err := b.OpenDownloadStreamByName(ctx, name, opts...)
if err != nil {
return 0, err
}
// copy data
n, err := io.Copy(w, stream)
if err != nil {
return 0, err
}
return n, nil
}
// Drop will drop the files and chunks collection. If the bucket is tracked, the
// marker collection is also dropped.
func (b *Bucket) Drop(ctx context.Context) error {
// drop files
err := b.files.Drop(ctx)
if err != nil {
return err
}
// drop chunks
err = b.chunks.Drop(ctx)
if err != nil {
return err
}
// drop markers if bucket is tracked
if b.tracked {
err = b.markers.Drop(ctx)
if err != nil {
return err
}
}
// reset flag
b.indexMutex.Lock()
b.indexEnsured = false
b.indexMutex.Unlock()
return nil
}
// Find will perform a query on the underlying file collection.
func (b *Bucket) Find(ctx context.Context, filter interface{}, opts ...*options.GridFSFindOptions) (ICursor, error) {
// merge options
opt := options.MergeGridFSFindOptions(opts...)
// options are asserted by find method
// prepare find options
find := options.Find()
if opt.BatchSize != nil {
find.SetBatchSize(*opt.BatchSize)
}
if opt.Limit != nil {
find.SetLimit(int64(*opt.Limit))
}
if opt.MaxTime != nil {
find.SetMaxTime(*opt.MaxTime)
}
if opt.NoCursorTimeout != nil {
find.SetNoCursorTimeout(*opt.NoCursorTimeout)
}
if opt.Skip != nil {
find.SetSkip(int64(*opt.Skip))
}
if opt.Sort != nil {
find.SetSort(opt.Sort)
}
// find files
csr, err := b.files.Find(ctx, filter, find)
if err != nil {
return nil, err
}
return csr, nil
}
// OpenDownloadStream will open a download stream for the file with the
// specified id.
func (b *Bucket) OpenDownloadStream(ctx context.Context, id interface{}) (*DownloadStream, error) {
// create stream
stream := newDownloadStream(ctx, b, id, "", -1)
return stream, nil
}
// OpenDownloadStreamByName will open a download stream for the file with the
// specified name.
func (b *Bucket) OpenDownloadStreamByName(ctx context.Context, name string, opts ...*options.NameOptions) (*DownloadStream, error) {
// merge options
opt := options.MergeNameOptions(opts...)
// assert supported options
assertOptions(opt, map[string]string{
"Revision": supported,
})
// get revision
revision := int(options.DefaultRevision)
if opt.Revision != nil {
revision = int(*opt.Revision)
}
// create stream
stream := newDownloadStream(ctx, b, nil, name, revision)
return stream, nil
}
// OpenUploadStream will open an upload stream for a new file with the provided
// name.
func (b *Bucket) OpenUploadStream(ctx context.Context, name string, opts ...*options.UploadOptions) (*UploadStream, error) {
return b.OpenUploadStreamWithID(ctx, primitive.NewObjectID(), name, opts...)
}
// OpenUploadStreamWithID will open an upload stream for a new file with the
// provided id and name.
func (b *Bucket) OpenUploadStreamWithID(ctx context.Context, id interface{}, name string, opts ...*options.UploadOptions) (*UploadStream, error) {
// merge options
opt := options.MergeUploadOptions(opts...)
// assert supported options
assertOptions(opt, map[string]string{
"ChunkSizeBytes": supported,
"Metadata": supported,
"Registry": ignored,
})
// ensure indexes
err := b.EnsureIndexes(ctx, false)
if err != nil {
return nil, err
}
// get chunk size
chunkSize := b.chunkSize
if opt.ChunkSizeBytes != nil {
chunkSize = int(*opt.ChunkSizeBytes)
}
// create stream
stream := newUploadStream(ctx, b, id, name, chunkSize, opt.Metadata)
return stream, nil
}
// Rename will rename the file with the specified id to the provided name.
func (b *Bucket) Rename(ctx context.Context, id interface{}, name string) error {
// rename file
res, err := b.files.UpdateOne(ctx, bson.M{
"_id": id,
}, bson.M{
"$set": bson.M{
"filename": name,
},
})
if err != nil {
return err
}
// check result
if res.MatchedCount == 0 {
return ErrFileNotFound
}
return nil
}
// UploadFromStream will upload a new file using the contents read from the
// provided reader.
func (b *Bucket) UploadFromStream(ctx context.Context, name string, r io.Reader, opts ...*options.UploadOptions) (primitive.ObjectID, error) {
// prepare id
id := primitive.NewObjectID()
// upload from stream
err := b.UploadFromStreamWithID(ctx, id, name, r, opts...)
if err != nil {
return primitive.ObjectID{}, err
}
return id, nil
}
// UploadFromStreamWithID will upload a new file using the contents read from
// the provided reader.
func (b *Bucket) UploadFromStreamWithID(ctx context.Context, id interface{}, name string, r io.Reader, opts ...*options.UploadOptions) error {
// open stream
stream, err := b.OpenUploadStreamWithID(ctx, id, name, opts...)
if err != nil {
return err
}
// copy data
_, err = io.Copy(stream, r)
if err != nil {
_ = stream.Abort()
return err
}
// close stream
err = stream.Close()
if err != nil {
return err
}
return nil
}
// ClaimUpload will claim a tracked upload by creating the file and removing
// the marker.
func (b *Bucket) ClaimUpload(ctx context.Context, id interface{}) error {
// check if tracked
if !b.tracked {
return fmt.Errorf("bucket not tracked")
}
// get marker
var marker BucketMarker
err := b.markers.FindOne(ctx, bson.M{
"files_id": id,
}).Decode(&marker)
if err != nil {
return err
}
// check marker
if marker.State != BucketMarkerStateUploaded {
return fmt.Errorf("upload is not finished")
}
// create file
_, err = b.files.InsertOne(ctx, BucketFile{
ID: id,
Length: marker.Length,
ChunkSize: marker.ChunkSize,
UploadDate: time.Now(),
Filename: marker.Filename,
Metadata: marker.Metadata,
})
if err != nil {
return err
}
// remove upload marker
_, err = b.markers.DeleteOne(nil, bson.M{
"_id": marker.ID,
})
if err != nil {
return err
}
return nil
}
// Cleanup will remove unfinished uploads older than the specified age and all
// files marked for deletion.
func (b *Bucket) Cleanup(ctx context.Context, age time.Duration) error {
// check if tracked
if !b.tracked {
return fmt.Errorf("bucket not tracked")
}
// get cursor for old uploads and delete markers
csr, err := b.markers.Find(ctx, bson.M{
"$or": []bson.M{
{
"state": bson.M{
"$in": bson.A{BucketMarkerStateUploading, BucketMarkerStateUploaded},
},
"timestamp": bson.M{
"$lt": time.Now().Add(-age),
},
},
{
"state": BucketMarkerStateDeleted,
},
},
})
if err != nil {
return err
}
defer csr.Close(ctx)
// iterate over cursor
for csr.Next(ctx) {
// decode marker
var marker BucketMarker
err = csr.Decode(&marker)
if err != nil {
return err
}
// flag marker as deleted if not already
if marker.State != BucketMarkerStateDeleted {
res, err := b.markers.UpdateOne(ctx, bson.M{
"_id": marker.ID,
"state": marker.State,
}, bson.M{
"state": BucketMarkerStateDeleted,
})
if err != nil {
return err
}
// continue if marker has been claimed
if res.ModifiedCount == 0 {
continue
}
}
// delete file
_, err := b.files.DeleteOne(ctx, bson.M{
"_id": marker.File,
})
if err != nil {
return err
}
// delete chunks
_, err = b.chunks.DeleteMany(ctx, bson.M{
"files_id": marker.File,
})
if err != nil {
return err
}
// delete marker
_, err = b.markers.DeleteOne(ctx, bson.M{
"_id": marker.ID,
})
if err != nil {
return err
}
}
// check error
err = csr.Err()
if err != nil {
return err
}
return nil
}
// EnsureIndexes will check if all required indexes exist and create them when
// needed. Usually, this is done automatically when uploading the first file
// using a bucket. However, when transactions are used to upload files, the
// indexes must be created before the first upload as index creation is
// prohibited during transactions.
func (b *Bucket) EnsureIndexes(ctx context.Context, force bool) error {
// acquire mutex
b.indexMutex.Lock()
defer b.indexMutex.Unlock()
// return if indexes have been ensured
if b.indexEnsured {
return nil
}
// clone collection with primary read preference
files, err := b.files.Clone(options.Collection().SetReadPreference(readpref.Primary()))
if err != nil {
return err
}
// unless force is specified, skip index ensuring if files exists already
if !force {
err = files.FindOne(ctx, bson.M{}).Err()
if err != nil && err != ErrNoDocuments {
return err
} else if err == nil {
b.indexEnsured = true
return nil
}
}
// prepare files index
filesIndex := mongo.IndexModel{
Keys: bson.D{
{Key: "filename", Value: 1},
{Key: "uploadDate", Value: 1},
},
}
// prepare chunks index
chunksIndex := mongo.IndexModel{
Keys: bson.D{
{Key: "files_id", Value: 1},
{Key: "n", Value: 1},
},
Options: options.Index().SetUnique(true),
}
// prepare markers index
markersIndex := mongo.IndexModel{
Keys: bson.D{
{Key: "files_id", Value: 1},
},
Options: options.Index().SetUnique(true),
}
// check files index existence
hasFilesIndex, err := b.hasIndex(ctx, b.files, filesIndex)
if err != nil {
return err
}
// check chunks index existence
hasChunksIndex, err := b.hasIndex(ctx, b.chunks, chunksIndex)
if err != nil {
return err
}
// check markers index existence
hasMarkersIndex, err := b.hasIndex(ctx, b.markers, markersIndex)
if err != nil {
return err
}
// create files index if missing
if !hasFilesIndex {
_, err = b.files.Indexes().CreateOne(ctx, filesIndex)
if err != nil {
return err
}
}
// create chunks index if missing
if !hasChunksIndex {
_, err = b.chunks.Indexes().CreateOne(ctx, chunksIndex)
if err != nil {
return err
}
}
// create markers index if missing
if !hasMarkersIndex {
_, err = b.markers.Indexes().CreateOne(ctx, markersIndex)
if err != nil {
return err
}
}
// set flag
b.indexEnsured = true
return nil
}
func (b *Bucket) hasIndex(ctx context.Context, coll ICollection, model mongo.IndexModel) (bool, error) {
// get indexes
var indexes []mongo.IndexModel
csr, err := coll.Indexes().List(ctx)
if err != nil {
return false, err
}
err = csr.All(nil, &indexes)
if err != nil {
return false, err
}
// check if index with same keys already exists
for _, index := range indexes {
if bsonkit.Compare(index.Keys, model.Keys) == 0 {
return true, nil
}
}
return false, nil
}
// UploadStream is used to upload a single file.
type UploadStream struct {
context context.Context
bucket *Bucket
id interface{}
name string
metadata interface{}
chunkSize int
marker *BucketMarker
length int
chunks int
buffer []byte
bufLen int
closed bool
mutex sync.Mutex
}
func newUploadStream(ctx context.Context, bucket *Bucket, id interface{}, name string, chunkSize int, metadata interface{}) *UploadStream {
return &UploadStream{
context: ctx,
bucket: bucket,
id: id,
name: name,
metadata: metadata,
chunkSize: chunkSize,
buffer: make([]byte, gridfs.UploadBufferSize),
}
}
// Resume will try to resume a previous tracked upload that has been suspended.
// It will return the amount of bytes that have already been written.
func (s *UploadStream) Resume() (int64, error) {
// acquire mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// check if tracked
if !s.bucket.tracked {
return 0, fmt.Errorf("bucket not tracked")
}
// check if pristine
if s.marker != nil || s.bufLen > 0 {
return 0, fmt.Errorf("stream not pristine")
}
// get marker
err := s.bucket.markers.FindOne(s.context, bson.M{
"files_id": s.id,
}).Decode(&s.marker)
if err != nil {
return 0, err
}
// check marker
if s.marker.State != BucketMarkerStateUploading {
return 0, fmt.Errorf("invalid marker state")
}
// check marker chunk size
if s.marker.ChunkSize != s.chunkSize {
return 0, fmt.Errorf("marker chunk size does not match")
}
// create cursor
csr, err := s.bucket.chunks.Find(s.context, bson.M{
"files_id": s.id,
}, options.Find().SetSort(bson.M{
"n": 1,
}))
if err != nil {
return 0, err
}
// ensure cursor is closed
defer csr.Close(s.context)
// prepare counters
var number int
var length int
// check all chunks
for csr.Next(s.context) {
// decode chunk
var chunk BucketChunk
err = csr.Decode(&chunk)
if err != nil {
return 0, err
}
// check chunk
if chunk.Num != number || len(chunk.Data) != s.chunkSize {
return 0, fmt.Errorf("found invalid chunk")
}
// increment
number = chunk.Num
length += len(chunk.Data)
}
// check error
err = csr.Err()
if err != nil {
return 0, err
}
// set state
s.chunks = number + 1
s.length = length
return int64(length), nil
}
// Abort will abort the upload and remove uploaded chunks. If the bucket is
// tracked it will also remove the potentially created marker. If the abort
// fails the upload may get cleaned up.
func (s *UploadStream) Abort() error {
// acquire mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// check if stream has been closed
if s.closed {
return gridfs.ErrStreamClosed
}
// delete uploaded chunks
if s.chunks > 0 {
_, err := s.bucket.chunks.DeleteMany(s.context, bson.M{
"files_id": s.id,
})
if err != nil {
return err
}
}
// delete marker if it exists
if s.marker != nil {
_, err := s.bucket.markers.DeleteOne(s.context, bson.M{
"_id": s.marker.ID,
})
if err != nil {
return err
}
}
// set flag
s.closed = true
return nil
}
// Suspend will upload fully buffered chunks and close the stream. The stream
// may be reopened and resumed later to finish the upload. Until that happens
// the upload may be cleaned up.
func (s *UploadStream) Suspend() (int64, error) {
// acquire mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// check if tracked
if !s.bucket.tracked {
return 0, fmt.Errorf("bucket not tracked")
}
// check if stream has been closed
if s.closed {
return 0, gridfs.ErrStreamClosed
}
// upload buffered data
if s.bufLen > 0 {
err := s.upload(false)
if err != nil {
return 0, err
}
}
// set flag
s.closed = true
return int64(s.length), nil
}
// Close will finish the upload and close the stream. If the bucket is tracked
// the method will not finalize the upload by creating a file. Instead, the user
// should call ClaimUpload as part of a multi-document transaction to safely
// claim the upload. Until that happens the upload may be cleaned up.
func (s *UploadStream) Close() error {
// acquire mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// check if stream has been closed
if s.closed {
return gridfs.ErrStreamClosed
}
// upload buffered data
if s.bufLen > 0 {
err := s.upload(true)
if err != nil {
return err
}
}
// update marker if bucket is tracked
if s.bucket.tracked {
res, err := s.bucket.markers.ReplaceOne(s.context, bson.M{
"_id": s.marker.ID,
}, &BucketMarker{
ID: s.marker.ID,
File: s.id,
State: BucketMarkerStateUploaded,
Timestamp: time.Now(),
Length: s.length,
ChunkSize: s.chunkSize,
Filename: s.name,
Metadata: s.metadata,
})
if err != nil {
return err
} else if res.ModifiedCount != 1 {
return fmt.Errorf("unable to update marker")
}
}
// otherwise, create file directly
if !s.bucket.tracked {
_, err := s.bucket.files.InsertOne(s.context, BucketFile{
ID: s.id,
Length: s.length,
ChunkSize: s.chunkSize,
UploadDate: time.Now(),
Filename: s.name,
Metadata: s.metadata,
})
if err != nil {
return err
}
}
// set flag
s.closed = true
return nil
}
// Write will write the provided data to chunks in the background. If the bucket
// is tracked and an upload already exists, it must be resumed before writing
// more data.
func (s *UploadStream) Write(data []uint8) (int, error) {
// acquire mutex
s.mutex.Lock()
defer s.mutex.Unlock()
// check if stream has been closed
if s.closed {
return 0, gridfs.ErrStreamClosed
}
// buffer and upload data in chunks
var written int
for {
// check if done
if len(data) == 0 {
break
}
// fill buffer
n := copy(s.buffer[s.bufLen:], data)
s.bufLen += n
// resize data
data = data[n:]
// increment counter
written += n
// upload if buffer is full
if s.bufLen == len(s.buffer) {
err := s.upload(false)
if err != nil {
return 0, err
}
}
}
return written, nil
}
func (s *UploadStream) upload(final bool) error {
// prepare chunks
chunks := make([]interface{}, 0, (s.bufLen/s.chunkSize)+1)
// split buffer into chunks
var chunkedBytes int
for i := 0; i < s.bufLen; i += s.chunkSize {
// get chunk size
size := s.bufLen - i
if size > s.chunkSize {
size = s.chunkSize
}
// skip partial chunks if not final
if size < s.chunkSize && !final {
break
}
// append chunk
chunks = append(chunks, BucketChunk{
ID: primitive.NewObjectID(),
File: s.id,
Num: s.chunks + len(chunks),
Data: s.buffer[i : i+size],