raw
9982-getdata            1 import time
9982-getdata 2 from broadcast import Broadcast
9982-getdata 3 from direct import Direct
9982-getdata 4 from commands import BROADCAST
9982-getdata 5 from commands import DIRECT
9982-getdata 6
9982-getdata 7
9982-getdata 8 class OrderBuffer(object):
9982-getdata 9 def __init__(self, state):
9982-getdata 10 self.buffer = {}
9982-getdata 11 self.state = state
9982-getdata 12
9982-getdata 13 def add(self, message):
9982-getdata 14 ts = time.time()
9982-getdata 15 if message['command'] == BROADCAST:
9982-getdata 16 m = Broadcast(message, self.state)
9982-getdata 17 elif message['command'] == DIRECT:
9982-getdata 18 m = Direct(message, self.state)
9982-getdata 19 else:
9982-getdata 20 return
9982-getdata 21
9982-getdata 22 if self.buffer.get(ts) is None:
9982-getdata 23 self.buffer[ts] = [m]
9982-getdata 24 else:
9982-getdata 25 self.buffer[ts].append(m)
9982-getdata 26
9982-getdata 27 def expects(self, message_hash):
9982-getdata 28 for value in self.buffer.values():
9982-getdata 29 for message in value:
9982-getdata 30 if message_hash == message.self_chain:
9982-getdata 31 return True
9982-getdata 32 elif message_hash == message.net_chain:
9982-getdata 33 return True
9982-getdata 34 return False
9982-getdata 35
9982-getdata 36 def has(self, message_hash):
9982-getdata 37 for value in self.buffer.values():
9982-getdata 38 for message in value:
9982-getdata 39 if message_hash == message.message_hash:
9982-getdata 40 return True
9982-getdata 41 return False
9982-getdata 42
9982-getdata 43 def dequeue_and_order_mature_messages(self):
9982-getdata 44 current_time = time.time()
9982-getdata 45 sorted_messages = sorted(self.buffer.keys())
9982-getdata 46 mature_messages = []
9982-getdata 47 for timestamp in sorted_messages:
9982-getdata 48 if timestamp < current_time - int(self.state.get_knob('order_buffer_expiration_seconds')):
9982-getdata 49 if isinstance(self.buffer[timestamp], list):
9982-getdata 50 if len(self.buffer[timestamp]) > 0:
9982-getdata 51 for message in self.buffer[timestamp]:
9982-getdata 52 mature_messages.append(message)
9982-getdata 53 del self.buffer[timestamp]
9982-getdata 54 else:
9982-getdata 55 mature_messages.append(self.buffer[timestamp])
9982-getdata 56 del self.buffer[timestamp]
9982-getdata 57 return sorted(mature_messages, key=lambda m: m.timestamp)