Last active
August 29, 2015 14:01
-
-
Save posita/2a666446f5c012a865cb to your computer and use it in GitHub Desktop.
pub-sub (i.e., fan-out) for Twisted Deferreds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*-mode: python; encoding: utf-8; test-case-name: TestDeferredTee.TestDeferredTee-*- | |
#========================================================================= | |
""" | |
Copyright (c) 2014 Matt Bogosian. <https://github.com/posita>. | |
Permission is hereby granted, free of charge, to any person obtaining a | |
copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be included | |
in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
""" | |
#========================================================================= | |
from __future__ import ( | |
absolute_import, | |
division, | |
print_function, | |
unicode_literals, | |
with_statement, | |
) | |
#---- Imports ------------------------------------------------------------ | |
from functools import partial | |
from twisted.internet.defer import Deferred | |
from twisted.python.failure import Failure | |
#---- Classes ------------------------------------------------------------ | |
#========================================================================= | |
class DeferredTee(object, Deferred): | |
""" | |
Implements a kind of publish-subscribe (fan-out) model in terms of | |
Twisted Deferreds. This class behaves like a normal Deferred (which | |
means it can participate in chains) with one addition: it also | |
propagates calls to its callback, cancel, and errback methods to each | |
callable added via one of the respective tee... methods. | |
Exceptions raised from any tee'd callable are silently ignored. In | |
other words, if you want to capture errors on a tee, create your own | |
Deferred chain and add the parent via the teeDeferred method. | |
""" | |
#---- Constructors --------------------------------------------------- | |
#===================================================================== | |
def __init__(self, canceller=None): | |
object.__init__(self) | |
Deferred.__init__(self, canceller) | |
self._t_result = DeferredTee._SENTINEL | |
self._t_cbs = [] | |
self._t_ebs = [] | |
#---- Public methods ------------------------------------------------- | |
#===================================================================== | |
def teeBoth(self, callback, *args, **kw): | |
return self.teeCallbacks(callback, callback, callbackArgs=args, callbackKeywords=kw, errbackArgs=args, errbackKeywords=kw) | |
#===================================================================== | |
def teeCallbacks(self, callback, errback=None, callbackArgs=(), callbackKeywords={}, errbackArgs=(), errbackKeywords={}): # pylint: disable=dangerous-default-value | |
if callback is not None: | |
cb = partial(callback, *callbackArgs, **callbackKeywords) # pylint: disable=star-args | |
if not self.called: | |
self._t_cbs.append(cb) | |
elif not isinstance(self._t_result, Failure): | |
try: | |
cb(self._t_result) | |
except Exception: # pylint: disable=broad-except | |
# Ignore failures | |
pass | |
if errback is not None: | |
eb = partial(errback, *errbackArgs, **errbackKeywords) # pylint: disable=star-args | |
if not self.called: | |
self._t_ebs.append(eb) | |
elif isinstance(self._t_result, Failure): | |
try: | |
eb(self._t_result) | |
except Exception: # pylint: disable=broad-except | |
# Ignore failures | |
pass | |
return self | |
#===================================================================== | |
def teeCallback(self, callback, *args, **kw): | |
return self.teeCallbacks(callback, None, callbackArgs=args, callbackKeywords=kw) | |
#===================================================================== | |
def teeDeferred(self, d): | |
d._chainedTo = self # pylint: disable=protected-access | |
return self.teeCallbacks(d.callback, d.errback) | |
#===================================================================== | |
def teeErrback(self, errback, *args, **kw): | |
return self.teeCallbacks(None, errback, errbackArgs=args, errbackKeywords=kw) | |
#---- Private hook methods ------------------------------------------- | |
#===================================================================== | |
def _runCallbacks(self): | |
if self._t_result is DeferredTee._SENTINEL: | |
self._t_result = self.result | |
self._runTeedUp() | |
Deferred._runCallbacks(self) | |
#---- Private methods ------------------------------------------------ | |
#===================================================================== | |
def _runTeedUp(self): | |
if isinstance(self._t_result, Failure): | |
funcs = self._t_ebs | |
else: | |
funcs = self._t_cbs | |
self._t_cbs = None | |
self._t_cbs = None | |
for func in funcs: | |
try: | |
func(self._t_result) | |
except Exception: # pylint: disable=broad-except | |
# Ignore failures | |
pass | |
#---- Private static constants --------------------------------------- | |
_SENTINEL = type('_SENTINEL', ( object, ), {}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*-mode: python; encoding: utf-8-*- | |
#========================================================================= | |
""" | |
Copyright (c) 2014 Matt Bogosian. <https://github.com/posita>. | |
Permission is hereby granted, free of charge, to any person obtaining a | |
copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be included | |
in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
""" | |
#========================================================================= | |
from __future__ import ( | |
absolute_import, | |
division, | |
print_function, | |
unicode_literals, | |
with_statement, | |
) | |
#---- Imports ------------------------------------------------------------ | |
from functools import partial | |
from unittest import TestCase | |
from DeferredTee import DeferredTee | |
#---- Classes ------------------------------------------------------------ | |
#========================================================================= | |
class TestDeferredTee(TestCase): | |
#---- Public hook methods -------------------------------------------- | |
#===================================================================== | |
def test_teeBoth(self): | |
results = {} | |
seta = partial(results.__setitem__, 'a') | |
setb = partial(results.__setitem__, 'b') | |
setc = partial(results.__setitem__, 'c') | |
setd = partial(results.__setitem__, 'd') | |
addbar = lambda x: x + 'bar' | |
results.clear() | |
d = DeferredTee() | |
d.teeBoth(seta) | |
d.teeBoth(setb) | |
d.teeBoth(setc) | |
d.addCallback(addbar) | |
d.addCallback(setd) | |
result = 'foo' | |
d.callback(result) | |
self.assertEqual(results, { 'a': result, 'b': result, 'c': result, 'd': result + 'bar' }) | |
results.clear() | |
d = DeferredTee() | |
d.teeBoth(seta) | |
d.teeBoth(setb) | |
d.teeBoth(setc) | |
d.addCallback(addbar) | |
d.addCallback(setd) | |
result = ValueError('foo') | |
d.errback(result) | |
self.assertEqual(result, results['a'].value) | |
self.assertEqual(result, results['b'].value) | |
self.assertEqual(result, results['c'].value) | |
self.assertEqual([ 'a', 'b', 'c' ], sorted(results.keys())) | |
#===================================================================== | |
def test_teeCallbackErrback(self): | |
results = {} | |
seta = partial(results.__setitem__, 'a') | |
setb = partial(results.__setitem__, 'b') | |
setc = partial(results.__setitem__, 'c') | |
setd = partial(results.__setitem__, 'd') | |
sete = partial(results.__setitem__, 'e') | |
setf = partial(results.__setitem__, 'f') | |
setg = partial(results.__setitem__, 'g') | |
def raisesValueError(*a_args, **a_kwargs): # pylint: disable=unused-argument | |
raise ValueError('baz') | |
addbar = lambda x: str(x) + 'bar' | |
results.clear() | |
d = DeferredTee() | |
d.teeCallback(seta) | |
d.teeCallback(setb) | |
d.teeCallback(raisesValueError) | |
d.teeErrback(setd) | |
d.teeErrback(sete) | |
d.addCallback(addbar) | |
result = 'foo' | |
d.callback(result) | |
self.assertEqual(results, { 'a': result, 'b': result }) | |
d.teeCallback(setc) | |
d.teeCallback(raisesValueError) | |
d.teeErrback(setf) | |
d.addCallback(setg) | |
self.assertEqual(results, { 'a': result, 'b': result, 'c': result, 'g': result + 'bar' }) | |
results.clear() | |
d = DeferredTee() | |
d.teeCallback(seta) | |
d.teeCallback(setb) | |
d.teeErrback(setd) | |
d.teeErrback(sete) | |
d.teeErrback(raisesValueError) | |
d.addCallback(addbar) | |
d.addCallback(setg) | |
result = ValueError('foo') | |
d.errback(result) | |
self.assertEqual(result, results['d'].value) | |
self.assertEqual(result, results['e'].value) | |
self.assertEqual([ 'd', 'e' ], sorted(results.keys())) | |
d.teeCallback(setc) | |
d.teeCallback(raisesValueError) | |
d.teeErrback(setf) | |
self.assertEqual(result, results['d'].value) | |
self.assertEqual(result, results['e'].value) | |
self.assertEqual(result, results['f'].value) | |
self.assertEqual([ 'd', 'e', 'f' ], sorted(results.keys())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment