-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTemporaryBlobFile.cs
More file actions
280 lines (249 loc) · 16.1 KB
/
TemporaryBlobFile.cs
File metadata and controls
280 lines (249 loc) · 16.1 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
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Arcus.Testing
{
/// <summary>
/// Represents a temporary Azure Blob file that will be deleted after the instance is disposed.
/// </summary>
public class TemporaryBlobFile : IAsyncDisposable
{
private readonly bool _createdByUs;
private readonly BinaryData _originalData;
private readonly ILogger _logger;
private readonly BlobClient _client;
private bool _isDisposed;
private TemporaryBlobFile(
BlobClient blobClient,
bool createdByUs,
BinaryData originalData,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(blobClient);
_createdByUs = createdByUs;
_originalData = originalData;
_logger = logger ?? NullLogger.Instance;
_client = blobClient;
}
/// <summary>
/// Gets the name of the Azure Blob file currently in storage.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public string Name => Client.Name;
/// <summary>
/// Gets the name of the Azure Blob container where the Azure Blob file is currently stored.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public string ContainerName => Client.BlobContainerName;
/// <summary>
/// Gets the client to interact with the temporary stored Azure Blob file currently in storage.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown when the test fixture was already teared down.</exception>
public BlobClient Client
{
get
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
return _client;
}
}
/// <summary>
/// Uploads a temporary blob to the Azure Blob container.
/// </summary>
/// <remarks>
/// Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.
/// </remarks>
/// <param name="blobContainerUri">
/// A <see cref="BlobContainerClient.Uri" /> referencing the blob container that includes the name of the account and the name of the container.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}".
/// </param>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobContainerUri"/> or the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="blobContainerUri"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
[Obsolete("Will be removed in v3.0, please use the " + nameof(UpsertFileAsync) + " instead which provides the exact same functionality", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobFile> UploadIfNotExistsAsync(Uri blobContainerUri, string blobName, BinaryData blobContent, ILogger logger)
{
return UpsertFileAsync(blobContainerUri, blobName, blobContent, logger);
}
/// <summary>
/// Uploads a temporary blob to the Azure Blob container.
/// </summary>
/// <param name="blobClient">The Azure Blob client to interact with Azure Blob Storage.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobClient"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
[Obsolete("Will be removed in v3.0, please use the " + nameof(UpsertFileAsync) + " instead which provides the exact same functionality", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobFile> UploadIfNotExistsAsync(BlobClient blobClient, BinaryData blobContent, ILogger logger)
{
return UpsertFileAsync(blobClient, blobContent, logger);
}
/// <summary>
/// Creates a new or replaces an existing Azure Blob file in an Azure Blob container.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// <para>⚡ File will be deleted (if new) or reverted (if existing) when the <see cref="TemporaryBlobFile"/> is disposed.</para>
/// </remarks>
/// <param name="blobContainerUri">
/// <para>The <see cref="BlobContainerClient.Uri" /> referencing the blob container that includes the name of the account and the name of the container.</para>
/// <para>This is likely to be similar to <a href="">https://{account_name}.blob.core.windows.net/{container_name}</a>.</para>
/// </param>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobContainerUri"/> or the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="blobContainerUri"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(UpsertFileAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobFile> UpsertFileAsync(Uri blobContainerUri, string blobName, BinaryData blobContent, ILogger logger)
{
return UpsertFileAsync(blobContainerUri, blobName, blobContent, logger, CancellationToken.None);
}
/// <summary>
/// Creates a new or replaces an existing Azure Blob file in an Azure Blob container.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// <para>⚡ File will be deleted (if new) or reverted (if existing) when the <see cref="TemporaryBlobFile"/> is disposed.</para>
/// </remarks>
/// <param name="blobContainerUri">
/// <para>The <see cref="BlobContainerClient.Uri" /> referencing the blob container that includes the name of the account and the name of the container.</para>
/// <para>This is likely to be similar to <a href="">https://{account_name}.blob.core.windows.net/{container_name}</a>.</para>
/// </param>
/// <param name="blobName">The name of the blob to upload.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentException">Thrown when the <paramref name="blobContainerUri"/> or the <paramref name="blobName"/> is blank.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="blobContainerUri"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static Task<TemporaryBlobFile> UpsertFileAsync(
Uri blobContainerUri,
string blobName,
BinaryData blobContent,
ILogger logger,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(blobContainerUri);
ArgumentException.ThrowIfNullOrWhiteSpace(blobName);
cancellationToken.ThrowIfCancellationRequested();
var containerClient = new BlobContainerClient(blobContainerUri, new DefaultAzureCredential());
BlobClient blobClient = containerClient.GetBlobClient(blobName);
return UpsertFileAsync(blobClient, blobContent, logger, cancellationToken);
}
/// <summary>
/// Creates a new or replaces an existing Azure Blob file in an Azure Blob container.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// <para>⚡ File will be deleted (if new) or reverted (if existing) when the <see cref="TemporaryBlobFile"/> is disposed.</para>
/// </remarks>
/// <param name="blobClient">The Azure Blob client to interact with Azure Blob Storage.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobClient"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
[Obsolete("Will be removed in v3, please use the " + nameof(UpsertFileAsync) + " overload instead that provides cancellation token support", DiagnosticId = ObsoleteDefaults.DiagnosticId)]
public static Task<TemporaryBlobFile> UpsertFileAsync(BlobClient blobClient, BinaryData blobContent, ILogger logger)
{
return UpsertFileAsync(blobClient, blobContent, logger, CancellationToken.None);
}
/// <summary>
/// Creates a new or replaces an existing Azure Blob file in an Azure Blob container.
/// </summary>
/// <remarks>
/// <para>⚡ Uses <see cref="DefaultAzureCredential"/> to authenticate with Azure Blob Storage.</para>
/// <para>⚡ File will be deleted (if new) or reverted (if existing) when the <see cref="TemporaryBlobFile"/> is disposed.</para>
/// </remarks>
/// <param name="blobClient">The Azure Blob client to interact with Azure Blob Storage.</param>
/// <param name="blobContent">The content of the blob to upload.</param>
/// <param name="logger">The logger to write diagnostic messages during the upload process.</param>
/// <param name="cancellationToken">The optional token to propagate notifications that the operation should be cancelled.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="blobClient"/> or the <paramref name="blobContent"/> is <c>null</c>.</exception>
/// <exception cref="RequestFailedException">Thrown when the interaction with Azure failed.</exception>
public static async Task<TemporaryBlobFile> UpsertFileAsync(
BlobClient blobClient,
BinaryData blobContent,
ILogger logger,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(blobClient);
ArgumentNullException.ThrowIfNull(blobContent);
cancellationToken.ThrowIfCancellationRequested();
logger ??= NullLogger.Instance;
(bool createdByUs, BinaryData originalData) =
await EnsureBlobContentCreatedAsync(blobClient, blobContent, logger, cancellationToken).ConfigureAwait(false);
return new TemporaryBlobFile(blobClient, createdByUs, originalData, logger);
}
private static async Task<(bool createdByUs, BinaryData originalData)> EnsureBlobContentCreatedAsync(
BlobClient client,
BinaryData newContent,
ILogger logger,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (await client.ExistsAsync(cancellationToken).ConfigureAwait(false))
{
BlobDownloadResult originalContent = await client.DownloadContentAsync(cancellationToken).ConfigureAwait(false);
logger.LogSetupReplaceFile(client.Name, client.AccountName, client.BlobContainerName);
await client.UploadAsync(newContent, overwrite: true, cancellationToken).ConfigureAwait(false);
return (createdByUs: false, originalContent.Content);
}
logger.LogSetupUploadNewFile(client.Name, client.AccountName, client.BlobContainerName);
await client.UploadAsync(newContent, cancellationToken).ConfigureAwait(false);
return (createdByUs: true, originalData: null);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
/// </summary>
/// <returns>A task that represents the asynchronous dispose operation.</returns>
public async ValueTask DisposeAsync()
{
if (_isDisposed)
{
return;
}
if (_createdByUs)
{
_logger.LogTeardownDeleteFile(_client.Name, _client.AccountName, _client.BlobContainerName);
await _client.DeleteIfExistsAsync().ConfigureAwait(false);
}
else if (_originalData != null)
{
_logger.LogTeardownRevertFile(_client.Name, _client.AccountName, _client.BlobContainerName);
await _client.UploadAsync(_originalData, overwrite: true).ConfigureAwait(false);
}
_isDisposed = true;
GC.SuppressFinalize(this);
}
}
internal static partial class TempBlobFileILoggerExtensions
{
private const LogLevel SetupTeardownLogLevel = LogLevel.Debug;
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Setup] Upload Azure Blob file '{BlobName}' to container '{AccountName}/{ContainerName}'")]
internal static partial void LogSetupUploadNewFile(this ILogger logger, string blobName, string accountName, string containerName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Setup] Replace already existing Azure Blob file '{BlobName}' in container '{AccountName}/{ContainerName}'")]
internal static partial void LogSetupReplaceFile(this ILogger logger, string blobName, string accountName, string containerName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Teardown] Delete Azure Blob file '{BlobName}' from container '{AccountName}/{ContainerName}'")]
internal static partial void LogTeardownDeleteFile(this ILogger logger, string blobName, string accountName, string containerName);
[LoggerMessage(
Level = SetupTeardownLogLevel,
Message = "[Test:Teardown] Revert replaced Azure Blob file '{BlobName}' to original content in container '{AccountName}/{ContainerName}'")]
internal static partial void LogTeardownRevertFile(this ILogger logger, string blobName, string accountName, string containerName);
}
}