-
-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathAWSS3StorageCache.cs
More file actions
207 lines (183 loc) · 7.49 KB
/
AWSS3StorageCache.cs
File metadata and controls
207 lines (183 loc) · 7.49 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
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Globalization;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp.Web.AWS.Resolvers;
using SixLabors.ImageSharp.Web.Caching;
using SixLabors.ImageSharp.Web.Resolvers;
namespace SixLabors.ImageSharp.Web.AWS.Caching;
/// <summary>
/// Implements an AWS S3 Storage based cache.
/// </summary>
public class AWSS3StorageCache : IImageCache, IDisposable
{
private readonly AmazonS3BucketClient amazonS3Client;
private readonly string bucketName;
private readonly string cacheFolder;
private bool isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="AWSS3StorageCache"/> class.
/// </summary>
/// <param name="cacheOptions">The cache options.</param>
/// <param name="serviceProvider">The current service provider.</param>
public AWSS3StorageCache(IOptions<AWSS3StorageCacheOptions> cacheOptions, IServiceProvider serviceProvider)
{
Guard.NotNull(cacheOptions, nameof(cacheOptions));
AWSS3StorageCacheOptions options = cacheOptions.Value;
this.amazonS3Client =
options.S3ClientFactory?.Invoke(options, serviceProvider)
?? AmazonS3ClientFactory.CreateClient(options);
this.bucketName = this.amazonS3Client.BucketName;
this.cacheFolder = string.IsNullOrEmpty(options.CacheFolder)
? string.Empty
: options.CacheFolder.Trim().Trim('/') + '/';
}
/// <inheritdoc/>
public async Task<IImageCacheResolver?> GetAsync(string key)
{
string keyWithFolder = this.GetKeyWithFolder(key);
GetObjectMetadataRequest request = new() { BucketName = this.bucketName, Key = keyWithFolder };
try
{
// HEAD request throws a 404 if not found.
MetadataCollection metadata = (await this.amazonS3Client.Client.GetObjectMetadataAsync(request)).Metadata;
return new AWSS3StorageCacheResolver(this.amazonS3Client.Client, this.bucketName, keyWithFolder, metadata);
}
catch
{
return null;
}
}
/// <inheritdoc/>
public Task SetAsync(string key, Stream stream, ImageCacheMetadata metadata)
{
PutObjectRequest request = new()
{
BucketName = this.bucketName,
Key = this.GetKeyWithFolder(key),
ContentType = metadata.ContentType,
InputStream = stream,
AutoCloseStream = false,
UseChunkEncoding = false
};
foreach (KeyValuePair<string, string> d in metadata.ToDictionary())
{
request.Metadata.Add(d.Key, d.Value);
}
return this.amazonS3Client.Client.PutObjectAsync(request);
}
/// <summary>
/// Creates a new bucket under the specified account if a bucket
/// with the same name does not already exist.
/// </summary>
/// <param name="options">The AWS S3 Storage cache options.</param>
/// <param name="acl">
/// Specifies whether data in the bucket may be accessed publicly and the level of access.
/// <see cref="S3CannedACL.PublicRead"/> specifies full public read access for bucket
/// and object data. <see cref="S3CannedACL.Private"/> specifies that the bucket
/// data is private to the account owner.
/// </param>
/// <returns>
/// If the bucket does not already exist, a <see cref="PutBucketResponse"/> describing the newly
/// created bucket. If the container already exists, <see langword="null"/>.
/// </returns>
public static PutBucketResponse? CreateIfNotExists(AWSS3StorageCacheOptions options, S3CannedACL acl)
=> AsyncHelper.RunSync(() => CreateIfNotExistsAsync(options, acl));
/// <summary>
/// Releases the unmanaged resources used by the <see cref="AWSS3StorageCache"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.amazonS3Client?.Dispose();
}
this.isDisposed = true;
}
}
/// <inheritdoc/>
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
this.Dispose(disposing: true);
GC.SuppressFinalize(this);
}
private static async Task<PutBucketResponse?> CreateIfNotExistsAsync(AWSS3StorageCacheOptions options, S3CannedACL acl)
{
using AmazonS3BucketClient bucketClient = AmazonS3ClientFactory.CreateClient(options);
AmazonS3Client client = bucketClient.Client;
bool foundBucket = false;
ListBucketsResponse listBucketsResponse = await client.ListBucketsAsync();
foreach (S3Bucket b in listBucketsResponse.Buckets)
{
if (b.BucketName == options.BucketName)
{
foundBucket = true;
break;
}
}
if (!foundBucket)
{
PutBucketRequest putBucketRequest = new()
{
BucketName = options.BucketName,
BucketRegion = options.Region,
CannedACL = acl
};
return await client.PutBucketAsync(putBucketRequest);
}
return null;
}
private string GetKeyWithFolder(string key)
=> this.cacheFolder + key;
/// <summary>
/// <see href="https://github.com/aspnet/AspNetIdentity/blob/b7826741279450c58b230ece98bd04b4815beabf/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs"/>
/// </summary>
private static class AsyncHelper
{
private static readonly TaskFactory TaskFactory
= new(
CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
/// <summary>
/// Executes an async <see cref="Task"/> method synchronously.
/// </summary>
/// <param name="task">The task to execute.</param>
public static void RunSync(Func<Task> task)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
TaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return task();
}).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Executes an async <see cref="Task{TResult}"/> method which has
/// a <paramref name="task"/> return type synchronously.
/// </summary>
/// <typeparam name="TResult">The type of result to return.</typeparam>
/// <param name="task">The task to execute.</param>
/// <returns>The <typeparamref name="TResult"/>.</returns>
public static TResult RunSync<TResult>(Func<Task<TResult>> task)
{
CultureInfo cultureUi = CultureInfo.CurrentUICulture;
CultureInfo culture = CultureInfo.CurrentCulture;
return TaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return task();
}).Unwrap().GetAwaiter().GetResult();
}
}
}