-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathTransferManager.cpp
More file actions
1511 lines (1319 loc) · 79 KB
/
TransferManager.cpp
File metadata and controls
1511 lines (1319 loc) · 79 KB
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
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/platform/FileSystem.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/stream/PreallocatedStreamBuf.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/AbortMultipartUploadRequest.h>
#include <aws/s3/model/CompleteMultipartUploadRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/ListObjectsV2Request.h>
#include <aws/transfer/TransferManager.h>
#include <sys/stat.h>
#include <algorithm>
#include <fstream>
namespace Aws
{
namespace Transfer
{
static inline bool IsS3KeyPrefix(const Aws::String& path)
{
return (path.find_last_of('/') == path.size() - 1 || path.find_last_of('\\') == path.size() - 1);
}
template <typename RequestT>
static void SetChecksumOnRequest(RequestT& request, S3::Model::ChecksumAlgorithm checksumAlgorithm, const Aws::String& checksum) {
if (checksumAlgorithm == S3::Model::ChecksumAlgorithm::CRC64NVME) {
request.SetChecksumCRC64NVME(checksum);
} else if (checksumAlgorithm == S3::Model::ChecksumAlgorithm::CRC32) {
request.SetChecksumCRC32(checksum);
} else if (checksumAlgorithm == S3::Model::ChecksumAlgorithm::CRC32C) {
request.SetChecksumCRC32C(checksum);
} else if (checksumAlgorithm == S3::Model::ChecksumAlgorithm::SHA1) {
request.SetChecksumSHA1(checksum);
} else if (checksumAlgorithm == S3::Model::ChecksumAlgorithm::SHA256) {
request.SetChecksumSHA256(checksum);
}
}
struct TransferHandleAsyncContext : public Aws::Client::AsyncCallerContext
{
std::shared_ptr<TransferHandle> handle;
PartPointer partState;
};
struct DownloadDirectoryContext : public Aws::Client::AsyncCallerContext
{
Aws::String rootDirectory;
Aws::String prefix;
};
std::shared_ptr<TransferManager> TransferManager::Create(const TransferManagerConfiguration& config)
{
// Because TransferManager's ctor is private (to ensure it's always constructed as a shared_ptr)
// Aws::MakeShared does not have access to that private constructor. This workaround essentially
// enables Aws::MakeShared to construct TransferManager.
struct MakeSharedEnabler : public TransferManager {
MakeSharedEnabler(const TransferManagerConfiguration& config) : TransferManager(config) {}
};
return Aws::MakeShared<MakeSharedEnabler>(CLASS_TAG, config);
}
TransferManager::TransferManager(const TransferManagerConfiguration& configuration) : m_transferConfig(configuration)
{
assert(m_transferConfig.s3Client);
if (!m_transferConfig.transferExecutor)
{
if(!m_transferConfig.spExecutor && m_transferConfig.executorCreateFn)
{
m_transferConfig.spExecutor = m_transferConfig.executorCreateFn();
}
m_transferConfig.transferExecutor = m_transferConfig.spExecutor.get();
}
if (!m_transferConfig.transferExecutor)
{
AWS_LOGSTREAM_FATAL(CLASS_TAG, "Failed to init TransferManager: transferExecutor is null");
}
assert(m_transferConfig.transferExecutor);
m_transferConfig.s3Client->AppendToUserAgent("ft/s3-transfer");
for (uint64_t i = 0; i < m_transferConfig.transferBufferMaxHeapSize; i += m_transferConfig.bufferSize)
{
m_bufferManager.PutResource(Aws::NewArray<unsigned char>(static_cast<size_t>(m_transferConfig.bufferSize), CLASS_TAG));
}
}
Transfer::TransferStatus TransferManager::WaitUntilAllFinished(int64_t timeoutMs)
{
Transfer::TransferStatus status = Transfer::TransferStatus::IN_PROGRESS;
do
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
if (m_tasks.empty())
{
status = Transfer::TransferStatus::COMPLETED;
break;
}
const auto waitStarted = std::chrono::steady_clock::now();
m_tasksSignal.wait_for(lock, std::chrono::milliseconds(timeoutMs));
timeoutMs -= std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - waitStarted).count();
}
while(status != Transfer::TransferStatus::COMPLETED && timeoutMs > 0);
return status;
}
void TransferManager::CancelAll()
{
Aws::UnorderedSet<std::shared_ptr<TransferHandle>> tasksCopy;
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
tasksCopy = m_tasks;
}
for(auto& it : tasksCopy)
{
assert(it.get());
it->Cancel();
}
}
void TransferManager::AddTask(std::shared_ptr<TransferHandle> handle)
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
m_tasks.emplace(std::move(handle));
}
void TransferManager::RemoveTask(const std::shared_ptr<TransferHandle>& handle) {
std::unique_lock<std::mutex> lock(m_tasksMutex);
m_tasks.erase(handle);
m_tasksSignal.notify_all();
}
TransferManager::~TransferManager() {
for (auto buffer : m_bufferManager.ShutdownAndWait(
static_cast<size_t>(m_transferConfig.transferBufferMaxHeapSize / m_transferConfig.bufferSize))) {
Aws::Delete(buffer);
}
}
std::shared_ptr<TransferHandle> TransferManager::UploadFile(const Aws::String& fileName, const Aws::String& bucketName,
const Aws::String& keyName, const Aws::String& contentType,
const Aws::Map<Aws::String, Aws::String>& metadata,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context,
const Aws::String& precalculatedChecksum) {
// destructor of FStream will close stream automatically (when out of scope), no need to call close explicitly
#ifdef _MSC_VER
auto wide = Aws::Utils::StringUtils::ToWString(fileName.c_str());
auto fileStream = Aws::MakeShared<Aws::FStream>(CLASS_TAG, wide.c_str(), std::ios_base::in | std::ios_base::binary);
#else
auto fileStream = Aws::MakeShared<Aws::FStream>(CLASS_TAG, fileName.c_str(), std::ios_base::in | std::ios_base::binary);
#endif
auto handle = CreateUploadFileHandle(fileStream.get(), bucketName, keyName, contentType, metadata, context, fileName,
precalculatedChecksum);
return SubmitUpload(handle);
}
std::shared_ptr<TransferHandle> TransferManager::UploadFile(const std::shared_ptr<Aws::IOStream>& fileStream,
const Aws::String& bucketName, const Aws::String& keyName,
const Aws::String& contentType,
const Aws::Map<Aws::String, Aws::String>& metadata,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context,
const Aws::String& precalculatedChecksum) {
auto handle =
CreateUploadFileHandle(fileStream.get(), bucketName, keyName, contentType, metadata, context, "", precalculatedChecksum);
return SubmitUpload(handle, fileStream);
}
std::shared_ptr<TransferHandle> TransferManager::DownloadFile(const Aws::String& bucketName,
const Aws::String& keyName,
CreateDownloadStreamCallback writeToStreamfn,
const DownloadConfiguration& downloadConfig,
const Aws::String& writeToFile,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
auto handle = Aws::MakeShared<TransferHandle>(CLASS_TAG, bucketName, keyName, writeToStreamfn, writeToFile);
handle->ApplyDownloadConfiguration(downloadConfig);
handle->SetContext(context);
auto self = shared_from_this();
AddTask(handle);
m_transferConfig.transferExecutor->Submit(
[self, handle]
{
self->DoDownload(handle);
self->RemoveTask(handle);
});
return handle;
}
std::shared_ptr<TransferHandle> TransferManager::DownloadFile(const Aws::String& bucketName,
const Aws::String& keyName,
uint64_t fileOffset,
uint64_t downloadBytes,
CreateDownloadStreamCallback writeToStreamfn,
const DownloadConfiguration& downloadConfig,
const Aws::String& writeToFile,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
auto handle = Aws::MakeShared<TransferHandle>(CLASS_TAG, bucketName, keyName, fileOffset, downloadBytes, writeToStreamfn, writeToFile);
handle->ApplyDownloadConfiguration(downloadConfig);
handle->SetContext(context);
auto self = shared_from_this();
AddTask(handle);
m_transferConfig.transferExecutor->Submit(
[self, handle]
{
self->DoDownload(handle);
self->RemoveTask(handle);
});
return handle;
}
std::shared_ptr<TransferHandle> TransferManager::DownloadFile(const Aws::String& bucketName,
const Aws::String& keyName,
const Aws::String& writeToFile,
const DownloadConfiguration& downloadConfig,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
#ifdef _MSC_VER
auto createFileFn = [=]() { return Aws::New<Aws::FStream>(CLASS_TAG, Aws::Utils::StringUtils::ToWString(writeToFile.c_str()).c_str(),
std::ios_base::out | std::ios_base::in | std::ios_base::binary | std::ios_base::trunc);};
#else
auto createFileFn = [=]() { return Aws::New<Aws::FStream>(CLASS_TAG, writeToFile.c_str(),
std::ios_base::out | std::ios_base::in | std::ios_base::binary | std::ios_base::trunc);};
#endif
return DownloadFile(bucketName, keyName, createFileFn, downloadConfig, writeToFile, context);
}
std::shared_ptr<TransferHandle> TransferManager::RetryUpload(const Aws::String& fileName, const std::shared_ptr<TransferHandle>& retryHandle)
{
#ifdef _MSC_VER
auto fileStream = Aws::MakeShared<Aws::FStream>(CLASS_TAG, Aws::Utils::StringUtils::ToWString(fileName.c_str()).c_str(), std::ios_base::in | std::ios_base::binary);
#else
auto fileStream = Aws::MakeShared<Aws::FStream>(CLASS_TAG, fileName.c_str(), std::ios_base::in | std::ios_base::binary);
#endif
return RetryUpload(fileStream, retryHandle);
}
std::shared_ptr<TransferHandle> TransferManager::RetryUpload(const std::shared_ptr<Aws::IOStream>& stream, const std::shared_ptr<TransferHandle>& retryHandle)
{
assert(retryHandle->GetStatus() != TransferStatus::IN_PROGRESS);
assert(retryHandle->GetStatus() != TransferStatus::COMPLETED);
assert(retryHandle->GetStatus() != TransferStatus::NOT_STARTED);
AWS_LOGSTREAM_INFO(CLASS_TAG, "Transfer handle [" << retryHandle->GetId()
<< "] Retrying upload to Bucket: [" << retryHandle->GetBucketName() << "] with Key: ["
<< retryHandle->GetKey() << "] with Upload ID: [" << retryHandle->GetMultiPartId()
<< "]. Current handle status: [" << retryHandle->GetStatus() << "].");
bool hasFileName = (retryHandle->GetTargetFilePath().size() != 0);
if (retryHandle->GetStatus() == TransferStatus::ABORTED)
{
if (hasFileName)
{
AWS_LOGSTREAM_TRACE(CLASS_TAG, "Transfer handle [" << retryHandle->GetId() << "] Uploading file: "
<< retryHandle->GetTargetFilePath() << " from disk. In Bucket: ["
<< retryHandle->GetBucketName() << "] with Key: ["
<< retryHandle->GetKey() << "].");
return UploadFile(retryHandle->GetTargetFilePath(), retryHandle->GetBucketName(), retryHandle->GetKey(), retryHandle->GetContentType(), retryHandle->GetMetadata());
}
else
{
AWS_LOGSTREAM_TRACE(CLASS_TAG, "Transfer handle [" << retryHandle->GetId() << "] Uploading bytes"
" from stream. In Bucket: [" << retryHandle->GetBucketName() << "] with Key: ["
<< retryHandle->GetKey() << "].");
return UploadFile(stream, retryHandle->GetBucketName(), retryHandle->GetKey(), retryHandle->GetContentType(), retryHandle->GetMetadata());
}
}
retryHandle->UpdateStatus(TransferStatus::NOT_STARTED);
retryHandle->Restart();
TriggerTransferStatusUpdatedCallback(retryHandle);
SubmitUpload(retryHandle, hasFileName ? nullptr : stream);
return retryHandle;
}
void TransferManager::AbortMultipartUpload(const std::shared_ptr<TransferHandle>& inProgressHandle)
{
assert(inProgressHandle->IsMultipart());
assert(inProgressHandle->GetTransferDirection() == TransferDirection::UPLOAD);
AWS_LOGSTREAM_INFO(CLASS_TAG, "Transfer handle [" << inProgressHandle->GetId() << "] Attempting to abort multipart upload.");
inProgressHandle->Cancel();
auto self = shared_from_this();
AddTask(inProgressHandle);
m_transferConfig.transferExecutor->Submit(
[self, inProgressHandle]
{
self->WaitForCancellationAndAbortUpload(inProgressHandle);
self->RemoveTask(inProgressHandle);
});
}
void TransferManager::UploadDirectory(const Aws::String& directory, const Aws::String& bucketName, const Aws::String& prefix, const Aws::Map<Aws::String, Aws::String>& metadata)
{
assert(m_transferConfig.transferInitiatedCallback);
auto handle = Aws::MakeShared<TransferHandle>(CLASS_TAG, bucketName, prefix); // fake handle
auto self = shared_from_this();
auto visitor = [self, bucketName, prefix, metadata, handle](const Aws::FileSystem::DirectoryTree*, const Aws::FileSystem::DirectoryEntry& entry)
{
if (!handle || !handle->ShouldContinue())
{
return false; // Allow to cancel directory upload
}
if (entry && entry.fileType == Aws::FileSystem::FileType::File)
{
Aws::StringStream ssKey;
Aws::String relativePath = entry.relativePath;
char delimiter[] = { Aws::FileSystem::PATH_DELIM, 0 };
Aws::Utils::StringUtils::Replace(relativePath, delimiter, "/");
ssKey << prefix << "/" << relativePath;
Aws::String keyName = ssKey.str();
AWS_LOGSTREAM_DEBUG(CLASS_TAG, "Uploading file: " << entry.path
<< " as part of directory upload to S3 Bucket: [" << bucketName << "] and Key: ["
<< keyName << "].");
self->m_transferConfig.transferInitiatedCallback(self.get(), self->UploadFile(entry.path, bucketName, keyName, DEFAULT_CONTENT_TYPE, metadata));
}
return true;
};
AddTask(handle);
m_transferConfig.transferExecutor->Submit(
[directory, visitor, self, handle]()
{
Aws::FileSystem::DirectoryTree dir(directory);
dir.TraverseDepthFirst(visitor);
self->RemoveTask(handle);
});
}
void TransferManager::DownloadToDirectory(const Aws::String& directory, const Aws::String& bucketName, const Aws::String& prefix)
{
assert(m_transferConfig.transferInitiatedCallback);
Aws::FileSystem::CreateDirectoryIfNotExists(directory.c_str());
auto self = shared_from_this(); // keep transfer manager alive until all callbacks are finished.
auto handle = Aws::MakeShared<TransferHandle>(CLASS_TAG, bucketName, prefix); // fake handle
AddTask(handle);
auto handler =
[self, handle](const Aws::S3::S3Client* client,
const Aws::S3::Model::ListObjectsV2Request& request,
const Aws::S3::Model::ListObjectsV2Outcome& outcome,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
self->HandleListObjectsResponse(client, request, outcome, context);
self->RemoveTask(handle);
};
Aws::S3::Model::ListObjectsV2Request request;
request.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
request.WithBucket(bucketName)
.WithPrefix(prefix);
auto context = Aws::MakeShared<DownloadDirectoryContext>(CLASS_TAG);
context->rootDirectory = directory;
context->prefix = prefix;
m_transferConfig.s3Client->ListObjectsV2Async(request, handler, context);
}
void TransferManager::DoMultiPartUpload(const std::shared_ptr<TransferHandle>& handle)
{
#ifdef _MSC_VER
auto wide = Aws::Utils::StringUtils::ToWString(handle->GetTargetFilePath().c_str());
auto streamToPut = Aws::MakeShared<Aws::FStream>(CLASS_TAG, wide.c_str(), std::ios_base::in | std::ios_base::binary);
DoMultiPartUpload(streamToPut, handle);
#else
auto streamToPut =
Aws::MakeShared<Aws::FStream>(CLASS_TAG, handle->GetTargetFilePath().c_str(), std::ios_base::in | std::ios_base::binary);
DoMultiPartUpload(streamToPut, handle);
#endif
}
void TransferManager::DoMultiPartUpload(const std::shared_ptr<Aws::IOStream>& streamToPut, const std::shared_ptr<TransferHandle>& handle)
{
handle->SetIsMultipart(true);
bool isRetry = !handle->GetMultiPartId().empty();
uint64_t sentBytes = 0;
if (!isRetry) {
Aws::S3::Model::CreateMultipartUploadRequest createMultipartRequest = m_transferConfig.createMultipartUploadTemplate;
createMultipartRequest.SetChecksumAlgorithm(m_transferConfig.checksumAlgorithm);
createMultipartRequest.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
createMultipartRequest.SetBucket(handle->GetBucketName());
createMultipartRequest.SetContentType(handle->GetContentType());
createMultipartRequest.SetKey(handle->GetKey());
createMultipartRequest.SetMetadata(handle->GetMetadata());
auto createMultipartResponse = m_transferConfig.s3Client->CreateMultipartUpload(createMultipartRequest);
if (createMultipartResponse.IsSuccess()) {
handle->SetMultipartId(createMultipartResponse.GetResult().GetUploadId());
uint64_t totalSize = handle->GetBytesTotalSize();
uint64_t partCount = (totalSize + m_transferConfig.bufferSize - 1) / m_transferConfig.bufferSize;
AWS_LOGSTREAM_DEBUG(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] Successfully created a multi-part upload request. Upload ID: ["
<< createMultipartResponse.GetResult().GetUploadId()
<< "]. Splitting the multi-part upload to " << partCount << " part(s).");
for (uint64_t i = 0; i < partCount; ++i) {
uint64_t partSize = (std::min)(totalSize - i * m_transferConfig.bufferSize, m_transferConfig.bufferSize);
bool lastPart = (i == partCount - 1) ? true : false;
handle->AddQueuedPart(Aws::MakeShared<PartState>(CLASS_TAG, static_cast<int>(i + 1), 0, partSize, lastPart));
}
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId() << "] Failed to create a "
"multi-part upload request. Bucket: [" << handle->GetBucketName()
<< "] with Key: [" << handle->GetKey() << "]. " << createMultipartResponse.GetError());
handle->SetError(createMultipartResponse.GetError());
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
TriggerErrorCallback(handle, createMultipartResponse.GetError());
TriggerTransferStatusUpdatedCallback(handle);
return;
}
} else {
uint64_t bytesLeft = 0;
// at this point we've been going synchronously so this is consistent
const auto failedPartsSize = handle->GetFailedParts().size();
for (auto failedParts : handle->GetFailedParts()) {
bytesLeft += failedParts.second->GetSizeInBytes();
handle->AddQueuedPart(failedParts.second);
}
sentBytes = handle->GetBytesTotalSize() - bytesLeft;
AWS_LOGSTREAM_DEBUG(CLASS_TAG, "Transfer handle [" << handle->GetId() << "] Retrying multi-part upload for "
<< failedPartsSize << " failed parts of total size " << bytesLeft
<< " bytes. Upload ID [" << handle->GetMultiPartId() << "].");
}
//still consistent
PartStateMap queuedParts = handle->GetQueuedParts();
auto partsIter = queuedParts.begin();
handle->UpdateStatus(TransferStatus::IN_PROGRESS);
TriggerTransferStatusUpdatedCallback(handle);
while (sentBytes < handle->GetBytesTotalSize() && handle->ShouldContinue() && partsIter != queuedParts.end()) {
auto buffer = m_bufferManager.Acquire();
if (handle->ShouldContinue()) {
auto lengthToWrite = partsIter->second->GetSizeInBytes();
streamToPut->seekg((partsIter->first - 1) * m_transferConfig.bufferSize);
streamToPut->read(reinterpret_cast<char*>(buffer), lengthToWrite);
auto streamBuf = Aws::New<Aws::Utils::Stream::PreallocatedStreamBuf>(CLASS_TAG, buffer, static_cast<size_t>(lengthToWrite));
auto preallocatedStreamReader = Aws::MakeShared<Aws::IOStream>(CLASS_TAG, streamBuf);
auto self = shared_from_this(); // keep transfer manager alive until all callbacks are finished.
PartPointer partPtr = partsIter->second;
Aws::S3::Model::UploadPartRequest uploadPartRequest = m_transferConfig.uploadPartTemplate;
uploadPartRequest.SetChecksumAlgorithm(m_transferConfig.checksumAlgorithm);
uploadPartRequest.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
uploadPartRequest.SetBucket(handle->GetBucketName());
uploadPartRequest.SetContentLength(static_cast<long long>(lengthToWrite));
uploadPartRequest.SetKey(handle->GetKey());
uploadPartRequest.SetPartNumber(partsIter->first);
uploadPartRequest.SetUploadId(handle->GetMultiPartId());
uploadPartRequest.SetContinueRequestHandler([handle](const Aws::Http::HttpRequest*) { return handle->ShouldContinue(); });
uploadPartRequest.SetDataSentEventHandler([self, handle, partPtr](const Aws::Http::HttpRequest*, long long amount) {
partPtr->OnDataTransferred(amount, handle);
self->TriggerUploadProgressCallback(handle);
});
uploadPartRequest.SetRequestRetryHandler([partPtr](const AmazonWebServiceRequest&) { partPtr->Reset(); });
handle->AddPendingPart(partsIter->second);
uploadPartRequest.SetBody(preallocatedStreamReader);
uploadPartRequest.SetContentType(handle->GetContentType());
auto asyncContext = Aws::MakeShared<TransferHandleAsyncContext>(CLASS_TAG);
asyncContext->handle = handle;
asyncContext->partState = partsIter->second;
auto uploadTask = Aws::MakeShared<TransferHandle>(CLASS_TAG, handle->GetBucketName(), handle->GetKey()); // fake handle
AddTask(uploadTask);
auto callback = [self, uploadTask](const Aws::S3::S3Client* client, const Aws::S3::Model::UploadPartRequest& request,
const Aws::S3::Model::UploadPartOutcome& outcome,
const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) {
self->HandleUploadPartResponse(client, request, outcome, context);
self->RemoveTask(uploadTask);
};
m_transferConfig.s3Client->UploadPartAsync(uploadPartRequest, callback, asyncContext);
sentBytes += lengthToWrite;
++partsIter;
} else {
m_bufferManager.Release(buffer);
}
}
//parts get moved from queued to pending on this thread.
//still consistent.
for (; partsIter != queuedParts.end(); ++partsIter)
{
handle->ChangePartToFailed(partsIter->second);
}
if (handle->HasFailedParts())
{
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
TriggerTransferStatusUpdatedCallback(handle);
}
}
void TransferManager::DoSinglePartUpload(const std::shared_ptr<TransferHandle>& handle)
{
#ifdef _MSC_VER
auto wide = Aws::Utils::StringUtils::ToWString(handle->GetTargetFilePath().c_str());
auto streamToPut = Aws::MakeShared<Aws::FStream>(CLASS_TAG, wide.c_str(), std::ios_base::in | std::ios_base::binary);
DoSinglePartUpload(streamToPut, handle);
#else
auto streamToPut =
Aws::MakeShared<Aws::FStream>(CLASS_TAG, handle->GetTargetFilePath().c_str(), std::ios_base::in | std::ios_base::binary);
DoSinglePartUpload(streamToPut, handle);
#endif
}
void TransferManager::DoSinglePartUpload(const std::shared_ptr<Aws::IOStream>& streamToPut, const std::shared_ptr<TransferHandle>& handle)
{
auto partState = Aws::MakeShared<PartState>(CLASS_TAG, 1, 0, handle->GetBytesTotalSize(), true);
handle->UpdateStatus(TransferStatus::IN_PROGRESS);
handle->SetIsMultipart(false);
handle->AddPendingPart(partState);
TriggerTransferStatusUpdatedCallback(handle);
auto putObjectRequest = m_transferConfig.putObjectTemplate;
putObjectRequest.SetChecksumAlgorithm(m_transferConfig.checksumAlgorithm);
putObjectRequest.SetBucket(handle->GetBucketName());
putObjectRequest.SetKey(handle->GetKey());
putObjectRequest.SetContentLength(static_cast<long long>(handle->GetBytesTotalSize()));
putObjectRequest.SetMetadata(handle->GetMetadata());
putObjectRequest.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
putObjectRequest.SetContinueRequestHandler([handle](const Aws::Http::HttpRequest*) { return handle->ShouldContinue(); });
putObjectRequest.SetContentType(handle->GetContentType());
if (!handle->GetChecksum().empty()) {
SetChecksumOnRequest(putObjectRequest, m_transferConfig.checksumAlgorithm, handle->GetChecksum());
}
auto buffer = m_bufferManager.Acquire();
//check if upload was canceled while waiting for buffer
if (!handle->ShouldContinue()) {
m_bufferManager.Release(buffer);
return;
}
auto lengthToWrite = (std::min)(m_transferConfig.bufferSize, handle->GetBytesTotalSize());
streamToPut->read((char*)buffer, lengthToWrite);
auto streamBuf = Aws::New<Aws::Utils::Stream::PreallocatedStreamBuf>(CLASS_TAG, buffer, static_cast<size_t>(lengthToWrite));
auto preallocatedStreamReader = Aws::MakeShared<Aws::IOStream>(CLASS_TAG, streamBuf);
putObjectRequest.SetBody(preallocatedStreamReader);
auto self = shared_from_this(); // keep transfer manager alive until all callbacks are finished.
auto uploadProgressCallback = [self, partState, handle](const Aws::Http::HttpRequest*, long long progress)
{
partState->OnDataTransferred(progress, handle);
self->TriggerUploadProgressCallback(handle);
};
auto retryHandlerCallback = [self, partState, handle](const Aws::AmazonWebServiceRequest&)
{
partState->Reset();
self->TriggerUploadProgressCallback(handle);
};
putObjectRequest.SetDataSentEventHandler(uploadProgressCallback);
putObjectRequest.SetRequestRetryHandler(retryHandlerCallback);
auto asyncContext = Aws::MakeShared<TransferHandleAsyncContext>(CLASS_TAG);
asyncContext->handle = handle;
asyncContext->partState = partState;
auto putObjectTask = Aws::MakeShared<TransferHandle>(CLASS_TAG, handle->GetBucketName(), handle->GetKey()); // fake handle
AddTask(putObjectTask);
auto callback = [self, putObjectTask](const Aws::S3::S3Client* client, const Aws::S3::Model::PutObjectRequest& request,
const Aws::S3::Model::PutObjectOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
self->HandlePutObjectResponse(client, request, outcome, context);
self->RemoveTask(putObjectTask);
};
m_transferConfig.s3Client->PutObjectAsync(putObjectRequest, callback, asyncContext);
}
void TransferManager::HandleUploadPartResponse(const Aws::S3::S3Client*, const Aws::S3::Model::UploadPartRequest& request,
const Aws::S3::Model::UploadPartOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
std::shared_ptr<TransferHandleAsyncContext> transferContext =
std::const_pointer_cast<TransferHandleAsyncContext>(std::static_pointer_cast<const TransferHandleAsyncContext>(context));
auto originalStreamBuffer = (Aws::Utils::Stream::PreallocatedStreamBuf*)request.GetBody()->rdbuf();
m_bufferManager.Release(originalStreamBuffer->GetBuffer());
Aws::Delete(originalStreamBuffer);
const auto& handle = transferContext->handle;
const auto& partState = transferContext->partState;
if (outcome.IsSuccess())
{
if (handle->ShouldContinue())
{
partState->SetChecksum([&]() -> Aws::String {
if (m_transferConfig.checksumAlgorithm == S3::Model::ChecksumAlgorithm::CRC32)
{
return outcome.GetResult().GetChecksumCRC32();
}
else if (m_transferConfig.checksumAlgorithm == S3::Model::ChecksumAlgorithm::CRC32C)
{
return outcome.GetResult().GetChecksumCRC32C();
}
else if (m_transferConfig.checksumAlgorithm == S3::Model::ChecksumAlgorithm::SHA1)
{
return outcome.GetResult().GetChecksumSHA1();
}
else if (m_transferConfig.checksumAlgorithm == S3::Model::ChecksumAlgorithm::SHA256)
{
return outcome.GetResult().GetChecksumSHA256();
}
//Return empty checksum for not set.
return "";
}());
handle->ChangePartToCompleted(partState, outcome.GetResult().GetETag());
AWS_LOGSTREAM_DEBUG(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< " successfully uploaded Part: [" << partState->GetPartId() << "] to Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey() << "] with Upload ID: ["
<< handle->GetMultiPartId() << "].");
TriggerUploadProgressCallback(handle);
}
else
{
// marking this as failed so we eventually update the handle's status to CANCELED.
// Updating the handle's status to CANCELED here might result in a race-condition between a
// potentially restarting upload and a latent successful part.
handle->ChangePartToFailed(partState);
AWS_LOGSTREAM_WARN(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< " successfully uploaded Part: [" << partState->GetPartId() << "] to Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey() << "] with Upload ID: ["
<< handle->GetMultiPartId() << "] but transfer has been cancelled meanwhile.");
}
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId() << "] Failed to upload part ["
<< partState->GetPartId() << "] to Bucket: [" << handle->GetBucketName()
<< "] with Key: [" << handle->GetKey() << "] with Upload ID: [" << handle->GetMultiPartId()
<< "]. " << outcome.GetError());
handle->ChangePartToFailed(partState);
handle->SetError(outcome.GetError());
TriggerErrorCallback(handle, outcome.GetError());
}
TriggerTransferStatusUpdatedCallback(handle);
PartStateMap pendingParts, queuedParts, failedParts, completedParts;
handle->GetAllPartsTransactional(queuedParts, pendingParts, failedParts, completedParts);
if (pendingParts.size() == 0 && queuedParts.size() == 0 && handle->LockForCompletion())
{
if (failedParts.size() == 0 && (handle->GetBytesTransferred() >= handle->GetBytesTotalSize()))
{
Aws::S3::Model::CompletedMultipartUpload completedUpload;
for (auto& part : handle->GetCompletedParts())
{
auto completedPart = Aws::S3::Model::CompletedPart()
.WithPartNumber(part.first)
.WithETag(part.second->GetETag());
SetChecksumForAlgorithm(part.second, completedPart);
completedUpload.AddParts(completedPart);
}
Aws::S3::Model::CompleteMultipartUploadRequest completeMultipartUploadRequest;
completeMultipartUploadRequest.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
completeMultipartUploadRequest.SetContinueRequestHandler([=](const Aws::Http::HttpRequest*) { return handle->ShouldContinue(); });
completeMultipartUploadRequest.WithBucket(handle->GetBucketName())
.WithKey(handle->GetKey())
.WithUploadId(handle->GetMultiPartId())
.WithMultipartUpload(completedUpload);
if (m_transferConfig.uploadPartTemplate.SSECustomerAlgorithmHasBeenSet())
{
completeMultipartUploadRequest.WithSSECustomerAlgorithm(m_transferConfig.uploadPartTemplate.GetSSECustomerAlgorithm())
.WithSSECustomerKey(m_transferConfig.uploadPartTemplate.GetSSECustomerKey())
.WithSSECustomerKeyMD5(m_transferConfig.uploadPartTemplate.GetSSECustomerKeyMD5());
}
if (!handle->GetChecksum().empty()) {
SetChecksumOnRequest(completeMultipartUploadRequest, m_transferConfig.checksumAlgorithm, handle->GetChecksum());
completeMultipartUploadRequest.SetChecksumType(Aws::S3::Model::ChecksumType::FULL_OBJECT);
}
auto completeUploadOutcome = m_transferConfig.s3Client->CompleteMultipartUpload(completeMultipartUploadRequest);
if (completeUploadOutcome.IsSuccess())
{
AWS_LOGSTREAM_INFO(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] Multi-part upload completed successfully to Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey()
<< "] with Upload ID: [" << handle->GetMultiPartId() << "].");
handle->UpdateStatus(TransferStatus::COMPLETED);
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] Failed to complete multi-part upload. In Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey()
<< "] with Upload ID: [" << handle->GetMultiPartId()
<< "]. " << completeUploadOutcome.GetError());
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
}
}
else
{
AWS_LOGSTREAM_TRACE(CLASS_TAG, "Transfer handle [" << handle->GetId() << "] " << failedParts.size()
<< " Failed parts. " << handle->GetBytesTransferred() << " bytes transferred out of "
<< handle->GetBytesTotalSize() << " total bytes.");
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
}
TriggerTransferStatusUpdatedCallback(handle);
}
}
void TransferManager::HandlePutObjectResponse(const Aws::S3::S3Client*, const Aws::S3::Model::PutObjectRequest& request,
const Aws::S3::Model::PutObjectOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context)
{
std::shared_ptr<TransferHandleAsyncContext> transferContext =
std::const_pointer_cast<TransferHandleAsyncContext>(std::static_pointer_cast<const TransferHandleAsyncContext>(context));
auto originalStreamBuffer = static_cast<Aws::Utils::Stream::PreallocatedStreamBuf*>(request.GetBody()->rdbuf());
m_bufferManager.Release(originalStreamBuffer->GetBuffer());
Aws::Delete(originalStreamBuffer);
const auto& handle = transferContext->handle;
const auto& partState = transferContext->partState;
if (outcome.IsSuccess())
{
AWS_LOGSTREAM_INFO(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] PutObject completed successfully to Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey()
<< "].");
handle->ChangePartToCompleted(partState, outcome.GetResult().GetETag());
handle->UpdateStatus(TransferStatus::COMPLETED);
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId() << "] Failed to upload object to "
"Bucket: [" << handle->GetBucketName() << "] with Key: [" << handle->GetKey()
<< "] " << outcome.GetError());
handle->ChangePartToFailed(partState);
handle->SetError(outcome.GetError());
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
TriggerErrorCallback(handle, outcome.GetError());
}
TriggerTransferStatusUpdatedCallback(handle);
}
std::shared_ptr<TransferHandle> TransferManager::RetryDownload(const std::shared_ptr<TransferHandle>& retryHandle)
{
assert(retryHandle->GetStatus() != TransferStatus::IN_PROGRESS);
assert(retryHandle->GetStatus() != TransferStatus::COMPLETED);
assert(retryHandle->GetStatus() != TransferStatus::NOT_STARTED);
if (retryHandle->GetStatus() == TransferStatus::ABORTED)
{
DownloadConfiguration retryDownloadConfig;
retryDownloadConfig.versionId = retryHandle->GetVersionId();
return DownloadFile(retryHandle->GetBucketName(), retryHandle->GetKey(), retryHandle->GetCreateDownloadStreamFunction(), retryDownloadConfig, retryHandle->GetTargetFilePath());
}
retryHandle->UpdateStatus(TransferStatus::NOT_STARTED);
retryHandle->Restart();
TriggerTransferStatusUpdatedCallback(retryHandle);
auto self = shared_from_this();
AddTask(retryHandle);
m_transferConfig.transferExecutor->Submit(
[self, retryHandle]
{
self->DoDownload(retryHandle);
self->RemoveTask(retryHandle);
});
return retryHandle;
}
static Aws::String FormatRangeSpecifier(uint64_t rangeStart, uint64_t rangeEnd)
{
Aws::StringStream rangeStream;
rangeStream << "bytes=" << rangeStart << "-" << rangeEnd;
return rangeStream.str();
}
void TransferManager::DoSinglePartDownload(const std::shared_ptr<TransferHandle>& handle)
{
auto queuedParts = handle->GetQueuedParts();
assert(queuedParts.size() == 1);
auto partState = queuedParts.begin()->second;
auto request = m_transferConfig.getObjectTemplate;
request.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
request.SetContinueRequestHandler([handle](const Aws::Http::HttpRequest*) { return handle->ShouldContinue(); });
if (handle->GetBytesTotalSize() != 0)
{
request.SetRange(
FormatRangeSpecifier(
handle->GetBytesOffset(),
handle->GetBytesOffset() + handle->GetBytesTotalSize() - 1));
}
request.WithBucket(handle->GetBucketName())
.WithKey(handle->GetKey());
if (handle->GetVersionId().size() > 0)
{
request.SetVersionId(handle->GetVersionId());
}
request.SetResponseStreamFactory(handle->GetCreateDownloadStreamFunction());
request.SetDataReceivedEventHandler([this, handle, partState](const Aws::Http::HttpRequest*, Aws::Http::HttpResponse*, long long progress)
{
partState->OnDataTransferred(progress, handle);
TriggerDownloadProgressCallback(handle);
});
request.SetRequestRetryHandler([this, handle, partState](const Aws::AmazonWebServiceRequest&)
{
partState->Reset();
TriggerDownloadProgressCallback(handle);
});
if (handle->GetEtag().size() > 0) {
request.SetIfMatch(handle->GetEtag());
}
auto getObjectOutcome = m_transferConfig.s3Client->GetObject(request);
if (getObjectOutcome.IsSuccess())
{
handle->SetMetadata(getObjectOutcome.GetResult().GetMetadata());
handle->SetContentType(getObjectOutcome.GetResult().GetContentType());
handle->ChangePartToCompleted(partState, getObjectOutcome.GetResult().GetETag());
getObjectOutcome.GetResult().GetBody().flush();
handle->UpdateStatus(TransferStatus::COMPLETED);
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] Failed to download object to Bucket: [" << handle->GetBucketName() << "] with Key: ["
<< handle->GetKey() << "] " << getObjectOutcome.GetError());
handle->ChangePartToFailed(partState);
handle->UpdateStatus(DetermineIfFailedOrCanceled(*handle));
handle->SetError(getObjectOutcome.GetError());
TriggerErrorCallback(handle, getObjectOutcome.GetError());
}
TriggerTransferStatusUpdatedCallback(handle);
}
bool TransferManager::InitializePartsForDownload(const std::shared_ptr<TransferHandle>& handle)
{
bool isRetry = handle->HasParts();
uint64_t bufferSize = m_transferConfig.bufferSize;
if (!isRetry)
{
auto headObjectRequest = m_transferConfig.headObjectTemplate;
headObjectRequest.SetCustomizedAccessLogTag(m_transferConfig.customizedAccessLogTag);
headObjectRequest.WithBucket(handle->GetBucketName())
.WithKey(handle->GetKey());
if(!handle->GetVersionId().empty())
{
headObjectRequest.SetVersionId(handle->GetVersionId());
}
if (handle->GetBytesTotalSize() != 0)
{
// if non zero, then offset and numbytes were passed, so using part download
headObjectRequest.SetRange(
FormatRangeSpecifier(
handle->GetBytesOffset(),
handle->GetBytesOffset() + handle->GetBytesTotalSize() - 1));
}
auto headObjectOutcome = m_transferConfig.s3Client->HeadObject(headObjectRequest);
if (!headObjectOutcome.IsSuccess())
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Transfer handle [" << handle->GetId()
<< "] Failed to get download parts information for object in Bucket: ["
<< handle->GetBucketName() << "] with Key: [" << handle->GetKey()
<< "] " << headObjectOutcome.GetError());
handle->UpdateStatus(TransferStatus::FAILED);
handle->SetError(headObjectOutcome.GetError());
TriggerErrorCallback(handle, headObjectOutcome.GetError());
TriggerTransferStatusUpdatedCallback(handle);
return false;
}
auto downloadSize = static_cast<uint64_t>(headObjectOutcome.GetResult().GetContentLength());
handle->SetBytesTotalSize(downloadSize);
handle->SetContentType(headObjectOutcome.GetResult().GetContentType());
handle->SetMetadata(headObjectOutcome.GetResult().GetMetadata());
handle->SetEtag(headObjectOutcome.GetResult().GetETag());
/* When bucket versioning is suspended, head object will return "null" for unversioned object.
* Send following GetObject with "null" as versionId will result in 403 access denied error if your IAM role or policy
* doesn't have GetObjectVersion permission.
*/
if(handle->GetVersionId().empty() && headObjectOutcome.GetResult().GetVersionId() != "null")
{
handle->SetVersionId(headObjectOutcome.GetResult().GetVersionId());
}
// For empty file, we create 1 part here to make downloading behaviors consistent for files with different size.
auto partCount = (std::max)((downloadSize + bufferSize - 1) / bufferSize, static_cast<uint64_t>(1));
handle->SetIsMultipart(partCount > 1); // doesn't make a difference but let's be accurate
for(std::size_t i = 0; i < partCount; ++i)
{
auto partSize = (i + 1 < partCount ) ? bufferSize : (downloadSize - bufferSize * (partCount - 1));
bool lastPart = (i == partCount - 1) ? true : false;
auto partState = Aws::MakeShared<PartState>(CLASS_TAG, static_cast<int>(i + 1), 0, partSize, lastPart);
partState->SetRangeBegin(i * bufferSize);
handle->AddQueuedPart(partState);
}
}
else
{
for (auto failedPart : handle->GetFailedParts())
{
handle->AddQueuedPart(failedPart.second);
}
}
return true;
}
void TransferManager::DoDownload(const std::shared_ptr<TransferHandle>& handle)
{
if (!handle->ShouldContinue() || !InitializePartsForDownload(handle))
{
return;
}
handle->UpdateStatus(TransferStatus::IN_PROGRESS);
TriggerTransferStatusUpdatedCallback(handle);
bool isMultipart = handle->IsMultipart();
uint64_t bufferSize = m_transferConfig.bufferSize;
if(!isMultipart)
{
// Special case this for performance (avoid the intermediate buffer write)
DoSinglePartDownload(handle);
return;
}
auto queuedParts = handle->GetQueuedParts();
auto queuedPartIter = queuedParts.begin();
while(queuedPartIter != queuedParts.end() && handle->ShouldContinue())
{
const auto& partState = queuedPartIter->second;
uint64_t rangeStart = handle->GetBytesOffset() + ( partState->GetPartId() - 1 ) * bufferSize;
uint64_t rangeEnd = rangeStart + partState->GetSizeInBytes() - 1;
auto buffer = m_bufferManager.Acquire();
partState->SetDownloadBuffer(buffer);