-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzureCacheStorage.cs
More file actions
249 lines (215 loc) · 7.79 KB
/
AzureCacheStorage.cs
File metadata and controls
249 lines (215 loc) · 7.79 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
//An IStorage provider for MiniProfiler.
///See https://github.com/joekaiser/MiniProfiler.AzureCacheStorage
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;
using StackExchange.Profiling;
using StackExchange.Profiling.Storage;
/// <summary>
/// Understands how to store a <see cref="MiniProfiler"/> to the distributed Azure Cache with absolute expiration.
/// </summary>
public class AzureCacheStorage : IStorage
{
// FYI: SortedList on uses the comparer for both key lookups and insertion
class ProfileInfo : IComparable<ProfileInfo>
{
public DateTime Started { get; set; }
public Guid Id { get; set; }
public int CompareTo(ProfileInfo other)
{
var comp = Started.CompareTo(other.Started);
if (comp == 0) comp = Id.CompareTo(other.Id);
return comp;
}
}
DataCache Cache = null;
SortedList<ProfileInfo, object> profiles = new SortedList<ProfileInfo, object>();
/// <summary>
/// The string that prefixes all keys that MiniProfilers are saved under, e.g.
/// "mini-profiler-ecfb0050-7ce8-4bf1-bf82-2cb38e90e31e".
/// </summary>
public const string CacheKeyPrefix = "mini-profiler-";
/// <summary>
/// How long to cache each <see cref="MiniProfiler"/> for (i.e. the absolute expiration parameter of
/// <see cref="System.Web.Caching.Cache.Insert(string, object, System.Web.Caching.CacheDependency, System.DateTime, System.TimeSpan, System.Web.Caching.CacheItemUpdateCallback)"/>)
/// </summary>
public TimeSpan CacheDuration { get; set; }
/// <summary>
/// Returns a new AzureCacheStorage class that will cache MiniProfilers for the specified duration.
/// It will use the "default" cache specified in your configuration
/// </summary>
public AzureCacheStorage(TimeSpan cacheDuration)
: this(cacheDuration, "default")
{
}
/// <summary>
/// Returns a new AzureCacheStorage class that will cache MiniProfilers for the specified duration.
/// </summary>
/// <param name="cacheProfileName">Data cache to save profiler information to</param>
public AzureCacheStorage(TimeSpan cacheDuration, string cacheProfileName)
{
CacheDuration = cacheDuration;
Cache = new DataCacheFactory().GetCache(cacheProfileName);
}
/// <summary>
/// Saves <paramref name="profiler"/> to the Azure Cache under a key concated with <see cref="CacheKeyPrefix"/>
/// and the parameter's <see cref="MiniProfiler.Id"/>.
/// </summary>
public void Save(MiniProfiler profiler)
{
InsertIntoCache(GetCacheKey(profiler.Id), profiler);
lock (profiles)
{
var profileInfo = new ProfileInfo { Id = profiler.Id, Started = profiler.Started };
if (profiles.IndexOfKey(profileInfo) < 0)
{
profiles.Add(profileInfo, null);
}
while (profiles.Count > 0)
{
var first = profiles.Keys[0];
if (first.Started < DateTime.UtcNow.Add(-CacheDuration))
{
profiles.RemoveAt(0);
}
else
{
break;
}
}
}
}
/// <summary>
/// remembers we did not view the profile
/// </summary>
public void SetUnviewed(string user, Guid id)
{
var ids = GetPerUserUnviewedIds(user);
lock (ids)
{
if (!ids.Contains(id))
{
ids.Add(id);
}
}
}
/// <summary>
/// Set the profile to viewed for this user
/// </summary>
public void SetViewed(string user, Guid id)
{
var ids = GetPerUserUnviewedIds(user);
lock (ids)
{
ids.Remove(id);
}
}
/// <summary>
/// Returns the saved <see cref="MiniProfiler"/> identified by <paramref name="id"/>. Also marks the resulting
/// profiler <see cref="MiniProfiler.HasUserViewed"/> to true.
/// </summary>
public MiniProfiler Load(Guid id)
{
var result = Cache[GetCacheKey(id)] as MiniProfiler;
return result;
}
/// <summary>
/// Returns a list of <see cref="MiniProfiler.Id"/>s that haven't been seen by <paramref name="user"/>.
/// </summary>
/// <param name="user">User identified by the current <see cref="MiniProfiler.Settings.UserProvider"/>.</param>
public List<Guid> GetUnviewedIds(string user)
{
var ids = GetPerUserUnviewedIds(user);
lock (ids)
{
return new List<Guid>(ids);
}
}
private void InsertIntoCache(string key, object value)
{
Cache.Put(key, value, CacheDuration);
}
private string GetCacheKey(Guid id)
{
return CacheKeyPrefix + id;
}
private string GetPerUserUnviewedCacheKey(string user)
{
return CacheKeyPrefix + "unviewed-for-user-" + user;
}
private List<Guid> GetPerUserUnviewedIds(MiniProfiler profiler)
{
return GetPerUserUnviewedIds(profiler.User);
}
private List<Guid> GetPerUserUnviewedIds(string user)
{
var key = GetPerUserUnviewedCacheKey(user);
var result = Cache[key] as List<Guid>;
if (result == null)
{
lock (AddPerUserUnviewedIdsLock)
{
// check again, as we could have been waiting
result = Cache[key] as List<Guid>;
if (result == null)
{
result = new List<Guid>();
InsertIntoCache(key, result);
}
}
}
return result;
}
public IEnumerable<Guid> List(int maxResults, DateTime? start = null, DateTime? finish = null, ListResultsOrder orderBy = ListResultsOrder.Decending)
{
List<Guid> guids = new List<Guid>();
lock (profiles)
{
int idxStart = 0;
int idxFinish = profiles.Count - 1;
if (start != null) idxStart = BinaryClosestSearch(start.Value);
if (finish != null) idxFinish = BinaryClosestSearch(finish.Value);
if (idxStart < 0) idxStart = 0;
if (idxFinish >= profiles.Count) idxFinish = profiles.Count - 1;
var keys = profiles.Keys;
if (orderBy == ListResultsOrder.Ascending)
{
for (int i = idxStart; i <= idxFinish; i++)
{
guids.Add(keys[i].Id);
if (guids.Count == maxResults) break;
}
}
else
{
for (int i = idxFinish; i >= idxStart; i--)
{
guids.Add(keys[i].Id);
if (guids.Count == maxResults) break;
}
}
}
return guids;
}
private int BinaryClosestSearch(DateTime date)
{
int lower = 0;
int upper = profiles.Count - 1;
while (lower <= upper)
{
int adjustedIndex = lower + ((upper - lower) >> 1);
int comparison = profiles.Keys[adjustedIndex].Started.CompareTo(date);
if (comparison == 0)
return adjustedIndex;
else if (comparison < 0)
lower = adjustedIndex + 1;
else
upper = adjustedIndex - 1;
}
return lower;
}
/// <summary>
/// Syncs access to cache when adding a new list of ids for a user.
/// </summary>
private static readonly object AddPerUserUnviewedIdsLock = new object();
}