1 /*
2  * Entity - Entity is an object-relational mapping tool for the D programming language. Referring to the design idea of JPA.
3  *
4  * Copyright (C) 2015-2018  Shanghai Putao Technology Co., Ltd
5  *
6  * Developer: HuntLabs.cn
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.entity.eql.EqlCache;
13 
14 import std.array;
15 import std.string;
16 import core.sync.rwmutex;
17 import std.digest.md;
18 import hunt.collection;
19 import hunt.logging;
20 import std.uni;
21 
22 class EqlCacheManager
23 {
24 
25     string get(string eql)
26     {
27         synchronized (_mutex.reader)
28         {
29             auto key = cast(string)toLower(toHexString(md5Of(eql)));
30             // logDebug(" Eql cache try hit eql ( %s , %s ) ".format(eql,key));
31             if(_cacheMap.containsKey(key))
32                 return _cacheMap.get(key);
33             else
34                 return null;
35         }
36 
37     }
38 
39     void put(string eql, string parsedEql)
40     {
41         _mutex.writer.lock();
42         scope (exit)
43             _mutex.writer.unlock();
44 
45         auto key = cast(string)toLower(toHexString(md5Of(eql)));
46         auto isHave = _cacheMap.containsKey(key);
47         if (!isHave)
48         {
49             if(_cacheMap.size() >= MAX_TREE_MAP)
50             {
51                 int cnt = 100;
52                 string[] keys;
53                 foreach(k , v; _cacheMap) {
54                     if(cnt-- > 0)
55                     {
56                         keys ~= k;
57                     }
58                 }
59                 foreach(k; keys)
60                 {
61                     _cacheMap.remove(k);
62                 }
63             }            
64 
65             _cacheMap.put(key , parsedEql);
66             // logDebug(" Eql cache Map ( %s ) ".format(_cacheMap));
67         }
68     }
69 
70 private:
71     this()
72     {
73         _mutex = new ReadWriteMutex();
74         _cacheMap = new HashMap!(string,string)();
75     }
76 
77     ~this()
78     {
79         _mutex.destroy;
80     }
81 
82     HashMap!(string, string) _cacheMap;
83 
84     ReadWriteMutex _mutex;
85 
86     enum MAX_TREE_MAP = 1000;
87 }
88 
89 @property EqlCacheManager eqlCache()
90 {
91     return _eqlcache;
92 }
93 
94 shared static this()
95 {
96     _eqlcache = new EqlCacheManager();
97 }
98 
99 private:
100 __gshared EqlCacheManager _eqlcache;