TimeBoundedCache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Security
  5. {
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Runtime;
  10. using System.ServiceModel;
  11. using System.ServiceModel.Channels;
  12. using System.Threading;
  13. // NOTE: this class does minimum argument checking as it is all internal
  14. class TimeBoundedCache
  15. {
  16. static Action<object> purgeCallback;
  17. ReaderWriterLock cacheLock;
  18. Hashtable entries;
  19. // if there are less than lowWaterMark entries, no purging is done
  20. int lowWaterMark;
  21. int maxCacheItems;
  22. DateTime nextPurgeTimeUtc;
  23. TimeSpan purgeInterval;
  24. PurgingMode purgingMode;
  25. IOThreadTimer purgingTimer;
  26. bool doRemoveNotification;
  27. protected TimeBoundedCache(int lowWaterMark, int maxCacheItems, IEqualityComparer keyComparer, PurgingMode purgingMode, TimeSpan purgeInterval, bool doRemoveNotification)
  28. {
  29. this.entries = new Hashtable(keyComparer);
  30. this.cacheLock = new ReaderWriterLock();
  31. this.lowWaterMark = lowWaterMark;
  32. this.maxCacheItems = maxCacheItems;
  33. this.purgingMode = purgingMode;
  34. this.purgeInterval = purgeInterval;
  35. this.doRemoveNotification = doRemoveNotification;
  36. this.nextPurgeTimeUtc = DateTime.UtcNow.Add(this.purgeInterval);
  37. }
  38. public int Count
  39. {
  40. get
  41. {
  42. return this.entries.Count;
  43. }
  44. }
  45. static Action<object> PurgeCallback
  46. {
  47. get
  48. {
  49. if (purgeCallback == null)
  50. {
  51. purgeCallback = new Action<object>(PurgeCallbackStatic);
  52. }
  53. return purgeCallback;
  54. }
  55. }
  56. protected int Capacity
  57. {
  58. get
  59. {
  60. return this.maxCacheItems;
  61. }
  62. }
  63. protected Hashtable Entries
  64. {
  65. get
  66. {
  67. return this.entries;
  68. }
  69. }
  70. protected ReaderWriterLock CacheLock
  71. {
  72. get
  73. {
  74. return this.cacheLock;
  75. }
  76. }
  77. protected bool TryAddItem(object key, object item, DateTime expirationTime, bool replaceExistingEntry)
  78. {
  79. return this.TryAddItem(key, new ExpirableItem(item, expirationTime), replaceExistingEntry);
  80. }
  81. void CancelTimerIfNeeded()
  82. {
  83. if (this.Count == 0 && this.purgingTimer != null)
  84. {
  85. this.purgingTimer.Cancel();
  86. this.purgingTimer = null;
  87. }
  88. }
  89. void StartTimerIfNeeded()
  90. {
  91. if (this.purgingMode != PurgingMode.TimerBasedPurge)
  92. {
  93. return;
  94. }
  95. if (this.purgingTimer == null)
  96. {
  97. this.purgingTimer = new IOThreadTimer(PurgeCallback, this, false);
  98. this.purgingTimer.Set(this.purgeInterval);
  99. }
  100. }
  101. protected bool TryAddItem(object key, IExpirableItem item, bool replaceExistingEntry)
  102. {
  103. bool lockHeld = false;
  104. try
  105. {
  106. try { }
  107. finally
  108. {
  109. this.cacheLock.AcquireWriterLock(-1);
  110. lockHeld = true;
  111. }
  112. PurgeIfNeeded();
  113. EnforceQuota();
  114. IExpirableItem currentItem = this.entries[key] as IExpirableItem;
  115. if (currentItem == null || IsExpired(currentItem))
  116. {
  117. this.entries[key] = item;
  118. }
  119. else if (!replaceExistingEntry)
  120. {
  121. return false;
  122. }
  123. else
  124. {
  125. this.entries[key] = item;
  126. }
  127. if (currentItem != null && doRemoveNotification)
  128. {
  129. this.OnRemove(ExtractItem(currentItem));
  130. }
  131. StartTimerIfNeeded();
  132. return true;
  133. }
  134. finally
  135. {
  136. if (lockHeld)
  137. {
  138. this.cacheLock.ReleaseWriterLock();
  139. }
  140. }
  141. }
  142. protected bool TryReplaceItem(object key, object item, DateTime expirationTime)
  143. {
  144. bool lockHeld = false;
  145. try
  146. {
  147. try { }
  148. finally
  149. {
  150. this.cacheLock.AcquireWriterLock(-1);
  151. lockHeld = true;
  152. }
  153. PurgeIfNeeded();
  154. EnforceQuota();
  155. IExpirableItem currentItem = this.entries[key] as IExpirableItem;
  156. if (currentItem == null || IsExpired(currentItem))
  157. {
  158. return false;
  159. }
  160. else
  161. {
  162. this.entries[key] = new ExpirableItem(item, expirationTime);
  163. if (currentItem != null && doRemoveNotification)
  164. {
  165. this.OnRemove(ExtractItem(currentItem));
  166. }
  167. StartTimerIfNeeded();
  168. return true;
  169. }
  170. }
  171. finally
  172. {
  173. if (lockHeld)
  174. {
  175. this.cacheLock.ReleaseWriterLock();
  176. }
  177. }
  178. }
  179. protected void ClearItems()
  180. {
  181. bool lockHeld = false;
  182. try
  183. {
  184. try { }
  185. finally
  186. {
  187. this.cacheLock.AcquireWriterLock(-1);
  188. lockHeld = true;
  189. }
  190. int count = this.entries.Count;
  191. if (doRemoveNotification)
  192. {
  193. foreach (IExpirableItem item in this.entries.Values)
  194. {
  195. OnRemove(ExtractItem(item));
  196. }
  197. }
  198. this.entries.Clear();
  199. CancelTimerIfNeeded();
  200. }
  201. finally
  202. {
  203. if (lockHeld)
  204. {
  205. this.cacheLock.ReleaseWriterLock();
  206. }
  207. }
  208. }
  209. protected object GetItem(object key)
  210. {
  211. bool lockHeld = false;
  212. try
  213. {
  214. try { }
  215. finally
  216. {
  217. this.cacheLock.AcquireReaderLock(-1);
  218. lockHeld = true;
  219. }
  220. IExpirableItem item = this.entries[key] as IExpirableItem;
  221. if (item == null)
  222. {
  223. return null;
  224. }
  225. else if (IsExpired(item))
  226. {
  227. // this is a stale item
  228. return null;
  229. }
  230. else
  231. {
  232. return ExtractItem(item);
  233. }
  234. }
  235. finally
  236. {
  237. if (lockHeld)
  238. {
  239. this.cacheLock.ReleaseReaderLock();
  240. }
  241. }
  242. }
  243. protected virtual ArrayList OnQuotaReached(Hashtable cacheTable)
  244. {
  245. this.ThrowQuotaReachedException();
  246. return null;
  247. }
  248. protected virtual void OnRemove(object item)
  249. {
  250. }
  251. protected bool TryRemoveItem(object key)
  252. {
  253. bool lockHeld = false;
  254. try
  255. {
  256. try { }
  257. finally
  258. {
  259. this.cacheLock.AcquireWriterLock(-1);
  260. lockHeld = true;
  261. }
  262. PurgeIfNeeded();
  263. IExpirableItem currentItem = this.entries[key] as IExpirableItem;
  264. bool result = (currentItem != null) && !IsExpired(currentItem);
  265. if (currentItem != null)
  266. {
  267. this.entries.Remove(key);
  268. if (doRemoveNotification)
  269. {
  270. this.OnRemove(ExtractItem(currentItem));
  271. }
  272. CancelTimerIfNeeded();
  273. }
  274. return result;
  275. }
  276. finally
  277. {
  278. if (lockHeld)
  279. {
  280. this.cacheLock.ReleaseWriterLock();
  281. }
  282. }
  283. }
  284. void EnforceQuota()
  285. {
  286. if (!(this.cacheLock.IsWriterLockHeld == true))
  287. {
  288. // we failfast here because if we don't have the lock we could corrupt the cache
  289. Fx.Assert("Cache write lock is not held.");
  290. DiagnosticUtility.FailFast("Cache write lock is not held.");
  291. }
  292. if (this.Count >= this.maxCacheItems)
  293. {
  294. ArrayList keysToBeRemoved;
  295. keysToBeRemoved = this.OnQuotaReached(this.entries);
  296. if (keysToBeRemoved != null)
  297. {
  298. for (int i = 0; i < keysToBeRemoved.Count; ++i)
  299. {
  300. this.entries.Remove(keysToBeRemoved[i]);
  301. }
  302. }
  303. CancelTimerIfNeeded();
  304. if (this.Count >= this.maxCacheItems)
  305. {
  306. this.ThrowQuotaReachedException();
  307. }
  308. }
  309. }
  310. protected object ExtractItem(IExpirableItem val)
  311. {
  312. ExpirableItem wrapper = (val as ExpirableItem);
  313. if (wrapper != null)
  314. {
  315. return wrapper.Item;
  316. }
  317. else
  318. {
  319. return val;
  320. }
  321. }
  322. bool IsExpired(IExpirableItem item)
  323. {
  324. Fx.Assert(item.ExpirationTime == DateTime.MaxValue || item.ExpirationTime.Kind == DateTimeKind.Utc, "");
  325. return (item.ExpirationTime <= DateTime.UtcNow);
  326. }
  327. bool ShouldPurge()
  328. {
  329. if (this.Count >= this.maxCacheItems)
  330. {
  331. return true;
  332. }
  333. else if (this.purgingMode == PurgingMode.AccessBasedPurge && DateTime.UtcNow > this.nextPurgeTimeUtc && this.Count > this.lowWaterMark)
  334. {
  335. return true;
  336. }
  337. else
  338. {
  339. return false;
  340. }
  341. }
  342. void PurgeIfNeeded()
  343. {
  344. if (!(this.cacheLock.IsWriterLockHeld == true))
  345. {
  346. // we failfast here because if we don't have the lock we could corrupt the cache
  347. Fx.Assert("Cache write lock is not held.");
  348. DiagnosticUtility.FailFast("Cache write lock is not held.");
  349. }
  350. if (ShouldPurge())
  351. {
  352. PurgeStaleItems();
  353. }
  354. }
  355. /// <summary>
  356. /// This method must be called from within a writer lock
  357. /// </summary>
  358. void PurgeStaleItems()
  359. {
  360. if (!(this.cacheLock.IsWriterLockHeld == true))
  361. {
  362. // we failfast here because if we don't have the lock we could corrupt the cache
  363. Fx.Assert("Cache write lock is not held.");
  364. DiagnosticUtility.FailFast("Cache write lock is not held.");
  365. }
  366. ArrayList expiredItems = new ArrayList();
  367. foreach (object key in this.entries.Keys)
  368. {
  369. IExpirableItem item = this.entries[key] as IExpirableItem;
  370. if (IsExpired(item))
  371. {
  372. // this is a stale item. Remove!
  373. this.OnRemove(ExtractItem(item));
  374. expiredItems.Add(key);
  375. }
  376. }
  377. for (int i = 0; i < expiredItems.Count; ++i)
  378. {
  379. this.entries.Remove(expiredItems[i]);
  380. }
  381. CancelTimerIfNeeded();
  382. this.nextPurgeTimeUtc = DateTime.UtcNow.Add(this.purgeInterval);
  383. }
  384. void ThrowQuotaReachedException()
  385. {
  386. string message = SR.GetString(SR.CacheQuotaReached, this.maxCacheItems);
  387. Exception inner = new QuotaExceededException(message);
  388. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
  389. }
  390. static void PurgeCallbackStatic(object state)
  391. {
  392. TimeBoundedCache self = (TimeBoundedCache)state;
  393. bool lockHeld = false;
  394. try
  395. {
  396. try { }
  397. finally
  398. {
  399. self.cacheLock.AcquireWriterLock(-1);
  400. lockHeld = true;
  401. }
  402. if (self.purgingTimer == null)
  403. {
  404. return;
  405. }
  406. self.PurgeStaleItems();
  407. if (self.Count > 0 && self.purgingTimer != null)
  408. {
  409. self.purgingTimer.Set(self.purgeInterval);
  410. }
  411. }
  412. finally
  413. {
  414. if (lockHeld)
  415. {
  416. self.cacheLock.ReleaseWriterLock();
  417. }
  418. }
  419. }
  420. internal interface IExpirableItem
  421. {
  422. DateTime ExpirationTime { get; }
  423. }
  424. internal class ExpirableItemComparer : IComparer<IExpirableItem>
  425. {
  426. static ExpirableItemComparer instance;
  427. public static ExpirableItemComparer Default
  428. {
  429. get
  430. {
  431. if (instance == null)
  432. {
  433. instance = new ExpirableItemComparer();
  434. }
  435. return instance;
  436. }
  437. }
  438. // positive, if item1 will expire before item2.
  439. public int Compare(IExpirableItem item1, IExpirableItem item2)
  440. {
  441. if (ReferenceEquals(item1, item2))
  442. {
  443. return 0;
  444. }
  445. Fx.Assert(item1.ExpirationTime.Kind == item2.ExpirationTime.Kind, "");
  446. if (item1.ExpirationTime < item2.ExpirationTime)
  447. {
  448. return 1;
  449. }
  450. else if (item1.ExpirationTime > item2.ExpirationTime)
  451. {
  452. return -1;
  453. }
  454. else
  455. {
  456. return 0;
  457. }
  458. }
  459. }
  460. internal sealed class ExpirableItem : IExpirableItem
  461. {
  462. DateTime expirationTime;
  463. object item;
  464. public ExpirableItem(object item, DateTime expirationTime)
  465. {
  466. this.item = item;
  467. Fx.Assert( expirationTime == DateTime.MaxValue || expirationTime.Kind == DateTimeKind.Utc, "");
  468. this.expirationTime = expirationTime;
  469. }
  470. public DateTime ExpirationTime { get { return this.expirationTime; } }
  471. public object Item { get { return this.item; } }
  472. }
  473. }
  474. enum PurgingMode
  475. {
  476. TimerBasedPurge,
  477. AccessBasedPurge
  478. }
  479. }