forked from googleapis/google-cloud-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection_impl.cc
More file actions
1349 lines (1250 loc) · 61 KB
/
connection_impl.cc
File metadata and controls
1349 lines (1250 loc) · 61 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 2018 Google LLC
//
// 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
//
// https://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.
#include "google/cloud/storage/internal/connection_impl.h"
#include "google/cloud/storage/internal/retry_object_read_source.h"
#include "google/cloud/internal/filesystem.h"
#include "google/cloud/internal/opentelemetry.h"
#include "google/cloud/internal/rest_retry_loop.h"
#include "google/cloud/log.h"
#include "absl/strings/match.h"
#include <chrono>
#include <fstream>
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
using ::google::cloud::Idempotency;
using ::google::cloud::internal::MergeOptions;
using ::google::cloud::rest_internal::RestRetryLoop;
// Returns an error if the response contains an unexpected (or invalid)
// committed size.
Status ValidateCommittedSize(UploadChunkRequest const& request,
QueryResumableUploadResponse const& response,
std::uint64_t expected_committed_size) {
// This should not happen, it indicates an invalid sequence of responses
// from the server.
if (*response.committed_size < request.offset()) {
std::stringstream os;
os << __func__ << ": server previously confirmed " << request.offset()
<< " bytes as committed, but the current response only reports "
<< response.committed_size.value_or(0) << " bytes as committed."
<< " This is most likely a bug in the GCS client library, possibly"
<< " related to parsing the server response."
<< " If you believe this is a bug in the client library, please contact"
<< " support (https://cloud.google.com/support/), or report the bug"
<< " (https://github.com/googleapis/google-cloud-cpp/issues/new)."
<< " Please include as much information as you can including this"
<< " message and the following details:";
os << " session_id=" << request.upload_session_url();
os << ", result=" << response;
os << ", request=" << request;
return google::cloud::internal::InternalError(std::move(os).str(),
GCP_ERROR_INFO());
}
if (*response.committed_size > expected_committed_size) {
std::stringstream os;
os << __func__ << ": the server indicates that "
<< response.committed_size.value_or(0) << " bytes are committed "
<< " but given the current request no more than "
<< expected_committed_size << " are expected be."
<< " Most likely your application resumed an upload, and the client"
<< " library queried the service to find the current persisted bytes."
<< " In some cases, the service is still writing data in the background"
<< " and conservatively reports fewer bytes as persisted."
<< " In this case, the next upload may report a much higher number of"
<< " bytes persisted than expected. It is not possible for the client"
<< " library to recover from this situation. The application needs to"
<< " resume the upload."
<< " This could also be caused by multiple instances of a distributed"
<< " application trying to use the same resumable upload, this is a bug"
<< " in the application."
<< " If you believe this is a bug in the client library, please contact"
<< " support (https://cloud.google.com/support/), or report the bug"
<< " (https://github.com/googleapis/google-cloud-cpp/issues/new)."
<< " Please include as much information as you can including this"
<< " message and the following details:";
os << " session_id=" << request.upload_session_url();
os << ", result=" << response;
os << ", request=" << request;
return google::cloud::internal::InternalError(std::move(os).str(),
GCP_ERROR_INFO());
}
return {};
}
// For resumable uploads over gRPC we need to treat some non-retryable errors
// as retryable.
bool UploadChunkOnFailure(RetryPolicy& retry_policy, Status const& status) {
// TODO(#9273) - use ErrorInfo when it becomes available
if (status.code() == StatusCode::kAborted &&
absl::StartsWith(status.message(), "Concurrent requests received.")) {
return retry_policy.OnFailure(google::cloud::internal::UnavailableError(
"TODO(#9273) - workaround service problems", status.error_info()));
}
return retry_policy.OnFailure(status);
}
Status RetryError(Status const& status, RetryPolicy const& retry_policy,
char const* function_name) {
return google::cloud::internal::RetryLoopError(status, function_name,
retry_policy.IsExhausted());
}
Status MissingCommittedSize(int error_count, int upload_count, int reset_count,
Status last_status) {
if (error_count > 0) return last_status;
std::ostringstream os;
os << "All requests (" << upload_count << ") have succeeded, but they lacked"
<< " a committed_size value. This requires querying the write status."
<< " The client library performed " << reset_count << " such queries.";
return google::cloud::internal::DeadlineExceededError(std::move(os).str(),
GCP_ERROR_INFO());
}
Status PartialWriteStatus(int error_count, int upload_count,
std::int64_t committed_size,
std::int64_t expected_committed_size,
Status last_status) {
if (error_count > 0) return last_status;
std::ostringstream os;
os << "All requests (" << upload_count << ") have succeeded, but they have"
<< " not completed the full write. The expected committed size is "
<< expected_committed_size << " and the current committed size is "
<< committed_size;
return google::cloud::internal::DeadlineExceededError(std::move(os).str(),
GCP_ERROR_INFO());
}
auto constexpr kIdempotencyTokenHeader = "x-goog-gcs-idempotency-token";
} // namespace
std::shared_ptr<StorageConnectionImpl> StorageConnectionImpl::Create(
std::unique_ptr<storage_internal::GenericStub> stub, Options options) {
// Cannot use `std::make_shared<>` because the constructor is private.
return std::shared_ptr<StorageConnectionImpl>(
new StorageConnectionImpl(std::move(stub), std::move(options)));
}
StorageConnectionImpl::StorageConnectionImpl(
std::unique_ptr<storage_internal::GenericStub> stub, Options options)
: stub_(std::move(stub)),
options_(MergeOptions(std::move(options), stub_->options())),
client_options_(MakeBackwardsCompatibleClientOptions(options_)) {}
ClientOptions const& StorageConnectionImpl::client_options() const {
return client_options_;
}
Options StorageConnectionImpl::options() const { return options_; }
StatusOr<ListBucketsResponse> StorageConnectionImpl::ListBuckets(
ListBucketsRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->ListBuckets(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketMetadata> StorageConnectionImpl::CreateBucket(
CreateBucketRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->CreateBucket(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketMetadata> StorageConnectionImpl::GetBucketMetadata(
GetBucketMetadataRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->GetBucketMetadata(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<EmptyResponse> StorageConnectionImpl::DeleteBucket(
DeleteBucketRequest const& request) {
auto idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->DeleteBucket(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketMetadata> StorageConnectionImpl::UpdateBucket(
UpdateBucketRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->UpdateBucket(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketMetadata> StorageConnectionImpl::PatchBucket(
PatchBucketRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->PatchBucket(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<NativeIamPolicy> StorageConnectionImpl::GetNativeBucketIamPolicy(
GetBucketIamPolicyRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->GetNativeBucketIamPolicy(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<NativeIamPolicy> StorageConnectionImpl::SetNativeBucketIamPolicy(
SetNativeBucketIamPolicyRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->SetNativeBucketIamPolicy(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<TestBucketIamPermissionsResponse>
StorageConnectionImpl::TestBucketIamPermissions(
TestBucketIamPermissionsRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->TestBucketIamPermissions(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketMetadata> StorageConnectionImpl::LockBucketRetentionPolicy(
LockBucketRetentionPolicyRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->LockBucketRetentionPolicy(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::InsertObjectMedia(
InsertObjectMediaRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->InsertObjectMedia(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::CopyObject(
CopyObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->CopyObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::GetObjectMetadata(
GetObjectMetadataRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->GetObjectMetadata(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<std::unique_ptr<ObjectReadSource>> StorageConnectionImpl::ReadObject(
ReadObjectRangeRequest const& request) {
auto current = google::cloud::internal::SaveCurrentOptions();
auto self = shared_from_this();
auto const* where = __func__;
auto factory = [self = shared_from_this(), current, where](
ReadObjectRangeRequest const& request,
RetryPolicy& retry_policy, BackoffPolicy& backoff_policy) {
auto const idempotency =
current->get<IdempotencyPolicyOption>()->IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
retry_policy, backoff_policy, idempotency,
[self, token = self->MakeIdempotencyToken()](
rest_internal::RestContext& context, Options const& options,
ReadObjectRangeRequest const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return self->stub_->ReadObject(context, options, request);
},
*current, request, where);
};
auto retry_policy = current->get<RetryPolicyOption>()->clone();
auto backoff_policy = current->get<BackoffPolicyOption>()->clone();
auto child = factory(request, *retry_policy, *backoff_policy);
if (!child) return child;
return std::unique_ptr<ObjectReadSource>(
std::make_unique<RetryObjectReadSource>(
std::move(factory), std::move(current), request, *std::move(child),
std::move(retry_policy), std::move(backoff_policy)));
}
StatusOr<ListObjectsResponse> StorageConnectionImpl::ListObjects(
ListObjectsRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->ListObjects(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<EmptyResponse> StorageConnectionImpl::DeleteObject(
DeleteObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->DeleteObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::UpdateObject(
UpdateObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->UpdateObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::MoveObject(
MoveObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->MoveObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::PatchObject(
PatchObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->PatchObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::ComposeObject(
ComposeObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->ComposeObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<RewriteObjectResponse> StorageConnectionImpl::RewriteObject(
RewriteObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->RewriteObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectMetadata> StorageConnectionImpl::RestoreObject(
RestoreObjectRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->RestoreObject(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<CreateResumableUploadResponse>
StorageConnectionImpl::CreateResumableUpload(
ResumableUploadRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->CreateResumableUpload(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<QueryResumableUploadResponse>
StorageConnectionImpl::QueryResumableUpload(
QueryResumableUploadRequest const& request) {
auto const idempotency = Idempotency::kIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->QueryResumableUpload(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<EmptyResponse> StorageConnectionImpl::DeleteResumableUpload(
DeleteResumableUploadRequest const& request) {
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(),
Idempotency::kIdempotent,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->DeleteResumableUpload(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
// Implements the retry loop for a resumable upload session.
//
// A description of resumable uploads can be found at:
// https://cloud.google.com/storage/docs/performing-resumable-uploads
//
// A description of the gRPC analog can be found in the proto file. Pay
// particular attention to the documentation for `WriteObject()`,
// `WriteObjectRequest`, `StartResumableWrite()` and `QueryResumableWrite()`:
// https://github.com/googleapis/googleapis/blob/master/google/storage/v2/storage.proto
//
// At a high level one starts a resumable upload by creating a "session". These
// sessions are persistent (they survive disconnections from the service). One
// can even resume uploads after shutting down and restarting an application.
// Their current state can be queried using a simple RPC (or a PUT request
// without payload).
//
// Resumable uploads make progress by sending "chunks", either a single PUT
// request in REST-based transports, or a client-side streaming RPC for
// gRPC-based transports.
//
// Resumable uploads complete when the application sends the last bytes of the
// object. In the client library we mostly start uploads without knowing the
// number of bytes until a "final" chunk. In this final chunk we set the
// `Content-Range:` header to the `bytes X-N/N` format (there is an equivalent
// form in gRPC). In some cases the application can short-circuit this by
// setting the X-Upload-Content-Length header when the upload is created.
//
// When a chunk upload fails the application should query the state of the
// session before continuing.
//
// There are a couple of subtle cases:
// - A chunk uploads can "succeed", but report that 0 bytes were committed,
// or not report how many bytes were committed. The application should
// query the state of the upload in this case:
// https://cloud.google.com/storage/docs/performing-resumable-uploads#status-check
// > If Cloud Storage has not yet persisted any bytes, the 308 response does
// > **not have a Range header**. In this case, you should start your upload
// > from the beginning.
// - A chunk upload can partially succeed, in this case the application should
// resend the remaining bytes.
// - Resending already persisted bytes is safe:
// https://cloud.google.com/storage/docs/performing-resumable-uploads#resume-upload
// > Cloud Storage ignores any bytes you send at an offset that
// > Cloud Storage has already persisted.
//
// In summary, after a failed upload operation the retry loop may need to query
// the status of the session before uploading more data. Note that the query
// operations themselves may fail with transients, and thus need to be performed
// as part of the retry loop.
//
// To simplify the loop we keep a pointer to the current "operation" that the
// retry loop is trying to get to succeed. First we try an upload, if that
// fails (a transient failure, or a 0-committed-bytes success) we switch to
// trying the ResetSession() operation until it succeeds, at which point we
// can start the upload operations again.
//
StatusOr<QueryResumableUploadResponse> StorageConnectionImpl::UploadChunk(
UploadChunkRequest const& request) {
auto const& current = google::cloud::internal::CurrentOptions();
std::function<void(std::chrono::milliseconds)> sleeper =
[](std::chrono::milliseconds d) { std::this_thread::sleep_for(d); };
sleeper = google::cloud::internal::MakeTracedSleeper(
current, std::move(sleeper), "Backoff");
auto last_status = google::cloud::internal::DeadlineExceededError(
"Retry policy exhausted before first attempt was made.",
GCP_ERROR_INFO());
auto retry_policy = current_retry_policy();
auto backoff_policy = current_backoff_policy();
// `operation` represents the RPC we will make. In the happy case it is just
// calls to `upload()`, but on a transient error we switch to calling
// `ResetSession()` until there is a successful result.
using Action =
std::function<StatusOr<QueryResumableUploadResponse>(std::uint64_t)>;
int upload_count = 0;
auto upload = Action(
[&upload_count, ¤t, &request, this](std::uint64_t committed_size) {
// There is no need to use an idempotency token for this function, as
// we do not "retry" the operation. On transient failures we call
// QueryResumableUpload() before trying the request again.
rest_internal::RestContext context(current);
++upload_count;
return stub_->UploadChunk(context, current,
request.RemainingChunk(committed_size));
});
int reset_count = 0;
auto reset = Action([&reset_count, &request, this](std::uint64_t) {
QueryResumableUploadRequest query(request.upload_session_url());
query.set_multiple_options(request.GetOption<QuotaUser>(),
request.GetOption<UserIp>());
++reset_count;
return this->QueryResumableUpload(query);
});
auto* operation = &upload;
auto committed_size = request.offset();
auto const expected_committed_size =
request.offset() + request.payload_size();
int error_count = 0;
while (!retry_policy->IsExhausted()) {
auto result = (*operation)(committed_size);
if (!result) {
++error_count;
// On a failure we preserve the error, then query if retry policy allows
// retrying. If so, we backoff, and switch to calling
// QueryResumableUpload().
last_status = std::move(result).status();
if (!UploadChunkOnFailure(*retry_policy, last_status)) {
return RetryError(std::move(last_status), *retry_policy, __func__);
}
auto delay = backoff_policy->OnCompletion();
sleeper(delay);
operation = &reset;
continue;
}
// While normally a `UploadFinalChunk()` call completes an upload, sometimes
// the upload can complete in a regular `UploadChunk()` or a
// `ResetSession()` call. For example, the server can detect a completed
// upload "early" if the application includes the X-Upload-Content-Length`
// header.
if (result->payload.has_value()) return result;
// This indicates that the response was missing a `Range:` header, or that
// the range header was in the wrong format. Either way, treat that as a
// (transient) failure and query the current status to find out what to do
// next.
if (!result->committed_size.has_value()) {
last_status = MissingCommittedSize(error_count, upload_count, reset_count,
std::move(last_status));
if (operation != &reset) {
operation = &reset;
continue;
}
// When a reset returns a response without a committed size we can safely
// treat that as 0.
result->committed_size = 0;
}
// With a successful operation, we can continue (or go back to) uploading.
operation = &upload;
auto validate =
ValidateCommittedSize(request, *result, expected_committed_size);
if (!validate.ok()) return validate;
if (committed_size != *result->committed_size) {
// A partial write is a sign of progress. We reset the backoff policy.
// Otherwise we would unnecessarily delay the next upload.
backoff_policy = current_backoff_policy();
committed_size = *result->committed_size;
}
if (committed_size != expected_committed_size || request.last_chunk()) {
// If we still have to send data, restart the loop. On the last chunk,
// even if the service reports all the data as received, we need to keep
// "finalizing" the object until the object metadata is returned. Note
// that if we had the object metadata we would have already exited this
// function.
last_status =
PartialWriteStatus(error_count, upload_count, committed_size,
expected_committed_size, std::move(last_status));
continue;
}
// On a full write we can return immediately.
return result;
}
return RetryError(last_status, *retry_policy, __func__);
}
StatusOr<std::unique_ptr<std::string>> StorageConnectionImpl::UploadFileSimple(
std::string const& file_name, std::size_t file_size,
InsertObjectMediaRequest& request) {
auto upload_offset = request.GetOption<UploadFromOffset>().value_or(0);
if (file_size < upload_offset) {
std::ostringstream os;
os << __func__ << "(" << request << ", " << file_name
<< "): UploadFromOffset (" << upload_offset
<< ") is bigger than the size of file source (" << file_size << ")";
return google::cloud::internal::InvalidArgumentError(std::move(os).str(),
GCP_ERROR_INFO());
}
auto upload_size = (std::min)(
request.GetOption<UploadLimit>().value_or(file_size - upload_offset),
file_size - upload_offset);
std::ifstream is(file_name, std::ios::binary);
if (!is.is_open()) {
std::ostringstream os;
os << __func__ << "(" << request << ", " << file_name
<< "): cannot open upload file source";
return google::cloud::internal::NotFoundError(std::move(os).str(),
GCP_ERROR_INFO());
}
auto payload = std::make_unique<std::string>(
static_cast<std::size_t>(upload_size), char{});
is.seekg(upload_offset, std::ios::beg);
// We need to use `&payload[0]` until C++17
// NOLINTNEXTLINE(readability-container-data-pointer)
is.read(&(*payload)[0], payload->size());
if (static_cast<std::size_t>(is.gcount()) < payload->size()) {
std::ostringstream os;
os << __func__ << "(" << request << ", " << file_name << "): Actual read ("
<< is.gcount() << ") is smaller than upload_size (" << payload->size()
<< ")";
return google::cloud::internal::InternalError(std::move(os).str(),
GCP_ERROR_INFO());
}
is.close();
return payload;
}
StatusOr<std::unique_ptr<std::istream>>
StorageConnectionImpl::UploadFileResumable(std::string const& file_name,
ResumableUploadRequest& request) {
auto upload_offset = request.GetOption<UploadFromOffset>().value_or(0);
auto status = google::cloud::internal::status(file_name);
if (!is_regular(status)) {
GCP_LOG(WARNING) << "Trying to upload " << file_name
<< R"""( which is not a regular file.
This is often a problem because:
- Some non-regular files are infinite sources of data, and the load will
never complete.
- Some non-regular files can only be read once, and UploadFile() may need to
read the file more than once to compute the checksum and hashes needed to
preserve data integrity.
Consider using UploadLimit option or Client::WriteObject(). You may also need to disable data
integrity checks using the DisableMD5Hash() and DisableCrc32cChecksum() options.
)""";
} else {
std::error_code size_err;
auto file_size = google::cloud::internal::file_size(file_name, size_err);
if (size_err) {
return google::cloud::internal::NotFoundError(size_err.message(),
GCP_ERROR_INFO());
}
if (file_size < upload_offset) {
std::ostringstream os;
os << __func__ << "(" << request << ", " << file_name
<< "): UploadFromOffset (" << upload_offset
<< ") is bigger than the size of file source (" << file_size << ")";
return google::cloud::internal::InvalidArgumentError(std::move(os).str(),
GCP_ERROR_INFO());
}
auto upload_size = (std::min)(
request.GetOption<UploadLimit>().value_or(file_size - upload_offset),
file_size - upload_offset);
request.set_option(UploadContentLength(upload_size));
}
auto source = std::make_unique<std::ifstream>(file_name, std::ios::binary);
if (!source->is_open()) {
std::ostringstream os;
os << __func__ << "(" << request << ", " << file_name
<< "): cannot open upload file source";
return google::cloud::internal::NotFoundError(std::move(os).str(),
GCP_ERROR_INFO());
}
// We set its offset before passing it to `UploadStreamResumable` so we don't
// need to compute `UploadFromOffset` again.
source->seekg(upload_offset, std::ios::beg);
return std::unique_ptr<std::istream>(std::move(source));
}
StatusOr<ListBucketAclResponse> StorageConnectionImpl::ListBucketAcl(
ListBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->ListBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketAccessControl> StorageConnectionImpl::GetBucketAcl(
GetBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->GetBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketAccessControl> StorageConnectionImpl::CreateBucketAcl(
CreateBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->CreateBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<EmptyResponse> StorageConnectionImpl::DeleteBucketAcl(
DeleteBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->DeleteBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ListObjectAclResponse> StorageConnectionImpl::ListObjectAcl(
ListObjectAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->ListObjectAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketAccessControl> StorageConnectionImpl::UpdateBucketAcl(
UpdateBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->UpdateBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<BucketAccessControl> StorageConnectionImpl::PatchBucketAcl(
PatchBucketAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->PatchBucketAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<ObjectAccessControl> StorageConnectionImpl::CreateObjectAcl(
CreateObjectAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->CreateObjectAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}
StatusOr<EmptyResponse> StorageConnectionImpl::DeleteObjectAcl(
DeleteObjectAclRequest const& request) {
auto const idempotency = current_idempotency_policy().IsIdempotent(request)
? Idempotency::kIdempotent
: Idempotency::kNonIdempotent;
return RestRetryLoop(
current_retry_policy(), current_backoff_policy(), idempotency,
[token = MakeIdempotencyToken(), this](
rest_internal::RestContext& context, Options const& options,
auto const& request) {
context.AddHeader(kIdempotencyTokenHeader, token);
return stub_->DeleteObjectAcl(context, options, request);
},
google::cloud::internal::CurrentOptions(), request, __func__);
}