added interface for storage and the ability to pass an instance to the Server constructor

This commit is contained in:
Brian Muller 2014-12-09 16:55:44 -05:00
parent 33d0fc898b
commit a7c0a75b8d
2 changed files with 44 additions and 2 deletions

View File

@ -22,7 +22,7 @@ class Server(object):
to start listening as an active node on the network. to start listening as an active node on the network.
""" """
def __init__(self, ksize=20, alpha=3, id=None): def __init__(self, ksize=20, alpha=3, id=None, storage=None):
""" """
Create a server instance. This will start listening on the given port. Create a server instance. This will start listening on the given port.
@ -33,7 +33,7 @@ class Server(object):
self.ksize = ksize self.ksize = ksize
self.alpha = alpha self.alpha = alpha
self.log = Logger(system=self) self.log = Logger(system=self)
self.storage = ForgetfulStorage() self.storage = storage or ForgetfulStorage()
self.node = Node(id or digest(random.getrandbits(255))) self.node = Node(id or digest(random.getrandbits(255)))
self.protocol = KademliaProtocol(self.node, self.storage, ksize) self.protocol = KademliaProtocol(self.node, self.storage, ksize)
self.refreshLoop = LoopingCall(self.refreshTable).start(3600) self.refreshLoop = LoopingCall(self.refreshTable).start(3600)

View File

@ -5,8 +5,50 @@ from itertools import takewhile
import operator import operator
from collections import OrderedDict from collections import OrderedDict
from zope.interface import implements
from zope.interface import Interface
class IStorage(Interface):
"""
Local storage for this node.
"""
def __setitem__(key, value):
"""
Set a key to the given value.
"""
def __getitem__(key):
"""
Get the given key. If item doesn't exist, raises C{KeyError}
"""
def get(key, default=None):
"""
Get given key. If not found, return default.
"""
def __iter__():
"""
Get the iterator for this storage, should yield tuple of (key, (birth, value))
where birth is the float timestamp when the value was set.
"""
def iteritemsOlderThan(secondsOld):
"""
Return the an iterator over (key, value) tuples for items older than the given secondsOld.
"""
def iteritems():
"""
Get the iterator for this storage, should yield tuple of (key, value)
"""
class ForgetfulStorage(object): class ForgetfulStorage(object):
implements(IStorage)
def __init__(self, ttl=604800): def __init__(self, ttl=604800):
""" """
By default, max age is a week. By default, max age is a week.