-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathGridFSForwardOnlyUploadStream.cs
534 lines (470 loc) · 16.7 KB
/
GridFSForwardOnlyUploadStream.cs
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
/* Copyright 2015-present MongoDB Inc.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Core.Bindings;
using MongoDB.Driver.Core.Operations;
namespace MongoDB.Driver.GridFS
{
internal class GridFSForwardOnlyUploadStream<TFileId> : GridFSUploadStream<TFileId>
{
#region static
// private static fields
private static readonly Task __completedTask = Task.FromResult(true);
#endregion
// fields
private bool _aborted;
private List<byte[]> _batch;
private long _batchPosition;
private int _batchSize;
private readonly IWriteBinding _binding;
private readonly GridFSBucket<TFileId> _bucket;
private readonly int _chunkSizeBytes;
private bool _closed;
private bool _disposed;
private readonly string _filename;
private readonly TFileId _id;
private readonly BsonValue _idAsBsonValue;
private long _length;
private readonly BsonDocument _metadata;
// constructors
public GridFSForwardOnlyUploadStream(
GridFSBucket<TFileId> bucket,
IWriteBinding binding,
TFileId id,
string filename,
BsonDocument metadata,
int chunkSizeBytes,
int batchSize)
{
_bucket = bucket;
_binding = binding;
_id = id;
_filename = filename;
_metadata = metadata; // can be null
_chunkSizeBytes = chunkSizeBytes;
_batchSize = batchSize;
_batch = new List<byte[]>();
var idSerializer = bucket.Options.SerializerRegistry.GetSerializer<TFileId>();
var idSerializationInfo = new BsonSerializationInfo("_id", idSerializer, typeof(TFileId));
_idAsBsonValue = idSerializationInfo.SerializeValue(id);
}
// properties
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override TFileId Id
{
get { return _id; }
}
public override long Length
{
get { return _length; }
}
public override long Position
{
get
{
return _length;
}
set
{
throw new NotSupportedException();
}
}
// methods
public override void Abort(CancellationToken cancellationToken = default(CancellationToken))
{
if (_aborted)
{
return;
}
ThrowIfClosedOrDisposed();
_aborted = true;
var operation = CreateAbortOperation();
operation.Execute(_binding, cancellationToken);
}
public override async Task AbortAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_aborted)
{
return;
}
ThrowIfClosedOrDisposed();
_aborted = true;
var operation = CreateAbortOperation();
await operation.ExecuteAsync(_binding, cancellationToken).ConfigureAwait(false);
}
public override void Close(CancellationToken cancellationToken)
{
try
{
CloseIfNotAlreadyClosed(cancellationToken);
}
finally
{
Dispose();
}
}
public override async Task CloseAsync(CancellationToken cancellationToken = default(CancellationToken))
{
try
{
await CloseIfNotAlreadyClosedAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
Dispose();
}
}
public override void Flush()
{
// do nothing
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// do nothing
return __completedTask;
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfAbortedClosedOrDisposed();
while (count > 0)
{
var chunk = GetCurrentChunk(CancellationToken.None);
var partialCount = Math.Min(count, chunk.Count);
Buffer.BlockCopy(buffer, offset, chunk.Array, chunk.Offset, partialCount);
offset += partialCount;
count -= partialCount;
_length += partialCount;
}
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ThrowIfAbortedClosedOrDisposed();
while (count > 0)
{
var chunk = await GetCurrentChunkAsync(cancellationToken).ConfigureAwait(false);
var partialCount = Math.Min(count, chunk.Count);
Buffer.BlockCopy(buffer, offset, chunk.Array, chunk.Offset, partialCount);
offset += partialCount;
count -= partialCount;
_length += partialCount;
}
}
// private methods
private void CloseIfNotAlreadyClosed(CancellationToken cancellationToken)
{
if (!_closed)
{
try
{
CloseImplementation(cancellationToken);
}
finally
{
_closed = true;
}
}
}
private async Task CloseIfNotAlreadyClosedAsync(CancellationToken cancellationToken)
{
if (!_closed)
{
try
{
await CloseImplementationAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
_closed = true;
}
}
}
private void CloseIfNotAlreadyClosedFromDispose(bool disposing)
{
if (disposing)
{
try
{
CloseIfNotAlreadyClosed(CancellationToken.None);
}
catch
{
// ignore any exceptions from CloseIfNotAlreadyClosed when called from Dispose
}
}
}
private void CloseImplementation(CancellationToken cancellationToken)
{
if (!_aborted)
{
WriteFinalBatch(cancellationToken);
WriteFilesCollectionDocument(cancellationToken);
}
}
private async Task CloseImplementationAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (!_aborted)
{
await WriteFinalBatchAsync(cancellationToken).ConfigureAwait(false);
await WriteFilesCollectionDocumentAsync(cancellationToken).ConfigureAwait(false);
}
}
private BulkMixedWriteOperation CreateAbortOperation()
{
var chunksCollectionNamespace = _bucket.GetChunksCollectionNamespace();
var filter = new BsonDocument("files_id", _idAsBsonValue);
var deleteRequest = new DeleteRequest(filter) { Limit = 0 };
var requests = new WriteRequest[] { deleteRequest };
var messageEncoderSettings = _bucket.GetMessageEncoderSettings();
return new BulkMixedWriteOperation(chunksCollectionNamespace, requests, messageEncoderSettings)
{
WriteConcern = _bucket.Options.WriteConcern
};
}
private BsonDocument CreateFilesCollectionDocument()
{
var uploadDateTime = DateTime.UtcNow;
return new BsonDocument
{
{ "_id", _idAsBsonValue },
{ "length", _length },
{ "chunkSize", _chunkSizeBytes },
{ "uploadDate", uploadDateTime },
{ "filename", _filename },
{ "metadata", _metadata, _metadata != null }
};
}
private IEnumerable<BsonDocument> CreateWriteBatchChunkDocuments()
{
var chunkDocuments = new List<BsonDocument>();
var n = (int)(_batchPosition / _chunkSizeBytes);
foreach (var chunk in _batch)
{
var chunkDocument = new BsonDocument
{
{ "_id", ObjectId.GenerateNewId() },
{ "files_id", _idAsBsonValue },
{ "n", n++ },
{ "data", new BsonBinaryData(chunk, BsonBinarySubType.Binary) }
};
chunkDocuments.Add(chunkDocument);
_batchPosition += chunk.Length;
}
return chunkDocuments;
}
protected override void Dispose(bool disposing)
{
CloseIfNotAlreadyClosedFromDispose(disposing);
if (!_disposed)
{
_disposed = true;
if (disposing)
{
_binding.Dispose();
}
}
base.Dispose(disposing);
}
private void ExecuteOrSetAbortedOnException(Action action)
{
try
{
action();
}
catch
{
_aborted = true;
throw;
}
}
private async Task ExecuteOrSetAbortedOnExceptionAsync(Func<Task> action)
{
try
{
await action().ConfigureAwait(false);
}
catch
{
_aborted = true;
throw;
}
}
private IMongoCollection<BsonDocument> GetChunksCollection()
{
return GetCollection("chunks");
}
private IMongoCollection<BsonDocument> GetCollection(string suffix)
{
var database = _bucket.Database;
var collectionName = _bucket.Options.BucketName + "." + suffix;
var writeConcern = _bucket.Options.WriteConcern ?? database.Settings.WriteConcern;
var settings = new MongoCollectionSettings { WriteConcern = writeConcern };
return database.GetCollection<BsonDocument>(collectionName, settings);
}
private ArraySegment<byte> GetCurrentChunk(CancellationToken cancellationToken)
{
var batchIndex = (int)((_length - _batchPosition) / _chunkSizeBytes);
if (batchIndex == _batchSize)
{
WriteBatch(cancellationToken);
_batch.Clear();
batchIndex = 0;
}
return GetCurrentChunkSegment(batchIndex);
}
private async Task<ArraySegment<byte>> GetCurrentChunkAsync(CancellationToken cancellationToken)
{
var batchIndex = (int)((_length - _batchPosition) / _chunkSizeBytes);
if (batchIndex == _batchSize)
{
await WriteBatchAsync(cancellationToken).ConfigureAwait(false);
_batch.Clear();
batchIndex = 0;
}
return GetCurrentChunkSegment(batchIndex);
}
private ArraySegment<byte> GetCurrentChunkSegment(int batchIndex)
{
if (_batch.Count <= batchIndex)
{
_batch.Add(new byte[_chunkSizeBytes]);
}
var chunk = _batch[batchIndex];
var offset = (int)(_length % _chunkSizeBytes);
var count = _chunkSizeBytes - offset;
return new ArraySegment<byte>(chunk, offset, count);
}
private IMongoCollection<BsonDocument> GetFilesCollection()
{
return GetCollection("files");
}
private void ThrowIfAbortedClosedOrDisposed()
{
if (_aborted)
{
throw new InvalidOperationException("The upload was aborted.");
}
ThrowIfClosedOrDisposed();
}
private void ThrowIfClosedOrDisposed()
{
if (_closed)
{
throw new InvalidOperationException("The stream is closed.");
}
ThrowIfDisposed();
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
private void TruncateFinalChunk()
{
var finalChunkSize = (int)(_length % _chunkSizeBytes);
if (finalChunkSize > 0)
{
var finalChunk = _batch[_batch.Count - 1];
if (finalChunk.Length != finalChunkSize)
{
var truncatedFinalChunk = new byte[finalChunkSize];
Buffer.BlockCopy(finalChunk, 0, truncatedFinalChunk, 0, finalChunkSize);
_batch[_batch.Count - 1] = truncatedFinalChunk;
}
}
}
private void WriteBatch(CancellationToken cancellationToken)
=> ExecuteOrSetAbortedOnException(() =>
{
var chunksCollection = GetChunksCollection();
var chunkDocuments = CreateWriteBatchChunkDocuments();
chunksCollection.InsertMany(chunkDocuments, cancellationToken: cancellationToken);
_batch.Clear();
});
private Task WriteBatchAsync(CancellationToken cancellationToken)
=> ExecuteOrSetAbortedOnExceptionAsync(async () =>
{
var chunksCollection = GetChunksCollection();
var chunkDocuments = CreateWriteBatchChunkDocuments();
await chunksCollection.InsertManyAsync(chunkDocuments, cancellationToken: cancellationToken).ConfigureAwait(false);
_batch.Clear();
});
private void WriteFilesCollectionDocument(CancellationToken cancellationToken)
=> ExecuteOrSetAbortedOnException(() =>
{
var filesCollection = GetFilesCollection();
var filesCollectionDocument = CreateFilesCollectionDocument();
filesCollection.InsertOne(filesCollectionDocument, cancellationToken: cancellationToken);
});
private Task WriteFilesCollectionDocumentAsync(CancellationToken cancellationToken)
=> ExecuteOrSetAbortedOnExceptionAsync(() =>
{
var filesCollection = GetFilesCollection();
var filesCollectionDocument = CreateFilesCollectionDocument();
return filesCollection.InsertOneAsync(filesCollectionDocument, cancellationToken: cancellationToken);
});
private void WriteFinalBatch(CancellationToken cancellationToken)
{
if (_batch.Count > 0)
{
TruncateFinalChunk();
WriteBatch(cancellationToken);
}
}
private async Task WriteFinalBatchAsync(CancellationToken cancellationToken)
{
if (_batch.Count > 0)
{
TruncateFinalChunk();
await WriteBatchAsync(cancellationToken).ConfigureAwait(false);
}
}
}
}