-
-
Notifications
You must be signed in to change notification settings - Fork 323
/
DynamoDataProvider.cs
281 lines (260 loc) · 11.3 KB
/
DynamoDataProvider.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
using System;
using Audit.Core;
using System.Threading.Tasks;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DocumentModel;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
namespace Audit.DynamoDB.Providers
{
/// <summary>
/// Amazon DynamoDB data provider for Audit.NET. Store the audit events into DynamoDB tables.
/// </summary>
public class DynamoDataProvider : AuditDataProvider
{
private static readonly ConcurrentDictionary<string, Table> TableCache = new ConcurrentDictionary<string, Table>();
/// <summary>
/// Top-level attributes to be added to the event and document before saving
/// </summary>
public Dictionary<string, Setting<object>> CustomAttributes { get; set; } = new Dictionary<string, Setting<object>>();
/// <summary>
/// Factory that creates the client
/// </summary>
public Lazy<IAmazonDynamoDB> Client { get; set; }
/// <summary>
/// The DynamoDB table name to use when saving an audit event.
/// </summary>
public Setting<string> TableName { get; set; }
/// <summary>
/// Creates a new DynamoDB data provider using the given client.
/// </summary>
/// <param name="client">The amazon DynamoDB client instance</param>
public DynamoDataProvider(IAmazonDynamoDB client)
{
Client = new Lazy<IAmazonDynamoDB>(() => client);
}
/// <summary>
/// Creates a new DynamoDB data provider using the given client.
/// </summary>
/// <param name="client">The amazon DynamoDB client instance</param>
public DynamoDataProvider(AmazonDynamoDBClient client)
{
Client = new Lazy<IAmazonDynamoDB>(() => client);
}
/// <summary>
/// Creates a new DynamoDB data provider.
/// </summary>
public DynamoDataProvider()
{
}
/// <summary>
/// Creates a new DynamoDB data provider with the given configuration options.
/// </summary>
public DynamoDataProvider(Action<Configuration.IDynamoProviderConfigurator> config)
{
var dynaDbConfig = new Configuration.DynamoProviderConfigurator();
if (config != null)
{
config.Invoke(dynaDbConfig);
Client = dynaDbConfig._clientFactory;
TableName = dynaDbConfig._tableConfigurator?._tableName ?? new Setting<string>();
CustomAttributes = dynaDbConfig._tableConfigurator?._attrConfigurator?._attributes;
}
}
/// <summary>
/// Inserts an event into DynamoDB
/// </summary>
public override object InsertEvent(AuditEvent auditEvent)
{
var table = GetTable(auditEvent);
var document = CreateDocument(auditEvent, true);
table.PutItemAsync(document).GetAwaiter().GetResult();
return GetKeyValues(document, table);
}
/// <summary>
/// Asynchronously inserts an event into DynamoDB
/// </summary>
public override async Task<object> InsertEventAsync(AuditEvent auditEvent, CancellationToken cancellationToken = default)
{
var table = GetTable(auditEvent);
var document = CreateDocument(auditEvent, true);
await table.PutItemAsync(document, cancellationToken);
return GetKeyValues(document, table);
}
/// <summary>
/// Replaces an event into DynamoDB
/// </summary>
public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
{
var table = GetTable(auditEvent);
var document = CreateDocument(auditEvent, false);
table.PutItemAsync(document).GetAwaiter().GetResult();
}
/// <summary>
/// Asynchronously replaces an event into DynamoDB
/// </summary>
public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent, CancellationToken cancellationToken = default)
{
var table = GetTable(auditEvent);
var document = CreateDocument(auditEvent, false);
await table.PutItemAsync(document, cancellationToken);
}
/// <summary>
/// Gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="hashKey">The primary key Hash portion</param>
/// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
public T GetEvent<T>(Primitive hashKey, Primitive rangeKey) where T : AuditEvent
{
var table = GetTable(null);
Document doc;
if (rangeKey == null)
{
doc = table.GetItemAsync(hashKey).GetAwaiter().GetResult();
}
else
{
doc = table.GetItemAsync(hashKey, rangeKey).GetAwaiter().GetResult();
}
return AuditEvent.FromJson<T>(doc.ToJson());
}
/// <summary>
/// Gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="hashKey">The primary key Hash portion</param>
/// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
/// <param name="cancellationToken">The Cancellation Token.</param>
public async Task<T> GetEventAsync<T>(Primitive hashKey, Primitive rangeKey, CancellationToken cancellationToken = default) where T : AuditEvent
{
var table = GetTable(null);
Document doc;
if (rangeKey == null)
{
doc = await table.GetItemAsync(hashKey, cancellationToken);
}
else
{
doc = await table.GetItemAsync(hashKey, rangeKey, cancellationToken);
}
return AuditEvent.FromJson<T>(doc.ToJson());
}
/// <summary>
/// Gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="hashKey">The primary key Hash portion</param>
/// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
public T GetEvent<T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey) where T : AuditEvent
{
return GetEvent<T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive());
}
/// <summary>
/// Asynchronously gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="hashKey">The primary key Hash portion</param>
/// <param name="rangeKey">The primary key Range portion, if any. Otherwise NULL.</param>
/// <param name="cancellationToken">The Cancellation Token.</param>
public async Task<T> GetEventAsync<T>(DynamoDBEntry hashKey, DynamoDBEntry rangeKey, CancellationToken cancellationToken = default) where T : AuditEvent
{
return await GetEventAsync<T>(hashKey?.AsPrimitive(), rangeKey?.AsPrimitive(), cancellationToken);
}
/// <summary>
/// Gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="eventId">The event ID to retrieve.
/// Must be a Primitive, a DynamoDBEntry or an array of any of these two types. The first (or only) element must be the Hash key, and the second element is the range key.
/// </param>
public override T GetEvent<T>(object eventId)
{
if (eventId == null)
{
return null;
}
if (eventId is Primitive[] keys)
{
return GetEvent<T>(keys[0], keys.Length > 1 ? keys[1] : null);
}
if (eventId is Primitive key)
{
return GetEvent<T>(key, null);
}
if (eventId is DynamoDBEntry[] ekeys)
{
return GetEvent<T>(ekeys[0], ekeys.Length > 1 ? ekeys[1] : null);
}
if (eventId is DynamoDBEntry ekey)
{
return GetEvent<T>(ekey, null);
}
throw new ArgumentException("Parameter must be convertible to Primitive, Primitive[], DynamoDBEntry or DynamoDBEntry[]", "eventId");
}
/// <summary>
/// Asynchronously gets an audit event from its primary key
/// </summary>
/// <typeparam name="T">The audit event type</typeparam>
/// <param name="eventId">The event ID to retrieve.
/// Must be a Primitive, a DynamoDBEntry or an array of any of these two types. The first (or only) element must be the Hash key, and the second element is the range key.
/// </param>
/// <param name="cancellationToken">The cancellation token</param>
public override async Task<T> GetEventAsync<T>(object eventId, CancellationToken cancellationToken = default)
{
if (eventId == null)
{
return null;
}
if (eventId is Primitive[] keys)
{
return await GetEventAsync<T>(keys[0], keys.Length > 1 ? keys[1] : null, cancellationToken);
}
if (eventId is Primitive key)
{
return await GetEventAsync<T>(key, null, cancellationToken);
}
if (eventId is DynamoDBEntry[] ekeys)
{
return await GetEventAsync<T>(ekeys[0], ekeys.Length > 1 ? ekeys[1] : null, cancellationToken);
}
if (eventId is DynamoDBEntry ekey)
{
return await GetEventAsync<T>(ekey, null, cancellationToken);
}
throw new ArgumentException("Parameter must be convertible to Primitive, Primitive[], DynamoDBEntry or DynamoDBEntry[]", "eventId");
}
protected Table GetTable(AuditEvent auditEvent)
{
var tableName = TableName.GetValue(auditEvent) ?? auditEvent?.GetType().Name ?? "AuditEvent";
if (TableCache.TryGetValue(tableName, out Table table))
{
return table;
}
table = Table.LoadTable(Client.Value, tableName);
TableCache[tableName] = table;
return table;
}
private Primitive[] GetKeyValues(Document document, Table table)
{
var keyValues = new List<Primitive>() { document[table.HashKeys[0]].AsPrimitive() };
if (table.RangeKeys.Count > 0)
{
keyValues.Add(document[table.RangeKeys[0]].AsPrimitive());
}
return keyValues.ToArray();
}
protected Document CreateDocument(AuditEvent auditEvent, bool addCustomFields)
{
if (addCustomFields && CustomAttributes != null)
{
foreach (var attrib in CustomAttributes)
{
auditEvent.CustomFields[attrib.Key] = attrib.Value.GetValue(auditEvent);
}
}
return Document.FromJson(auditEvent.ToJson());
}
}
}