forked from aspnet/AspNetSessionState
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInProcSessionStateStoreAsync.cs
593 lines (517 loc) · 19.4 KB
/
InProcSessionStateStoreAsync.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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See the License.txt file in the project root for full license information.
namespace Microsoft.AspNet.SessionState
{
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.Caching;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;
using Resources;
/// <summary>
/// Default in-memory SessionState provider for async SessionState module
/// </summary>
public sealed class InProcSessionStateStoreAsync : SessionStateStoreProviderAsyncBase
{
private const int NewLockCookie = 1;
private static readonly MemoryCache s_store = new MemoryCache("InProcSessionStateStoreAsync");
private CacheEntryRemovedCallback _callback;
private SessionStateItemExpireCallback _expireCallback;
/// <inheritdoc />
public override void Initialize(string name, NameValueCollection config)
{
if(string.IsNullOrEmpty(name))
{
name = "InProc async session state provider";
}
base.Initialize(name, config);
_callback = new CacheEntryRemovedCallback(OnCacheItemRemoved);
}
/// <inheritdoc />
public override SessionStateStoreData CreateNewStoreData(HttpContextBase context, int timeout)
{
return CreateLegitStoreData(context, null, null, timeout);
}
/// <inheritdoc />
public override Task CreateUninitializedItemAsync(
HttpContextBase context,
string id,
int timeout,
CancellationToken cancellationToken)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (id.Length > SessionIDManager.SessionIDMaxLength)
{
throw new ArgumentException(SR.Session_id_too_long);
}
var state = new InProcSessionState(
null,
null,
timeout,
false,
DateTime.MinValue,
NewLockCookie,
(int)SessionStateItemFlags.Uninitialized);
InsertToCache(id, state);
return Task.CompletedTask;
}
/// <inheritdoc />
public override void Dispose()
{
}
/// <inheritdoc />
public override Task EndRequestAsync(HttpContextBase context)
{
return Task.CompletedTask;
}
/// <inheritdoc />
public override Task<GetItemResult> GetItemAsync(HttpContextBase context, string id, CancellationToken cancellationToken)
{
return DoGetAsync(context, id, false);
}
/// <inheritdoc />
public override Task<GetItemResult> GetItemExclusiveAsync(HttpContextBase context, string id,
CancellationToken cancellationToken)
{
return DoGetAsync(context, id, true);
}
/// <inheritdoc />
public override void InitializeRequest(HttpContextBase context)
{
}
/// <inheritdoc />
public override Task ReleaseItemExclusiveAsync(
HttpContextBase context,
string id,
object lockId,
CancellationToken cancellationToken)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (id.Length > SessionIDManager.SessionIDMaxLength)
{
throw new ArgumentException(SR.Session_id_too_long);
}
var lockCookie = (int)lockId;
var state = (InProcSessionState)s_store.Get(id);
if(state != null && state.Locked)
{
bool lockTaken = false;
try
{
state.SpinLock.Enter(ref lockTaken);
if(state.Locked && lockCookie == state.LockCookie)
{
state.Locked = false;
}
}
finally
{
if(lockTaken)
{
state.SpinLock.Exit();
}
}
}
return Task.CompletedTask;
}
/// <inheritdoc />
public override Task RemoveItemAsync(
HttpContextBase context,
string id,
object lockId,
SessionStateStoreData item,
CancellationToken cancellationToken)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (id.Length > SessionIDManager.SessionIDMaxLength)
{
throw new ArgumentException(SR.Session_id_too_long);
}
s_store.Remove(id);
return Task.CompletedTask;
}
/// <inheritdoc />
public override Task ResetItemTimeoutAsync(HttpContextBase context, string id, CancellationToken cancellationToken)
{
s_store.Get(id);
return Task.CompletedTask;
}
/// <inheritdoc />
public override Task SetAndReleaseItemExclusiveAsync(
HttpContextBase context,
string id,
SessionStateStoreData item,
object lockId,
bool newItem,
CancellationToken cancellationToken)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (id.Length > SessionIDManager.SessionIDMaxLength)
{
throw new ArgumentException(SR.Session_id_too_long);
}
Debug.Assert(item != null, "item != null");
Debug.Assert(item.StaticObjects != null, "item.StaticObjects != null");
ISessionStateItemCollection items = null;
HttpStaticObjectsCollection staticObjects = null;
var doInsert = true;
var lockCookieForInsert = NewLockCookie;
if (item.Items.Count > 0)
{
items = item.Items;
}
if(!item.StaticObjects.NeverAccessed)
{
staticObjects = item.StaticObjects;
}
if(!newItem)
{
var currentState = (InProcSessionState)s_store.Get(id);
var lockCookie = (int)lockId;
if(currentState == null)
{
return Task.CompletedTask;
}
var lockTaken = false;
try
{
currentState.SpinLock.Enter(ref lockTaken);
// we can change the state in place if the timeout hasn't changed
if(currentState.Timeout == item.Timeout)
{
currentState.Copy(items, staticObjects, item.Timeout, false, DateTime.MinValue, lockCookie, currentState.Flags);
doInsert = false;
}
else
{
/* We are going to insert a new item to replace the current one in Cache
because the expiry time has changed.
Pleas note that an insert will cause the Session_End to be incorrectly raised.
Please note that the item itself should not expire between now and
where we do MemoryCache.Insert below because MemoryCache.Get above have just
updated its expiry time.
*/
currentState.Flags |= (int)SessionStateItemFlags.IgnoreCacheItemRemoved;
lockCookieForInsert = lockCookie;
}
}
finally
{
if(lockTaken)
{
currentState.SpinLock.Exit();
}
}
}
if (doInsert)
{
var newState = new InProcSessionState(
items,
staticObjects,
item.Timeout,
false,
DateTime.MinValue,
lockCookieForInsert,
0);
InsertToCache(id, newState);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
_expireCallback = expireCallback;
return true;
}
private void OnCacheItemRemoved(CacheEntryRemovedArguments arguments)
{
var state = (InProcSessionState)arguments.CacheItem.Value;
if((state.Flags & (int)SessionStateItemFlags.IgnoreCacheItemRemoved) != 0 ||
(state.Flags & (int)SessionStateItemFlags.Uninitialized) != 0)
{
return;
}
if(_expireCallback != null)
{
var item = CreateLegitStoreData(null, state.SessionItems, state.StaticObjects, state.Timeout);
_expireCallback(arguments.CacheItem.Key, item);
}
}
private Task<GetItemResult> DoGetAsync(HttpContextBase context, string id, bool exclusive)
{
bool locked;
TimeSpan lockAge;
object lockId;
SessionStateActions actionFlags;
var item = DoGet(context, id, exclusive, out locked, out lockAge, out lockId, out actionFlags);
GetItemResult result = new GetItemResult(item, locked, lockAge, lockId, actionFlags);
return Task.FromResult<GetItemResult>(result);
}
private SessionStateStoreData DoGet(HttpContextBase context,
String id,
bool exclusive,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags)
{
// Set default return values
locked = false;
lockId = null;
lockAge = TimeSpan.Zero;
actionFlags = 0;
InProcSessionState state = (InProcSessionState)s_store.Get(id);
if (state != null)
{
bool lockedByOther; // True if the state is locked by another session
int initialFlags;
initialFlags = state.Flags;
if ((initialFlags & (int)SessionStateItemFlags.Uninitialized) != 0)
{
// It is an uninitialized item. We have to remove that flag.
// We only allow one request to do that.
// If initialFlags != return value of CompareExchange, it means another request has
// removed the flag.
if (initialFlags == Interlocked.CompareExchange(
ref state.Flags,
initialFlags & (~((int)SessionStateItemFlags.Uninitialized)),
initialFlags))
{
actionFlags = SessionStateActions.InitializeItem;
}
}
if (exclusive)
{
lockedByOther = true;
// If unlocked, use a spinlock to test and lock the state.
if (!state.Locked)
{
var lockTaken = false;
try
{
state.SpinLock.Enter(ref lockTaken);
if (!state.Locked)
{
lockedByOther = false;
state.Locked = true;
state.LockDate = DateTime.UtcNow;
state.LockCookie++;
}
lockId = state.LockCookie;
}
finally
{
if(lockTaken)
{
state.SpinLock.Exit();
}
}
}
else
{
// It's already locked by another request. Return the lockCookie to caller.
lockId = state.LockCookie;
}
}
else
{
var lockTaken = false;
state.SpinLock.Enter(ref lockTaken);
try
{
lockedByOther = state.Locked;
lockId = state.LockCookie;
}
finally
{
if (lockTaken)
{
state.SpinLock.Exit();
}
}
}
if (lockedByOther)
{
// Item found, but locked
locked = true;
lockAge = DateTime.UtcNow - state.LockDate;
return null;
}
else
{
return CreateLegitStoreData(context, state.SessionItems, state.StaticObjects, state.Timeout);
}
}
// Not found
return null;
}
private void InsertToCache(string key, InProcSessionState value)
{
var cachePolicy = new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(0, value.Timeout, 0),
RemovedCallback = _callback,
Priority = CacheItemPriority.NotRemovable
};
s_store.Set(key, value, cachePolicy);
}
private SessionStateStoreData CreateLegitStoreData(
HttpContextBase context,
ISessionStateItemCollection sessionItems,
HttpStaticObjectsCollection staticObjects,
int timeout)
{
if (sessionItems == null)
{
sessionItems = new ThreadSafeSessionStateItemCollection();
}
if (staticObjects == null && context != null)
{
staticObjects = SessionStateUtility.GetSessionStaticObjects(context.ApplicationInstance.Context);
}
return new SessionStateStoreData(sessionItems, staticObjects, timeout);
}
}
/// <summary>
/// The data structure used to store a session in the memory
/// </summary>
public sealed class InProcSessionState
{
private ISessionStateItemCollection _sessionItems;
private HttpStaticObjectsCollection _staticObjects;
private int _timeout;
/// <summary>
/// Gets session state items
/// </summary>
public ISessionStateItemCollection SessionItems
{
get
{
return _sessionItems;
}
}
/// <summary>
/// Gets a static objects collection
/// </summary>
public HttpStaticObjectsCollection StaticObjects
{
get
{
return _staticObjects;
}
}
/// <summary>
/// Gets timeout of a Session
/// </summary>
public int Timeout
{
get
{
return _timeout;
}
}
/// <summary>
/// Gets or sets if a session is locked
/// </summary>
public bool Locked { get; set; }
/// <summary>
/// Gets or sets the lock date of a session
/// </summary>
public DateTime LockDate { get; set; }
/// <summary>
/// Gets or sets the lock id of a session
/// </summary>
public int LockCookie { get; set; }
/// <summary>
/// The locker of a session
/// </summary>
public SpinLock SpinLock;
/// <summary>
/// SessionStateItem flags
/// </summary>
public int Flags; // Can't use property in Interlocked.CompareExchange
/// <summary>
/// Constructor
/// </summary>
/// <param name="sessionItems">Session state items</param>
/// <param name="staticObjects">A static objects collection</param>
/// <param name="timeout">Timeout of the session</param>
/// <param name="locked">Whether the session is locked or not</param>
/// <param name="utcLockDate">Datetime the session is locked</param>
/// <param name="lockCookie">The lock id of the session</param>
/// <param name="flags">SessionStateItem flags</param>
public InProcSessionState(
ISessionStateItemCollection sessionItems,
HttpStaticObjectsCollection staticObjects,
int timeout,
bool locked,
DateTime utcLockDate,
int lockCookie,
int flags)
{
SpinLock = new SpinLock();
Copy(sessionItems, staticObjects, timeout, locked, utcLockDate, lockCookie, flags);
}
/// <summary>
/// Copy InProcSessionState data to the instance
/// </summary>
/// <param name="sessionItems">Session state items</param>
/// <param name="staticObjects">A static objects collection</param>
/// <param name="timeout">Timeout of the session</param>
/// <param name="locked">Whether the session is locked or not</param>
/// <param name="utcLockDate">Datetime the session is locked</param>
/// <param name="lockCookie">The lock id of the session</param>
/// <param name="flags">SessionStateItem flags</param>
public void Copy(
ISessionStateItemCollection sessionItems,
HttpStaticObjectsCollection staticObjects,
int timeout,
bool locked,
DateTime utcLockDate,
int lockCookie,
int flags)
{
_sessionItems = sessionItems;
_staticObjects = staticObjects;
_timeout = timeout;
Locked = locked;
LockDate = utcLockDate;
LockCookie = lockCookie;
Flags = flags;
}
}
/// <summary>
/// The state of session state item
/// </summary>
[Flags]
public enum SessionStateItemFlags : int
{
/// <summary>
/// No flag
/// </summary>
None = 0x00000000,
/// <summary>
/// Unintialized session state
/// </summary>
Uninitialized = 0x00000001,
/// <summary>
/// Avoid to trigger cache item removed callback due to the sessionstate timeout change
/// </summary>
IgnoreCacheItemRemoved = 0x00000002
}
}