-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
BlobBatchClient.cs
939 lines (868 loc) · 38.4 KB
/
BlobBatchClient.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Batch;
using Azure.Storage.Blobs.Models;
#pragma warning disable SA1402 // File may only contain a single type
namespace Azure.Storage.Blobs.Specialized
{
/// <summary>
/// The <see cref="BlobBatchClient"/> allows you to batch multiple Azure
/// Storage operations in a single request.
/// </summary>
public class BlobBatchClient
{
/// <summary>
/// Gets the blob service's primary <see cref="Uri"/> endpoint.
/// </summary>
private readonly Uri _uri;
/// <summary>
/// Gets the blob service's primary <see cref="Uri"/> endpoint.
/// </summary>
public virtual Uri Uri => _uri;
/// <summary>
/// If this BlobBatchClient is scoped to a container.
/// </summary>
private readonly bool _isContainerScoped;
/// <summary>
/// If this BlobBatchClient is scoped to a container.
/// </summary>
internal virtual bool IsContainerScoped => _isContainerScoped;
/// <summary>
/// The <see cref="HttpPipeline"/> transport pipeline used to send
/// every request.
/// </summary>
private readonly HttpPipeline _pipeline;
/// <summary>
/// The <see cref="HttpPipeline"/> transport pipeline used to send
/// every request.
/// </summary>
internal virtual HttpPipeline Pipeline => _pipeline;
/// <summary>
/// The version of the service to use when sending requests.
/// </summary>
private readonly BlobClientOptions.ServiceVersion _version;
/// <summary>
/// The version of the service to use when sending requests.
/// </summary>
internal virtual BlobClientOptions.ServiceVersion Version => _version;
/// <summary>
/// The <see cref="ClientDiagnostics"/> instance used to create diagnostic scopes
/// every request.
/// </summary>;
private readonly ClientDiagnostics _clientDiagnostics;
/// <summary>
/// The <see cref="ClientDiagnostics"/> instance used to create diagnostic scopes
/// every request.
/// </summary>
internal virtual ClientDiagnostics ClientDiagnostics => _clientDiagnostics;
/// <summary>
/// The <see cref="HttpPipeline"/> transport pipeline used to prepare
/// requests for batching without actually sending them.
/// </summary>
private readonly HttpPipeline _batchOperationPipeline;
/// <summary>
/// The <see cref="HttpPipeline"/> transport pipeline used to prepare
/// requests for batching without actually sending them.
/// </summary>
internal virtual HttpPipeline BatchOperationPipeline => _batchOperationPipeline;
/// <summary>
/// <see cref="ServiceRestClient"/>.
/// </summary>
private readonly ServiceRestClient _serviceRestClient;
/// <summary>
/// <see cref="ServiceRestClient"/>.
/// </summary>
internal virtual ServiceRestClient ServiceRestClient => _serviceRestClient;
/// <summary>
/// <see cref="Blobs.ContainerRestClient"/>.
/// </summary>
private readonly ContainerRestClient _containerRestClient;
/// <summary>
/// <see cref="Blobs.ContainerRestClient"/>.
/// </summary>
internal virtual ContainerRestClient ContainerRestClient => _containerRestClient;
/// <summary>
/// The name of the container associated with the BlobBatchClient,
/// or null if the BlobBatchClient is assocaited with a BlobServiceClient.
/// </summary>
private readonly string _containerName;
/// <summary>
/// The name of the container associated with the BlobBatchClient,
/// or null if the BlobBatchClient is assocaited with a BlobServiceClient.
/// </summary>
internal virtual string ContainerName => _containerName;
#region ctors
/// <summary>
/// Initializes a new instance of the <see cref="BlobBatchClient"/>
/// class for mocking.
/// </summary>
protected BlobBatchClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobBatchClient"/>
/// class for the same account as the <see cref="BlobServiceClient"/>.
/// The new <see cref="BlobBatchClient"/> uses the same request policy
/// pipeline as the <see cref="BlobServiceClient"/>.
/// </summary>
/// <param name="client">The <see cref="BlobServiceClient"/>.</param>
public BlobBatchClient(BlobServiceClient client)
{
_uri = client.Uri;
_pipeline = BlobServiceClientInternals.GetHttpPipeline(client);
BlobClientOptions options = BlobServiceClientInternals.GetClientOptions(client);
_version = options.Version;
_clientDiagnostics = new ClientDiagnostics(options);
// Construct a dummy pipeline for processing batch sub-operations
// if we don't have one cached on the service
_batchOperationPipeline = CreateBatchPipeline(
_pipeline,
BlobServiceClientInternals.GetAuthenticationPolicy(client),
_version);
(ServiceRestClient serviceRestClient, ContainerRestClient containerRestClient) = BuildRestClients(_uri);
_serviceRestClient = serviceRestClient;
_containerRestClient = containerRestClient;
_isContainerScoped = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="BlobBatchClient"/>
/// class for container associated with the <see cref="BlobContainerClient"/>.
/// The new <see cref="BlobBatchClient"/> uses the same request policy
/// pipeline as the <see cref="BlobContainerClient"/>.
/// </summary>
/// <param name="client">The <see cref="BlobContainerClient"/>.</param>
public BlobBatchClient(BlobContainerClient client)
{
_uri = client.Uri;
BlobServiceClient blobServiceClient = client.GetParentBlobServiceClient();
_pipeline = BlobServiceClientInternals.GetHttpPipeline(blobServiceClient);
BlobClientOptions options = BlobServiceClientInternals.GetClientOptions(blobServiceClient);
_version = options.Version;
_clientDiagnostics = new ClientDiagnostics(options);
// Construct a dummy pipeline for processing batch sub-operations
// if we don't have one cached on the service
_batchOperationPipeline = CreateBatchPipeline(
_pipeline,
BlobServiceClientInternals.GetAuthenticationPolicy(blobServiceClient),
_version);
(ServiceRestClient serviceRestClient, ContainerRestClient containerRestClient) = BuildRestClients(blobServiceClient.Uri);
_serviceRestClient = serviceRestClient;
_containerRestClient = containerRestClient;
_containerName = client.Name;
_isContainerScoped = true;
}
/// <summary>
/// Creates a pipeline to use for processing sub-operations before they
/// are combined into a single multipart request.
/// </summary>
/// <param name="pipeline">
/// The pipeline used to submit the live request.
/// </param>
/// <param name="authenticationPolicy">
/// An optional <see cref="HttpPipelinePolicy"/> used to authenticate
/// the sub-operations.
/// </param>
/// <param name="serviceVersion">
/// The serviceVersion used when generating sub-requests.
/// </param>
/// <returns>A pipeline to use for processing sub-operations.</returns>
private static HttpPipeline CreateBatchPipeline(
HttpPipeline pipeline,
HttpPipelinePolicy authenticationPolicy,
BlobClientOptions.ServiceVersion serviceVersion)
{
// Configure the options to use minimal policies
var options = new BlobClientOptions(serviceVersion);
options.Diagnostics.IsLoggingEnabled = false;
options.Diagnostics.IsTelemetryEnabled = false;
options.Diagnostics.IsDistributedTracingEnabled = false;
options.Retry.MaxRetries = 0;
// Use an empty transport so requests aren't sent
options.Transport = new BatchPipelineTransport(pipeline);
// Use the same authentication mechanism
return HttpPipelineBuilder.Build(new HttpPipelineOptions(options)
{
PerRetryPolicies = { RemoveVersionHeaderPolicy.Shared, authenticationPolicy },
RequestFailedDetailsParser = new StorageRequestFailedDetailsParser()
});
}
private (ServiceRestClient ServiceClient, ContainerRestClient ContainerClient) BuildRestClients(Uri serviceUri)
{
ServiceRestClient serviceRestClient = new ServiceRestClient(
clientDiagnostics: _clientDiagnostics,
pipeline: _pipeline,
url: serviceUri.AbsoluteUri,
version: _version.ToVersionString());
ContainerRestClient containerRestClient = new ContainerRestClient(
clientDiagnostics: _clientDiagnostics,
pipeline: _pipeline,
url: serviceUri.AbsoluteUri,
version: _version.ToVersionString());
return (serviceRestClient, containerRestClient);
}
/// <summary>
/// Helper to access protected static members of BlobServiceClient
/// that should not be exposed directly to customers.
/// </summary>
private class BlobServiceClientInternals : BlobServiceClient
{
/// <summary>
/// Prevent instantiation.
/// </summary>
private BlobServiceClientInternals() { }
/// <summary>
/// Get a <see cref="BlobServiceClient"/>'s <see cref="HttpPipeline"/>
/// for creating child clients.
/// </summary>
/// <param name="client">The BlobServiceClient.</param>
/// <returns>The BlobServiceClient's HttpPipeline.</returns>
public static new HttpPipeline GetHttpPipeline(BlobServiceClient client) =>
BlobServiceClient.GetHttpPipeline(client);
/// <summary>
/// Get a <see cref="BlobServiceClient"/>'s authentication
/// <see cref="HttpPipelinePolicy"/> for creating child clients.
/// </summary>
/// <param name="client">The BlobServiceClient.</param>
/// <returns>The BlobServiceClient's authentication policy.</returns>
public static new HttpPipelinePolicy GetAuthenticationPolicy(BlobServiceClient client) =>
BlobServiceClient.GetAuthenticationPolicy(client);
/// <summary>
/// Get a <see cref="BlobServiceClient"/>'s <see cref="BlobClientOptions"/>
/// for creating child clients.
/// </summary>
/// <param name="client">The BlobServiceClient.</param>
/// <returns>The BlobServiceClient's BlobClientOptions.</returns>
public static new BlobClientOptions GetClientOptions(BlobServiceClient client) =>
BlobServiceClient.GetClientOptions(client);
}
#endregion ctors
#region Create/SubmitBatch
/// <summary>
/// Creates a new <see cref="BlobBatch"/> to collect sub-operations
/// that can be submitted together via <see cref="SubmitBatch"/>.
/// </summary>
/// <returns>A new <see cref="BlobBatch"/>.</returns>
public virtual BlobBatch CreateBatch() => new BlobBatch(this);
/// <summary>
/// Submit a <see cref="BlobBatch"/> of sub-operations.
/// </summary>
/// <param name="batch">
/// A <see cref="BlobBatch"/> of sub-operations.
/// </param>
/// <param name="throwOnAnyFailure">
/// A value indicating whether or not to throw exceptions for
/// sub-operation failures.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully submitting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will only throw if <paramref name="throwOnAnyFailure"/> is
/// true and be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual Response SubmitBatch(
BlobBatch batch,
bool throwOnAnyFailure = false,
CancellationToken cancellationToken = default) =>
SubmitBatchInternal(
batch,
throwOnAnyFailure,
async: false,
cancellationToken)
.EnsureCompleted();
/// <summary>
/// Submit a <see cref="BlobBatch"/> of sub-operations.
/// </summary>
/// <param name="batch">
/// A <see cref="BlobBatch"/> of sub-operations.
/// </param>
/// <param name="throwOnAnyFailure">
/// A value indicating whether or not to throw exceptions for
/// sub-operation failures.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully submitting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will only throw if <paramref name="throwOnAnyFailure"/> is
/// true and be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual async Task<Response> SubmitBatchAsync(
BlobBatch batch,
bool throwOnAnyFailure = false,
CancellationToken cancellationToken = default) =>
await SubmitBatchInternal(
batch,
throwOnAnyFailure,
async: true,
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// Submit a <see cref="BlobBatch"/> of sub-operations.
/// </summary>
/// <param name="batch">
/// A <see cref="BlobBatch"/> of sub-operations.
/// </param>
/// <param name="throwOnAnyFailure">
/// A value indicating whether or not to throw exceptions for
/// sub-operation failures.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response"/> on successfully submitting.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will only throw if <paramref name="throwOnAnyFailure"/> is
/// true and be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
private async Task<Response> SubmitBatchInternal(
BlobBatch batch,
bool throwOnAnyFailure,
bool async,
CancellationToken cancellationToken)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(BlobBatchClient)}.{nameof(SubmitBatch)}");
try
{
scope.Start();
batch = batch ?? throw new ArgumentNullException(nameof(batch));
if (batch.Submitted)
{
throw BatchErrors.CannotResubmitBatch(nameof(batch));
}
else if (!batch.IsAssociatedClient(this))
{
throw BatchErrors.BatchClientDoesNotMatch(nameof(batch));
}
// Get the sub-operation messages to submit
IList<HttpMessage> messages = batch.GetMessagesToSubmit();
if (messages.Count == 0)
{
throw BatchErrors.CannotSubmitEmptyBatch(nameof(batch));
}
// TODO: Consider validating the upper limit of 256 messages
// Merge the sub-operations into a single multipart/mixed Stream
(Stream content, string contentType) =
await MergeOperationRequests(
messages,
async,
cancellationToken)
.ConfigureAwait(false);
Response response;
if (IsContainerScoped)
{
if (async)
{
response = await _containerRestClient.SubmitBatchAsync(
containerName: ContainerName,
contentLength: content.Length,
multipartContentType: contentType,
content: RequestContent.Create(content),
context: new RequestContext{ CancellationToken = cancellationToken })
.ConfigureAwait(false);
}
else
{
response = _containerRestClient.SubmitBatch(
containerName: ContainerName,
contentLength: content.Length,
multipartContentType: contentType,
content: RequestContent.Create(content),
context: new RequestContext{ CancellationToken = cancellationToken });
}
}
else
{
if (async)
{
response = await _serviceRestClient.SubmitBatchAsync(
contentLength: content.Length,
multipartContentType: contentType,
content: RequestContent.Create(content),
context: new RequestContext{ CancellationToken = cancellationToken })
.ConfigureAwait(false);
}
else
{
response = _serviceRestClient.SubmitBatch(
contentLength: content.Length,
multipartContentType: contentType,
content: RequestContent.Create(content),
context: new RequestContext{ CancellationToken = cancellationToken });
}
}
await UpdateOperationResponses(messages, response, throwOnAnyFailure, async, cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
/// <summary>
/// Merge the batch sub-operation messages into a single content stream
/// and content type.
/// </summary>
/// <param name="messages">
/// The batch sub-operation messages to submit together.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// A tuple containing the batch sub-operation messages merged into a
/// single multipart/mixed content stream and content type.
/// </returns>
private async Task<(Stream ContentStream, string ContentType)> MergeOperationRequests(
IList<HttpMessage> messages,
bool async,
CancellationToken cancellationToken)
{
// Send all of the requests through a batch sub-operation pipeline
// to prepare the requests with various headers like Authorization
foreach (HttpMessage message in messages)
{
if (async)
{
await BatchOperationPipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
BatchOperationPipeline.Send(message, cancellationToken);
}
}
// Build the multipart/mixed request body
return await Multipart.CreateAsync(
messages,
"batch",
async,
cancellationToken)
.ConfigureAwait(false);
}
/// <summary>
/// Split the batch multipart response into individual sub-operation
/// responses and update the delayed responses already returned when
/// the sub-operation was added.
/// </summary>
/// <param name="messages">
/// The batch sub-operation messages that were submitted.
/// </param>
/// <param name="rawResponse">
/// The raw batch response.
/// </param>
/// <param name="throwOnAnyFailure">
/// A value indicating whether or not to throw exceptions for
/// sub-operation failures.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>A ValueTask representing the update operation.</returns>
private async ValueTask UpdateOperationResponses(
IList<HttpMessage> messages,
Response rawResponse,
bool throwOnAnyFailure,
bool async,
CancellationToken cancellationToken)
{
// Parse the response content into individual responses
Response[] responses;
try
{
responses = async
? await MultipartResponse.ParseAsync(rawResponse, true, cancellationToken).ConfigureAwait(false)
: MultipartResponse.Parse(rawResponse, true, cancellationToken);
// Ensure we have the right number of responses
if (messages.Count != responses.Length)
{
// If we get one response and it's a 400, this is the
// service failing the entire batch and sending it back in
// a format not currently documented by the spec
if (responses.Length == 1 && responses[0].Status == 400)
{
// We'll re-process this response as a batch result
throw new RequestFailedException(responses[0]);
}
else
{
throw BatchErrors.UnexpectedResponseCount(messages.Count, responses.Length);
}
}
}
catch (InvalidOperationException ex)
{
// Wrap any parsing errors in a RequestFailedException
throw BatchErrors.InvalidResponse(ClientDiagnostics, rawResponse, ex);
}
// Update the delayed responses
List<Exception> failures = new List<Exception>();
for (int i = 0; i < responses.Length; i++)
{
try
{
if (messages[i].TryGetProperty(BatchConstants.DelayedResponsePropertyName, out object value) &&
value is DelayedResponse response)
{
#pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope.
response.SetLiveResponse(responses[i], throwOnAnyFailure);
#pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope.
}
}
catch (Exception ex)
{
failures.Add(ex);
}
}
// Throw any failures
if (failures.Count > 0)
{
throw BatchErrors.ResponseFailures(failures);
}
}
#endregion Create/SubmitBatch
#region DeleteBlobs
/// <summary>
/// The DeleteBlobs operation marks the specified blobs for deletion.
/// The blobs are later deleted during garbage collection which could take
/// several minutes. All of the deletions are sent as a single batched request.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <param name="blobUris">URIs of the blobs to delete.</param>
/// <param name="snapshotsOption">
/// Specifies options for deleting blob snapshots.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Delete operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual Response[] DeleteBlobs(
IEnumerable<Uri> blobUris,
DeleteSnapshotsOption snapshotsOption = default,
CancellationToken cancellationToken = default) =>
DeleteBlobsInteral(
blobUris,
snapshotsOption,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The DeleteBlobsAsync operation marks the specified blobs for
/// deletion. The blobs are later deleted during garbage collection
/// which could take several minutes.
/// All of the deletions are sent as a single batched request.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <param name="blobUris">URIs of the blobs to delete.</param>
/// <param name="snapshotsOption">
/// Specifies options for deleting blob snapshots.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Delete operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual async Task<Response[]> DeleteBlobsAsync(
IEnumerable<Uri> blobUris,
DeleteSnapshotsOption snapshotsOption = default,
CancellationToken cancellationToken = default) =>
await DeleteBlobsInteral(
blobUris,
snapshotsOption,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The DeleteBlobsAsync operation marks the specified blobs for
/// deletion. The blobs are later deleted during garbage collection
/// which could take several minutes.
/// All of the deletions are sent as a single batched request.
/// </summary>
/// <param name="blobUris">URIs of the blobs to delete.</param>
/// <param name="snapshotsOption">
/// Specifies options for deleting blob snapshots.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Delete operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
internal async Task<Response[]> DeleteBlobsInteral(
IEnumerable<Uri> blobUris,
DeleteSnapshotsOption snapshotsOption,
bool async,
CancellationToken cancellationToken)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(BlobBatchClient)}.{nameof(DeleteBlobs)}");
try
{
scope.Start();
blobUris = blobUris ?? throw new ArgumentNullException(nameof(blobUris));
var responses = new List<Response>();
// Create the batch
BlobBatch batch = CreateBatch();
foreach (Uri uri in blobUris)
{
responses.Add(batch.DeleteBlob(uri, snapshotsOption));
}
// Submit the batch
await SubmitBatchInternal(
batch,
true,
async,
cancellationToken)
.ConfigureAwait(false);
return responses.ToArray();
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion DeleteBlobs
#region SetBlobsAccessTier
/// <summary>
/// The SetBlobsAccessTier operation sets the tier on blobs. The
/// operation is allowed on block blobs in a blob storage or general
/// purpose v2 account.
/// </summary>
/// <param name="blobUris">URIs of the blobs to set the tiers of.</param>
/// <param name="accessTier">
/// Indicates the tier to be set on the blobs.
/// </param>
/// <param name="rehydratePriority">
/// Optional <see cref="RehydratePriority"/>
/// Indicates the priority with which to rehydrate an archived blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Set Tier operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual Response[] SetBlobsAccessTier(
IEnumerable<Uri> blobUris,
AccessTier accessTier,
RehydratePriority? rehydratePriority = default,
CancellationToken cancellationToken = default) =>
SetBlobsAccessTierInteral(
blobUris,
accessTier,
rehydratePriority,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The SetBlobsAccessTierAsync operation sets the tier on blobs. The
/// operation is allowed on block blobs in a blob storage or general
/// purpose v2 account.
/// </summary>
/// <param name="blobUris">URIs of the blobs to set the tiers of.</param>
/// <param name="accessTier">
/// Indicates the tier to be set on the blobs.
/// </param>
/// <param name="rehydratePriority">
/// Optional <see cref="RehydratePriority"/>
/// Indicates the priority with which to rehydrate an archived blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Set Tier operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
[ForwardsClientCalls]
public virtual async Task<Response[]> SetBlobsAccessTierAsync(
IEnumerable<Uri> blobUris,
AccessTier accessTier,
RehydratePriority? rehydratePriority = default,
CancellationToken cancellationToken = default) =>
await SetBlobsAccessTierInteral(
blobUris,
accessTier,
rehydratePriority,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The SetBlobsAccessTierAsync operation sets the tier on blobs. The
/// operation is allowed on block blobs in a blob storage or general
/// purpose v2 account.
/// </summary>
/// <param name="blobUris">
/// URIs of the blobs to set the tiers of.
/// </param>
/// <param name="accessTier">
/// Indicates the tier to be set on the blobs.
/// </param>
/// <param name="rehydratePriority">
/// Optional <see cref="RehydratePriority"/>
/// Indicates the priority with which to rehydrate an archived blob.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be cancelled.
/// </param>
/// <returns>
/// The <see cref="Response"/>s for the individual Set Tier operations.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure to submit the batch occurs. Individual sub-operation
/// failures will be wrapped in an <see cref="AggregateException"/>.
/// </remarks>
internal async Task<Response[]> SetBlobsAccessTierInteral(
IEnumerable<Uri> blobUris,
AccessTier accessTier,
RehydratePriority? rehydratePriority,
bool async,
CancellationToken cancellationToken)
{
DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(BlobBatchClient)}.{nameof(SetBlobsAccessTier)}");
try
{
scope.Start();
blobUris = blobUris ?? throw new ArgumentNullException(nameof(blobUris));
var responses = new List<Response>();
// Create the batch
BlobBatch batch = CreateBatch();
foreach (Uri uri in blobUris)
{
responses.Add(batch.SetBlobAccessTier(uri, accessTier, rehydratePriority));
}
// Submit the batch
await SubmitBatchInternal(
batch,
true,
async,
cancellationToken)
.ConfigureAwait(false);
return responses.ToArray();
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
finally
{
scope.Dispose();
}
}
#endregion SetBlobsAccessTier
}
/// <summary>
/// Add easy to discover methods to <see cref="BlobServiceClient"/> for
/// creating <see cref="BlobBatchClient"/> instances.
/// </summary>
public static partial class SpecializedBlobExtensions
{
/// <summary>
/// Create a new <see cref="BlobBatchClient"/> object for the same
/// account as the <see cref="BlobServiceClient"/>. The new
/// <see cref="BlobBatchClient"/> uses the same request policy pipeline
/// as the <see cref="BlobServiceClient"/>.
/// </summary>
/// <param name="client">The <see cref="BlobServiceClient"/>.</param>
/// <returns>A new <see cref="BlobBatchClient"/> instance.</returns>
public static BlobBatchClient GetBlobBatchClient(this BlobServiceClient client)
=> new BlobBatchClient(client);
/// <summary>
/// Create a new <see cref="BlobBatchClient"/> object for the
/// container associated with the <see cref="BlobContainerClient"/>. The new
/// <see cref="BlobBatchClient"/> uses the same request policy pipeline
/// as the <see cref="BlobContainerClient"/>.
/// </summary>
/// <param name="client">The <see cref="BlobContainerClient"/>.</param>
/// <returns>A new <see cref="BlobBatchClient"/> instance.</returns>
public static BlobBatchClient GetBlobBatchClient(this BlobContainerClient client)
=> new BlobBatchClient(client);
}
}