Python源码示例:asyncio.InvalidStateError()
示例1
def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly check
the state of the Future and call ``Future.set_exception`` instead of
this wrapper.
Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 6.0
"""
if not future.cancelled():
future.set_exception(exc)
else:
app_log.error("Exception after Future was cancelled", exc_info=exc)
示例2
def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
(previously ``asyncio.InvalidStateError`` would be raised)
"""
if exc_info[1] is None:
raise Exception("future_set_exc_info called with no exception")
future_set_exception_unless_cancelled(future, exc_info[1])
示例3
def get_transport(self, transport: str) -> ClientTransport:
"""Look up initialized client transport methods.
Args:
transport: Name of the transport.
Returns:
A :class:`ClientTransport` NamedTuple for the specified transport.
Raises:
KeyError: If the specified transport was not provided when calling
:meth:`__init__`.
asyncio.InvalidStateError: If PT has not yet started, or if the
transport is not yet initialized.
RuntimeError: If the PT returned an error while initializing the
specified transport.
"""
self._check_running()
return self._transports[transport].result()
示例4
def get_transport(self, transport: str) -> ServerTransport:
"""Look up initialized server transport methods.
Args:
transport: Name of the transport.
Returns:
A :class:`ServerTransport` NamedTuple for the specified transport.
Raises:
KeyError: If the specified transport was not provided when calling
:meth:`__init__`.
asyncio.InvalidStateError: If PT has not yet started, or if the
transport is not yet initialized.
RuntimeError: If the PT returned an error while initializing the
specified transport.
"""
self._check_running()
return self._transports[transport].result()
示例5
def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly check
the state of the Future and call ``Future.set_exception`` instead of
this wrapper.
Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 6.0
"""
if not future.cancelled():
future.set_exception(exc)
else:
app_log.error("Exception after Future was cancelled", exc_info=exc)
示例6
def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
(previously ``asyncio.InvalidStateError`` would be raised)
"""
if exc_info[1] is None:
raise Exception("future_set_exc_info called with no exception")
future_set_exception_unless_cancelled(future, exc_info[1])
示例7
def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
(previously ``asyncio.InvalidStateError`` would be raised)
"""
if exc_info[1] is None:
raise Exception("future_set_exc_info called with no exception")
future_set_exception_unless_cancelled(future, exc_info[1])
示例8
def _ping_interval(self):
while True:
await asyncio.sleep(self.options["ping_interval"], loop=self._loop)
if not self.is_connected:
continue
try:
self._pings_outstanding += 1
if self._pings_outstanding > self.options[
"max_outstanding_pings"]:
await self._process_op_err(ErrStaleConnection)
return
await self._send_ping()
except asyncio.CancelledError:
break
# except asyncio.InvalidStateError:
# pass
示例9
def _complete_future(self, ray_object_id):
# TODO(ilr): Consider race condition between popping from the
# waiting_dict and as_future appending to the waiting_dict's list.
logger.debug(
"Completing plasma futures for object id {}".format(ray_object_id))
if ray_object_id not in self._waiting_dict:
return
obj = self._worker.get_objects([ray_object_id], timeout=0)[0]
futures = self._waiting_dict.pop(ray_object_id)
for fut in futures:
try:
fut.set_result(obj)
except asyncio.InvalidStateError:
# Avoid issues where process_notifications
# and check_immediately both get executed
logger.debug("Failed to set result for future {}."
"Most likely already set.".format(fut))
示例10
def test_exception(self):
exc = RuntimeError()
f = asyncio.Future(loop=self.loop)
self.assertRaises(asyncio.InvalidStateError, f.exception)
# StopIteration cannot be raised into a Future - CPython issue26221
self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised",
f.set_exception, StopIteration)
f.set_exception(exc)
self.assertFalse(f.cancelled())
self.assertTrue(f.done())
self.assertRaises(RuntimeError, f.result)
self.assertEqual(f.exception(), exc)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())
示例11
def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly check
the state of the Future and call ``Future.set_exception`` instead of
this wrapper.
Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 6.0
"""
if not future.cancelled():
future.set_exception(exc)
else:
app_log.error("Exception after Future was cancelled", exc_info=exc)
示例12
def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
(previously ``asyncio.InvalidStateError`` would be raised)
"""
if exc_info[1] is None:
raise Exception("future_set_exc_info called with no exception")
future_set_exception_unless_cancelled(future, exc_info[1])
示例13
def test_exception(self):
exc = RuntimeError()
f = self._new_future(loop=self.loop)
self.assertRaises(asyncio.InvalidStateError, f.exception)
# StopIteration cannot be raised into a Future - CPython issue26221
self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised",
f.set_exception, StopIteration)
f.set_exception(exc)
self.assertFalse(f.cancelled())
self.assertTrue(f.done())
self.assertRaises(RuntimeError, f.result)
self.assertEqual(f.exception(), exc)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())
示例14
def _set_reply(self, correlation_id, msg):
if correlation_id in self._futures:
try:
self._futures[correlation_id].set_result(msg)
except asyncio.InvalidStateError as e:
LOGGER.error(
'Attempting to set result on already-resolved future: %s',
str(e))
示例15
def _fail_reply(self, correlation_id, err):
if correlation_id in self._futures and \
not self._futures[correlation_id].done():
try:
self._futures[correlation_id].set_exception(err)
except asyncio.InvalidStateError as e:
LOGGER.error(
'Attempting to set exception on already-resolved future: '
'%s',
str(e))
示例16
def future_set_result_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
"""Set the given ``value`` as the `Future`'s result, if not cancelled.
Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 5.0
"""
if not future.cancelled():
future.set_result(value)
示例17
def _check_not_started(self) -> None:
if self._process:
raise asyncio.InvalidStateError('PT has already started')
示例18
def _check_started(self) -> None:
if not self._process:
raise asyncio.InvalidStateError('PT has not yet started')
示例19
def _check_running(self) -> None:
self._check_started()
if self._stopping:
raise asyncio.InvalidStateError('PT is stopping or has stopped')
示例20
def cancel_awaitable(
awaitable: Awaitable[Any],
log: Logger,
done_cb: Optional[Callable[[Awaitable[Any]], Any]] = None
) -> None:
"""
Cancel a coroutine or a :class:`asyncio.Task`.
Arguments:
- `coroutine_or_task`: The coroutine or
:class:`asyncio.Task` to be cancelled.
- `done_cb`: An optional callback to be called once the task
has been cancelled. Will be called immediately if
`coroutine_or_task` is a coroutine.
"""
if asyncio.iscoroutine(awaitable):
coroutine = cast(Coroutine[Any, Any, None], awaitable)
log.debug('Closing coroutine {}', coroutine)
coroutine.close()
if done_cb is not None:
done_cb(coroutine)
else:
task = cast('asyncio.Task[None]', awaitable)
# A cancelled task can still contain an exception, so we try to
# fetch that first to avoid having the event loop's exception
# handler yelling at us.
try:
exc = task.exception()
except asyncio.CancelledError:
log.debug('Already cancelled task {}', task)
except asyncio.InvalidStateError:
log.debug('Cancelling task {}', task)
task.cancel()
else:
if exc is not None:
log.debug('Ignoring completion of task {} with {}', task, task.result())
else:
log.debug('Ignoring exception of task {}: {}', task, repr(exc))
if done_cb is not None:
# noinspection PyTypeChecker
task.add_done_callback(done_cb)
示例21
def _task_done_handler(self, task: 'asyncio.Task[None]') -> None:
assert self._tasks is not None
self._tasks_remaining -= 1
self._log.debug('Task done (#tasks={}, #running={}), {}',
len(self._tasks), self._tasks_remaining, task)
# A cancelled task can still contain an exception, so we try to
# fetch that first to avoid having the event loop's exception
# handler yelling at us.
try:
exc = task.exception()
except asyncio.CancelledError:
# We don't care about cancelled tasks unless it's the last one and no
# exception has been set.
self._log.debug('Task was cancelled')
if self._tasks_remaining == 0 and not self._have_result:
error = 'All tasks have been cancelled prior to an exception'
self._set_result(Result(InternalError(error)))
self._cancelled = True
return
except asyncio.InvalidStateError as exc_:
# Err... what the... ?
self._log.exception('Task done but not done... what the...', exc_)
exc = exc_
# Tasks may not ever return without an exception
if exc is None:
result = task.result()
exc = InternalError('Task returned unexpectedly with {}: {}'.format(
type(result), result))
# Store the result and cancel all running tasks
self._set_result(Result(exc))
self._cancel()
示例22
def future_set_result_unless_cancelled(future, value):
"""Set the given ``value`` as the `Future`'s result, if not cancelled.
Avoids asyncio.InvalidStateError when calling set_result() on
a cancelled `asyncio.Future`.
.. versionadded:: 5.0
"""
if not future.cancelled():
future.set_result(value)
示例23
def future_set_result_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
"""Set the given ``value`` as the `Future`'s result, if not cancelled.
Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 5.0
"""
if not future.cancelled():
future.set_result(value)
示例24
def future_set_result_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
"""Set the given ``value`` as the `Future`'s result, if not cancelled.
Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 5.0
"""
if not future.cancelled():
future.set_result(value)
示例25
def _read_loop(self):
"""
Coroutine which gathers bytes sent by the server
and feeds them to the protocol parser.
In case of error while reading, it will stop running
and its task has to be rescheduled.
"""
while True:
try:
should_bail = self.is_closed or self.is_reconnecting
if should_bail or self._io_reader is None:
break
if self.is_connected and self._io_reader.at_eof():
if self._error_cb is not None:
await self._error_cb(ErrStaleConnection)
await self._process_op_err(ErrStaleConnection)
break
b = await self._io_reader.read(DEFAULT_BUFFER_SIZE)
await self._ps.parse(b)
except ErrProtocol:
await self._process_op_err(ErrProtocol)
break
except OSError as e:
await self._process_op_err(e)
break
except asyncio.CancelledError:
break
# except asyncio.InvalidStateError:
# pass
示例26
def process_events(self, events, parsed):
"""Process an event by activating futures or pushing to the queue.
"""
fut_map = self._futures_map
for event in events:
# self.log.log(
# utils.TRACE, "Event packet:\n{}".format(pformat(event)))
ctype = event.get('Content-Type', None)
if ctype == 'command/reply':
if event.get('Job-UUID'):
ctype = 'job/reply'
futures = fut_map.get(ctype, None)
if ctype == 'text/disconnect-notice':
event['Event-Name'] = 'SERVER_DISCONNECTED'
self.event_queue.put_nowait(event)
return
if futures is None: # ship it for consumption
self.event_queue.put_nowait(event)
else:
try:
fut = futures.popleft()
fut.set_result(event)
except IndexError:
self.log.warn("no scheduled future could be found "
"for event?\n{!r}".format(event))
except asyncio.InvalidStateError:
if not fut.cancelled():
self.log.warn(
"future was already cancelled for event {}"
.format(event))
else:
raise
示例27
def exception(self):
try:
return self._task.exception()
except (asyncio.CancelledError, asyncio.InvalidStateError):
return None
示例28
def rpc_call(self, method: str, args):
try:
async with async_timeout.timeout(self._timeout):
return await self.client.RPC(method, *args)
except asyncio.InvalidStateError:
raise
except ElectrumErrorResponse as e:
if e.args and isinstance(e.args[0], dict):
return e.args[0]
except Exception as e:
Logger.electrum.warning(
'exception on rpc call: %s, %s, %s', self.client.server_info, self.client.protocol, e
)
self.loop.create_task(self.delayer(self.on_error(e)))
示例29
def test_cancel(self):
f = asyncio.Future(loop=self.loop)
self.assertTrue(f.cancel())
self.assertTrue(f.cancelled())
self.assertTrue(f.done())
self.assertRaises(asyncio.CancelledError, f.result)
self.assertRaises(asyncio.CancelledError, f.exception)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())
示例30
def test_result(self):
f = asyncio.Future(loop=self.loop)
self.assertRaises(asyncio.InvalidStateError, f.result)
f.set_result(42)
self.assertFalse(f.cancelled())
self.assertTrue(f.done())
self.assertEqual(f.result(), 42)
self.assertEqual(f.exception(), None)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())