diff --git a/LICENSE.md b/LICENSE.md index f9c5f7f..5368eaf 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,4 +1,4 @@ -Copyright (c) 2014, Shiz +Copyright (c) 2014-2016, Shiz All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/docs/conf.py b/docs/conf.py index 6ea497c..5dbb89e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -35,8 +35,7 @@ # Documentation links for projects we link to. intersphinx_mapping = { - 'python': ('http://docs.python.org/3', None), - 'tornado': ('http://www.tornadoweb.org/en/stable', None), + 'python': ('http://docs.python.org/3', None) } diff --git a/docs/index.rst b/docs/index.rst index c4489c9..76f0bbb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -28,7 +28,7 @@ Features No half-assing functionality. - **Asynchronous** - IRC is an asychronous protocol; it only makes sense a clients that implements it is asynchronous as well. Built on top of the wonderful Tornado_ library, pydle relies on proven technologies to deliver proper high-performance asynchronous functionality and primitives. + IRC is an asychronous protocol; it only makes sense a clients that implements it is asynchronous as well. Built on top of the wonderful asyncio_ library, pydle relies on proven technologies to deliver proper high-performance asynchronous functionality and primitives. pydle allows using Futures to make asynchronous programming just as intuitive as doing regular blocking operations. No callback spaghetti. @@ -45,7 +45,7 @@ Features .. _WHOX: https://hg.quakenet.org/snircd/file/tip/doc/readme.who .. _IRCv3.1: http://ircv3.org/ .. _IRCv3.2: http://ircv3.org/ -.. _Tornado: http://tornadoweb.org +.. _asyncio: https://docs.python.org/3/library/asyncio.html Contents -------- diff --git a/docs/intro.rst b/docs/intro.rst index a2acc32..091a400 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -4,7 +4,7 @@ Introduction to pydle What is pydle? -------------- -pydle is an IRC library for Python 3.2 and up. +pydle is an IRC library for Python 3.4 and up. Although old and dated on some fronts, IRC is still used by a variety of communities as the real-time communication method of choice, and the most popular IRC networks can still count on tens of thousands of users at any point during the day. @@ -23,7 +23,7 @@ and APIs are prone to change or removal at least until version 1.0 has been reac Requirements ------------ Most of pydle is written in pure, portable Python that only relies on the standard library. -However, pydle relies on Tornado_ to do the heavy lifting on the asynchronous front. +If your Python version is from before 3.4, you may install the asyncio_ backport. Be aware that new keywords such as `await` and `async` are not supported in this case. Optionally, if you plan to use pydle's SASL functionality for authentication, the excellent pure-sasl_ library is required. All dependencies can be installed using the standard package manager for Python, pip, and the included requirements file: @@ -32,7 +32,7 @@ All dependencies can be installed using the standard package manager for Python, pip install -r requirements.txt -.. _Tornado: http://www.tornadoweb.org/ +.. _asyncio: https://github.com/python/asyncio .. _pure-sasl: https://github.com/thobbs/pure-sasl Compatibility diff --git a/docs/licensing.rst b/docs/licensing.rst index f26639c..ee2368b 100644 --- a/docs/licensing.rst +++ b/docs/licensing.rst @@ -7,7 +7,7 @@ pydle license :: - Copyright (c) 2014, Shiz + Copyright (c) 2014-2016, Shiz All rights reserved. Redistribution and use in source and binary forms, with or without @@ -35,219 +35,6 @@ pydle license ------ -pydle relies on Tornado_ for a significant part of its networking code; its license is printed in verbatim below. - -.. _Tornado: http://tornadoweb.org - -Tornado license ---------------- - -:: - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ------ - pydle optionally relies on pure-sasl_ to provide SASL authentication methods; its license is printed in verbatim below. .. _pure-sasl: https://github.com/thobbs/pure-sasl diff --git a/pydle/async.py b/pydle/async.py index d6bb078..63f8169 100644 --- a/pydle/async.py +++ b/pydle/async.py @@ -8,103 +8,35 @@ import datetime import types -import tornado.concurrent -import tornado.ioloop +import asyncio FUTURE_TIMEOUT = 30 -class Future(tornado.concurrent.TracebackFuture): +class Future(asyncio.Future): """ A future. An object that represents a result that has yet to be created or returned. """ - -def coroutine(func): - """ Decorator for coroutine functions that need to block for asynchronous operations. """ - @functools.wraps(func) - def wrapper(*args, **kwargs): - return_future = Future() - - def handle_future(future): - # Chained futures! - try: - if future.exception() is not None: - result = gen.throw(future.exception()) - else: - result = gen.send(future.result()) - if isinstance(result, tuple): - result = parallel(*result) - result.add_done_callback(handle_future) - except StopIteration as e: - return_future.set_result(getattr(e, 'value', None)) - except Exception as e: - return_future.set_exception(e) - - try: - # Handle initial value. - gen = func(*args, **kwargs) - except Exception as e: - return_future.set_exception(e) - return return_future - else: - # If this isn't a generator, then wrap the result with a future. - if not isinstance(gen, types.GeneratorType): - return_future.set_result(gen) - return return_future - - try: - result = next(gen) - if isinstance(result, tuple): - result = parallel(*result) - result.add_done_callback(handle_future) - except StopIteration as e: - return_future.set_result(getattr(e, 'value', None)) - except Exception as e: - return_future.set_exception(e) - - return return_future - return wrapper +def coroutine(f): + return asyncio.coroutine(f) def parallel(*futures): - """ Create a single future that will be completed when all the given futures are. """ - result_future = Future() - results = collections.OrderedDict(zip(futures, itertools.repeat(None))) - futures = list(futures) - - if not futures: - # If we don't have any futures, then we return an empty tuple. - result_future.set_result(()) - return result_future - - def done(future): - futures.remove(future) - results[future] = future.result() - # All out of futures. set the result. - if not futures: - result_future.set_result(tuple(results.values())) - - for future in futures: - future.add_done_callback(done) - - return result_future + return asyncio.gather(*futures) class EventLoop: """ A light wrapper around what event loop mechanism pydle uses underneath. """ - EVENT_MAPPING = { - 'read': tornado.ioloop.IOLoop.READ, - 'write': tornado.ioloop.IOLoop.WRITE, - 'error': tornado.ioloop.IOLoop.ERROR - } def __init__(self, io_loop=None): - self.io_loop = io_loop or tornado.ioloop.IOLoop.current() - self.running = False - self.run_thread = None + self.io_loop = io_loop or asyncio.get_event_loop() self.handlers = {} + self.handling = {} self.future_timeout = FUTURE_TIMEOUT - self._registered_events = set() + self.event_types = { + 'read': (self.io_loop.add_reader, self.io_loop.remove_reader), + 'write': (self.io_loop.add_writer, self.io_loop.remove_writer) + } self._future_timeouts = {} self._timeout_id = 0 self._timeout_handles = {} @@ -113,13 +45,20 @@ def __del__(self): self.io_loop.close() + @property + def running(self): + return self.io_loop.is_running() + + def register(self, fd): """ Register a file descriptor with this event loop. """ - self.handlers[fd] = { key: [] for key in self.EVENT_MAPPING } + self.handlers[fd] = {e: [] for e in self.event_types} + self.handling[fd] = {e: False for e in self.event_types} def unregister(self, fd): """ Unregister a file descriptor with this event loop. """ del self.handlers[fd] + del self.handling[fd] def on_read(self, fd, callback): @@ -138,14 +77,6 @@ def on_write(self, fd, callback): self.handlers[fd]['write'].append(callback) self._update_events(fd) - def on_error(self, fd, callback): - """ - Add a callback for when an error has occurred on the given file descriptor. - Callback will be called with file descriptor as sole argument. - """ - self.handlers[fd]['error'].append(callback) - self._update_events(fd) - def off_read(self, fd, callback): """ Remove read callback for given file descriptor. """ self.handlers[fd]['read'].remove(callback) @@ -156,11 +87,6 @@ def off_write(self, fd, callback): self.handlers[fd]['write'].remove(callback) self._update_events(fd) - def off_error(self, fd, callback): - """ Remove error callback for given file descriptor. """ - self.handlers[fd]['error'].remove(callback) - self._update_events(fd) - def handles_read(self, fd, callback): """ Return whether or the given read callback is active for the given file descriptor. """ return callback in self.handlers[fd]['read'] @@ -169,31 +95,22 @@ def handles_write(self, fd, callback): """ Return whether or the given write callback is active for the given file descriptor. """ return callback in self.handlers[fd]['write'] - def handles_error(self, fd, callback): - """ Return whether or the given error callback is active for the given file descriptor. """ - return callback in self.handlers[fd]['error'] - def _update_events(self, fd): - if fd in self._registered_events: - self.io_loop.remove_handler(fd) - - events = 0 - for event, ident in self.EVENT_MAPPING.items(): - if self.handlers[fd][event]: - events |= ident - - self.io_loop.add_handler(fd, self._do_on_event, events) - self._registered_events.add(fd) - - def _do_on_event(self, fd, events): + for e, (adder, remover) in self.event_types.items(): + if self.handlers[fd][e] and not self.handling[fd][e]: + adder(fd, self._do_on_event, fd, e) + self.handling[fd][e] = True + elif not self.handlers[fd][e] and self.handling[fd][e]: + remover(fd) + self.handling[fd][e] = False + + def _do_on_event(self, fd, event): if fd not in self.handlers: return - for event, ident in self.EVENT_MAPPING.items(): - if events & ident: - for handler in self.handlers[fd][event]: - handler(fd) + for handler in self.handlers[fd][event]: + handler(fd) def on_future(self, _future, _callback, *_args, **_kwargs): @@ -202,7 +119,7 @@ def on_future(self, _future, _callback, *_args, **_kwargs): # Create timeout handler and regular handler. self._future_timeouts[_future] = self.schedule_in(self.future_timeout, callback) - self.io_loop.add_future(_future, callback) + future.add_done_callback(callback) def _do_on_future(self, callback, args, kwargs, future): # This was a time-out. @@ -230,24 +147,19 @@ def _get_schedule_handle(self): def schedule(self, _callback, *_args, **_kwargs): """ Schedule a callback to be ran as soon as possible in this loop. """ - self.io_loop.add_callback(_callback, *_args, **_kwargs) + self.io_loop.call_soon_threadsafe(_callback, *_args, **_kwargs) def schedule_in(self, _when, _callback, *_args, **_kwargs): """ Schedule a callback to be ran as soon as possible after `when` seconds have passed. Will return an opaque handle that can be passed to `unschedule` to unschedule the function. """ - if not isinstance(_when, datetime.timedelta): - _when = datetime.timedelta(seconds=_when) + if isinstance(_when, datetime.timedelta): + _when = _when.total_seconds() # Create ID for this timeout. id = self._get_schedule_handle() - - if self.run_thread != threading.current_thread().ident: - # Schedule scheduling in IOLoop thread because of thread-safety. - self.schedule(functools.partial(self._do_schedule_in, id, _when, _callback, _args, _kwargs)) - else: - self._do_schedule_in(id, _when, _callback, _args, _kwargs) + self._timeout_handles[id] = self.io_loop.call_later(_when, functools.partial(_callback, *_args, **_kwargs)) return id @@ -257,34 +169,22 @@ def schedule_periodically(self, _interval, _callback, *_args, **_kwargs): Will return an opaque handle that can be passed to unschedule() to unschedule the interval function. A function will also stop being scheduled if it returns False or raises an Exception. """ - if not isinstance(_interval, datetime.timedelta): - _interval = datetime.timedelta(seconds=_interval) + if isinstance(_interval, datetime.timedelta): + _interval = _interval.total_seconds() # Create ID for this periodic. id = self._get_schedule_handle() - - if self.run_thread != threading.current_thread().ident: - # Schedule scheduling in IOLoop thread because of thread-safety. - self.schedule(functools.partial(self._do_schedule_periodically, id, _interval, _callback, _args, _kwargs)) - else: - self._do_schedule_periodically(id, _interval, _callback, _args, _kwargs) + self._timeout_handles[id] = self.io_loop.call_later(interval, functools.partial(self._periodic_handler, id, interval, callback, args, kwargs)) return id - def _do_schedule_in(self, id, when, callback, args, kwargs): - self._timeout_handles[id] = self.io_loop.add_timeout(when, functools.partial(callback, *args, **kwargs)) - - def _do_schedule_periodically(self, id, interval, callback, args, kwargs): - # Use a wrapper function. - self._timeout_handles[id] = self.io_loop.add_timeout(interval, functools.partial(self._periodic_handler, id, interval, callback, args, kwargs)) - def _periodic_handler(self, id, interval, callback, args, kwargs): # We could've been unscheduled for some reason. if not self.is_scheduled(id): return # Call callback, and schedule again if it doesn't return False. - self._do_schedule_periodically(id, interval, callback, args, kwargs) + self._timeout_handles[id] = self.io_loop.call_later(interval, functools.partial(self._periodic_handler, id, interval, callback, args, kwargs)) result = False try: @@ -301,29 +201,21 @@ def unschedule(self, handle): """ Unschedule a given timeout or periodical callback. """ if self.is_scheduled(handle): handle = self._timeout_handles.pop(handle) - self.io_loop.remove_timeout(handle) + handle.cancel() def run(self): """ Run the event loop. """ if not self.running: - self.running = True - self.run_thread = threading.current_thread().ident - self.io_loop.start() - self.run_thread = None - self.running = False + self.io_loop.run_forever() def run_with(self, func): """ Run loop, call function, stop loop. If function returns a future, run until the future has been resolved. """ - self.running = True - self.run_thread = threading.current_thread().ident - self.io_loop.run_sync(func) - self.run_thread = None - self.running = False + return self.run_until(asyncio.ensure_future(func)) def run_until(self, future): """ Run until future is resolved. """ - return self.run_with(lambda: future) + self.io_loop.run_until_complete(future) def stop(self): """ Stop the event loop. """ diff --git a/pydle/connection.py b/pydle/connection.py index ac92507..bf2ab42 100644 --- a/pydle/connection.py +++ b/pydle/connection.py @@ -55,7 +55,7 @@ def __init__(self, hostname, port, tls=False, tls_verify=True, tls_certificate_f self.socket = None self.socket_lock = threading.RLock() self.eventloop = eventloop or async.EventLoop() - self.handlers = { 'read': [], 'write': [], 'error': [] } + self.handlers = {'read': [], 'write': [], 'error': []} self.send_queue = collections.deque() self.send_queue_lock = threading.RLock() @@ -238,7 +238,6 @@ def setup_handlers(self): self.remove_handlers() with self.socket_lock: self.eventloop.on_read(self.socket.fileno(), self._on_read) - self.eventloop.on_error(self.socket.fileno(), self._on_error) self.update_write_handler() @@ -252,8 +251,6 @@ def remove_handlers(self): self.eventloop.off_read(self.socket.fileno(), self._on_read) if self.eventloop.handles_write(self.socket.fileno(), self._on_write): self.eventloop.off_write(self.socket.fileno(), self._on_write) - if self.eventloop.handles_error(self.socket.fileno(), self._on_error): - self.eventloop.off_error(self.socket.fileno(), self._on_error) def update_write_handler(self): """ diff --git a/requirements.txt b/requirements.txt index 9e88c1c..3000040 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1 @@ -tornado -e git+https://github.com/thobbs/pure-sasl#egg=pure-sasl diff --git a/setup.py b/setup.py index 896f0fb..95b3f5f 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,6 @@ 'pydle.features.ircv3', 'pydle.utils' ], - install_requires=['tornado'], extras_require={ 'sasl': 'pure-sasl >=0.1.6', # for pydle.features.sasl 'docs': 'sphinx_rtd_theme', # the Sphinx theme we use