Files
shadowsocks/shadowsocks/lru_cache.py

131 lines
3.7 KiB
Python
Raw Normal View History

2014-04-24 01:36:22 +08:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
2014-11-01 12:25:44 +08:00
#
2015-02-03 14:10:36 +08:00
# Copyright 2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
2014-11-01 12:25:44 +08:00
#
2015-02-03 14:10:36 +08:00
# http://www.apache.org/licenses/LICENSE-2.0
2014-11-01 12:25:44 +08:00
#
2015-02-03 14:10:36 +08:00
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
2014-11-01 12:25:44 +08:00
2014-10-31 18:28:22 +08:00
from __future__ import absolute_import, division, print_function, \
with_statement
2014-04-24 01:36:22 +08:00
import collections
import logging
import time
2014-10-31 15:49:24 +08:00
# this LRUCache is optimized for concurrency, not QPS
# n: concurrency, keys stored in the cache
# m: visits not timed out, proportional to QPS * timeout
# get & set is O(1), not O(n). thus we can support very large n
# TODO: if timeout or QPS is too large, then this cache is not very efficient,
# as sweep() causes long pause
2014-04-24 01:36:22 +08:00
class LRUCache(collections.MutableMapping):
"""This class is not thread safe"""
2014-04-24 12:34:31 +08:00
def __init__(self, timeout=60, close_callback=None, *args, **kwargs):
2014-04-24 01:36:22 +08:00
self.timeout = timeout
2014-04-24 12:34:31 +08:00
self.close_callback = close_callback
2014-06-08 14:38:09 +08:00
self._store = {}
self._time_to_keys = collections.defaultdict(list)
2014-10-31 14:33:43 +08:00
self._keys_to_last_time = {}
2014-10-31 15:49:24 +08:00
self._last_visits = collections.deque()
2014-04-24 01:36:22 +08:00
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
2014-10-31 15:49:24 +08:00
# O(1)
2014-04-24 01:36:22 +08:00
t = time.time()
2014-10-31 14:33:43 +08:00
self._keys_to_last_time[key] = t
2014-06-08 14:38:09 +08:00
self._time_to_keys[t].append(key)
2014-10-31 15:49:24 +08:00
self._last_visits.append(t)
2014-06-08 14:38:09 +08:00
return self._store[key]
2014-04-24 01:36:22 +08:00
def __setitem__(self, key, value):
2014-10-31 15:49:24 +08:00
# O(1)
2014-04-24 01:36:22 +08:00
t = time.time()
2014-10-31 14:33:43 +08:00
self._keys_to_last_time[key] = t
2014-06-08 14:38:09 +08:00
self._store[key] = value
self._time_to_keys[t].append(key)
2014-10-31 15:49:24 +08:00
self._last_visits.append(t)
2014-04-24 01:36:22 +08:00
def __delitem__(self, key):
2014-06-08 14:38:09 +08:00
# O(1)
del self._store[key]
2014-10-31 14:33:43 +08:00
del self._keys_to_last_time[key]
2014-04-24 01:36:22 +08:00
def __iter__(self):
2014-06-08 14:38:09 +08:00
return iter(self._store)
2014-04-24 01:36:22 +08:00
def __len__(self):
2014-06-08 14:38:09 +08:00
return len(self._store)
2014-04-24 01:36:22 +08:00
def sweep(self):
2014-06-08 14:38:09 +08:00
# O(m)
2014-04-24 01:36:22 +08:00
now = time.time()
c = 0
2014-06-08 14:38:09 +08:00
while len(self._last_visits) > 0:
least = self._last_visits[0]
2014-04-24 01:36:22 +08:00
if now - least <= self.timeout:
break
2014-06-23 21:35:23 +08:00
if self.close_callback is not None:
for key in self._time_to_keys[least]:
2014-12-11 14:09:18 +08:00
if key in self._store:
2014-10-31 14:33:43 +08:00
if now - self._keys_to_last_time[key] > self.timeout:
value = self._store[key]
self.close_callback(value)
2014-06-08 14:38:09 +08:00
for key in self._time_to_keys[least]:
2014-10-31 15:49:24 +08:00
self._last_visits.popleft()
2014-12-11 14:09:18 +08:00
if key in self._store:
2014-10-31 14:33:43 +08:00
if now - self._keys_to_last_time[key] > self.timeout:
del self._store[key]
2014-10-31 15:14:28 +08:00
del self._keys_to_last_time[key]
2014-10-31 14:33:43 +08:00
c += 1
2014-06-08 14:38:09 +08:00
del self._time_to_keys[least]
2014-04-24 01:36:22 +08:00
if c:
logging.debug('%d keys swept' % c)
2014-10-31 14:33:43 +08:00
def test():
c = LRUCache(timeout=0.3)
c['a'] = 1
assert c['a'] == 1
time.sleep(0.5)
c.sweep()
assert 'a' not in c
c['a'] = 2
c['b'] = 3
time.sleep(0.2)
c.sweep()
assert c['a'] == 2
assert c['b'] == 3
time.sleep(0.2)
c.sweep()
c['b']
time.sleep(0.2)
c.sweep()
assert 'a' not in c
assert c['b'] == 3
time.sleep(0.5)
c.sweep()
assert 'a' not in c
assert 'b' not in c
if __name__ == '__main__':
test()