1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.core.cache;
7 
8 /// Thread-local cache.
9 private ICacheEntry[string] _cache;
10 /// Global cache.
11 private __gshared ICacheEntry[string] _globalCache;
12 
13 /// An interface around a cache entry.
14 private interface ICacheEntry { }
15 
16 /// Wrapper around a cache entry.
17 private class CacheEntry(T) : ICacheEntry
18 {
19   /// The value to be cached.
20   T value;
21 }
22 
23 /**
24 * Adds an entry to the thread-local cache.
25 * Params:
26 *   key =   The key of the entry.
27 *   value = The value to cache.
28 *   cacheTime = The amount of time the value should be cached. (0 = forever)
29 */
30 void addCache(T)(string key, T value, size_t cacheTime = 0)
31 {
32   _cache[key] = new CacheEntry!T(value);
33 
34   if (cacheTime)
35   {
36     import diamond.tasks : executeTask, sleep, msecs;
37 
38     executeTask(
39     {
40       sleep(cacheTime.msecs);
41 
42       removeCache(key);
43     });
44   }
45 }
46 
47 /**
48 * Removes a cached value.
49 * Params:
50 *   key = the key of the cached entry to remove.
51 */
52 void removeCache(string key)
53 {
54   _cache.remove(key);
55 }
56 
57 /**
58 * Gets a value from the cache.
59 * Params:
60 *   key = The key of the value to get.
61 */
62 T getCache(T)(string key)
63 {
64   auto entry = _cache.get(key, null);
65 
66   if (!entry)
67   {
68     return T.init;
69   }
70 
71   return (cast(CacheEntry!T)entry).value;
72 }
73 
74 /// Clears the cache.
75 void clearCache()
76 {
77   _cache.clear();
78 }
79 
80 /**
81 * Adds an entry to the global cache.
82 * Params:
83 *   key =   The key of the entry.
84 *   value = The value to cache.
85 *   cacheTime = The amount of time the value should be cached. (0 = forever)
86 */
87 void addGlobalCache(T)(string key, T value, size_t cacheTime = 0)
88 {
89   _globalCache[key] = new CacheEntry!T(value);
90 
91   if (cacheTime)
92   {
93     import diamond.tasks : executeTask, sleep, msecs;
94 
95     executeTask(
96     {
97       sleep(cacheTime.msecs);
98 
99       removeCache(key);
100     });
101   }
102 }
103 
104 /**
105 * Removes a globally cached value.
106 * Params:
107 *   key = the key of the cached entry to remove.
108 */
109 void removeGlobalCache(string key)
110 {
111   _globalCache.remove(key);
112 }
113 
114 /**
115 * Gets a value from the global cache.
116 * Params:
117 *   key = The key of the value to get.
118 */
119 T getGlobalCache(T)(string key)
120 {
121   auto entry = _globalCache.get(key, null);
122 
123   if (!entry)
124   {
125     return T.init;
126   }
127 
128   return (cast(CacheEntry!T)entry).value;
129 }
130 
131 /// Clears the global cache.
132 void clearGlobalCache()
133 {
134   _globalCache.clear();
135 }