from .base_events import *
from .coroutines import *
from .events import *
+from .exceptions import *
from .futures import *
from .locks import *
from .protocols import *
__all__ = (base_events.__all__ +
coroutines.__all__ +
events.__all__ +
+ exceptions.__all__ +
futures.__all__ +
locks.__all__ +
protocols.__all__ +
from . import constants
from . import coroutines
from . import events
+from . import exceptions
from . import futures
from . import protocols
from . import sslproto
try:
await self._serving_forever_fut
- except futures.CancelledError:
+ except exceptions.CancelledError:
try:
self.close()
await self.wait_closed()
try:
return await self._sock_sendfile_native(sock, file,
offset, count)
- except events.SendfileNotAvailableError as exc:
+ except exceptions.SendfileNotAvailableError as exc:
if not fallback:
raise
return await self._sock_sendfile_fallback(sock, file,
async def _sock_sendfile_native(self, sock, file, offset, count):
# NB: sendfile syscall is not supported for SSL sockets and
# non-mmap files even if sendfile is supported by OS
- raise events.SendfileNotAvailableError(
+ raise exceptions.SendfileNotAvailableError(
f"syscall sendfile is not available for socket {sock!r} "
"and file {file!r} combination")
try:
return await self._sendfile_native(transport, file,
offset, count)
- except events.SendfileNotAvailableError as exc:
+ except exceptions.SendfileNotAvailableError as exc:
if not fallback:
raise
offset, count)
async def _sendfile_native(self, transp, file, offset, count):
- raise events.SendfileNotAvailableError(
+ raise exceptions.SendfileNotAvailableError(
"sendfile syscall is not supported")
async def _sendfile_fallback(self, transp, file, offset, count):
__all__ = ()
-import concurrent.futures
import reprlib
from . import format_helpers
-CancelledError = concurrent.futures.CancelledError
-TimeoutError = concurrent.futures.TimeoutError
-InvalidStateError = concurrent.futures.InvalidStateError
-
-
# States for Future.
_PENDING = 'PENDING'
_CANCELLED = 'CANCELLED'
__all__ = (
'AbstractEventLoopPolicy',
'AbstractEventLoop', 'AbstractServer',
- 'Handle', 'TimerHandle', 'SendfileNotAvailableError',
+ 'Handle', 'TimerHandle',
'get_event_loop_policy', 'set_event_loop_policy',
'get_event_loop', 'set_event_loop', 'new_event_loop',
'get_child_watcher', 'set_child_watcher',
import threading
from . import format_helpers
-
-
-class SendfileNotAvailableError(RuntimeError):
- """Sendfile syscall is not available.
-
- Raised if OS does not support sendfile syscall for given socket or
- file type.
- """
+from . import exceptions
class Handle:
--- /dev/null
+"""asyncio exceptions."""
+
+
+__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
+ 'IncompleteReadError', 'LimitOverrunError',
+ 'SendfileNotAvailableError')
+
+import concurrent.futures
+from . import base_futures
+
+
+class CancelledError(concurrent.futures.CancelledError):
+ """The Future or Task was cancelled."""
+
+
+class TimeoutError(concurrent.futures.TimeoutError):
+ """The operation exceeded the given deadline."""
+
+
+class InvalidStateError(concurrent.futures.InvalidStateError):
+ """The operation is not allowed in this state."""
+
+
+class SendfileNotAvailableError(RuntimeError):
+ """Sendfile syscall is not available.
+
+ Raised if OS does not support sendfile syscall for given socket or
+ file type.
+ """
+
+
+class IncompleteReadError(EOFError):
+ """
+ Incomplete read error. Attributes:
+
+ - partial: read bytes string before the end of stream was reached
+ - expected: total number of expected bytes (or None if unknown)
+ """
+ def __init__(self, partial, expected):
+ super().__init__(f'{len(partial)} bytes read on a total of '
+ f'{expected!r} expected bytes')
+ self.partial = partial
+ self.expected = expected
+
+ def __reduce__(self):
+ return type(self), (self.partial, self.expected)
+
+
+class LimitOverrunError(Exception):
+ """Reached the buffer limit while looking for a separator.
+
+ Attributes:
+ - consumed: total number of to be consumed bytes.
+ """
+ def __init__(self, message, consumed):
+ super().__init__(message)
+ self.consumed = consumed
+
+ def __reduce__(self):
+ return type(self), (self.args[0], self.consumed)
"""A Future class similar to the one in PEP 3148."""
__all__ = (
- 'CancelledError', 'TimeoutError', 'InvalidStateError',
'Future', 'wrap_future', 'isfuture',
)
from . import base_futures
from . import events
+from . import exceptions
from . import format_helpers
-CancelledError = base_futures.CancelledError
-InvalidStateError = base_futures.InvalidStateError
-TimeoutError = base_futures.TimeoutError
isfuture = base_futures.isfuture
the future is done and has an exception set, this exception is raised.
"""
if self._state == _CANCELLED:
- raise CancelledError
+ raise exceptions.CancelledError
if self._state != _FINISHED:
- raise InvalidStateError('Result is not ready.')
+ raise exceptions.InvalidStateError('Result is not ready.')
self.__log_traceback = False
if self._exception is not None:
raise self._exception
InvalidStateError.
"""
if self._state == _CANCELLED:
- raise CancelledError
+ raise exceptions.CancelledError
if self._state != _FINISHED:
- raise InvalidStateError('Exception is not set.')
+ raise exceptions.InvalidStateError('Exception is not set.')
self.__log_traceback = False
return self._exception
InvalidStateError.
"""
if self._state != _PENDING:
- raise InvalidStateError('{}: {!r}'.format(self._state, self))
+ raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
self._result = result
self._state = _FINISHED
self.__schedule_callbacks()
InvalidStateError.
"""
if self._state != _PENDING:
- raise InvalidStateError('{}: {!r}'.format(self._state, self))
+ raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
if isinstance(exception, type):
exception = exception()
if type(exception) is StopIteration:
fut.set_result(result)
+def _convert_future_exc(exc):
+ exc_class = type(exc)
+ if exc_class is concurrent.futures.CancelledError:
+ return exceptions.CancelledError(*exc.args)
+ elif exc_class is concurrent.futures.TimeoutError:
+ return exceptions.TimeoutError(*exc.args)
+ elif exc_class is concurrent.futures.InvalidStateError:
+ return exceptions.InvalidStateError(*exc.args)
+ else:
+ return exc
+
+
def _set_concurrent_future_state(concurrent, source):
"""Copy state from a future to a concurrent.futures.Future."""
assert source.done()
return
exception = source.exception()
if exception is not None:
- concurrent.set_exception(exception)
+ concurrent.set_exception(_convert_future_exc(exception))
else:
result = source.result()
concurrent.set_result(result)
else:
exception = source.exception()
if exception is not None:
- dest.set_exception(exception)
+ dest.set_exception(_convert_future_exc(exception))
else:
result = source.result()
dest.set_result(result)
from . import events
from . import futures
+from . import exceptions
from .coroutines import coroutine
await fut
finally:
self._waiters.remove(fut)
- except futures.CancelledError:
+ except exceptions.CancelledError:
if not self._locked:
self._wake_up_first()
raise
try:
await self.acquire()
break
- except futures.CancelledError:
+ except exceptions.CancelledError:
cancelled = True
if cancelled:
- raise futures.CancelledError
+ raise exceptions.CancelledError
async def wait_for(self, predicate):
"""Wait until a predicate becomes true.
from . import constants
from . import events
from . import futures
+from . import exceptions
from . import protocols
from . import sslproto
from . import transports
self._force_close(exc)
except OSError as exc:
self._fatal_error(exc, 'Fatal read error on pipe transport')
- except futures.CancelledError:
+ except exceptions.CancelledError:
if not self._closing:
raise
else:
try:
fileno = file.fileno()
except (AttributeError, io.UnsupportedOperation) as err:
- raise events.SendfileNotAvailableError("not a regular file")
+ raise exceptions.SendfileNotAvailableError("not a regular file")
try:
fsize = os.fstat(fileno).st_size
except OSError as err:
- raise events.SendfileNotAvailableError("not a regular file")
+ raise exceptions.SendfileNotAvailableError("not a regular file")
blocksize = count if count else fsize
if not blocksize:
return 0 # empty file
if f is not None:
f.result() # may raise
f = self._proactor.recv(self._ssock, 4096)
- except futures.CancelledError:
+ except exceptions.CancelledError:
# _close_self_pipe() has been called, stop waiting for data
return
except Exception as exc:
elif self._debug:
logger.debug("Accept failed on socket %r",
sock, exc_info=True)
- except futures.CancelledError:
+ except exceptions.CancelledError:
sock.close()
else:
self._accept_futures[sock.fileno()] = f
__all__ = (
'StreamReader', 'StreamWriter', 'StreamReaderProtocol',
- 'open_connection', 'start_server',
- 'IncompleteReadError', 'LimitOverrunError',
-)
+ 'open_connection', 'start_server')
import socket
from . import coroutines
from . import events
+from . import exceptions
from . import protocols
from .log import logger
from .tasks import sleep
_DEFAULT_LIMIT = 2 ** 16 # 64 KiB
-class IncompleteReadError(EOFError):
- """
- Incomplete read error. Attributes:
-
- - partial: read bytes string before the end of stream was reached
- - expected: total number of expected bytes (or None if unknown)
- """
- def __init__(self, partial, expected):
- super().__init__(f'{len(partial)} bytes read on a total of '
- f'{expected!r} expected bytes')
- self.partial = partial
- self.expected = expected
-
- def __reduce__(self):
- return type(self), (self.partial, self.expected)
-
-
-class LimitOverrunError(Exception):
- """Reached the buffer limit while looking for a separator.
-
- Attributes:
- - consumed: total number of to be consumed bytes.
- """
- def __init__(self, message, consumed):
- super().__init__(message)
- self.consumed = consumed
-
- def __reduce__(self):
- return type(self), (self.args[0], self.consumed)
-
-
async def open_connection(host=None, port=None, *,
loop=None, limit=_DEFAULT_LIMIT, **kwds):
"""A wrapper for create_connection() returning a (reader, writer) pair.
seplen = len(sep)
try:
line = await self.readuntil(sep)
- except IncompleteReadError as e:
+ except exceptions.IncompleteReadError as e:
return e.partial
- except LimitOverrunError as e:
+ except exceptions.LimitOverrunError as e:
if self._buffer.startswith(sep, e.consumed):
del self._buffer[:e.consumed + seplen]
else:
# see upper comment for explanation.
offset = buflen + 1 - seplen
if offset > self._limit:
- raise LimitOverrunError(
+ raise exceptions.LimitOverrunError(
'Separator is not found, and chunk exceed the limit',
offset)
if self._eof:
chunk = bytes(self._buffer)
self._buffer.clear()
- raise IncompleteReadError(chunk, None)
+ raise exceptions.IncompleteReadError(chunk, None)
# _wait_for_data() will resume reading if stream was paused.
await self._wait_for_data('readuntil')
if isep > self._limit:
- raise LimitOverrunError(
+ raise exceptions.LimitOverrunError(
'Separator is found, but chunk is longer than limit', isep)
chunk = self._buffer[:isep + seplen]
if self._eof:
incomplete = bytes(self._buffer)
self._buffer.clear()
- raise IncompleteReadError(incomplete, n)
+ raise exceptions.IncompleteReadError(incomplete, n)
await self._wait_for_data('readexactly')
from . import base_tasks
from . import coroutines
from . import events
+from . import exceptions
from . import futures
from .coroutines import coroutine
def __step(self, exc=None):
if self.done():
- raise futures.InvalidStateError(
+ raise exceptions.InvalidStateError(
f'_step(): already done: {self!r}, {exc!r}')
if self._must_cancel:
- if not isinstance(exc, futures.CancelledError):
- exc = futures.CancelledError()
+ if not isinstance(exc, exceptions.CancelledError):
+ exc = exceptions.CancelledError()
self._must_cancel = False
coro = self._coro
self._fut_waiter = None
if self._must_cancel:
# Task is cancelled right before coro stops.
self._must_cancel = False
- super().set_exception(futures.CancelledError())
+ super().set_exception(exceptions.CancelledError())
else:
super().set_result(exc.value)
- except futures.CancelledError:
+ except exceptions.CancelledError:
super().cancel() # I.e., Future.cancel(self).
except Exception as exc:
super().set_exception(exc)
return fut.result()
fut.cancel()
- raise futures.TimeoutError()
+ raise exceptions.TimeoutError()
waiter = loop.create_future()
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
# wait until the future completes or the timeout
try:
await waiter
- except futures.CancelledError:
+ except exceptions.CancelledError:
fut.remove_done_callback(cb)
fut.cancel()
raise
# after wait_for() returns.
# See https://bugs.python.org/issue32751
await _cancel_and_wait(fut, loop=loop)
- raise futures.TimeoutError()
+ raise exceptions.TimeoutError()
finally:
timeout_handle.cancel()
f = await done.get()
if f is None:
# Dummy value from _on_timeout().
- raise futures.TimeoutError
+ raise exceptions.TimeoutError
return f.result() # May raise f.exception().
for f in todo:
# Check if 'fut' is cancelled first, as
# 'fut.exception()' will *raise* a CancelledError
# instead of returning it.
- exc = futures.CancelledError()
+ exc = exceptions.CancelledError()
outer.set_exception(exc)
return
else:
# Check if 'fut' is cancelled first, as
# 'fut.exception()' will *raise* a CancelledError
# instead of returning it.
- res = futures.CancelledError()
+ res = exceptions.CancelledError()
else:
res = fut.exception()
if res is None:
# If gather is being cancelled we must propagate the
# cancellation regardless of *return_exceptions* argument.
# See issue 32684.
- outer.set_exception(futures.CancelledError())
+ outer.set_exception(exceptions.CancelledError())
else:
outer.set_result(results)
from . import constants
from . import coroutines
from . import events
+from . import exceptions
from . import futures
from . import selector_events
from . import tasks
try:
os.sendfile
except AttributeError as exc:
- raise events.SendfileNotAvailableError(
+ raise exceptions.SendfileNotAvailableError(
"os.sendfile() is not available")
try:
fileno = file.fileno()
except (AttributeError, io.UnsupportedOperation) as err:
- raise events.SendfileNotAvailableError("not a regular file")
+ raise exceptions.SendfileNotAvailableError("not a regular file")
try:
fsize = os.fstat(fileno).st_size
except OSError as err:
- raise events.SendfileNotAvailableError("not a regular file")
+ raise exceptions.SendfileNotAvailableError("not a regular file")
blocksize = count if count else fsize
if not blocksize:
return 0 # empty file
# one being 'file' is not a regular mmap(2)-like
# file, in which case we'll fall back on using
# plain send().
- err = events.SendfileNotAvailableError(
+ err = exceptions.SendfileNotAvailableError(
"os.sendfile call failed")
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
fut.set_exception(err)
from . import events
from . import base_subprocess
from . import futures
+from . import exceptions
from . import proactor_events
from . import selector_events
from . import tasks
elif self._debug:
logger.warning("Accept pipe failed on pipe %r",
pipe, exc_info=True)
- except futures.CancelledError:
+ except exceptions.CancelledError:
if pipe:
pipe.close()
else:
# Coroutine closing the accept socket if the future is cancelled
try:
await future
- except futures.CancelledError:
+ except exceptions.CancelledError:
conn.close()
raise
def test__sock_sendfile_native_failure(self):
sock, proto = self.prepare()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"sendfile is not available"):
self.run_loop(self.loop._sock_sendfile_native(sock, self.file,
0, None))
def test_sock_sendfile_no_fallback(self):
sock, proto = self.prepare()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"sendfile is not available"):
self.run_loop(self.loop.sock_sendfile(sock, self.file,
fallback=False))
self.loop._sendfile_native = sendfile_native
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not supported"):
self.run_loop(
self.loop.sendfile(cli_proto.transport, self.file,
def test_sock_sendfile_not_a_file(self):
sock, proto = self.prepare()
f = object()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
def test_sock_sendfile_iobuffer(self):
sock, proto = self.prepare()
f = io.BytesIO()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
sock, proto = self.prepare()
f = mock.Mock()
f.fileno.return_value = -1
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
def test_sock_sendfile_not_available(self):
sock, proto = self.prepare()
with mock.patch('asyncio.unix_events.os', spec=[]):
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"os[.]sendfile[(][)] is not available"):
self.run_loop(self.loop._sock_sendfile_native(sock, self.file,
0, None))
def test_sock_sendfile_not_a_file(self):
sock, proto = self.prepare()
f = object()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
def test_sock_sendfile_iobuffer(self):
sock, proto = self.prepare()
f = io.BytesIO()
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
sock, proto = self.prepare()
f = mock.Mock()
f.fileno.return_value = -1
- with self.assertRaisesRegex(events.SendfileNotAvailableError,
+ with self.assertRaisesRegex(asyncio.SendfileNotAvailableError,
"not a regular file"):
self.run_loop(self.loop._sock_sendfile_native(sock, f,
0, None))
with self.assertRaises(KeyError):
self.loop._selector.get_key(sock)
exc = fut.exception()
- self.assertIsInstance(exc, events.SendfileNotAvailableError)
+ self.assertIsInstance(exc, asyncio.SendfileNotAvailableError)
self.assertEqual(0, self.file.tell())
def test_sock_sendfile_os_error_next_call(self):
fileno = self.file.fileno()
fut = self.loop.create_future()
- err = events.SendfileNotAvailableError()
+ err = asyncio.SendfileNotAvailableError()
with mock.patch('os.sendfile', side_effect=err):
self.loop._sock_sendfile_native_impl(fut, sock.fileno(),
sock, fileno,
--- /dev/null
+Create a dedicated ``asyncio.CancelledError``, ``asyncio.InvalidStateError``
+and ``asyncio.TimeoutError`` exception classes. Inherit them from
+corresponding exceptions from ``concurrent.futures`` package. Extract
+``asyncio`` exceptions into a separate file.
WITH_MOD("asyncio.base_futures")
GET_MOD_ATTR(asyncio_future_repr_info_func, "_future_repr_info")
+
+ WITH_MOD("asyncio.exceptions")
GET_MOD_ATTR(asyncio_InvalidStateError, "InvalidStateError")
GET_MOD_ATTR(asyncio_CancelledError, "CancelledError")