-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathDynamoDbCacheClient.cs
441 lines (399 loc) · 15.8 KB
/
DynamoDbCacheClient.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
using System;
using System.Collections.Generic;
using System.Globalization;
using Amazon;
using Amazon.DynamoDB;
using Amazon.DynamoDB.DocumentModel;
using Amazon.DynamoDB.Model;
using ServiceStack.Logging;
namespace ServiceStack.Caching.AwsDynamoDb
{
public class DynamoDbCacheClient : ICacheClient
{
private static readonly ILog Log = LogManager.GetLogger(typeof(DynamoDbCacheClient));
private AmazonDynamoDBClient _client;
private Table _awsCacheTableObj;
private string _cacheTableName;
private int _cacheReadCapacity = 10; // free-tier settings
private int _cacheWriteCapacity = 5; // free-tier settings
private readonly bool _cacheTableCreate;
private const string KeyName = "urn";
private const string ValueName = "value";
private const string ExpiresAtName = "expiresAt";
/// <summary>
/// AWS Access Key ID
/// </summary>
public string AwsAccessKey { get; set; }
/// <summary>
/// The name of the DynamoDB Table - either make sure it is already created with HashKey string named "urn" or pass true into constructor createTableIfMissing argument
/// </summary>
public string CacheTableName
{
get { return _cacheTableName; }
set { _cacheTableName = value; }
}
/// <summary>
/// AWS Secret Key ID
/// </summary>
public string AwsSecretKey { get; set; }
/// <summary>
/// AWS Region where the DynamoDB Table is stored
/// </summary>
public RegionEndpoint AwsRegion { get; set; }
/// <summary>
/// If the client needs to delete/re-create the DynamoDB table, this is the Read Capacity to use
/// </summary>
public int CacheReadCapacity
{
get { return _cacheReadCapacity; }
set { _cacheReadCapacity = value; }
}
/// <summary>
/// If the client needs to delete/re-create the DynamoDB table, this is the Write Capacity to use
/// </summary>
public int CacheWriteCapacity
{
get { return _cacheWriteCapacity; }
set { _cacheWriteCapacity = value; }
}
/// <summary>
/// DynamoDbCacheClient constructor
/// </summary>
/// <param name="awsAccessKey">AWS Access Key ID</param>
/// <param name="awsSecretKey">AWS Secret Key ID</param>
/// <param name="region">AWS Region</param>
/// <param name="cacheTableName">Name of DynamoDB Table</param>
/// <param name="readCapacity">Desired DynamoDB Read Capacity</param>
/// <param name="writeCapacity">Desired DynamoDB Write Capacity</param>
/// <param name="createTableIfMissing">Pass true if you'd like the client to create the DynamoDB table on startup</param>
public DynamoDbCacheClient(string awsAccessKey, string awsSecretKey, RegionEndpoint region,
string cacheTableName = "ICacheClientDynamo", int readCapacity = 10,
int writeCapacity = 5, bool createTableIfMissing = false)
{
CacheTableName = cacheTableName;
AwsAccessKey = awsAccessKey;
AwsSecretKey = awsSecretKey;
AwsRegion = region;
CacheReadCapacity = readCapacity;
CacheWriteCapacity = writeCapacity;
_cacheTableCreate = createTableIfMissing;
Init();
}
private void Init()
{
if (String.IsNullOrEmpty(CacheTableName))
{
throw new MissingFieldException("DynamoCacheClient", "_cacheTableName");
}
if (String.IsNullOrEmpty(AwsAccessKey))
{
throw new MissingFieldException("DynamoCacheClient", "_awsAccessKey");
}
_client = new AmazonDynamoDBClient(AwsAccessKey, AwsSecretKey, AwsRegion);
Log.Info("Successfully created AmazonDynamoDBClient");
if (_cacheTableCreate) CreateDynamoCacheTable();
}
private void CreateDynamoCacheTable()
{
if (String.IsNullOrEmpty(AwsSecretKey))
{
throw new MissingFieldException("DynamoCacheClient", "_awsSecretKey");
}
Log.InfoFormat("Attempting to load DynamoDB table {0}", _cacheTableName);
if (!Table.TryLoadTable(_client, CacheTableName, out _awsCacheTableObj))
{
Log.InfoFormat("DynamoDB table {0} does not exist, attempting to create", _cacheTableName);
try
{
_client.CreateTable(new CreateTableRequest
{
TableName = CacheTableName,
KeySchema = new KeySchema
{
HashKeyElement = new KeySchemaElement
{
AttributeName = KeyName,
AttributeType = "S"
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = CacheReadCapacity,
WriteCapacityUnits = CacheWriteCapacity,
}
});
Log.InfoFormat("Successfully created DynamoDB table {0}", _cacheTableName);
WaitUntilTableReady(_cacheTableName);
}
catch (Exception)
{
Log.ErrorFormat("Could not create DynamoDB table {0}", _cacheTableName);
throw;
}
}
}
private void WaitUntilTableDeleted(string tableName)
{
string status;
DateTime startWaitTime = DateTime.Now;
// Let us wait until table is created. Call DescribeTable.
do
{
System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
try
{
var res = _client.DescribeTable(new DescribeTableRequest
{
TableName = tableName
});
Log.InfoFormat("Table name: {0}, status: {1}",
res.DescribeTableResult.Table.TableName,
res.DescribeTableResult.Table.TableStatus);
status = res.DescribeTableResult.Table.TableStatus;
if (DateTime.Now.Subtract(startWaitTime).Seconds > 60)
{
throw new Exception(
"Waiting for too long for DynamoDB table to be deleted, please check your AWS Console");
}
}
catch (ResourceNotFoundException)
{
// When the resource is reported as not found, it's deleted so break out of the loop
break;
}
} while (status == "DELETING");
}
private void WaitUntilTableReady(string tableName)
{
string status = null;
DateTime startWaitTime = DateTime.Now;
// Let us wait until table is created. Call DescribeTable.
do
{
System.Threading.Thread.Sleep(5000); // Wait 5 seconds.
try
{
var res = _client.DescribeTable(new DescribeTableRequest
{
TableName = tableName
});
Log.InfoFormat("Table name: {0}, status: {1}",
res.DescribeTableResult.Table.TableName,
res.DescribeTableResult.Table.TableStatus);
status = res.DescribeTableResult.Table.TableStatus;
if (DateTime.Now.Subtract(startWaitTime).Seconds > 60)
{
throw new Exception(
"Waiting for too long for DynamoDB table to be created, please check your AWS Console");
}
}
catch (ResourceNotFoundException)
{
// DescribeTable is eventually consistent. So you might
// get resource not found. So we handle the potential exception.
}
} while (status != "ACTIVE");
}
private bool TryGetValue<T>(string key, out T entry)
{
Log.InfoFormat("Attempting cache get of key: {0}", key);
entry = default(T);
var response = _client.GetItem(
new GetItemRequest
{
TableName = CacheTableName,
Key = new Key { HashKeyElement = new AttributeValue { S = key } }
}
);
var item = response.GetItemResult.Item;
if (item != null)
{
DateTime expiresAt = Convert.ToDateTime(item[ExpiresAtName].S);
if (DateTime.UtcNow > expiresAt)
{
Log.InfoFormat("Cache key: {0} has expired, removing from cache!", key);
Remove(key);
return false;
}
string jsonData = item[ValueName].S;
entry = jsonData.FromJson<T>();
Log.InfoFormat("Cache hit on key: {0}", key);
return true;
}
return false;
}
private bool CacheAdd<T>(string key, T value, DateTime expiresAt)
{
T entry;
if (TryGetValue(key, out entry)) return false;
CacheSet(key, value, expiresAt);
return true;
}
private bool CacheSet<T>(string key, T value, DateTime expiresAt)
{
try
{
_client.PutItem(
new PutItemRequest
{
TableName = CacheTableName,
Item = new Dictionary<string, AttributeValue>
{
{ KeyName, new AttributeValue {S = key } },
{ ValueName, new AttributeValue {S = value.ToJson()} },
{
ExpiresAtName,
new AttributeValue {S = expiresAt.ToUniversalTime().ToString(CultureInfo.InvariantCulture)}
}
}
}
);
return true;
}
catch
{
return false;
}
}
private int UpdateCounter(string key, int value)
{
var response = _client.UpdateItem(new UpdateItemRequest
{
TableName = CacheTableName,
Key = new Key { HashKeyElement = new AttributeValue { S = key } },
AttributeUpdates = new Dictionary<string, AttributeValueUpdate>
{
{
ValueName,
new AttributeValueUpdate
{
Action = "ADD",
Value = new AttributeValue
{
N =value.ToString(CultureInfo.InvariantCulture)
}
}
}
},
ReturnValues = "ALL_NEW"
});
return Convert.ToInt32(response.UpdateItemResult.Attributes[ValueName].N);
}
public bool Add<T>(string key, T value, TimeSpan expiresIn)
{
return CacheAdd(key, value, DateTime.UtcNow.Add(expiresIn));
}
public bool Add<T>(string key, T value, DateTime expiresAt)
{
return CacheAdd(key, value, expiresAt.ToUniversalTime());
}
public bool Add<T>(string key, T value)
{
return CacheAdd(key, value, DateTime.MaxValue.ToUniversalTime());
}
public long Decrement(string key, uint amount)
{
return UpdateCounter(key, (int)-amount);
}
/// <summary>
/// IMPORTANT: This method will delete and re-create the DynamoDB table in order to reduce read/write capacity costs, make sure the proper table name and throughput properties are set!
/// TODO: This method may take upwards of a minute to complete, need to look into a faster implementation
/// </summary>
public void FlushAll()
{
// Is this the cheapest method per AWS pricing to clear a table? (instead of table scan / remove each item) ??
_client.DeleteTable(new DeleteTableRequest { TableName = CacheTableName });
// Scaning the table is limited to 1 MB chunks, with a large cache it could result in many Read requests and many Delete requests occurring very quickly which may tap out
// the throughput capacity...
WaitUntilTableDeleted(_cacheTableName);
CreateDynamoCacheTable();
}
public T Get<T>(string key)
{
T value;
return TryGetValue(key, out value) ? value : default(T);
}
public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
{
var valueMap = new Dictionary<string, T>();
foreach (var key in keys)
{
var value = Get<T>(key);
valueMap[key] = value;
}
return valueMap;
}
public long Increment(string key, uint amount)
{
return UpdateCounter(key, (int)amount);
}
public bool Remove(string key)
{
try
{
_client.DeleteItem(new DeleteItemRequest
{
TableName = CacheTableName,
Key = new Key { HashKeyElement = new AttributeValue { S = key } }
});
return true;
}
catch
{
return false;
}
}
public void RemoveAll(IEnumerable<string> keys)
{
foreach (var key in keys)
{
try
{
Remove(key);
}
catch (Exception ex)
{
Log.Error(string.Format("Error trying to remove {0} from the cache", key), ex);
}
}
}
public bool Replace<T>(string key, T value, TimeSpan expiresIn)
{
return Set(key, value, DateTime.UtcNow.Add(expiresIn));
}
public bool Replace<T>(string key, T value, DateTime expiresAt)
{
return Set(key, value, expiresAt.ToUniversalTime());
}
public bool Replace<T>(string key, T value)
{
return Set(key, value, DateTime.MaxValue.ToUniversalTime());
}
public bool Set<T>(string key, T value, TimeSpan expiresIn)
{
return CacheSet(key, value, DateTime.UtcNow.Add(expiresIn));
}
public bool Set<T>(string key, T value, DateTime expiresAt)
{
return CacheSet(key, value, expiresAt.ToUniversalTime());
}
public bool Set<T>(string key, T value)
{
return CacheSet(key, value, DateTime.MaxValue.ToUniversalTime());
}
public void SetAll<T>(IDictionary<string, T> values)
{
foreach (var entry in values)
{
Set(entry.Key, entry.Value);
}
}
public void Dispose()
{
if (_client != null)
{
_client.Dispose();
}
}
}
}