magic-wormhole/src/wormhole/journal.py

45 lines
1.2 KiB
Python
Raw Normal View History

2018-04-21 07:30:08 +00:00
from __future__ import absolute_import, print_function, unicode_literals
2017-02-13 09:50:25 +00:00
import contextlib
2018-04-21 07:30:08 +00:00
from zope.interface import implementer
from ._interfaces import IJournal
2017-02-13 09:50:25 +00:00
2018-04-21 07:30:08 +00:00
2017-02-22 20:51:53 +00:00
@implementer(IJournal)
class Journal(object):
2017-02-13 09:50:25 +00:00
def __init__(self, save_checkpoint):
self._save_checkpoint = save_checkpoint
self._outbound_queue = []
self._processing = False
def queue_outbound(self, fn, *args, **kwargs):
assert self._processing
2017-02-22 21:44:56 +00:00
self._outbound_queue.append((fn, args, kwargs))
2017-02-13 09:50:25 +00:00
@contextlib.contextmanager
def process(self):
assert not self._processing
assert not self._outbound_queue
self._processing = True
2018-04-21 07:30:08 +00:00
yield # process inbound messages, change state, queue outbound
2017-02-13 09:50:25 +00:00
self._save_checkpoint()
for (fn, args, kwargs) in self._outbound_queue:
fn(*args, **kwargs)
self._outbound_queue[:] = []
self._processing = False
2017-02-22 20:51:53 +00:00
@implementer(IJournal)
class ImmediateJournal(object):
2017-04-06 19:07:31 +00:00
def __init__(self):
pass
2018-04-21 07:30:08 +00:00
2017-02-22 20:51:53 +00:00
def queue_outbound(self, fn, *args, **kwargs):
fn(*args, **kwargs)
2018-04-21 07:30:08 +00:00
2017-02-22 20:51:53 +00:00
@contextlib.contextmanager
def process(self):
yield