Rename state to app and furhter cleanups
[pstop.git] / key_value_cache / key_value_cache.go
1 // key_value_cache provides an extremely simple string key to value cache.
2 // This is used to reduce the number of lookups from MySQL filename
3 // to the equivalent table or logical name given the conversion
4 // routines to do this use many regexps and this is quite expensive.
5 package key_value_cache
6
7 import (
8         "errors"
9
10         "github.com/sjmudd/pstop/lib"
11 )
12
13 // provide a mapping from filename to table.schema etc
14 type KeyValueCache struct {
15         cache                                            map[string]string
16         read_requests, served_from_cache, write_requests int
17 }
18
19 // Create a new KeyValueCache entry.
20 func NewKeyValueCache() KeyValueCache {
21         lib.Logger.Println("KeyValueCache()")
22
23         return KeyValueCache{}
24 }
25
26 // Given a lookup key return the value if found.
27 func (kvc *KeyValueCache) Get(key string) (result string, err error) {
28         lib.Logger.Println("KeyValueCache.Get(", key, ")")
29         if kvc.cache == nil {
30                 lib.Logger.Println("KeyValueCache.Get() kvc.cache is empty so enabling it")
31                 kvc.cache = make(map[string]string)
32                 kvc.read_requests = 0
33                 kvc.served_from_cache = 0
34                 kvc.write_requests = 0
35         }
36
37         kvc.read_requests++
38
39         if result, ok := kvc.cache[key]; ok {
40                 kvc.served_from_cache++
41                 lib.Logger.Println("Found: read_requests/servced_from_cache:", kvc.read_requests, kvc.served_from_cache)
42                 return result, nil
43         } else {
44                 lib.Logger.Println("Not found: read_requests/served_from_cache:", kvc.read_requests, kvc.served_from_cache)
45                 return "", errors.New("Not found")
46         }
47 }
48
49 // Write to cache and return the value saved.
50 func (kvc *KeyValueCache) Put(key, value string) string {
51         lib.Logger.Println("KeyValueCache.Put(", key, ",", value, ")")
52         kvc.cache[key] = value
53         return value
54 }
55
56 // Provide some staticts on read and write requests and the number
57 // of requests served from cache.
58 func (kvc *KeyValueCache) Statistics() (int, int, int) {
59         return kvc.read_requests, kvc.served_from_cache, kvc.write_requests
60 }