txZMQ-0.8.0/0000755000076500000240000000000013051415230012772 5ustar smirastaff00000000000000txZMQ-0.8.0/AUTHORS.txt0000644000076500000240000000045213012703031014655 0ustar smirastaff00000000000000* Andrey Smirnov * Duncan McGreggor * Erik Allik * Guillermo Gonzalez * Jan Dvořák * Aleks Clark * Ralph Bean * Alexander Else * David J. Felix * Vsevolod Novikov * Tim Tisdall txZMQ-0.8.0/LICENSE.txt0000644000076500000240000004311613012703031014616 0ustar smirastaff00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. txZMQ-0.8.0/PKG-INFO0000644000076500000240000000755313051415230014101 0ustar smirastaff00000000000000Metadata-Version: 1.1 Name: txZMQ Version: 0.8.0 Summary: Twisted bindings for ZeroMQ Home-page: https://github.com/smira/txZMQ Author: Andrey Smirnov Author-email: me@smira.ru License: GPLv2 Description: Twisted bindings for 0MQ ======================== .. image:: https://travis-ci.org/smira/txZMQ.png?branch=master :target: https://travis-ci.org/smira/txZMQ .. image:: https://coveralls.io/repos/smira/txZMQ/badge.png :target: https://coveralls.io/r/smira/txZMQ .. image:: https://badge.fury.io/py/txZMQ.svg :target: https://badge.fury.io/py/txZMQ Introduction ------------ txZMQ allows to integrate easily `ØMQ `_ sockets into Twisted event loop (reactor). txZMQ supports both CPython and PyPy and ØMQ library version 2.2.x or 3.2.x. Documentation is available at `ReadTheDocs `_ and CI is done by `Travis CI `_. Requirements ------------ C library required: * ØMQ library 2.2.x or 3.2.x Python packages required: * pyzmq >= 13 (for CPython & PyPy) * Twisted Details ------- txZMQ introduces support for general 0MQ sockets by class ``ZmqConnection`` that can do basic event loop integration, sending-receiving messages in non-blocking manner, scatter-gather for multipart messages. txZMQ uses ØMQ APIs to get file descriptor that is used to signal pending actions from ØMQ library IO thread running in separate thread. This is used in a custom file descriptor reader, which is then added to the Twisted reactor. Upgrading from 0.3.x -------------------- If you're upgrading from version 0.3.1 and earlier, please apply following changes to your code: * root package name was changed from ``txZMQ`` to ``txzmq``, adjust your imports accordingly; * ``ZmqEndpointType.Connect`` has been renamed to ``ZmqEndpointType.connect``; * ``ZmqEndpointType.Bind`` has been renamed to ``ZmqEndpointType.bind``; * ``ZmqConnection.__init__`` has been changed to accept keyword arguments instead of list of endpoints; if you were using one endpoint, no changes are required; if using multiple endpoints, please look for ``add_endpoints`` method. Hacking ------- Source code for txZMQ is available at `github `_; forks and pull requests are welcome. To start hacking, fork at github and clone to your working directory. To use the Makefile (for running unit tests, checking for PEP8 compliance and running pyflakes), you will want to have ``virtualenv`` installed (it includes a ``pip`` installation). Create a branch, add some unit tests, write your code, check it and test it! Some useful make targets are: * ``make env`` * ``make check`` * ``make test`` If you don't have an environment set up, a new one will be created for you in ``./env``. Additionally, txZMQ will be installed as well as required development libs. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 (GPLv2) Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries txZMQ-0.8.0/README.rst0000644000076500000240000000516013051414750014471 0ustar smirastaff00000000000000Twisted bindings for 0MQ ======================== .. image:: https://travis-ci.org/smira/txZMQ.png?branch=master :target: https://travis-ci.org/smira/txZMQ .. image:: https://coveralls.io/repos/smira/txZMQ/badge.png :target: https://coveralls.io/r/smira/txZMQ .. image:: https://badge.fury.io/py/txZMQ.svg :target: https://badge.fury.io/py/txZMQ Introduction ------------ txZMQ allows to integrate easily `ØMQ `_ sockets into Twisted event loop (reactor). txZMQ supports both CPython and PyPy and ØMQ library version 2.2.x or 3.2.x. Documentation is available at `ReadTheDocs `_ and CI is done by `Travis CI `_. Requirements ------------ C library required: * ØMQ library 2.2.x or 3.2.x Python packages required: * pyzmq >= 13 (for CPython & PyPy) * Twisted Details ------- txZMQ introduces support for general 0MQ sockets by class ``ZmqConnection`` that can do basic event loop integration, sending-receiving messages in non-blocking manner, scatter-gather for multipart messages. txZMQ uses ØMQ APIs to get file descriptor that is used to signal pending actions from ØMQ library IO thread running in separate thread. This is used in a custom file descriptor reader, which is then added to the Twisted reactor. Upgrading from 0.3.x -------------------- If you're upgrading from version 0.3.1 and earlier, please apply following changes to your code: * root package name was changed from ``txZMQ`` to ``txzmq``, adjust your imports accordingly; * ``ZmqEndpointType.Connect`` has been renamed to ``ZmqEndpointType.connect``; * ``ZmqEndpointType.Bind`` has been renamed to ``ZmqEndpointType.bind``; * ``ZmqConnection.__init__`` has been changed to accept keyword arguments instead of list of endpoints; if you were using one endpoint, no changes are required; if using multiple endpoints, please look for ``add_endpoints`` method. Hacking ------- Source code for txZMQ is available at `github `_; forks and pull requests are welcome. To start hacking, fork at github and clone to your working directory. To use the Makefile (for running unit tests, checking for PEP8 compliance and running pyflakes), you will want to have ``virtualenv`` installed (it includes a ``pip`` installation). Create a branch, add some unit tests, write your code, check it and test it! Some useful make targets are: * ``make env`` * ``make check`` * ``make test`` If you don't have an environment set up, a new one will be created for you in ``./env``. Additionally, txZMQ will be installed as well as required development libs. txZMQ-0.8.0/setup.py0000644000076500000240000000153113051414365014514 0ustar smirastaff00000000000000import io from distutils.core import setup setup( name='txZMQ', version=io.open('VERSION', encoding='utf-8').read().strip(), packages=['txzmq', 'txzmq.test'], license='GPLv2', author='Andrey Smirnov', author_email='me@smira.ru', url='https://github.com/smira/txZMQ', description='Twisted bindings for ZeroMQ', classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v2 (GPLv2)", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries", ], long_description=io.open('README.rst', encoding='utf-8').read(), install_requires=["Twisted>=10.0", "pyzmq>=13"], ) txZMQ-0.8.0/txzmq/0000755000076500000240000000000013051415230014155 5ustar smirastaff00000000000000txZMQ-0.8.0/txzmq/__init__.py0000644000076500000240000000137313012703031016266 0ustar smirastaff00000000000000""" ZeroMQ integration into Twisted reactor. """ from txzmq.connection import ZmqConnection, ZmqEndpoint, ZmqEndpointType from txzmq.factory import ZmqFactory from txzmq.pubsub import ZmqPubConnection, ZmqSubConnection from txzmq.pushpull import ZmqPushConnection, ZmqPullConnection from txzmq.req_rep import ZmqREQConnection, ZmqREPConnection, \ ZmqRequestTimeoutError from txzmq.router_dealer import ZmqRouterConnection, ZmqDealerConnection __all__ = ['ZmqConnection', 'ZmqEndpoint', 'ZmqEndpointType', 'ZmqFactory', 'ZmqPushConnection', 'ZmqPullConnection', 'ZmqPubConnection', 'ZmqSubConnection', 'ZmqREQConnection', 'ZmqREPConnection', 'ZmqRouterConnection', 'ZmqDealerConnection', 'ZmqRequestTimeoutError'] txZMQ-0.8.0/txzmq/compat.py0000644000076500000240000000063013012703031016005 0ustar smirastaff00000000000000import sys PY3 = sys.version_info[0] == 3 if PY3: # pragma: no cover binary_string_type = bytes else: # pragma: no cover binary_string_type = str if PY3: # pragma: no cover def is_nonstr_iter(v): if isinstance(v, (str, bytes)): return False return hasattr(v, '__iter__') else: # pragma: no cover def is_nonstr_iter(v): return hasattr(v, '__iter__') txZMQ-0.8.0/txzmq/connection.py0000644000076500000240000002535513012703031016674 0ustar smirastaff00000000000000""" ZeroMQ connection. """ from collections import deque, namedtuple from zmq import constants, error from zmq import Socket from zope.interface import implementer from twisted.internet import reactor from twisted.internet.interfaces import IFileDescriptor, IReadDescriptor from twisted.python import log from zmq import zmq_version_info from txzmq.compat import is_nonstr_iter ZMQ3 = zmq_version_info()[0] >= 3 class ZmqEndpointType(object): """ Endpoint could be "bound" or "connected". """ bind = "bind" """ Bind, listen for connection. """ connect = "connect" """ Connect to another endpoint. """ class ZmqEndpoint(namedtuple('ZmqEndpoint', ['type', 'address'])): """ ZeroMQ endpoint used when connecting or listening for connections. Consists of two members: `type` and `address`. :var type: Could be either :attr:`ZmqEndpointType.bind` or :attr:`ZmqEndpointType.connect`. :var address: ZeroMQ address of endpoint, could be IP address, filename, see ZeroMQ docs for more details. :vartype address: str """ @implementer(IReadDescriptor, IFileDescriptor) class ZmqConnection(object): """ Connection through ZeroMQ, wraps up ZeroMQ socket. This class isn't supposed to be used directly, instead use one of the descendants like :class:`ZmqPushConnection`. :class:`ZmqConnection` implements glue between ZeroMQ and Twisted reactor: putting polling ZeroMQ file descriptor into reactor, processing events, reading data from socket. :var socketType: socket type, from ZeroMQ :var allowLoopbackMulticast: is loopback multicast allowed? :vartype allowLoopbackMulticast: bool :var multicastRate: maximum allowed multicast rate, kbps :vartype multicastRate: int :var highWaterMark: hard limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer :vartype highWaterMark: int :var tcpKeepalive: if set to 1, enable TCP keepalive, otherwise leave it as default :vartype tcpKeepalive: int :var tcpKeepaliveCount: override TCP_KEEPCNT socket option (where supported by OS) :vartype tcpKeepaliveCount: int :var tcpKeepaliveIdle: override TCP_KEEPCNT(or TCP_KEEPALIVE on some OS) socket option(where supported by OS). :vartype tcpKeepaliveIdle: int :var tcpKeepaliveInterval: override TCP_KEEPINTVL socket option(where supported by OS) :vartype tcpKeepaliveInterval: int :var reconnectInterval: set reconnection interval :vartype reconnectInterval: int :var reconnectIntervalMax: set maximum reconnection interval :vartype reconnectIntervalMax: int :var factory: ZeroMQ Twisted factory reference :vartype factory: :class:`ZmqFactory` :var socket: ZeroMQ Socket :vartype socket: zmq.Socket :var endpoints: ZeroMQ addresses for connect/bind :vartype endpoints: list of :class:`ZmqEndpoint` :var fd: file descriptor of zmq mailbox :vartype fd: int :var queue: output message queue :vartype queue: deque """ socketType = None allowLoopbackMulticast = False multicastRate = 100 highWaterMark = 0 # Only supported by zeromq3 and pyzmq>=2.2.0.1 tcpKeepalive = 0 tcpKeepaliveCount = 0 tcpKeepaliveIdle = 0 tcpKeepaliveInterval = 0 reconnectInterval = 100 reconnectIntervalMax = 0 def __init__(self, factory, endpoint=None, identity=None): """ Constructor. One endpoint is passed to the constructor, more could be added via call to :meth:`addEndpoints`. :param factory: ZeroMQ Twisted factory :type factory: :class:`ZmqFactory` :param endpoint: ZeroMQ address for connect/bind :type endpoint: :class:`ZmqEndpoint` :param identity: socket identity (ZeroMQ), don't set unless you know how it works :type identity: str """ self.factory = factory self.endpoints = [] self.identity = identity self.socket = Socket(factory.context, self.socketType) self.queue = deque() self.recv_parts = [] self.read_scheduled = None self.fd = self.socket.get(constants.FD) self.socket.set(constants.LINGER, factory.lingerPeriod) if not ZMQ3: self.socket.set( constants.MCAST_LOOP, int(self.allowLoopbackMulticast)) self.socket.set(constants.RATE, self.multicastRate) if not ZMQ3: self.socket.set(constants.HWM, self.highWaterMark) else: self.socket.set(constants.SNDHWM, self.highWaterMark) self.socket.set(constants.RCVHWM, self.highWaterMark) if ZMQ3 and self.tcpKeepalive: self.socket.set( constants.TCP_KEEPALIVE, self.tcpKeepalive) self.socket.set( constants.TCP_KEEPALIVE_CNT, self.tcpKeepaliveCount) self.socket.set( constants.TCP_KEEPALIVE_IDLE, self.tcpKeepaliveIdle) self.socket.set( constants.TCP_KEEPALIVE_INTVL, self.tcpKeepaliveInterval) if ZMQ3 and self.reconnectInterval: self.socket.set( constants.RECONNECT_IVL, self.reconnectInterval) if ZMQ3 and self.reconnectIntervalMax: self.socket.set( constants.RECONNECT_IVL_MAX, self.reconnectIntervalMax) if self.identity is not None: self.socket.set(constants.IDENTITY, self.identity) if endpoint: self.addEndpoints([endpoint]) self.factory.connections.add(self) self.factory.reactor.addReader(self) self.doRead() def addEndpoints(self, endpoints): """ Add more connection endpoints. Connection may have many endpoints, mixing ZeroMQ protocols (TCP, IPC, ...) and types (connect or bind). :param endpoints: list of endpoints to add :type endpoints: list of :class:`ZmqEndpoint` """ self.endpoints.extend(endpoints) self._connectOrBind(endpoints) def shutdown(self): """ Shutdown (close) connection and ZeroMQ socket. """ self.factory.reactor.removeReader(self) self.factory.connections.discard(self) self.socket.close() self.socket = None self.factory = None if self.read_scheduled is not None: self.read_scheduled.cancel() self.read_scheduled = None def __repr__(self): return "%s(%r, %r)" % ( self.__class__.__name__, self.factory, self.endpoints) def fileno(self): """ Implementation of :tm:`IFileDescriptor `. Returns ZeroMQ polling file descriptor. :return: The platform-specified representation of a file descriptor number. """ return self.fd def connectionLost(self, reason): """ Called when the connection was lost. Implementation of :tm:`IFileDescriptor `. This is called when the connection on a selectable object has been lost. It will be called whether the connection was closed explicitly, an exception occurred in an event handler, or the other end of the connection closed it first. """ if self.factory: self.factory.reactor.removeReader(self) def _readMultipart(self): """ Read multipart in non-blocking manner, returns with ready message or raising exception (in case of no more messages available). """ while True: self.recv_parts.append(self.socket.recv(constants.NOBLOCK)) if not self.socket.get(constants.RCVMORE): result, self.recv_parts = self.recv_parts, [] return result def doRead(self): """ Some data is available for reading on ZeroMQ descriptor. ZeroMQ is signalling that we should process some events, we're starting to receive incoming messages. Implementation of :tm:`IReadDescriptor `. """ if self.read_scheduled is not None: if not self.read_scheduled.called: self.read_scheduled.cancel() self.read_scheduled = None while True: if self.factory is None: # disconnected return events = self.socket.get(constants.EVENTS) if (events & constants.POLLIN) != constants.POLLIN: return try: message = self._readMultipart() except error.ZMQError as e: if e.errno == constants.EAGAIN: continue raise e log.callWithLogger(self, self.messageReceived, message) def logPrefix(self): """ Implementation of :tm:`ILoggingContext `. :return: Prefix used during log formatting to indicate context. :rtype: str """ return 'ZMQ' def send(self, message): """ Send message via ZeroMQ socket. Sending is performed directly to ZeroMQ without queueing. If HWM is reached on ZeroMQ side, sending operation is aborted with exception from ZeroMQ (EAGAIN). After writing read is scheduled as ZeroMQ may not signal incoming messages after we touched socket with write request. :param message: message data, could be either list of str (multipart message) or just str :type message: str or list of str """ if not is_nonstr_iter(message): self.socket.send(message, constants.NOBLOCK) else: for m in message[:-1]: self.socket.send(m, constants.NOBLOCK | constants.SNDMORE) self.socket.send(message[-1], constants.NOBLOCK) if self.read_scheduled is None: self.read_scheduled = reactor.callLater(0, self.doRead) def messageReceived(self, message): """ Called when complete message is received. Not implemented in :class:`ZmqConnection`, should be overridden to handle incoming messages. :param message: message data """ raise NotImplementedError(self) def _connectOrBind(self, endpoints): """ Connect and/or bind socket to endpoints. """ for endpoint in endpoints: if endpoint.type == ZmqEndpointType.connect: self.socket.connect(endpoint.address) elif endpoint.type == ZmqEndpointType.bind: self.socket.bind(endpoint.address) else: assert False, "Unknown endpoint type %r" % endpoint txZMQ-0.8.0/txzmq/factory.py0000644000076500000240000000375113012703031016200 0ustar smirastaff00000000000000""" ZeroMQ Twisted factory which is controlling ZeroMQ context. """ from zmq import Context from twisted.internet import reactor class ZmqFactory(object): """ I control individual ZeroMQ connections. Factory creates and destroys ZeroMQ context. :var reactor: reference to Twisted reactor used by all the connections :var ioThreads: number of IO threads ZeroMQ will be using for this context :vartype ioThreads: int :var lingerPeriod: number of milliseconds to block when closing socket (terminating context), when there are some messages pending to be sent :vartype lingerPeriod: int :var connections: set of instanciated :class:`ZmqConnection` :vartype connections: set :var context: ZeroMQ context """ reactor = reactor ioThreads = 1 lingerPeriod = 100 trigger = None def __init__(self): """ Constructor. Create ZeroMQ context. """ self.connections = set() self.context = Context(self.ioThreads) def __repr__(self): return "ZmqFactory()" def shutdown(self): """ Shutdown factory. This is shutting down all created connections and terminating ZeroMQ context. Also cleans up Twisted reactor. """ for connection in self.connections.copy(): connection.shutdown() self.connections = None self.context.term() self.context = None if self.trigger: try: self.reactor.removeSystemEventTrigger(self.trigger) except Exception: pass # just ignore while triggered by the reactor def registerForShutdown(self): """ Register factory to be automatically shut down on reactor shutdown. It is recommended that this method is called on any created factory. """ self.trigger = self.reactor.addSystemEventTrigger( 'during', 'shutdown', self.shutdown ) txZMQ-0.8.0/txzmq/pubsub.py0000644000076500000240000000412313012703031016023 0ustar smirastaff00000000000000""" ZeroMQ PUB-SUB wrappers. """ from __future__ import unicode_literals from zmq import constants from txzmq.connection import ZmqConnection class ZmqPubConnection(ZmqConnection): """ Publishing in broadcast manner. """ socketType = constants.PUB def publish(self, message, tag=b''): """ Publish `message` with specified `tag`. :param message: message data :type message: str :param tag: message tag :type tag: str """ self.send(tag + b'\0' + message) class ZmqSubConnection(ZmqConnection): """ Subscribing to messages published by publishers. Subclass this class and implement :meth:`gotMessage` to handle incoming messages. """ socketType = constants.SUB def subscribe(self, tag): """ Subscribe to messages with specified tag (prefix). Function may be called several times. :param tag: message tag :type tag: str """ self.socket.set(constants.SUBSCRIBE, tag) def unsubscribe(self, tag): """ Unsubscribe from messages with specified tag (prefix). Function may be called several times. :param tag: message tag :type tag: str """ self.socket.set(constants.UNSUBSCRIBE, tag) def messageReceived(self, message): """ Overridden from :class:`ZmqConnection` to process and unframe incoming messages. All parsed messages are passed to :meth:`gotMessage`. :param message: message data """ if len(message) == 2: # compatibility receiving of tag as first part # of multi-part message self.gotMessage(message[1], message[0]) else: self.gotMessage(*reversed(message[0].split(b'\0', 1))) def gotMessage(self, message, tag): """ Called on incoming message recevied by subscriber. Should be overridden to handle incoming messages. :param message: message data :param tag: message tag """ raise NotImplementedError(self) txZMQ-0.8.0/txzmq/pushpull.py0000644000076500000240000000200313012703031016372 0ustar smirastaff00000000000000""" ZeroMQ PUSH-PULL wrappers. """ from zmq import constants from txzmq.connection import ZmqConnection class ZmqPushConnection(ZmqConnection): """ Pushing messages to the socket. Wrapper around ZeroMQ PUSH socket. """ socketType = constants.PUSH def push(self, message): """ Push a message L{message}. :param message: message data :type message: str """ self.send(message) class ZmqPullConnection(ZmqConnection): """ Pull messages from a socket. Wrapper around ZeroMQ PULL socket. Subclass and override :meth:`onPull`. """ socketType = constants.PULL def messageReceived(self, message): """ Called on incoming message from ZeroMQ. :param message: message data """ self.onPull(message) def onPull(self, message): """ Called on incoming message received by puller. :param message: message data """ raise NotImplementedError(self) txZMQ-0.8.0/txzmq/req_rep.py0000644000076500000240000001502113012703031016157 0ustar smirastaff00000000000000""" ZeroMQ REQ-REP wrappers. """ from __future__ import unicode_literals import uuid import warnings from zmq import constants from twisted.internet import defer, reactor from txzmq.connection import ZmqConnection class ZmqRequestTimeoutError(Exception): """ Request has been timed out. """ class ZmqREQConnection(ZmqConnection): """ A Request ZeroMQ connection. This is implemented with an underlying DEALER socket, even though semantics are closer to REQ socket. Socket mimics request-reply behavior by sending each message with unique uuid and recording Deferred associated with the message. When reply comes, it uses that Deferred to pass response back to the caller. :var defaultRequestTimeout: default timeout for requests, disabled by default (seconds) :type defaultRequestTimeout: float """ socketType = constants.DEALER defaultRequestTimeout = None # the number of new UUIDs to generate when the pool runs out of them UUID_POOL_GEN_SIZE = 5 def __init__(self, *args, **kwargs): ZmqConnection.__init__(self, *args, **kwargs) self._requests = {} self._uuids = [] def _getNextId(self): """ Returns an unique id. By default, generates pool of UUID in increments of ``UUID_POOL_GEN_SIZE``. Could be overridden to provide custom ID generation. :return: generated unique "on the wire" message ID :rtype: str """ if not self._uuids: for _ in range(self.UUID_POOL_GEN_SIZE): self._uuids.append(uuid.uuid4().bytes) return self._uuids.pop() def _releaseId(self, msgId): """ Release message ID to the pool. @param msgId: message ID, no longer on the wire @type msgId: C{str} """ self._uuids.append(msgId) if len(self._uuids) > 2 * self.UUID_POOL_GEN_SIZE: self._uuids[-self.UUID_POOL_GEN_SIZE:] = [] def _cancel(self, msgId): """ Cancel outstanding REQ, drop reply silently. @param msgId: message ID to cancel @type msgId: C{str} """ self._requests.pop(msgId, (None, None)) def _timeoutRequest(self, msgId): """ Cancel timedout request. @param msgId: message ID to cancel @type msgId: C{str} """ d, _ = self._requests.pop(msgId, (None, None)) if not d.called: d.errback(ZmqRequestTimeoutError(msgId)) def sendMsg(self, *messageParts, **kwargs): """ Send request and deliver response back when available. :param messageParts: message data :type messageParts: tuple :param timeout: as keyword argument, timeout on request :type timeout: float :return: Deferred that will fire when response comes back """ messageId = self._getNextId() d = defer.Deferred(canceller=lambda _: self._cancel(messageId)) timeout = kwargs.pop('timeout', None) if timeout is None: timeout = self.defaultRequestTimeout assert len(kwargs) == 0, "Unsupported keyword argument" canceller = None if timeout is not None: canceller = reactor.callLater(timeout, self._timeoutRequest, messageId) self._requests[messageId] = (d, canceller) self.send([messageId, b''] + list(messageParts)) return d def messageReceived(self, message): """ Called on incoming message from ZeroMQ. Dispatches message to back to the requestor. :param message: message data """ msgId, msg = message[0], message[2:] self._releaseId(msgId) d, canceller = self._requests.pop(msgId, (None, None)) if canceller is not None and canceller.active(): canceller.cancel() if d is None: # reply came for timed out or cancelled request, drop it silently return d.callback(msg) class ZmqREPConnection(ZmqConnection): """ A Reply ZeroMQ connection. This is implemented with an underlying ROUTER socket, but the semantics are close to REP socket. """ socketType = constants.ROUTER def __init__(self, *args, **kwargs): ZmqConnection.__init__(self, *args, **kwargs) self._routingInfo = {} # keep track of routing info def reply(self, messageId, *messageParts): """ Send reply to request with specified ``messageId``. :param messageId: message uuid :type messageId: str :param messageParts: message data :type messageParts: list """ routingInfo = self._routingInfo.pop(messageId) self.send(routingInfo + [messageId, b''] + list(messageParts)) def messageReceived(self, message): """ Called on incoming message from ZeroMQ. :param message: message data """ i = message.index(b'') assert i > 0 (routingInfo, msgId, payload) = ( message[:i - 1], message[i - 1], message[i + 1:]) msgParts = payload[0:] self._routingInfo[msgId] = routingInfo self.gotMessage(msgId, *msgParts) def gotMessage(self, messageId, *messageParts): """ Called on incoming request. Override this method in subclass and reply using :meth:`reply` using the same ``messageId``. :param messageId: message uuid :type messageId: str :param messageParts: message data """ raise NotImplementedError(self) class ZmqXREPConnection(ZmqREPConnection): """ Provided for backwards compatibility. Deprecated in favour of either ZmqREPConnection or ZmqROUTERConnection. """ def __init__(self, factory, *endpoints): warnings.warn("ZmqXREPConnection is deprecated in favour of " "either ZmqREPConnection or ZmqROUTERConnection", DeprecationWarning) ZmqREPConnection.__init__(self, factory) self.add_endpoints(endpoints) class ZmqXREQConnection(ZmqREQConnection): """ Provided for backwards compatibility. Deprecated in favour of either ZmqREQConnection or ZmqDEALERConnection. """ def __init__(self, factory, *endpoints): warnings.warn("ZmqXREQConnection is deprecated in favour of " "either ZmqREQConnection or ZmqDEALERConnection", DeprecationWarning) ZmqREQConnection.__init__(self, factory) self.add_endpoints(endpoints) txZMQ-0.8.0/txzmq/router_dealer.py0000644000076500000240000000472413012703031017366 0ustar smirastaff00000000000000""" ZeroMQ ROUTER and DEALER connection types. """ from zmq import constants from txzmq.connection import ZmqConnection # TODO: ideally, all connection classes would inherit from this in the future # so that we'd have a consistent wrapper API over all underlying socket types. class ZmqBase(ZmqConnection): """ Base class for all ZMQ connection classes with a uniform interface. Subclasses should override sendMsg and sendMultipart with their own connection-type specific implementations, which can have a different argument signature. Thus, ZmqBase does not attempt to hide away the differences between different connection classes--this is simply impossible--It simply attempts to provide a more consistent way of interacting with them. By default, these methods simply delegate to the unerlying low-level ZmqConnection.send, which handles both single and multi-part messages. Subclasses can/should add their own semantic aliases for sendMsg and sendMultipart, such as publish and publishMultipart for a PUB socket. """ def sendMsg(self, message): """ Provides a higher level wrapper over ZmqConnection.send for sending single-part messages. @param message: message data @type message: C{str} """ self.sendMultipart([message]) def sendMultipart(self, parts): """ Provides a higher level wrapper over ZmqConnection.send for sending multipart messages. @param parts: message data """ self.send(parts) def messageReceived(self, message): """ Called on incoming message from ZeroMQ. Override this to handle generic messages received and pass them to gotMessage with a socket-type specific signature. @param message: message data """ self.gotMessage(*message) def gotMessage(self, *args, **kwargs): raise NotImplementedError class ZmqDealerConnection(ZmqBase): """ Raw ZeroMQ DEALER connection. """ socketType = constants.DEALER class ZmqRouterConnection(ZmqBase): """ Raw ZeroMQ ROUTER connection. """ socketType = constants.ROUTER def sendMsg(self, recipientId, message): self.send([recipientId, message]) def sendMultipart(self, recipientId, parts): self.send([recipientId] + parts) def messageReceived(self, message): sender_id = message.pop(0) self.gotMessage(sender_id, *message) txZMQ-0.8.0/txzmq/test/0000755000076500000240000000000013051415230015134 5ustar smirastaff00000000000000txZMQ-0.8.0/txzmq/test/__init__.py0000644000076500000240000000027013012703031017240 0ustar smirastaff00000000000000""" Tests for L{txzmq}. """ from twisted.internet import defer, reactor def _wait(interval): d = defer.Deferred() reactor.callLater(interval, d.callback, None) return d txZMQ-0.8.0/txzmq/test/test_connection.py0000644000076500000240000001010313012703031020673 0ustar smirastaff00000000000000""" Tests for L{txzmq.connection}. """ from zmq import constants from zope.interface import verify as ziv from twisted.internet.interfaces import IFileDescriptor, IReadDescriptor from twisted.trial import unittest from txzmq.connection import ZmqConnection, ZmqEndpoint, ZmqEndpointType from txzmq.factory import ZmqFactory from txzmq.test import _wait class ZmqTestSender(ZmqConnection): socketType = constants.PUSH class ZmqTestReceiver(ZmqConnection): socketType = constants.PULL def messageReceived(self, message): if not hasattr(self, 'messages'): self.messages = [] self.messages.append(message) class ZmqConnectionTestCase(unittest.TestCase): """ Test case for L{zmq.twisted.connection.Connection}. """ def setUp(self): self.factory = ZmqFactory() def tearDown(self): self.factory.shutdown() def test_interfaces(self): ziv.verifyClass(IReadDescriptor, ZmqConnection) ziv.verifyClass(IFileDescriptor, ZmqConnection) def test_init(self): ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "inproc://#1")) ZmqTestSender( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "inproc://#1")) def test_addEndpoints(self): r = ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "inproc://#1")) r.addEndpoints([ZmqEndpoint(ZmqEndpointType.bind, "inproc://#2"), ZmqEndpoint(ZmqEndpointType.bind, "inproc://#3")]) s = ZmqTestSender( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "inproc://#3")) s.send(b'abcd') def check(ignore): result = getattr(r, 'messages', []) expected = [[b'abcd']] self.failUnlessEqual( result, expected, "Message should have been received") return _wait(0.01).addCallback(check) def test_repr(self): expected = ("ZmqTestReceiver(ZmqFactory(), " "[ZmqEndpoint(type='bind', address='inproc://#1')])") result = ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "inproc://#1")) self.failUnlessEqual(expected, repr(result)) def test_send_recv(self): r = ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "inproc://#1")) s = ZmqTestSender( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "inproc://#1")) s.send(b'abcd') def check(ignore): result = getattr(r, 'messages', []) expected = [[b'abcd']] self.failUnlessEqual( result, expected, "Message should have been received") return _wait(0.01).addCallback(check) def test_send_recv_tcp(self): r = ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "tcp://127.0.0.1:5555")) s = ZmqTestSender( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "tcp://127.0.0.1:5555")) for i in range(100): s.send(str(i).encode()) def check(ignore): result = getattr(r, 'messages', []) expected = [[str(i).encode()] for i in range(100)] self.failUnlessEqual( result, expected, "Messages should have been received") return _wait(0.01).addCallback(check) def test_send_recv_tcp_large(self): r = ZmqTestReceiver( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "tcp://127.0.0.1:5555")) s = ZmqTestSender( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "tcp://127.0.0.1:5555")) s.send([b'0' * 10000, b'1' * 10000]) def check(ignore): result = getattr(r, 'messages', []) expected = [[b'0' * 10000, b'1' * 10000]] self.failUnlessEqual( result, expected, "Messages should have been received") return _wait(0.01).addCallback(check) txZMQ-0.8.0/txzmq/test/test_factory.py0000644000076500000240000000052613012703031020213 0ustar smirastaff00000000000000""" Tests for L{txzmq.factory}. """ from twisted.trial import unittest from txzmq.factory import ZmqFactory class ZmqFactoryTestCase(unittest.TestCase): """ Test case for L{zmq.twisted.factory.Factory}. """ def setUp(self): self.factory = ZmqFactory() def test_shutdown(self): self.factory.shutdown() txZMQ-0.8.0/txzmq/test/test_pubsub.py0000644000076500000240000001044613012703031020046 0ustar smirastaff00000000000000""" Tests for L{txzmq.pubsub}. """ from twisted.trial import unittest from txzmq.connection import ZmqEndpoint, ZmqEndpointType from txzmq.factory import ZmqFactory from txzmq.pubsub import ZmqPubConnection, ZmqSubConnection from txzmq.test import _wait from zmq.error import ZMQError class ZmqTestSubConnection(ZmqSubConnection): def gotMessage(self, message, tag): if not hasattr(self, 'messages'): self.messages = [] self.messages.append([tag, message]) def _detect_epgm(): """ Utility function to test for presence of epgm:// in zeromq. """ import zmq context = zmq.Context() socket = zmq.Socket(context, zmq.constants.PUB) try: socket.bind("epgm://127.0.0.1;239.192.1.1:5557") return True except ZMQError: return False class ZmqConnectionTestCase(unittest.TestCase): """ Test case for L{zmq.twisted.connection.Connection}. In ZeroMQ 2.x, subscription is handled on receiving side: incoming messages are simply filtered, that's why connection.subscribe works immediately. In ZeroMQ 3.x, subscription is handled on publisher side: subscriber sends message to the publisher and publisher adjusts filtering on its side. So connection.subscribe doesn't start filtering immediately, it takes some time for messages to pass through the channel. """ def setUp(self): self.factory = ZmqFactory() ZmqPubConnection.allowLoopbackMulticast = True def tearDown(self): del ZmqPubConnection.allowLoopbackMulticast self.factory.shutdown() def test_send_recv(self): r = ZmqTestSubConnection( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "ipc://test-sock")) s = ZmqPubConnection( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "ipc://test-sock")) r.subscribe(b'tag') def publish(ignore): s.publish(b'xyz', b'different-tag') s.publish(b'abcd', b'tag1') s.publish(b'efgh', b'tag2') def check(ignore): result = getattr(r, 'messages', []) expected = [[b'tag1', b'abcd'], [b'tag2', b'efgh']] self.failUnlessEqual( result, expected, "Message should have been received") return _wait(0.01).addCallback(publish) \ .addCallback(lambda _: _wait(0.01)).addCallback(check) def test_send_recv_pgm(self): r = ZmqTestSubConnection(self.factory, ZmqEndpoint( ZmqEndpointType.bind, "epgm://127.0.0.1;239.192.1.1:5556")) s = ZmqPubConnection(self.factory, ZmqEndpoint( ZmqEndpointType.connect, "epgm://127.0.0.1;239.192.1.1:5556")) r.subscribe(b'tag') def publish(ignore): s.publish(b'xyz', b'different-tag') s.publish(b'abcd', b'tag1') def check(ignore): result = getattr(r, 'messages', []) expected = [[b'tag1', b'abcd']] self.failUnlessEqual( result, expected, "Message should have been received") return _wait(0.2).addCallback(publish) \ .addCallback(lambda _: _wait(0.2)).addCallback(check) def test_send_recv_multiple_endpoints(self): r = ZmqTestSubConnection( self.factory, ZmqEndpoint(ZmqEndpointType.bind, "tcp://127.0.0.1:5556")) r.addEndpoints([ZmqEndpoint(ZmqEndpointType.bind, "inproc://endpoint")]) s1 = ZmqPubConnection( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "tcp://127.0.0.1:5556")) s2 = ZmqPubConnection( self.factory, ZmqEndpoint(ZmqEndpointType.connect, "inproc://endpoint")) r.subscribe(b'') def publish(ignore): s1.publish(b'111', b'tag1') s2.publish(b'222', b'tag2') def check(ignore): result = getattr(r, 'messages', []) expected = [[b'tag1', b'111'], [b'tag2', b'222']] self.failUnlessEqual( sorted(result), expected, "Message should have been received") return _wait(0.1).addCallback(publish) \ .addCallback(lambda _: _wait(0.1)).addCallback(check) if not _detect_epgm(): test_send_recv_pgm.skip = "epgm:// not available" txZMQ-0.8.0/txzmq/test/test_reactor_shutdown.py0000644000076500000240000000216313012703031022135 0ustar smirastaff00000000000000""" Tests for L{txzmq.factory} automatic shutdown. """ from txzmq.factory import ZmqFactory from twisted.internet.test.reactormixins import ReactorBuilder from twisted.internet.interfaces import IReactorCore class ZmqReactorShutdownTestCase(ReactorBuilder): """ Test case for L{zmq.twisted.factory.Factory} automatic shutdown when the reactor is shutting down. """ requiredInterfaces = (IReactorCore,) def test_reactor_and_factory_shutdown(self): reactor = self.buildReactor() def _test(): factory = ZmqFactory() factory.reactor = reactor factory.registerForShutdown() factory.shutdown() reactor.stop() reactor.callWhenRunning(_test) reactor.run() def test_reactor_shutdown(self): reactor = self.buildReactor() def _test(): factory = ZmqFactory() factory.reactor = reactor factory.registerForShutdown() reactor.stop() reactor.callWhenRunning(_test) reactor.run() globals().update(ZmqReactorShutdownTestCase.makeTestCaseClasses()) txZMQ-0.8.0/txzmq/test/test_reqrep.py0000644000076500000240000001506013012703031020041 0ustar smirastaff00000000000000""" Tests for L{txzmq.req_rep}. """ from twisted.internet import defer, reactor from twisted.trial import unittest from txzmq.connection import ZmqEndpoint, ZmqEndpointType from txzmq.factory import ZmqFactory from txzmq.test import _wait from txzmq.req_rep import ZmqREPConnection, ZmqREQConnection, \ ZmqRequestTimeoutError from txzmq.compat import binary_string_type class ZmqTestREPConnection(ZmqREPConnection): def gotMessage(self, messageId, *messageParts): if not hasattr(self, 'messages'): self.messages = [] self.messages.append([messageId, messageParts]) self.reply(messageId, *messageParts) class ZmqSlowREPConnection(ZmqREPConnection): def gotMessage(self, messageId, *messageParts): reactor.callLater(0.1, self.reply, messageId, *messageParts) class ZmqREQREPConnectionTestCase(unittest.TestCase): """ Test case for L{zmq.req_rep.ZmqREPConnection}. """ def setUp(self): self.factory = ZmqFactory() b = ZmqEndpoint(ZmqEndpointType.bind, "ipc://#3") self.r = ZmqTestREPConnection(self.factory, b) c = ZmqEndpoint(ZmqEndpointType.connect, "ipc://#3") self.s = ZmqREQConnection(self.factory, c, identity=b'client') def tearDown(self): self.factory.shutdown() def test_getNextId(self): self.failUnlessEqual([], self.s._uuids) id1 = self.s._getNextId() self.failUnlessEqual(self.s.UUID_POOL_GEN_SIZE - 1, len(self.s._uuids)) self.failUnlessIsInstance(id1, binary_string_type) id2 = self.s._getNextId() self.failUnlessIsInstance(id2, binary_string_type) self.failIfEqual(id1, id2) ids = [self.s._getNextId() for _ in range(1000)] self.failUnlessEqual(len(ids), len(set(ids))) def test_releaseId(self): self.s._releaseId(self.s._getNextId()) self.failUnlessEqual(self.s.UUID_POOL_GEN_SIZE, len(self.s._uuids)) def test_send_recv(self): self.count = 0 def get_next_id(): self.count += 1 return b'msg_id_' + str(self.count).encode() self.s._getNextId = get_next_id self.s.sendMsg(b'aaa', b'aab') self.s.sendMsg(b'bbb') def check(ignore): result = getattr(self.r, 'messages', []) expected = [[b'msg_id_1', (b'aaa', b'aab')], [b'msg_id_2', (b'bbb',)]] self.failUnlessEqual( result, expected, "Message should have been received") return _wait(0.01).addCallback(check) def test_send_recv_reply(self): d = self.s.sendMsg(b'aaa') def check_response(response): self.assertEqual(response, [b'aaa']) d.addCallback(check_response) return d def test_lot_send_recv_reply(self): deferreds = [] for i in range(10): msg_id = "msg_id_%d" % (i,) d = self.s.sendMsg(b'aaa') def check_response(response, msg_id): self.assertEqual(response, [b'aaa']) d.addCallback(check_response, msg_id) deferreds.append(d) return defer.DeferredList(deferreds, fireOnOneErrback=True) def test_cleanup_requests(self): """The request dict is cleanedup properly.""" def check(ignore): self.assertEqual(self.s._requests, {}) self.failUnlessEqual(self.s.UUID_POOL_GEN_SIZE, len(self.s._uuids)) return self.s.sendMsg(b'aaa').addCallback(check) def test_cancel(self): d = self.s.sendMsg(b'aaa') d.cancel() def check_requests(_): self.assertEqual(self.s._requests, {}) self.failUnlessEqual(self.s.UUID_POOL_GEN_SIZE, len(self.s._uuids) + 1) return d.addCallbacks(lambda _: self.fail("Should have errored"), lambda fail: fail.trap( "twisted.internet.defer.CancelledError")) \ .addCallback(check_requests) \ .addCallback(lambda _: _wait(0.01)) def test_send_timeout_ok(self): return self.s.sendMsg(b'aaa', timeout=0.1).addCallback( lambda response: self.assertEquals(response, [b'aaa']) ) def test_send_timeout_fail(self): b = ZmqEndpoint(ZmqEndpointType.bind, "ipc://#4") ZmqSlowREPConnection(self.factory, b) c = ZmqEndpoint(ZmqEndpointType.connect, "ipc://#4") s = ZmqREQConnection(self.factory, c, identity=b'client2') return s.sendMsg(b'aaa', timeout=0.05) \ .addCallbacks(lambda _: self.fail("Should timeout"), lambda fail: fail.trap(ZmqRequestTimeoutError)) \ .addCallback(lambda _: _wait(0.1)) class ZmqReplyConnection(ZmqREPConnection): def messageReceived(self, message): if not hasattr(self, 'message_count'): self.message_count = 0 if message[1] == b'stop': reactor.callLater(0, self.send, [b'master', b'exit']) else: self.message_count += 1 self.send([b'master', b'event']) for _ in range(2): reactor.callLater(0, self.send, [b'master', b'event']) class ZmqRequestConnection(ZmqREQConnection): def messageReceived(self, message): if not hasattr(self, 'message_count'): self.message_count = 0 if message[0] == b'event': self.message_count += 1 elif message[0] == b'exit': self.d.callback(None) else: assert False class ZmqREQREPTwoFactoryConnectionTestCase(unittest.TestCase): """ Test case for L{zmq.req_rep} with REQ/REP in two factories. """ REQUEST_COUNT = 10000 def setUp(self): self.factory1 = ZmqFactory() self.factory2 = ZmqFactory() c = ZmqEndpoint(ZmqEndpointType.connect, "tcp://127.0.0.1:7859") self.c1 = ZmqRequestConnection(self.factory1, c, identity=b'master') b = ZmqEndpoint(ZmqEndpointType.bind, "tcp://127.0.0.1:7859") self.c2 = ZmqReplyConnection(self.factory2, b, identity=b'slave') self.c1.d = defer.Deferred() def tearDown(self): self.factory2.shutdown() self.factory1.shutdown() def test_start(self): for _ in range(self.REQUEST_COUNT): reactor.callLater(0, self.c1.send, b'req') reactor.callLater(0, self.c1.send, b'stop') def checkResults(_): self.failUnlessEqual(self.c1.message_count, 3 * self.REQUEST_COUNT) self.failUnlessEqual(self.c2.message_count, self.REQUEST_COUNT) return self.c1.d.addCallback(checkResults) txZMQ-0.8.0/txzmq/test/test_router_dealer.py0000644000076500000240000000454713012703031021407 0ustar smirastaff00000000000000""" Tests for L{txzmq.router_dealer}. """ from twisted.internet import defer, reactor from twisted.trial import unittest from txzmq.connection import ZmqEndpoint, ZmqEndpointType from txzmq.factory import ZmqFactory from txzmq.router_dealer import ZmqRouterConnection, ZmqDealerConnection class ZmqTestRouterConnection(ZmqRouterConnection): message_count = 0 def gotMessage(self, senderId, message): assert senderId == b'dealer' if message == b'stop': reactor.callLater(0, self.sendMsg, b'dealer', b'exit') else: self.message_count += 1 self.sendMsg(b'dealer', b'event') for _ in range(2): reactor.callLater(0, self.sendMsg, b'dealer', b'event') class ZmqTestDealerConnection(ZmqDealerConnection): message_count = 0 def gotMessage(self, message): if message == b'event': self.message_count += 1 elif message == b'exit': self.d.callback(None) else: assert False, "received unexpected message: %r" % (message,) class ZmqRouterDealerTwoFactoryConnectionTestCase(unittest.TestCase): """ Test case for L{txzmq.req_rep} with ROUTER/DEALER in two factories. """ REQUEST_COUNT = 10000 def setUp(self): self.factory1 = ZmqFactory() dealer_endpoint = ZmqEndpoint(ZmqEndpointType.connect, "ipc://#7") self.dealer = ZmqTestDealerConnection(self.factory1, dealer_endpoint, identity=b'dealer') self.dealer.d = defer.Deferred() self.factory2 = ZmqFactory() router_endpoint = ZmqEndpoint(ZmqEndpointType.bind, "ipc://#7") self.router = ZmqTestRouterConnection(self.factory2, router_endpoint, identity=b'router') def tearDown(self): self.factory2.shutdown() self.factory1.shutdown() def test_start(self): for _ in range(self.REQUEST_COUNT): reactor.callLater(0, self.dealer.sendMsg, b'req') reactor.callLater(0, self.dealer.sendMsg, b'stop') def checkResults(_): self.failUnlessEqual(self.dealer.message_count, 3 * self.REQUEST_COUNT) self.failUnlessEqual(self.router.message_count, self.REQUEST_COUNT) return self.dealer.d.addCallback(checkResults) txZMQ-0.8.0/VERSION0000644000076500000240000000000613051414370014042 0ustar smirastaff000000000000000.8.0