|
| 1 | +"""Implementation of a Twisted-friendly thread pool wrapper.""" |
| 2 | +from functools import partial |
| 3 | +from twisted.internet.threads import deferToThreadPool |
| 4 | +from twisted.internet.defer import fail |
| 5 | +from twisted.internet.error import ReactorNotRunning |
| 6 | + |
| 7 | +# Shamelessly stolen from: |
| 8 | +# https://github.com/lvh/thimble |
| 9 | +# https://pypi.python.org/pypi/thimble |
| 10 | + |
| 11 | +class Thimble(object): |
| 12 | + |
| 13 | + """A Twisted thread-pool wrapper for a blocking API.""" |
| 14 | + |
| 15 | + def __init__(self, reactor, pool, wrapped, blocking_methods): |
| 16 | + """Initialize a :class:`Thimble`. |
| 17 | + :param reactor: The reactor that will handle events. |
| 18 | + :type reactor: :class:`twisted.internet.interfaces.IReactorThreads` and |
| 19 | + :class:`twisted.internet.interfaces.IReactorCore`. Pretty much any |
| 20 | + real reactor implementation will do. |
| 21 | + :param pool: The thread pool to defer to. |
| 22 | + :type pool: :class:`twisted.python.threadpool.ThreadPool` |
| 23 | + :param wrapped: The blocking implementation being wrapped. |
| 24 | + :param blocking_methods: The names of the methods that will be wrapped |
| 25 | + and executed in the thread pool. |
| 26 | + :type blocking_methods: ``list`` of native ``str`` |
| 27 | + """ |
| 28 | + self._reactor = reactor |
| 29 | + self._pool = pool |
| 30 | + self._wrapped = wrapped |
| 31 | + self._blocking_methods = blocking_methods |
| 32 | + |
| 33 | + def _deferToThreadPool(self, f, *args, **kwargs): |
| 34 | + """Defer execution of ``f(*args, **kwargs)`` to the thread pool. |
| 35 | + This returns a deferred which will callback with the result of |
| 36 | + that expression, or errback with a failure wrapping the raised |
| 37 | + exception. |
| 38 | + """ |
| 39 | + if self._pool.joined: |
| 40 | + return fail( |
| 41 | + ReactorNotRunning("This thimble's threadpool already stopped.") |
| 42 | + ) |
| 43 | + if not self._pool.started: |
| 44 | + self._pool.start() |
| 45 | + self._reactor.addSystemEventTrigger( |
| 46 | + 'during', 'shutdown', self._pool.stop) |
| 47 | + |
| 48 | + return deferToThreadPool(self._reactor, self._pool, f, *args, **kwargs) |
| 49 | + |
| 50 | + def __getattr__(self, attr): |
| 51 | + """Get and maybe wraps an attribute from the wrapped object. |
| 52 | + If the attribute is blocking, it will be wrapped so that |
| 53 | + calling it will return a Deferred and the actual function will |
| 54 | + be ran in a thread pool. |
| 55 | + """ |
| 56 | + value = getattr(self._wrapped, attr) |
| 57 | + |
| 58 | + if attr in self._blocking_methods: |
| 59 | + value = partial(self._deferToThreadPool, value) |
| 60 | + |
| 61 | + return value |
0 commit comments