Python port of ShadowsocksR
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
4.8 KiB

11 years ago
#!/usr/bin/python
# -*- coding: utf-8 -*-
10 years ago
#
# 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
10 years ago
#
# http://www.apache.org/licenses/LICENSE-2.0
10 years ago
#
# 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.
10 years ago
from __future__ import absolute_import, division, print_function, \
with_statement
11 years ago
import collections
import logging
import time
9 years ago
if __name__ == '__main__':
import os, sys, inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
sys.path.insert(0, os.path.join(file_path, '../'))
try:
from collections import OrderedDict
print("loaded collections.OrderedDict")
except:
from shadowsocks.ordereddict import OrderedDict
# this LRUCache is optimized for concurrency, not QPS
# n: concurrency, keys stored in the cache
# m: visits not timed out, proportional to QPS * timeout
9 years ago
# get & set is O(1), not O(n). thus we can support very large n
# sweep is O((n - m)) or O(1024) at most,
# no metter how large the cache or timeout value is
SWEEP_MAX_ITEMS = 1024
11 years ago
class LRUCache(collections.MutableMapping):
"""This class is not thread safe"""
11 years ago
def __init__(self, timeout=60, close_callback=None, *args, **kwargs):
11 years ago
self.timeout = timeout
11 years ago
self.close_callback = close_callback
11 years ago
self._store = {}
9 years ago
self._keys_to_last_time = OrderedDict()
11 years ago
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
9 years ago
# O(1)
11 years ago
t = time.time()
9 years ago
last_t = self._keys_to_last_time[key]
del self._keys_to_last_time[key]
self._keys_to_last_time[key] = t
11 years ago
return self._store[key]
11 years ago
def __setitem__(self, key, value):
9 years ago
# O(1)
11 years ago
t = time.time()
if key in self._keys_to_last_time:
9 years ago
del self._keys_to_last_time[key]
self._keys_to_last_time[key] = t
11 years ago
self._store[key] = value
11 years ago
def __delitem__(self, key):
9 years ago
# O(1)
last_t = self._keys_to_last_time[key]
11 years ago
del self._store[key]
del self._keys_to_last_time[key]
11 years ago
def __iter__(self):
11 years ago
return iter(self._store)
11 years ago
def __len__(self):
11 years ago
return len(self._store)
11 years ago
def first(self):
if len(self._keys_to_last_time) > 0:
9 years ago
for key in self._keys_to_last_time:
return key
11 years ago
def sweep(self):
# O(n - m)
11 years ago
now = time.time()
c = 0
while c < SWEEP_MAX_ITEMS:
9 years ago
if len(self._keys_to_last_time) == 0:
break
9 years ago
for key in self._keys_to_last_time:
break
9 years ago
last_t = self._keys_to_last_time[key]
if now - last_t <= self.timeout:
11 years ago
break
value = self._store[key]
if self.close_callback is not None:
self.close_callback(value)
del self._store[key]
del self._keys_to_last_time[key]
c += 1
if c:
logging.debug('%d keys swept' % c)
return c < SWEEP_MAX_ITEMS
def clear(self):
now = time.time()
c = 0
while c < SWEEP_MAX_ITEMS:
if len(self._keys_to_last_time) == 0:
break
for key in self._keys_to_last_time:
break
last_t = self._keys_to_last_time[key]
value = self._store[key]
if self.close_callback is not None:
self.close_callback(value)
del self._store[key]
del self._keys_to_last_time[key]
c += 1
11 years ago
if c:
logging.debug('%d keys swept' % c)
return c < SWEEP_MAX_ITEMS
def test():
c = LRUCache(timeout=0.3)
c['a'] = 1
assert c['a'] == 1
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
global close_cb_called
close_cb_called = False
def close_cb(t):
global close_cb_called
assert not close_cb_called
close_cb_called = True
c = LRUCache(timeout=0.1, close_callback=close_cb)
c['s'] = 1
c['s']
time.sleep(0.1)
c['s']
time.sleep(0.3)
c.sweep()
if __name__ == '__main__':
test()