Python asyncio.InvalidStateError() Examples

The following are 30 code examples of asyncio.InvalidStateError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: async_plasma.py    From ray with Apache License 2.0 6 votes vote down vote up
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)) 
Example #2
Source File: concurrent.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: concurrent.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
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]) 
Example #4
Source File: concurrent.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
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]) 
Example #5
Source File: concurrent.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
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) 
Example #6
Source File: adapters.py    From ptadapter with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #7
Source File: adapters.py    From ptadapter with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #8
Source File: concurrent.py    From teleport with Apache License 2.0 6 votes vote down vote up
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]) 
Example #9
Source File: test_futures.py    From android_universal with MIT License 6 votes vote down vote up
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()) 
Example #10
Source File: test_futures.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #11
Source File: client.py    From nats.py with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: concurrent.py    From teleport with Apache License 2.0 6 votes vote down vote up
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]) 
Example #13
Source File: concurrent.py    From teleport with Apache License 2.0 6 votes vote down vote up
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) 
Example #14
Source File: test_futures.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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()) 
Example #15
Source File: async_call_scheduler.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _coro_scheduler(self, coro_queue: asyncio.Queue, interval: float = 0.01):
        while True:
            app_warning_msg = "API call error."
            try:
                fut, coro, timeout_seconds, app_warning_msg = await coro_queue.get()
                async with timeout(timeout_seconds):
                    fut.set_result(await coro)
            except asyncio.CancelledError:
                try:
                    fut.cancel()
                except Exception:
                    pass
                raise
            except asyncio.InvalidStateError:
                # The future is already cancelled from outside. Ignore.
                pass
            except Exception as e:
                # Add exception information.
                app_warning_msg += f" [[Got exception: {str(e)}]]"
                self.logger().debug(app_warning_msg,
                                    exc_info=True,
                                    app_warning_msg=app_warning_msg)
                try:
                    fut.set_exception(e)
                except Exception:
                    pass

            try:
                await asyncio.sleep(interval)
            except asyncio.CancelledError:
                raise
            except Exception:
                self.logger().error("Scheduler sleep interrupted.", exc_info=True) 
Example #16
Source File: test_futures.py    From android_universal with MIT License 5 votes vote down vote up
def test_cancel(self):
        f = self._new_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()) 
Example #17
Source File: handler.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def handle_pubcomp(self, pubcomp: PubcompPacket):
        packet_id = pubcomp.packet_id
        try:
            waiter = self._pubcomp_waiters[packet_id]
            waiter.set_result(pubcomp)
        except KeyError:
            self.logger.warning("Received PUBCOMP for unknown pending message with Id: %d" % packet_id)
        except InvalidStateError:
            self.logger.warning("PUBCOMP waiter with Id '%d' already done" % packet_id) 
Example #18
Source File: handler.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def handle_pubrec(self, pubrec: PubrecPacket):
        packet_id = pubrec.packet_id
        try:
            waiter = self._pubrec_waiters[packet_id]
            waiter.set_result(pubrec)
        except KeyError:
            self.logger.warning("Received PUBREC for unknown pending message with Id: %d" % packet_id)
        except InvalidStateError:
            self.logger.warning("PUBREC waiter with Id '%d' already done" % packet_id) 
Example #19
Source File: handler.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def handle_pubrel(self, pubrel: PubrelPacket):
        packet_id = pubrel.packet_id
        try:
            waiter = self._pubrel_waiters[packet_id]
            waiter.set_result(pubrel)
        except KeyError:
            self.logger.warning("Received PUBREL for unknown pending message with Id: %d" % packet_id)
        except InvalidStateError:
            self.logger.warning("PUBREL waiter with Id '%d' already done" % packet_id) 
Example #20
Source File: handler.py    From hbmqtt with MIT License 5 votes vote down vote up
def handle_puback(self, puback: PubackPacket):
        packet_id = puback.variable_header.packet_id
        try:
            waiter = self._puback_waiters[packet_id]
            waiter.set_result(puback)
        except KeyError:
            self.logger.warning("Received PUBACK for unknown pending message Id: '%d'" % packet_id)
        except InvalidStateError:
            self.logger.warning("PUBACK waiter with Id '%d' already done" % packet_id) 
Example #21
Source File: main.py    From RulesBot with MIT License 5 votes vote down vote up
def handle_exit(client):
    client.loop.create_task(client.logout())
    for t in asyncio.Task.all_tasks(loop=client.loop):
        if t.done():
            t.exception()
            continue
        t.cancel()
        try:
            client.loop.run_until_complete(asyncio.wait_for(t, 5, loop=client.loop))
            t.exception()
        except (InvalidStateError, TimeoutError, asyncio.CancelledError, futures.CancelledError):
            pass
        except:
            traceback.print_exc() 
Example #22
Source File: runner.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def status(self):
        """Return the runner status as a string.

        The possible statuses are: running, cancelled, failed, and finished.
        """
        try:
            self.task.result()
        except asyncio.CancelledError:
            return "cancelled"
        except asyncio.InvalidStateError:
            return "running"
        except Exception:
            return "failed"
        else:
            return "finished" 
Example #23
Source File: test_futures.py    From android_universal with MIT License 5 votes vote down vote up
def test_result(self):
        f = self._new_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()) 
Example #24
Source File: concurrent.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
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) 
Example #25
Source File: test_futures.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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()) 
Example #26
Source File: test_futures.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_exception(self):
        exc = RuntimeError()
        f = asyncio.Future(loop=self.loop)
        self.assertRaises(asyncio.InvalidStateError, f.exception)

        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()) 
Example #27
Source File: test_call_ordering.py    From unsync with MIT License 5 votes vote down vote up
def test_nested_unsync(self):
        @unsync
        async def long():
            @unsync
            async def other():
                await asyncio.sleep(0.1)
                return 'faff'
            return other().result()

        with self.assertRaises(asyncio.InvalidStateError):
            self.assertEqual('faff', long().result()) 
Example #28
Source File: test_futures.py    From annotated-py-projects with MIT License 5 votes vote down vote up
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()) 
Example #29
Source File: test_futures.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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()) 
Example #30
Source File: test_futures.py    From annotated-py-projects with MIT License 5 votes vote down vote up
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())