-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathCache.cs
More file actions
176 lines (162 loc) · 5.52 KB
/
Cache.cs
File metadata and controls
176 lines (162 loc) · 5.52 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
using Alachisoft.NCache.Client;
using Alachisoft.NCache.Runtime.Caching;
using IdentityServer4.Services;
using IdentityServer4.Stores.Serialization;
using Microsoft.Extensions.Logging;
using Polly.Wrap;
using System;
using System.Threading.Tasks;
namespace IdentityServer4.NCache.Caching
{
public class Cache<T> : ICache<T> where T:class
{
private readonly string entityType = $"{typeof(T).FullName}";
private readonly CacheHandle _handle;
private readonly IPersistentGrantSerializer _serializer =
new PersistentGrantSerializer();
private readonly ILogger<Cache<T>> _logger;
private readonly bool _debugLoggingEnabled;
private readonly bool _errorLoggingEnabled;
private readonly AsyncPolicyWrap<string> _getFallBack;
private readonly AsyncPolicyWrap<bool> _setFallBack;
public Cache(
CacheHandle handle,
ILogger<Cache<T>> logger)
{
_handle = handle ?? throw new ArgumentNullException(nameof(handle));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_debugLoggingEnabled =
logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug);
_errorLoggingEnabled =
logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Error);
_getFallBack = _handle.getFallBack;
_setFallBack = _handle.setFallBack;
}
public async Task<T> GetAsync(string key)
{
try
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentNullException(nameof(key));
}
var cacheKey = GetKey(key);
string json = await _getFallBack
.ExecuteAsync(async () =>
await Task.Run(
() => _handle.cache.Get<string>(cacheKey))
.ConfigureAwait(false)
)
.ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(json))
{
if (_debugLoggingEnabled)
{
_logger.LogDebug(
"Cache Miss: No item with key {key} in NCache", key);
}
return null;
}
else if (json.Equals(CacheHandle.CACHE_PROBLEMS))
{
if (_errorLoggingEnabled)
{
_logger.LogError(
$"Cache problems when accessing {key}");
}
return null;
}
else
{
if (_debugLoggingEnabled)
{
_logger.LogDebug(
"Cache Hit: Item with key {key} found in NCache", key);
}
return _serializer.Deserialize<T>(json);
}
}
catch (Exception ex)
{
if (_errorLoggingEnabled)
{
_logger.LogError(
ex,
$"Something wrong with GetAsync for key {key}");
}
throw;
}
}
public async Task SetAsync(
string key,
T item,
TimeSpan expiration)
{
var result = await _setFallBack
.ExecuteAsync(async () =>
await SetAsyncInner(key, item, expiration)
.ConfigureAwait(false))
.ConfigureAwait(false);
if (result)
{
if (_debugLoggingEnabled)
{
_logger.LogDebug(
$"Cache insert operation successful for {key}");
}
}
else
{
if (_errorLoggingEnabled)
{
_logger.LogDebug(
$"Caching problems when setting {key}");
}
}
}
private async Task<bool> SetAsyncInner(
string key,
T item,
TimeSpan expiration)
{
try
{
var cacheKey = GetKey(key);
await _handle.cache.InsertAsync(
cacheKey,
new CacheItem(_serializer.Serialize<T>(item))
{
Expiration =
GetExpiration(expiration)
}) ;
return true;
}
catch (Exception ex)
{
if (_errorLoggingEnabled)
{
_logger.LogError(
ex,
$"Something wrong with SetAsync for key {key}");
}
throw;
}
}
private string GetKey(string key)
{
return $"{entityType}:{key.Trim()}";
}
private Expiration GetExpiration(TimeSpan timeSpan)
{
if (_handle.options.Expiration ==
Options.CacheExpirationType.Absolute)
{
return new Expiration(ExpirationType.Absolute, timeSpan);
}
else
{
return new Expiration(ExpirationType.Sliding, timeSpan);
}
}
}
}