This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
CosmosStorageProvider.cs
233 lines (200 loc) · 11.5 KB
/
CosmosStorageProvider.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
// Copyright (c) 2020 Allan Mobley. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Identity;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Mobsites.Cosmos.Identity
{
/// <summary>
/// Represents a new instance of a default Cosmos storage provider which implements <see cref="IIdentityStorageProvider"/>.
/// </summary>
public class CosmosStorageProvider : IIdentityStorageProvider
{
private readonly CosmosClient cosmosClient;
private readonly Database database;
/// <summary>
/// Identity container.
/// </summary>
public Container Container { get; set; }
/// <summary>
/// Constructs a new instance of <see cref="CosmosStorageProvider"/>.
/// </summary>
/// <param name="optionsAccessor">The accessor used to access the <see cref="CosmosStorageProviderOptions"/>.</param>
public CosmosStorageProvider(IOptions<CosmosStorageProviderOptions> optionsAccessor)
{
var options = optionsAccessor?.Value ?? new CosmosStorageProviderOptions();
var containerProperties = options.ContainerProperties ?? new ContainerProperties { Id = "IdentityContainer", PartitionKeyPath = "/PartitionKey" };
if (string.IsNullOrEmpty(options.ConnectionString))
{
throw new Exception($"{nameof(CosmosStorageProvider)}(): No connection string provided.");
}
if (string.IsNullOrEmpty(options.DatabaseId))
{
throw new Exception($"{nameof(CosmosStorageProvider)}(): No database id provided.");
}
if (string.IsNullOrEmpty(containerProperties.Id))
{
throw new Exception($"{nameof(CosmosStorageProvider)}(): No container id provided.");
}
if (string.IsNullOrEmpty(containerProperties.PartitionKeyPath))
{
containerProperties.PartitionKeyPath = "/PartitionKey";
}
if (!containerProperties.PartitionKeyPath.StartsWith("/"))
{
containerProperties.PartitionKeyPath = "/" + containerProperties.PartitionKeyPath;
}
cosmosClient = new CosmosClient(options.ConnectionString, options.CosmosClientOptions);
database = cosmosClient.CreateDatabaseIfNotExistsAsync(options.DatabaseId, options.DatabaseThroughput, options.DatabaseRequestOptions).Result;
Container = database.CreateContainerIfNotExistsAsync(options.ContainerProperties, options.ContainerThroughput, options.ContainerRequestOptions).Result;
}
/// <summary>
/// Returns a queryable linq expression of the specified <typeparamref name="TCosmosStorageType" />.
/// </summary>
public IOrderedQueryable<TCosmosStorageType> Queryable<TCosmosStorageType>()
where TCosmosStorageType : ICosmosStorageType, new()
{
var partitionKey = new TCosmosStorageType().PartitionKey;
return Container.GetItemLinqQueryable<TCosmosStorageType>(
allowSynchronousQueryExecution:true,
requestOptions: new QueryRequestOptions
{
PartitionKey = string.IsNullOrEmpty(partitionKey) ? PartitionKey.None : new PartitionKey(partitionKey)
});
}
/// <summary>
/// Creates the specified <paramref name="cosmosStorageType"/> in the store.
/// </summary>
/// <param name="cosmosStorageType">The storage type to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the creation operation.
/// </returns>
public async Task<IdentityResult> CreateAsync<TCosmosStorageType>(TCosmosStorageType cosmosStorageType, CancellationToken cancellationToken = default)
where TCosmosStorageType : ICosmosStorageType, new()
{
IdentityResult result;
cancellationToken.ThrowIfCancellationRequested();
if (cosmosStorageType == null)
{
result = IdentityResult.Failed(new IdentityError() { Code = HttpStatusCode.BadRequest.ToString(), Description = $"Argument {nameof(cosmosStorageType)} cannot be null." });
}
else
{
try
{
var partitionKey = string.IsNullOrEmpty(cosmosStorageType.PartitionKey) ? PartitionKey.None : new PartitionKey(cosmosStorageType.PartitionKey);
var response = await Container.CreateItemAsync(cosmosStorageType, partitionKey, cancellationToken: cancellationToken);
result = response.StatusCode >= HttpStatusCode.BadRequest ?
IdentityResult.Failed(new IdentityError() { Code = response.StatusCode.ToString(), Description = $"The storage type {cosmosStorageType.GetType().Name} was not created." }) :
IdentityResult.Success;
}
catch (CosmosException ex)
{
result = IdentityResult.Failed(new IdentityError() { Code = ex.StatusCode.ToString(), Description = ex.Message });
}
}
return result;
}
/// <summary>
/// Updates the specified <paramref name="cosmosStorageType"/> in the store.
/// </summary>
/// <param name="cosmosStorageType">The storage type to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.
/// </returns>
public async Task<IdentityResult> UpdateAsync<TCosmosStorageType>(TCosmosStorageType cosmosStorageType, CancellationToken cancellationToken = default)
where TCosmosStorageType : ICosmosStorageType, new()
{
IdentityResult result;
cancellationToken.ThrowIfCancellationRequested();
if (cosmosStorageType == null)
{
result = IdentityResult.Failed(new IdentityError() { Code = HttpStatusCode.BadRequest.ToString(), Description = $"Argument {nameof(cosmosStorageType)} cannot be null." });
}
else
{
try
{
var partitionKey = string.IsNullOrEmpty(cosmosStorageType.PartitionKey) ? PartitionKey.None : new PartitionKey(cosmosStorageType.PartitionKey);
var response = await Container.ReplaceItemAsync(cosmosStorageType, cosmosStorageType.Id, partitionKey, cancellationToken: cancellationToken);
result = response.StatusCode >= HttpStatusCode.BadRequest ?
IdentityResult.Failed(new IdentityError() { Code = response.StatusCode.ToString(), Description = $"The storage type {cosmosStorageType.GetType().Name} was not updated." }) :
IdentityResult.Success;
}
catch (CosmosException ex)
{
result = IdentityResult.Failed(new IdentityError() { Code = ex.StatusCode.ToString(), Description = ex.Message });
}
}
return result;
}
/// <summary>
/// Deletes the specified <paramref name="cosmosStorageType"/> from the store.
/// </summary>
/// <param name="cosmosStorageType">The storage type to delete.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the delete operation.
/// </returns>
public async Task<IdentityResult> DeleteAsync<TCosmosStorageType>(TCosmosStorageType cosmosStorageType, CancellationToken cancellationToken = default)
where TCosmosStorageType : ICosmosStorageType, new()
{
IdentityResult result;
cancellationToken.ThrowIfCancellationRequested();
if (cosmosStorageType == null)
{
result = IdentityResult.Failed(new IdentityError() { Code = HttpStatusCode.BadRequest.ToString(), Description = $"Argument {nameof(cosmosStorageType)} cannot be null." });
}
else
{
try
{
var partitionKey = string.IsNullOrEmpty(cosmosStorageType.PartitionKey) ? PartitionKey.None : new PartitionKey(cosmosStorageType.PartitionKey);
var response = await Container.DeleteItemAsync<TCosmosStorageType>(cosmosStorageType.Id, partitionKey, cancellationToken: cancellationToken);
result = response.StatusCode >= HttpStatusCode.BadRequest ?
IdentityResult.Failed(new IdentityError() { Code = response.StatusCode.ToString(), Description = $"The storage type {cosmosStorageType.GetType().Name} was not deleted." }) :
IdentityResult.Success;
}
catch (CosmosException ex)
{
result = IdentityResult.Failed(new IdentityError() { Code = ex.StatusCode.ToString(), Description = ex.Message });
}
}
return result;
}
/// <summary>
/// Finds and returns the specified <typeparamref name="TCosmosStorageType" />, if any, which has the specified <paramref name="id"/>.
/// </summary>
/// <typeparam name="TCosmosStorageType">The type to find.</typeparam>
/// <param name="id">The id of the type to search for.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <typeparamref name="TCosmosStorageType" /> with the specified <paramref name="id"/> if it exists.
/// </returns>
public async Task<TCosmosStorageType> FindByIdAsync<TCosmosStorageType>(string id, CancellationToken cancellationToken = default)
where TCosmosStorageType : ICosmosStorageType, new()
{
cancellationToken.ThrowIfCancellationRequested();
if (!string.IsNullOrEmpty(id))
{
try
{
var cosmosStorageType = new TCosmosStorageType();
var partitionKey = string.IsNullOrEmpty(cosmosStorageType.PartitionKey) ? PartitionKey.None : new PartitionKey(cosmosStorageType.PartitionKey);
return await Container.ReadItemAsync<TCosmosStorageType>(id, partitionKey, cancellationToken: cancellationToken);
}
catch (CosmosException)
{
}
}
return default;
}
}
}