import time from lib.broadcast import Broadcast from lib.commands import BROADCAST, DIRECT from lib.direct import Direct from lib.message import EMPTY_CHAIN class LongBuffer(object): def __init__(self, state): self.state = state self.buffer = {} def exhume(self, message_hash): message = self.buffer.get(message_hash) if message: return message command, message_bytes = self.state.get_message(message_hash) if message_bytes: if command == DIRECT: return Direct({message_bytes: message_bytes}, self.state) elif command == BROADCAST: return Broadcast({'message_bytes': message_bytes}, self.state) def expunge_expired(self): for message in self.buffer.values(): if message.timestamp < time.time() - 3600: del self.buffer[message.message_hash] def intern(self, message): # somehow we are trying to intern a message we've already got if self.has(message.message_hash): return self.expunge_expired() self.buffer[message.message_hash] = message self.state.log_message(message) def has(self, message_hash): if EMPTY_CHAIN == message_hash: return True if self.buffer.get(message_hash) is None: if self.state.log_has_message(message_hash): return True return False else: return True