forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrmLiteCacheClient.cs
More file actions
473 lines (412 loc) · 13.8 KB
/
OrmLiteCacheClient.cs
File metadata and controls
473 lines (412 loc) · 13.8 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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ServiceStack.Auth;
using ServiceStack.Data;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
using ServiceStack.Text;
namespace ServiceStack.Caching
{
public class OrmLiteCacheClient : ICacheClient, IRequiresSchema, ICacheClientExtended, IRemoveByPattern
{
CacheEntry CreateEntry(string id, string data = null,
DateTime? created = null, DateTime? expires = null)
{
var createdDate = created ?? DateTime.UtcNow;
return new CacheEntry
{
Id = id,
Data = data,
ExpiryDate = expires,
CreatedDate = createdDate,
ModifiedDate = createdDate,
};
}
public IDbConnectionFactory DbFactory { get; set; }
public T Exec<T>(Func<IDbConnection, T> action)
{
using (JsConfig.With(excludeTypeInfo: false))
using (var db = DbFactory.Open())
{
return action(db);
}
}
public void Exec(Action<IDbConnection> action)
{
using (JsConfig.With(excludeTypeInfo: false))
using (var db = DbFactory.Open())
{
action(db);
}
}
public bool Remove(string key)
{
return Exec(db => db.DeleteById<CacheEntry>(key) > 0);
}
public void RemoveAll(IEnumerable<string> keys)
{
Exec(db => db.DeleteByIds<CacheEntry>(keys) > 0);
}
public T Get<T>(string key)
{
return Exec(db =>
{
var cache = Verify(db, db.SingleById<CacheEntry>(key));
return cache == null
? default(T)
: db.Deserialize<T>(cache.Data);
});
}
public long Increment(string key, uint amount)
{
return Exec(db =>
{
long nextVal;
using (var dbTrans = db.OpenTransaction(IsolationLevel.ReadCommitted))
{
var cache = Verify(db, db.SingleById<CacheEntry>(key));
if (cache == null)
{
nextVal = amount;
db.Insert(CreateEntry(key, nextVal.ToString()));
}
else
{
nextVal = long.Parse(cache.Data) + amount;
cache.Data = nextVal.ToString();
db.Update(cache);
}
dbTrans.Commit();
}
return nextVal;
});
}
public long Decrement(string key, uint amount)
{
return Exec(db =>
{
long nextVal;
using (var dbTrans = db.OpenTransaction(IsolationLevel.ReadCommitted))
{
var cache = Verify(db, db.SingleById<CacheEntry>(key));
if (cache == null)
{
nextVal = -amount;
db.Insert(CreateEntry(key, nextVal.ToString()));
}
else
{
nextVal = long.Parse(cache.Data) - amount;
cache.Data = nextVal.ToString();
db.Update(cache);
}
dbTrans.Commit();
}
return nextVal;
});
}
public bool Add<T>(string key, T value)
{
try
{
Exec(db =>
{
db.Insert(CreateEntry(key, db.Serialize(value)));
});
return true;
}
catch (Exception)
{
return false;
}
}
private static bool UpdateIfExists<T>(IDbConnection db, string key, T value)
{
var exists = db.UpdateOnly(new CacheEntry
{
Id = key,
Data = db.Serialize(value),
ModifiedDate = DateTime.UtcNow,
},
onlyFields: q => new { q.Data, q.ModifiedDate },
@where: q => q.Id == key) == 1;
return exists;
}
private static bool UpdateIfExists<T>(IDbConnection db, string key, T value, DateTime expiresAt)
{
var exists = db.UpdateOnly(new CacheEntry
{
Id = key,
Data = db.Serialize(value),
ExpiryDate = expiresAt,
ModifiedDate = DateTime.UtcNow,
},
onlyFields: q => new { q.Data, ExpiredDate = q.ExpiryDate, q.ModifiedDate },
@where: q => q.Id == key) == 1;
return exists;
}
public bool Set<T>(string key, T value)
{
return Exec(db =>
{
var exists = UpdateIfExists(db, key, value);
if (!exists)
{
try
{
db.Insert(CreateEntry(key, db.Serialize(value)));
}
catch (Exception)
{
exists = UpdateIfExists(db, key, value);
if (!exists) throw;
}
}
return true;
});
}
public bool Replace<T>(string key, T value)
{
return Exec(db =>
{
var exists = db.UpdateOnly(new CacheEntry
{
Id = key,
Data = db.Serialize(value),
ModifiedDate = DateTime.UtcNow,
},
onlyFields: q => new { q.Data, q.ModifiedDate },
where: q => q.Id == key) == 1;
if (!exists)
{
db.Insert(CreateEntry(key, db.Serialize(value)));
}
return true;
});
}
public bool Add<T>(string key, T value, DateTime expiresAt)
{
try
{
Exec(db =>
{
db.Insert(CreateEntry(key, db.Serialize(value), expires: expiresAt));
});
return true;
}
catch (Exception)
{
return false;
}
}
public bool Set<T>(string key, T value, DateTime expiresAt)
{
return Exec(db =>
{
var exists = UpdateIfExists(db, key, value, expiresAt);
if (!exists)
{
try
{
db.Insert(CreateEntry(key, db.Serialize(value), expires: expiresAt));
}
catch (Exception)
{
exists = UpdateIfExists(db, key, value, expiresAt);
if (!exists) throw;
}
}
return true;
});
}
public bool Replace<T>(string key, T value, DateTime expiresAt)
{
return Exec(db =>
{
var exists = db.UpdateOnly(new CacheEntry
{
Id = key,
Data = db.Serialize(value),
ExpiryDate = expiresAt,
ModifiedDate = DateTime.UtcNow,
},
onlyFields: q => new { q.Data, ExpiredDate = q.ExpiryDate, q.ModifiedDate },
where: q => q.Id == key) == 1;
if (!exists)
{
db.Insert(CreateEntry(key, db.Serialize(value), expires: expiresAt));
}
return true;
});
}
public bool Add<T>(string key, T value, TimeSpan expiresIn)
{
try
{
Exec(db =>
{
db.Insert(CreateEntry(key, db.Serialize(value),
expires: DateTime.UtcNow.Add(expiresIn)));
});
return true;
}
catch (Exception)
{
return false;
}
}
public bool Set<T>(string key, T value, TimeSpan expiresIn)
{
return Exec(db =>
{
var exists = UpdateIfExists(db, key, value, DateTime.UtcNow.Add(expiresIn));
if (!exists)
{
try
{
db.Insert(CreateEntry(key, db.Serialize(value), expires: DateTime.UtcNow.Add(expiresIn)));
}
catch (Exception)
{
exists = UpdateIfExists(db, key, value, DateTime.UtcNow.Add(expiresIn));
if (!exists) throw;
}
}
return true;
});
}
public bool Replace<T>(string key, T value, TimeSpan expiresIn)
{
return Exec(db =>
{
var exists = db.UpdateOnly(new CacheEntry
{
Id = key,
Data = db.Serialize(value),
ExpiryDate = DateTime.UtcNow.Add(expiresIn),
ModifiedDate = DateTime.UtcNow,
},
onlyFields: q => new { q.Data, ExpiredDate = q.ExpiryDate, q.ModifiedDate },
where: q => q.Id == key) == 1;
if (!exists)
{
db.Insert(CreateEntry(key, db.Serialize(value), expires: DateTime.UtcNow.Add(expiresIn)));
}
return true;
});
}
public void FlushAll()
{
Exec(db =>
{
db.DeleteAll<CacheEntry>();
});
}
public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
{
return Exec(db =>
{
var results = Verify(db, db.SelectByIds<CacheEntry>(keys));
var map = new Dictionary<string, T>();
results.Each(x =>
map[x.Id] = db.Deserialize<T>(x.Data));
foreach (var key in keys)
{
if (!map.ContainsKey(key))
map[key] = default(T);
}
return map;
});
}
public void SetAll<T>(IDictionary<string, T> values)
{
Exec(db =>
{
var rows = values.Select(entry =>
CreateEntry(entry.Key, db.Serialize(entry.Value)))
.ToList();
db.InsertAll(rows);
});
}
public void InitSchema()
{
Exec(db => db.CreateTableIfNotExists<CacheEntry>());
}
public List<CacheEntry> Verify(IDbConnection db, IEnumerable<CacheEntry> entries)
{
var results = entries.ToList();
var expired = results.RemoveAll(x => x.ExpiryDate != null && DateTime.UtcNow > x.ExpiryDate);
if (expired > 0)
{
db.Delete<CacheEntry>(q => DateTime.UtcNow > q.ExpiryDate);
}
return results;
}
public CacheEntry Verify(IDbConnection db, CacheEntry entry)
{
if (entry != null &&
entry.ExpiryDate != null && DateTime.UtcNow > entry.ExpiryDate)
{
db.Delete<CacheEntry>(q => DateTime.UtcNow > q.ExpiryDate);
return null;
}
return entry;
}
public TimeSpan? GetTimeToLive(string key)
{
return Exec(db =>
{
var cache = db.SingleById<CacheEntry>(key);
if (cache == null)
return null;
if (cache.ExpiryDate == null)
return TimeSpan.MaxValue;
return cache.ExpiryDate - DateTime.UtcNow;
});
}
public void RemoveByPattern(string pattern)
{
Exec(db => {
var dbPattern = pattern.Replace('*', '%');
db.DeleteFmt<CacheEntry>(db.GetDialectProvider().GetQuotedColumnName("Id") + " LIKE {0}", dbPattern);
});
}
public void RemoveByRegex(string regex)
{
throw new NotImplementedException();
}
public void Dispose() { }
}
public class CacheEntry
{
public string Id { get; set; }
[StringLength(StringLengthAttribute.MaxText)]
public string Data { get; set; }
public DateTime? ExpiryDate { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
public static class CacheExtensions
{
public static void InitSchema(this ICacheClient cache)
{
var requiresSchema = cache as IRequiresSchema;
if (requiresSchema != null)
{
requiresSchema.InitSchema();
}
}
public static string Serialize<T>(this IDbConnection db, T value)
{
return db.GetDialectProvider().StringSerializer.SerializeToString(value);
}
public static T Deserialize<T>(this IDbConnection db, string text)
{
return text == null
? default(T)
: db.GetDialectProvider().StringSerializer.DeserializeFromString<T>(text);
}
}
}