forked from mongodb/mongo-go-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucket.go
572 lines (475 loc) · 14.1 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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package gridfs // import "go.mongodb.org/mongo-driver/mongo/gridfs"
import (
"bytes"
"context"
"io"
"errors"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readconcern"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
"go.mongodb.org/mongo-driver/x/bsonx"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
// TODO: add sessions options
// DefaultChunkSize is the default size of each file chunk.
const DefaultChunkSize int32 = 255 * 1024 // 255 KiB
// ErrFileNotFound occurs if a user asks to download a file with a file ID that isn't found in the files collection.
var ErrFileNotFound = errors.New("file with given parameters not found")
// Bucket represents a GridFS bucket.
type Bucket struct {
db *mongo.Database
chunksColl *mongo.Collection // collection to store file chunks
filesColl *mongo.Collection // collection to store file metadata
name string
chunkSize int32
wc *writeconcern.WriteConcern
rc *readconcern.ReadConcern
rp *readpref.ReadPref
firstWriteDone bool
readBuf []byte
writeBuf []byte
readDeadline time.Time
writeDeadline time.Time
}
// Upload contains options to upload a file to a bucket.
type Upload struct {
chunkSize int32
metadata bsonx.Doc
}
// NewBucket creates a GridFS bucket.
func NewBucket(db *mongo.Database, opts ...*options.BucketOptions) (*Bucket, error) {
b := &Bucket{
name: "fs",
chunkSize: DefaultChunkSize,
db: db,
wc: db.WriteConcern(),
rc: db.ReadConcern(),
rp: db.ReadPreference(),
}
bo := options.MergeBucketOptions(opts...)
if bo.Name != nil {
b.name = *bo.Name
}
if bo.ChunkSizeBytes != nil {
b.chunkSize = *bo.ChunkSizeBytes
}
if bo.WriteConcern != nil {
b.wc = bo.WriteConcern
}
if bo.ReadConcern != nil {
b.rc = bo.ReadConcern
}
if bo.ReadPreference != nil {
b.rp = bo.ReadPreference
}
var collOpts = options.Collection().SetWriteConcern(b.wc).SetReadConcern(b.rc).SetReadPreference(b.rp)
b.chunksColl = db.Collection(b.name+".chunks", collOpts)
b.filesColl = db.Collection(b.name+".files", collOpts)
b.readBuf = make([]byte, b.chunkSize)
b.writeBuf = make([]byte, b.chunkSize)
return b, nil
}
// SetWriteDeadline sets the write deadline for this bucket.
func (b *Bucket) SetWriteDeadline(t time.Time) error {
b.writeDeadline = t
return nil
}
// SetReadDeadline sets the read deadline for this bucket
func (b *Bucket) SetReadDeadline(t time.Time) error {
b.readDeadline = t
return nil
}
// OpenUploadStream creates a file ID new upload stream for a file given the filename.
func (b *Bucket) OpenUploadStream(filename string, opts ...*options.UploadOptions) (*UploadStream, error) {
return b.OpenUploadStreamWithID(primitive.NewObjectID(), filename, opts...)
}
// OpenUploadStreamWithID creates a new upload stream for a file given the file ID and filename.
func (b *Bucket) OpenUploadStreamWithID(fileID interface{}, filename string, opts ...*options.UploadOptions) (*UploadStream, error) {
ctx, cancel := deadlineContext(b.writeDeadline)
if cancel != nil {
defer cancel()
}
if err := b.checkFirstWrite(ctx); err != nil {
return nil, err
}
upload, err := b.parseUploadOptions(opts...)
if err != nil {
return nil, err
}
return newUploadStream(upload, fileID, filename, b.chunksColl, b.filesColl), nil
}
// UploadFromStream creates a fileID and uploads a file given a source stream.
func (b *Bucket) UploadFromStream(filename string, source io.Reader, opts ...*options.UploadOptions) (primitive.ObjectID, error) {
fileID := primitive.NewObjectID()
err := b.UploadFromStreamWithID(fileID, filename, source, opts...)
return fileID, err
}
// UploadFromStreamWithID uploads a file given a source stream.
func (b *Bucket) UploadFromStreamWithID(fileID interface{}, filename string, source io.Reader, opts ...*options.UploadOptions) error {
us, err := b.OpenUploadStreamWithID(fileID, filename, opts...)
if err != nil {
return err
}
err = us.SetWriteDeadline(b.writeDeadline)
if err != nil {
_ = us.Close()
return err
}
for {
n, err := source.Read(b.readBuf)
if err != nil && err != io.EOF {
_ = us.Abort() // upload considered aborted if source stream returns an error
return err
}
if n > 0 {
_, err := us.Write(b.readBuf[:n])
if err != nil {
return err
}
}
if n == 0 || err == io.EOF {
break
}
}
return us.Close()
}
// OpenDownloadStream creates a stream from which the contents of the file can be read.
func (b *Bucket) OpenDownloadStream(fileID interface{}) (*DownloadStream, error) {
id, err := convertFileID(fileID)
if err != nil {
return nil, err
}
return b.openDownloadStream(bsonx.Doc{
{"_id", id},
})
}
// DownloadToStream downloads the file with the specified fileID and writes it to the provided io.Writer.
// Returns the number of bytes written to the steam and an error, or nil if there was no error.
func (b *Bucket) DownloadToStream(fileID interface{}, stream io.Writer) (int64, error) {
ds, err := b.OpenDownloadStream(fileID)
if err != nil {
return 0, err
}
return b.downloadToStream(ds, stream)
}
// OpenDownloadStreamByName opens a download stream for the file with the given filename.
func (b *Bucket) OpenDownloadStreamByName(filename string, opts ...*options.NameOptions) (*DownloadStream, error) {
var numSkip int32 = -1
var sortOrder int32 = 1
nameOpts := options.MergeNameOptions(opts...)
if nameOpts.Revision != nil {
numSkip = *nameOpts.Revision
}
if numSkip < 0 {
sortOrder = -1
numSkip = (-1 * numSkip) - 1
}
findOpts := options.Find().SetSkip(int64(numSkip)).SetSort(bsonx.Doc{{"uploadDate", bsonx.Int32(sortOrder)}})
return b.openDownloadStream(bsonx.Doc{{"filename", bsonx.String(filename)}}, findOpts)
}
// DownloadToStreamByName downloads the file with the given name to the given io.Writer.
func (b *Bucket) DownloadToStreamByName(filename string, stream io.Writer, opts ...*options.NameOptions) (int64, error) {
ds, err := b.OpenDownloadStreamByName(filename, opts...)
if err != nil {
return 0, err
}
return b.downloadToStream(ds, stream)
}
// Delete deletes all chunks and metadata associated with the file with the given file ID.
func (b *Bucket) Delete(fileID interface{}) error {
// delete document in files collection and then chunks to minimize race conditions
ctx, cancel := deadlineContext(b.writeDeadline)
if cancel != nil {
defer cancel()
}
id, err := convertFileID(fileID)
if err != nil {
return err
}
res, err := b.filesColl.DeleteOne(ctx, bsonx.Doc{{"_id", id}})
if err == nil && res.DeletedCount == 0 {
err = ErrFileNotFound
}
if err != nil {
_ = b.deleteChunks(ctx, fileID) // can attempt to delete chunks even if no docs in files collection matched
return err
}
return b.deleteChunks(ctx, fileID)
}
// Find returns the files collection documents that match the given filter.
func (b *Bucket) Find(filter interface{}, opts ...*options.GridFSFindOptions) (*mongo.Cursor, error) {
ctx, cancel := deadlineContext(b.readDeadline)
if cancel != nil {
defer cancel()
}
gfsOpts := options.MergeGridFSFindOptions(opts...)
find := options.Find()
if gfsOpts.BatchSize != nil {
find.SetBatchSize(*gfsOpts.BatchSize)
}
if gfsOpts.Limit != nil {
find.SetLimit(int64(*gfsOpts.Limit))
}
if gfsOpts.MaxTime != nil {
find.SetMaxTime(*gfsOpts.MaxTime)
}
if gfsOpts.NoCursorTimeout != nil {
find.SetNoCursorTimeout(*gfsOpts.NoCursorTimeout)
}
if gfsOpts.Skip != nil {
find.SetSkip(int64(*gfsOpts.Skip))
}
if gfsOpts.Sort != nil {
find.SetSort(gfsOpts.Sort)
}
return b.filesColl.Find(ctx, filter, find)
}
// Rename renames the stored file with the specified file ID.
func (b *Bucket) Rename(fileID interface{}, newFilename string) error {
ctx, cancel := deadlineContext(b.writeDeadline)
if cancel != nil {
defer cancel()
}
id, err := convertFileID(fileID)
if err != nil {
return err
}
res, err := b.filesColl.UpdateOne(ctx,
bsonx.Doc{{"_id", id}},
bsonx.Doc{{"$set", bsonx.Document(bsonx.Doc{{"filename", bsonx.String(newFilename)}})}},
)
if err != nil {
return err
}
if res.MatchedCount == 0 {
return ErrFileNotFound
}
return nil
}
// Drop drops the files and chunks collections associated with this bucket.
func (b *Bucket) Drop() error {
ctx, cancel := deadlineContext(b.writeDeadline)
if cancel != nil {
defer cancel()
}
err := b.filesColl.Drop(ctx)
if err != nil {
return err
}
return b.chunksColl.Drop(ctx)
}
func (b *Bucket) openDownloadStream(filter interface{}, opts ...*options.FindOptions) (*DownloadStream, error) {
ctx, cancel := deadlineContext(b.readDeadline)
if cancel != nil {
defer cancel()
}
cursor, err := b.findFile(ctx, filter, opts...)
if err != nil {
return nil, err
}
fileLenElem, err := cursor.Current.LookupErr("length")
if err != nil {
return nil, err
}
fileIDElem, err := cursor.Current.LookupErr("_id")
if err != nil {
return nil, err
}
var fileLen int64
switch fileLenElem.Type {
case bsontype.Int32:
fileLen = int64(fileLenElem.Int32())
default:
fileLen = fileLenElem.Int64()
}
if fileLen == 0 {
return newDownloadStream(nil, b.chunkSize, 0), nil
}
chunksCursor, err := b.findChunks(ctx, fileIDElem)
if err != nil {
return nil, err
}
return newDownloadStream(chunksCursor, b.chunkSize, int64(fileLen)), nil
}
func deadlineContext(deadline time.Time) (context.Context, context.CancelFunc) {
if deadline.Equal(time.Time{}) {
return context.Background(), nil
}
return context.WithDeadline(context.Background(), deadline)
}
func (b *Bucket) downloadToStream(ds *DownloadStream, stream io.Writer) (int64, error) {
err := ds.SetReadDeadline(b.readDeadline)
if err != nil {
_ = ds.Close()
return 0, err
}
copied, err := io.Copy(stream, ds)
if err != nil {
_ = ds.Close()
return 0, err
}
return copied, ds.Close()
}
func (b *Bucket) deleteChunks(ctx context.Context, fileID interface{}) error {
id, err := convertFileID(fileID)
if err != nil {
return err
}
_, err = b.chunksColl.DeleteMany(ctx, bsonx.Doc{{"files_id", id}})
return err
}
func (b *Bucket) findFile(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (*mongo.Cursor, error) {
cursor, err := b.filesColl.Find(ctx, filter, opts...)
if err != nil {
return nil, err
}
if !cursor.Next(ctx) {
_ = cursor.Close(ctx)
return nil, ErrFileNotFound
}
return cursor, nil
}
func (b *Bucket) findChunks(ctx context.Context, fileID interface{}) (*mongo.Cursor, error) {
id, err := convertFileID(fileID)
if err != nil {
return nil, err
}
chunksCursor, err := b.chunksColl.Find(ctx,
bsonx.Doc{{"files_id", id}},
options.Find().SetSort(bsonx.Doc{{"n", bsonx.Int32(1)}})) // sort by chunk index
if err != nil {
return nil, err
}
return chunksCursor, nil
}
// Create an index if it doesn't already exist
func createIndexIfNotExists(ctx context.Context, iv mongo.IndexView, model mongo.IndexModel) error {
c, err := iv.List(ctx)
if err != nil {
return err
}
defer func() {
_ = c.Close(ctx)
}()
var found bool
for c.Next(ctx) {
keyElem, err := c.Current.LookupErr("key")
if err != nil {
return err
}
keyElemDoc := keyElem.Document()
modelKeysDoc, err := bson.Marshal(model.Keys)
if err != nil {
return err
}
if bytes.Equal(modelKeysDoc, keyElemDoc) {
found = true
break
}
}
if !found {
_, err = iv.CreateOne(ctx, model)
if err != nil {
return err
}
}
return nil
}
// create indexes on the files and chunks collection if needed
func (b *Bucket) createIndexes(ctx context.Context) error {
// must use primary read pref mode to check if files coll empty
cloned, err := b.filesColl.Clone(options.Collection().SetReadPreference(readpref.Primary()))
if err != nil {
return err
}
docRes := cloned.FindOne(ctx, bsonx.Doc{}, options.FindOne().SetProjection(bsonx.Doc{{"_id", bsonx.Int32(1)}}))
_, err = docRes.DecodeBytes()
if err != mongo.ErrNoDocuments {
// nil, or error that occured during the FindOne operation
return err
}
filesIv := b.filesColl.Indexes()
chunksIv := b.chunksColl.Indexes()
filesModel := mongo.IndexModel{
Keys: bson.D{
{"filename", int32(1)},
{"uploadDate", int32(1)},
},
}
chunksModel := mongo.IndexModel{
Keys: bson.D{
{"files_id", int32(1)},
{"n", int32(1)},
},
Options: options.Index().SetUnique(true),
}
if err = createIndexIfNotExists(ctx, filesIv, filesModel); err != nil {
return err
}
if err = createIndexIfNotExists(ctx, chunksIv, chunksModel); err != nil {
return err
}
return nil
}
func (b *Bucket) checkFirstWrite(ctx context.Context) error {
if !b.firstWriteDone {
// before the first write operation, must determine if files collection is empty
// if so, create indexes if they do not already exist
if err := b.createIndexes(ctx); err != nil {
return err
}
b.firstWriteDone = true
}
return nil
}
func (b *Bucket) parseUploadOptions(opts ...*options.UploadOptions) (*Upload, error) {
upload := &Upload{
chunkSize: b.chunkSize, // upload chunk size defaults to bucket's value
}
uo := options.MergeUploadOptions(opts...)
if uo.ChunkSizeBytes != nil {
upload.chunkSize = *uo.ChunkSizeBytes
}
if uo.Registry == nil {
uo.Registry = bson.DefaultRegistry
}
if uo.Metadata != nil {
raw, err := bson.MarshalWithRegistry(uo.Registry, uo.Metadata)
if err != nil {
return nil, err
}
doc, err := bsonx.ReadDoc(raw)
if err != nil {
return nil, err
}
upload.metadata = doc
}
return upload, nil
}
type _convertFileID struct {
ID interface{} `bson:"_id"`
}
func convertFileID(fileID interface{}) (bsonx.Val, error) {
id := _convertFileID{
ID: fileID,
}
b, err := bson.Marshal(id)
if err != nil {
return bsonx.Val{}, err
}
val := bsoncore.Document(b).Lookup("_id")
var res bsonx.Val
err = res.UnmarshalBSONValue(val.Type, val.Data)
return res, err
}