-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathcache.py
162 lines (122 loc) · 4.18 KB
/
cache.py
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
# Copyright (C) 2018 Seeed
# Author: Jack Shao ([email protected])
#
# Expiring in-memory cache module
#
from collections import OrderedDict
from time import time
from tornado import ioloop
from tornado.log import *
class CacheException(Exception):
"""
Generic cache exception
"""
pass
class CachedObject(object):
def __init__(self, name, obj, ttl):
"""
Initializes a new cached object
Args:
name (str): Human readable name for the cached entry
obj (type): Object to be cached
ttl (int): The TTL in seconds for the cached object
"""
self.hits = 0
self.name = name
self.obj = obj
self.ttl = ttl
self.timestamp = time()
class CacheInventory(object):
"""
Inventory for cached objects
"""
def __init__(self, maxsize=0, housekeeping=0):
"""
Initializes a new cache inventory
Args:
maxsize (int): Upperbound limit on the number of items
that will be stored in the cache inventory
housekeeping (int): Time in seconds to perform periodic cache housekeeping
"""
if maxsize < 0:
raise CacheException('Cache inventory size cannot be negative')
if housekeeping < 0:
raise CacheException('Cache housekeeping period cannot be negative')
self._cache = OrderedDict()
self.maxsize = maxsize
self.housekeeping = housekeeping
if self.housekeeping > 0:
self._timer = ioloop.PeriodicCallback(self.housekeeper, self.housekeeping * 1000)
self._timer.start()
def __len__(self):
return len(self._cache)
def __contains__(self, key):
if key not in self._cache:
return False
item = self._cache[key]
if self._has_expired(item):
return False
return True
def _has_expired(self, item):
"""
Checks if a cached item has expired and removes it if needed
If the upperbound limit has been reached then the last item
is being removed from the inventory.
Args:
item (CachedObject): A cached object to lookup
"""
if item.ttl == 0:
return False
if time() > item.timestamp + item.ttl:
gen_log.debug(
'Object %s has expired and will be removed from cache [hits %d]',
item.name,
item.hits
)
self._cache.pop(item.name)
return True
return False
def add(self, key, obj, ttl=0):
"""
Add an item to the cache inventory
Args:
obj (CachedObject): A CachedObject instance to be added
Raises:
CacheException
"""
item = CachedObject(key, obj, ttl)
if self.maxsize > 0 and len(self._cache) == self.maxsize:
popped = self._cache.popitem(last=False)
gen_log.debug('Cache maxsize reached, removing %s [hits %d]', popped.name, popped.hits)
gen_log.debug('Caching object %s [ttl: %d seconds]', item.name, item.ttl)
self._cache[item.name] = item
def get(self, key):
"""
Retrieve an object from the cache inventory
Args:
key (str): Name of the cache item to retrieve
Returns:
The cached object if found, None otherwise
"""
if key not in self._cache:
return None
item = self._cache[key]
if self._has_expired(item):
return None
item.hits += 1
gen_log.debug(
'Returning object %s from cache [hits %d]',
item.name,
item.hits
)
return item.obj
def housekeeper(self):
"""
Remove expired entries from the cache on regular basis
"""
total = len(self._cache)
expired = 0
for name, item in self._cache.items():
if self._has_expired(item):
expired += 1
gen_log.debug('Cache housekeeper completed [%d total] [%d removed]', total, expired)