2015-08-20 17:27:15 +02:00
|
|
|
import UserDict
|
|
|
|
import constants
|
2017-10-10 19:08:22 +02:00
|
|
|
from interface import IDataStore
|
|
|
|
from zope.interface import implements
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
|
2017-10-10 19:08:22 +02:00
|
|
|
class DictDataStore(UserDict.DictMixin):
|
2015-08-20 17:27:15 +02:00
|
|
|
""" A datastore using an in-memory Python dictionary """
|
2017-10-10 19:08:22 +02:00
|
|
|
implements(IDataStore)
|
2017-03-31 19:32:43 +02:00
|
|
|
|
2018-05-23 22:53:35 +02:00
|
|
|
def __init__(self, getTime=None):
|
2015-08-20 17:27:15 +02:00
|
|
|
# Dictionary format:
|
|
|
|
# { <key>: (<value>, <lastPublished>, <originallyPublished> <originalPublisherID>) }
|
|
|
|
self._dict = {}
|
2018-05-23 22:53:35 +02:00
|
|
|
if not getTime:
|
|
|
|
from twisted.internet import reactor
|
|
|
|
getTime = reactor.seconds
|
|
|
|
self._getTime = getTime
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
def keys(self):
|
|
|
|
""" Return a list of the keys in this data store """
|
|
|
|
return self._dict.keys()
|
|
|
|
|
|
|
|
def removeExpiredPeers(self):
|
2018-05-23 22:53:35 +02:00
|
|
|
now = int(self._getTime())
|
2015-08-20 17:27:15 +02:00
|
|
|
for key in self._dict.keys():
|
2018-05-24 16:23:22 +02:00
|
|
|
unexpired_peers = filter(lambda peer: now - peer[2] < constants.dataExpireTimeout, self._dict[key])
|
|
|
|
if not unexpired_peers:
|
|
|
|
del self._dict[key]
|
|
|
|
else:
|
|
|
|
self._dict[key] = unexpired_peers
|
2015-08-20 17:27:15 +02:00
|
|
|
|
|
|
|
def hasPeersForBlob(self, key):
|
2018-05-24 16:23:22 +02:00
|
|
|
if key in self._dict and len(filter(lambda peer: self._getTime() - peer[2] < constants.dataExpireTimeout,
|
|
|
|
self._dict[key])):
|
2015-08-20 17:27:15 +02:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def addPeerToBlob(self, key, value, lastPublished, originallyPublished, originalPublisherID):
|
|
|
|
if key in self._dict:
|
2018-05-23 23:33:22 +02:00
|
|
|
if value not in map(lambda store_tuple: store_tuple[0], self._dict[key]):
|
|
|
|
self._dict[key].append((value, lastPublished, originallyPublished, originalPublisherID))
|
2015-08-20 17:27:15 +02:00
|
|
|
else:
|
|
|
|
self._dict[key] = [(value, lastPublished, originallyPublished, originalPublisherID)]
|
|
|
|
|
|
|
|
def getPeersForBlob(self, key):
|
2018-05-24 16:23:22 +02:00
|
|
|
return [] if key not in self._dict else [
|
|
|
|
val[0] for val in filter(lambda peer: self._getTime() - peer[2] < constants.dataExpireTimeout,
|
|
|
|
self._dict[key])
|
|
|
|
]
|
2017-10-10 19:27:44 +02:00
|
|
|
|
|
|
|
def removePeer(self, value):
|
|
|
|
for key in self._dict:
|
|
|
|
self._dict[key] = [val for val in self._dict[key] if val[0] != value]
|
|
|
|
if not self._dict[key]:
|
|
|
|
del self._dict[key]
|