magic-wormhole/src/wormhole/journal.py

39 lines
1.1 KiB
Python
Raw Normal View History

from __future__ import print_function, absolute_import, unicode_literals
2017-02-22 20:51:53 +00:00
from zope.interface import implementer
2017-02-13 09:50:25 +00:00
import contextlib
from ._interfaces import IJournal
2017-02-13 09:50:25 +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
yield # process inbound messages, change state, queue outbound
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
2017-02-22 20:51:53 +00:00
def queue_outbound(self, fn, *args, **kwargs):
fn(*args, **kwargs)
@contextlib.contextmanager
def process(self):
yield