-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathS3UploadStream.cs
More file actions
318 lines (275 loc) · 9.81 KB
/
S3UploadStream.cs
File metadata and controls
318 lines (275 loc) · 9.81 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
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using Amazon.S3;
using Amazon.S3.Model;
using Ramstack.FileSystem.Amazon.Utilities;
namespace Ramstack.FileSystem.Amazon;
/// <summary>
/// Represents a stream for uploading data to Amazon S3 using multipart upload.
/// This stream accumulates data in a temporary buffer and uploads it to S3 in parts
/// once the buffer reaches a predefined size.
/// </summary>
internal sealed class S3UploadStream : Stream
{
private const long PartSize = 5 * 1024 * 1024;
private readonly IAmazonS3 _client;
private readonly string _bucketName;
private readonly string _key;
private readonly string _uploadId;
private readonly FileStream _stream;
private readonly List<PartETag> _partETags;
private bool _disposed;
/// <inheritdoc />
public override bool CanRead => false;
/// <inheritdoc />
public override bool CanSeek => false;
/// <inheritdoc />
public override bool CanWrite => true;
/// <inheritdoc />
public override long Length
{
get
{
Error_NotSupported();
return 0;
}
}
/// <inheritdoc />
public override long Position
{
get
{
Error_NotSupported();
return 0;
}
// ReSharper disable once ValueParameterNotUsed
set => Error_NotSupported();
}
/// <summary>
/// Initializes a new instance of the <see cref="S3UploadStream"/> class.
/// </summary>
/// <param name="client">The Amazon S3 client used for uploading parts.</param>
/// <param name="bucketName">The name of the S3 bucket where the data will be uploaded.</param>
/// <param name="key">The key (path) in the S3 bucket where the data will be stored.</param>
/// <param name="uploadId">The multipart upload session identifier.</param>
public S3UploadStream(IAmazonS3 client, string bucketName, string key, string uploadId)
{
_client = client;
_bucketName = bucketName;
_key = key;
_uploadId = uploadId;
_partETags = [];
_stream = new FileStream(
Path.Combine(
Path.GetTempPath(),
Path.GetRandomFileName()),
FileMode.CreateNew,
FileAccess.ReadWrite,
FileShare.None,
bufferSize: 4096,
FileOptions.DeleteOnClose
| FileOptions.Asynchronous);
}
/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count)
{
Error_NotSupported();
return 0;
}
/// <inheritdoc />
public override void Write(byte[] buffer, int offset, int count) =>
Write(buffer.AsSpan(offset, count));
/// <inheritdoc />
public override void Write(ReadOnlySpan<byte> buffer)
{
try
{
_stream.Write(buffer);
if (_stream.Length >= PartSize)
UploadPart();
}
catch (Exception exception)
{
Abort();
ExceptionDispatchInfo.Throw(exception);
}
}
/// <inheritdoc />
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
/// <inheritdoc />
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
try
{
await _stream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
if (_stream.Length >= PartSize)
await UploadPartAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
await AbortAsync(cancellationToken).ConfigureAwait(false);
ExceptionDispatchInfo.Throw(exception);
}
}
/// <inheritdoc />
public override long Seek(long offset, SeekOrigin origin)
{
Error_NotSupported();
return 0;
}
/// <inheritdoc />
public override void SetLength(long value) =>
Error_NotSupported();
/// <inheritdoc />
public override void Flush()
{
_stream.Flush();
UploadPart();
}
/// <inheritdoc />
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
await UploadPartAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
using var scope = NullSynchronizationContext.CreateScope();
DisposeAsync().AsTask().Wait();
}
}
/// <inheritdoc />
public override async ValueTask DisposeAsync()
{
if (_disposed)
return;
try
{
_disposed = true;
await UploadPartAsync(CancellationToken.None).ConfigureAwait(false);
var request = new CompleteMultipartUploadRequest
{
BucketName = _bucketName,
Key = _key,
UploadId = _uploadId,
PartETags = _partETags
};
await _client
.CompleteMultipartUploadAsync(request)
.ConfigureAwait(false);
}
catch (Exception exception)
{
await AbortAsync(CancellationToken.None).ConfigureAwait(false);
ExceptionDispatchInfo.Throw(exception);
}
finally
{
await _stream
.DisposeAsync()
.ConfigureAwait(false);
}
}
/// <summary>
/// Uploads the current buffer to Amazon S3 as a part of the multipart upload.
/// This method blocks the calling thread and waits for the upload to complete.
/// </summary>
private void UploadPart()
{
using var scope = NullSynchronizationContext.CreateScope();
UploadPartAsync(CancellationToken.None).AsTask().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously uploads the current buffer to Amazon S3 as a part of the multipart upload.
/// </summary>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
private async ValueTask UploadPartAsync(CancellationToken cancellationToken)
{
// Upload an empty part if nothing has been uploaded yet,
// since we must specify at least one part.
if (_stream.Length != 0 || _partETags.Count == 0)
{
try
{
_stream.Position = 0;
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
// The maximum allowed part size is 5 gigabytes.
var request = new UploadPartRequest
{
BucketName = _bucketName,
Key = _key,
UploadId = _uploadId,
PartNumber = _partETags.Count + 1,
InputStream = _stream,
PartSize = _stream.Length
};
var response = await _client
.UploadPartAsync(request, cancellationToken)
.ConfigureAwait(false);
_partETags.Add(new PartETag(response));
_stream.Position = 0;
_stream.SetLength(0);
}
catch (Exception exception)
{
await AbortAsync(cancellationToken).ConfigureAwait(false);
ExceptionDispatchInfo.Throw(exception);
}
}
}
/// <summary>
/// Aborts the multipart upload session.
/// </summary>
/// <remarks>
/// This method sends a request to Amazon S3 to abort the multipart upload identified by the
/// <see cref="_uploadId"/>. Once aborted, the upload cannot be resumed, and any uploaded parts
/// will be deleted.
/// </remarks>
private void Abort()
{
using var scope = NullSynchronizationContext.CreateScope();
AbortAsync(CancellationToken.None).AsTask().GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously aborts the multipart upload session.
/// </summary>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> that represents the asynchronous abort operation.
/// </returns>
/// <remarks>
/// This method sends a request to Amazon S3 to abort the multipart upload identified by the
/// <see cref="_uploadId"/>. Once aborted, the upload cannot be resumed, and any uploaded parts
/// will be deleted.
/// </remarks>
private async ValueTask AbortAsync(CancellationToken cancellationToken)
{
var request = new AbortMultipartUploadRequest
{
BucketName = _bucketName,
Key = _key,
UploadId = _uploadId
};
await _client
.AbortMultipartUploadAsync(request, cancellationToken)
.ConfigureAwait(false);
_disposed = true;
// Prevent subsequent writes to the stream.
await _stream
.DisposeAsync()
.ConfigureAwait(false);
}
/// <summary>
/// Throws a <see cref="NotSupportedException"/>.
/// </summary>
[DoesNotReturn]
private static void Error_NotSupported() =>
throw new NotSupportedException();
}