-
Notifications
You must be signed in to change notification settings - Fork 610
Expand file tree
/
Copy pathRedisStorage.cs
More file actions
300 lines (265 loc) · 14.1 KB
/
RedisStorage.cs
File metadata and controls
300 lines (265 loc) · 14.1 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Profiling.Storage.Internal;
using StackExchange.Redis;
namespace StackExchange.Profiling.Storage
{
/// <summary>
/// StackExchange.Redis based storage provider for <see cref="MiniProfiler"/> results.
/// </summary>
public class RedisStorage : IAsyncStorage, IDisposable
{
private readonly ConnectionMultiplexer _multiplexer;
private readonly IDatabase _database;
/// <summary>
/// Gets or sets the key prefix for individual profiling results. Default is "MiniProfiler_Result_".
/// </summary>
public RedisKey ProfilerResultKeyPrefix { get; set; } = "MiniProfiler_Result_";
/// <summary>
/// Gets or sets the list key for the profiling results sorted set. Default is "MiniProfiler_ResultSet".
/// </summary>
public RedisKey ProfilerResultSetKey { get; set; } = "MiniProfiler_ResultSet";
/// <summary>
/// Gets or sets the key prefix for the per-user set of unviewed profiling results. Default is "MiniProfiler_UnviewedResultSet_".
/// </summary>
public RedisKey ProfilerResultUnviewedSetKeyPrefix { get; set; } = "MiniProfiler_UnviewedResultSet_";
/// <summary>
/// Gets or sets how long to cache each <see cref="MiniProfiler"/> for, in absolute terms. Default is 60 minutes.
/// </summary>
public TimeSpan CacheDuration { get; set; } = TimeSpan.FromMinutes(60);
/// <summary>
/// Gets or sets the maximum number of profiling results that will be stored in the profiling list. Default is 100.
/// </summary>
public int ResultListMaxLength { get; set; } = 100;
/// <summary>
/// Initializes a new instance of <see cref="RedisStorage"/> class with the specified Redis <see cref="IDatabase"/>.
/// </summary>
/// <param name="database">The <see cref="IDatabase"/> to use for storage.</param>
public RedisStorage(IDatabase database)
{
_database = database ?? throw new ArgumentNullException(nameof(database));
}
/// <summary>
/// Initializes a new instance of <see cref="RedisStorage"/> class with the specified Redis <see cref="ConnectionMultiplexer"/>.
/// </summary>
/// <param name="multiplexer">The <see cref="ConnectionMultiplexer"/> to use for storage.</param>
public RedisStorage(ConnectionMultiplexer multiplexer) : this (multiplexer.GetDatabase())
{
_multiplexer = multiplexer ?? throw new ArgumentNullException(nameof(multiplexer));
}
/// <summary>
/// Initializes a new instance of <see cref="RedisStorage"/> class with the specified <see cref="ConfigurationOptions"/>.
/// </summary>
/// <param name="options">Configuration options for the Redis connection.</param>
public RedisStorage(ConfigurationOptions options) : this(ConnectionMultiplexer.Connect(options ?? throw new ArgumentNullException(nameof(options)))) { }
/// <summary>
/// Initializes a new instance of <see cref="RedisStorage"/> class with the specified connection string.
/// For available options, see https://stackexchange.github.io/StackExchange.Redis/Configuration#configuration-options
/// </summary>
/// <param name="configuration">Connection string for the Redis connection.</param>
public RedisStorage(string configuration) : this (ConnectionMultiplexer.Connect(configuration ?? throw new ArgumentNullException(nameof(configuration)))) { }
/// <summary>
/// List the latest profiling results.
/// </summary>
/// <param name="maxResults">The maximum number of results to return.</param>
/// <param name="start">(Optional) The start of the date range to fetch.</param>
/// <param name="finish">(Optional) The end of the date range to fetch.</param>
/// <param name="orderBy">(Optional) The order to fetch profiler IDs in.</param>
public IEnumerable<Guid> List(
int maxResults,
DateTime? start = null,
DateTime? finish = null,
ListResultsOrder orderBy = ListResultsOrder.Descending)
{
var redisOrder = orderBy == ListResultsOrder.Ascending ? Order.Ascending : Order.Descending;
double startScore = start.HasValue ? ToEpoch(start.Value) : double.NegativeInfinity;
double finishScore = finish.HasValue ? ToEpoch(finish.Value) : double.PositiveInfinity;
return _database.SortedSetRangeByScore(ProfilerResultSetKey, startScore, finishScore, order: redisOrder, take: maxResults)
.Select(x => Guid.Parse(x));
}
/// <summary>
/// Stores <paramref name="profiler"/> under its <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="profiler">The <see cref="MiniProfiler"/> to save.</param>
/// <remarks>
/// Should also ensure the profiler is stored as being unviewed by its profiling <see cref="MiniProfiler.User"/>.
/// </remarks>
public void Save(MiniProfiler profiler)
{
var id = profiler.Id.ToString();
RedisKey key = ProfilerResultKeyPrefix.Append(id);
RedisValue value = profiler.ToRedisValue();
_database.StringSet(key, value, expiry: CacheDuration);
var score = ToEpoch(profiler.Started);
_database.SortedSetAdd(ProfilerResultSetKey, id, score);
_database.SortedSetRemoveRangeByRank(ProfilerResultSetKey, 0, -1 - 1 - ResultListMaxLength);
_database.KeyExpire(ProfilerResultSetKey, CacheDuration);
if (!profiler.HasUserViewed)
{
SetUnviewed(profiler.User, profiler.Id);
}
}
/// <summary>
/// Returns a <see cref="MiniProfiler"/> from storage based on <paramref name="id"/>,
/// which should map to <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="id">The profiler ID to load.</param>
/// <returns>The loaded <see cref="MiniProfiler"/>.</returns>
/// <remarks>
/// Should also update that the resulting profiler has been marked as viewed by its
/// profiling <see cref="MiniProfiler.User"/>.
/// </remarks>
public MiniProfiler Load(Guid id)
{
RedisKey key = ProfilerResultKeyPrefix.Append(id.ToString());
RedisValue value = _database.StringGet(key);
return value.ToMiniProfiler();
}
/// <summary>
/// Sets a particular profiler session so it is considered "unviewed"
/// </summary>
/// <param name="user">The user to set this profiler ID as unviewed for.</param>
/// <param name="id">The profiler ID to set unviewed.</param>
public void SetUnviewed(string user, Guid id)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
RedisValue value = id.ToString();
_database.SetAdd(key, value);
_database.KeyExpire(key, CacheDuration);
}
/// <summary>
/// Sets a particular profiler session to "viewed"
/// </summary>
/// <param name="user">The user to set this profiler ID as viewed for.</param>
/// <param name="id">The profiler ID to set viewed.</param>
public void SetViewed(string user, Guid id)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
RedisValue value = id.ToString();
_database.SetRemove(key, value);
}
/// <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 <c>MiniProfilerOptions.UserProvider</c></param>
public List<Guid> GetUnviewedIds(string user)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
var ids = _database.SetMembers(key);
return ids.Select(x => Guid.Parse(x)).ToList();
}
/// <summary>
/// Asynchronously list the latest profiling results.
/// </summary>
/// <param name="maxResults">The maximum number of results to return.</param>
/// <param name="start">(Optional) The start of the date range to fetch.</param>
/// <param name="finish">(Optional) The end of the date range to fetch.</param>
/// <param name="orderBy">(Optional) The order to fetch profiler IDs in.</param>
public async Task<IEnumerable<Guid>> ListAsync(
int maxResults,
DateTime? start = null,
DateTime? finish = null,
ListResultsOrder orderBy = ListResultsOrder.Descending)
{
var redisOrder = orderBy == ListResultsOrder.Ascending ? Order.Ascending : Order.Descending;
double startScore = start.HasValue ? ToEpoch(start.Value) : double.NegativeInfinity;
double finishScore = finish.HasValue ? ToEpoch(finish.Value) : double.PositiveInfinity;
var ids = await _database.SortedSetRangeByScoreAsync(ProfilerResultSetKey, startScore, finishScore, order: redisOrder, take: maxResults).ConfigureAwait(false);
return ids.Select(x => Guid.Parse(x));
}
/// <summary>
/// Asynchronously stores <paramref name="profiler"/> under its <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="profiler">The <see cref="MiniProfiler"/> to save.</param>
/// <remarks>
/// Should also ensure the profiler is stored as being unviewed by its profiling <see cref="MiniProfiler.User"/>.
/// </remarks>
public async Task SaveAsync(MiniProfiler profiler)
{
var id = profiler.Id.ToString();
RedisKey key = ProfilerResultKeyPrefix.Append(id);
RedisValue value = profiler.ToRedisValue();
await _database.StringSetAsync(key, value, expiry: CacheDuration).ConfigureAwait(false);
var score = ToEpoch(profiler.Started);
await _database.SortedSetAddAsync(ProfilerResultSetKey, id, score).ConfigureAwait(false);
await _database.SortedSetRemoveRangeByRankAsync(ProfilerResultSetKey, 0, -1 - 1 - ResultListMaxLength).ConfigureAwait(false);
await _database.KeyExpireAsync(ProfilerResultSetKey, CacheDuration).ConfigureAwait(false);
if (!profiler.HasUserViewed)
{
await SetUnviewedAsync(profiler.User, profiler.Id).ConfigureAwait(false);
}
}
/// <summary>
/// Asynchronously returns a <see cref="MiniProfiler"/> from storage based on <paramref name="id"/>,
/// which should map to <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="id">The profiler ID to load.</param>
/// <returns>The loaded <see cref="MiniProfiler"/>.</returns>
/// <remarks>
/// Should also update that the resulting profiler has been marked as viewed by its
/// profiling <see cref="MiniProfiler.User"/>.
/// </remarks>
public async Task<MiniProfiler> LoadAsync(Guid id)
{
RedisKey key = ProfilerResultKeyPrefix.Append(id.ToString());
RedisValue value = await _database.StringGetAsync(key).ConfigureAwait(false);
return value.ToMiniProfiler();
}
/// <summary>
/// Asynchronously sets a particular profiler session so it is considered "unviewed"
/// </summary>
/// <param name="user">The user to set this profiler ID as unviewed for.</param>
/// <param name="id">The profiler ID to set unviewed.</param>
public async Task SetUnviewedAsync(string user, Guid id)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
RedisValue value = id.ToString();
await _database.SetAddAsync(key, value).ConfigureAwait(false);
await _database.KeyExpireAsync(key, CacheDuration).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously sets a particular profiler session to "viewed"
/// </summary>
/// <param name="user">The user to set this profiler ID as viewed for.</param>
/// <param name="id">The profiler ID to set viewed.</param>
public Task SetViewedAsync(string user, Guid id)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
RedisValue value = id.ToString();
return _database.SetRemoveAsync(key, value);
}
/// <summary>
/// Asynchronously sets the provided profiler sessions to "viewed"
/// </summary>
/// <param name="user">The user to set this profiler ID as viewed for.</param>
/// <param name="ids">The profiler IDs to set viewed.</param>
public async Task SetViewedAsync(string user, IEnumerable<Guid> ids)
{
foreach (var id in ids)
{
await this.SetViewedAsync(user, id).ConfigureAwait(false);
}
}
/// <summary>
/// Asynchronously 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 <c>MiniProfilerOptions.UserProvider</c></param>
public async Task<List<Guid>> GetUnviewedIdsAsync(string user)
{
RedisKey key = ProfilerResultUnviewedSetKeyPrefix.Append(user ?? "");
var ids = await _database.SetMembersAsync(key).ConfigureAwait(false);
return ids.Select(x => Guid.Parse(x)).ToList();
}
private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static double ToEpoch(DateTime date) => Convert.ToInt64((date - _epoch).TotalSeconds);
/// <summary>
/// Disposes the multiplexer, if present.
/// </summary>
public void Dispose()
{
_multiplexer?.Dispose();
}
}
}