| 26 | |
| 27 | |
| 28 | class MessageBuffer: |
| 29 | def __init__(self): |
| 30 | # cond is notified whenever the message cache is updated |
| 31 | self.cond = tornado.locks.Condition() |
| 32 | self.cache = [] |
| 33 | self.cache_size = 200 |
| 34 | |
| 35 | def get_messages_since(self, cursor): |
| 36 | """Returns a list of messages newer than the given cursor. |
| 37 | |
| 38 | ``cursor`` should be the ``id`` of the last message received. |
| 39 | """ |
| 40 | results = [] |
| 41 | for msg in reversed(self.cache): |
| 42 | if msg["id"] == cursor: |
| 43 | break |
| 44 | results.append(msg) |
| 45 | results.reverse() |
| 46 | return results |
| 47 | |
| 48 | def add_message(self, message): |
| 49 | self.cache.append(message) |
| 50 | if len(self.cache) > self.cache_size: |
| 51 | self.cache = self.cache[-self.cache_size :] |
| 52 | self.cond.notify_all() |
| 53 | |
| 54 | |
| 55 | # Making this a non-singleton is left as an exercise for the reader. |