Beispiel #1
0
    def truncate(self, length: int = 0) -> asyncio.Future:
        if self.__fileno < 0:
            raise asyncio.InvalidStateError('AIOFile closed')

        return run_in_thread(os.ftruncate,
                             self.__fileno,
                             length,
                             loop=self.__loop)
Beispiel #2
0
    def open_fd(self, fd: int):
        if self.__fileno == AIO_FILE_CLOSED:
            raise asyncio.InvalidStateError('AIOFile closed')

        if self.__fileno != AIO_FILE_NOT_OPENED:
            raise RuntimeError('Already opened')

        self.__fileno = fd
Beispiel #3
0
def test_dup_send_success(app, aps, ieee):
    req = app._pending[253] = MagicMock()
    req.result.set_result.side_effect = asyncio.InvalidStateError()
    app.ezsp_callback_handler(
        "messageSentHandler",
        [t.EmberIncomingMessageType.INCOMING_MULTICAST, 0xBEED, aps, 253, 0, b""],
    )
    assert req.result.set_exception.call_count == 0
    assert req.result.set_result.call_count == 1
Beispiel #4
0
 def result(self, *args, **kwargs) -> T:
     # The asyncio Future may have completed before the concurrent one
     if self.future.done():
         return self.future.result()
     # Don't allow waiting in the unsync.thread loop since it will deadlock
     if threading.current_thread() == unsync.thread and not self.concurrent_future.done():
         raise asyncio.InvalidStateError("Calling result() in an unsync method is not allowed")
     # Wait on the concurrent Future outside unsync.thread
     return self.concurrent_future.result(*args, **kwargs)
Beispiel #5
0
    async def _write(self, request: RequestType) -> None:
        if self.done():
            raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
        if self._done_writing_flag:
            raise asyncio.InvalidStateError(_RPC_HALF_CLOSED_DETAILS)
        if not self._metadata_sent.is_set():
            await self._metadata_sent.wait()
            if self.done():
                await self._raise_for_status()

        serialized_request = _common.serialize(request,
                                               self._request_serializer)
        try:
            await self._cython_call.send_serialized_message(serialized_request)
        except asyncio.CancelledError:
            if not self.cancelled():
                self.cancel()
            await self._raise_for_status()
Beispiel #6
0
    async def send_code(self, code: str):
        """
        send_code sends `code` as back-script to peer's hosting endpoint for landing by its hosting
        environment. Only side effects are expected from landing of `code` at peer site.

        Note this can only be called in `send` stage, and from the dedicated hosting aio task, i.e.
        from functions exposed to the hosting environment and called by the peer-scripting-code from
        the remote posting conversation which triggered this ho co.

        """

        if self._send_done_fut is None or self._send_done_fut.done():
            raise asyncio.InvalidStateError("ho co not in send stage")

        hbic = self._hbic
        if self is not hbic._sender:
            raise asyncio.InvalidStateError("ho co not current sender")

        await hbic._send_packet(code)
Beispiel #7
0
    async def recv_obj(self):
        """
        recv_obj returns the landed result of a piece of peer-scripting-code sent by calling
        PoCo.send_obj() with the remote posting conversation which triggered this ho co.

        Note this can only be called in `recv` stage, and from the dedicated hosting aio task, i.e.
        from functions exposed to the hosting environment and called by the peer-scripting-code from
        the remote posting conversation which triggered this ho co.

        """

        if self._recv_done_fut.done():
            raise asyncio.InvalidStateError("ho co not in recv stage")

        hbic = self._hbic
        if self is not hbic._recver:
            raise asyncio.InvalidStateError("ho co not current recver")

        return await hbic._recv_one_obj(self.he)
Beispiel #8
0
 def xrlrs(self, xrlrs: int):
     if not self.locked():
         raise asyncio.InvalidStateError()
     now = time.time()
     xrlrs = int(xrlrs)
     if self._xra is None or xrlrs < self._xrlrs or self._xra <= now:
         self._xra = now + RATE.block + RATE.bpad
     self._xrlrs = xrlrs
     if xrlrs >= RATE.requests - RATE.rpad:
         self.defer()
Beispiel #9
0
    async def open(self):
        if self.__fileno == AIO_FILE_CLOSED:
            raise asyncio.InvalidStateError('AIOFile closed')

        if self.__fileno != AIO_FILE_NOT_OPENED:
            return

        self.__fileno = os.open(self.__fname,
                                flags=self.mode.flags,
                                mode=self.__access_mode)
Beispiel #10
0
    def cancel(self):
        if self._state == c._CANCELLED:
            raise asyncio.InvalidStateError("already cancelled")

        self._state = c._CANCELLED
        if self.process_handle is not None:
            if not self.process_handle._cancelled:
                self.process_handle.cancel()
        self._cancel_transfer_tasks()
        self.__protocol_connected = False
Beispiel #11
0
    async def _ho_co_finish_recv(self, co: HoCo):
        assert co is self._recver, "ho co not current recver ?!"
        assert not co._recv_done_fut.done(), "ho co finishing recv twice ?!"

        pkt = await self._recv_packet()

        if pkt is None:
            raise asyncio.InvalidStateError("hbic disconnected")
        payload, wire_dir = pkt

        if wire_dir != "co_end":
            raise asyncio.InvalidStateError(
                f"Extra packet not landed by ho co before leaving recv stage: [{payload!s}#{wire_dir!s}]"
            )
        if payload != co._co_seq:
            raise asyncio.InvalidStateError("co seq mismatch on co_end")

        # signal co_keeper to start receiving next co
        co._recv_done_fut.set_result(None)
Beispiel #12
0
    def result(self) -> _Any:

        if self._task is not None:
            raise _asyncio.InvalidStateError("ServerHandler still running")

        exc = self.exception()
        if exc is not None:
            raise exc

        return self._result
Beispiel #13
0
def test_receive_reply_after_timeout(prot_hndl):
    callback_mock = MagicMock(spec_set=asyncio.Future)
    callback_mock.set_result.side_effect = asyncio.InvalidStateError()
    prot_hndl._awaiting[0] = (0, prot_hndl.COMMANDS["version"][2], callback_mock)
    prot_hndl(b"\x00\xff\x00\x04\x05\x06")

    assert 0 not in prot_hndl._awaiting
    assert callback_mock.set_exception.call_count == 0
    assert callback_mock.set_result.call_count == 1
    callback_mock.set_result.assert_called_once_with([4, 5, 6])
    assert prot_hndl.cb_mock.call_count == 0
Beispiel #14
0
    async def fsync(self):
        if self.__fileno < 0:
            raise asyncio.InvalidStateError('AIOFile closed')

        return (
            await self.OPERATION_CLASS(
                self.IO_NOP,
                self.__fileno, 0, 0,
                self.__loop
            )
        )
Beispiel #15
0
    async def send_obj(self, code: str):
        """
        send_obj sends `code` to peer's hosting endpoint for landing by its hosting environment, and
        the landed value to be received by calling PoCo.recv_obj() with the remote posting conversation
        which triggered this ho co.

        Note this can only be called in `send` stage, and from the dedicated hosting aio task, i.e.
        from functions exposed to the hosting environment and called by the peer-scripting-code from
        the remote posting conversation which triggered this ho co.

        """

        if self._send_done_fut is None or self._send_done_fut.done():
            raise asyncio.InvalidStateError("ho co not in send stage")

        hbic = self._hbic
        if self is not hbic._sender:
            raise asyncio.InvalidStateError("ho co not current sender")

        await hbic._send_packet(code, b"co_recv")
Beispiel #16
0
 def on_cok_done(fut):
     cok_exc = fut.exception()
     if cok_exc is not None:
         logger.error(f"Unexpected failure in co_keeper: {cok_exc!s}")
     if not self._conn_fut.done():
         self._conn_fut.set_exception(
             cok_exc or asyncio.InvalidStateError("co_keeper exit"))
     if not self._disc_fut.done():
         self._disc_fut.set_result(None)
     if wire.is_connected():
         wire.disconnect()
Beispiel #17
0
    def local_port(self) -> str:
        transport = self.transport
        if transport is None:
            raise asyncio.InvalidStateError("Socket not wired!")

        sockname = transport.get_extra_info("sockname")
        if len(sockname) in (2, 4):
            return sockname[1]
        raise NotImplementedError(
            "Socket transport other than tcp4/tcp6 not supported yet."
        )
Beispiel #18
0
    def remote_host(self) -> str:
        transport = self.transport
        if transport is None:
            raise asyncio.InvalidStateError("Socket not wired!")

        peername = transport.get_extra_info("peername")
        if len(peername) in (2, 4):
            return peername[0]
        raise NotImplementedError(
            "Socket transport other than tcp4/tcp6 not supported yet."
        )
Beispiel #19
0
def test_receive_reply_after_timeout(ezsp_f):
    ezsp_f.handle_callback = mock.MagicMock()
    callback_mock = mock.MagicMock(spec_set=asyncio.Future)
    callback_mock.set_result.side_effect = asyncio.InvalidStateError()
    ezsp_f._awaiting[0] = (0, ezsp_f.COMMANDS['version'][2], callback_mock)
    ezsp_f.frame_received(b'\x00\xff\x00\x04\x05\x06')

    assert 0 not in ezsp_f._awaiting
    assert callback_mock.set_exception.call_count == 0
    assert callback_mock.set_result.call_count == 1
    callback_mock.set_result.assert_called_once_with([4, 5, 6])
    assert ezsp_f.handle_callback.call_count == 0
Beispiel #20
0
    def test_cancelled_future(self):
        """Ensures that cancelled futures are handled appropriately."""
        data = struct.pack("!H", len(self.response)) + self.response

        mock_future = unittest.mock.MagicMock(asyncio.Future)
        client_tcp = DNSClientProtocolTCP(self.dnsq, mock_future, "10.0.0.0")
        client_tcp.time_stamp = 1000000

        # If the future is cancelled, set_result raises InvalidStateError.
        mock_future.set_result.side_effect = asyncio.InvalidStateError(
            "CANCELLED: <Future cancelled>")
        client_tcp.data_received(data)
Beispiel #21
0
    async def write(self, request: RequestType) -> None:
        # If no queue was created it means that requests
        # should be expected through an iterators provided
        # by the caller.
        if self._write_to_iterator_queue is None:
            raise cygrpc.UsageError(_API_STYLE_ERROR)

        try:
            call = await self._interceptors_task
        except (asyncio.CancelledError, AioRpcError):
            raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)

        if call.done():
            raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
        elif call._done_writing_flag:
            raise asyncio.InvalidStateError(_RPC_HALF_CLOSED_DETAILS)

        await self._write_to_iterator_queue_interruptible(request, call)

        if call.done():
            raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)
Beispiel #22
0
    async def open(self):
        if self.__file_obj is not None:
            return

        if self.__file_obj and self.__file_obj.closed:
            raise asyncio.InvalidStateError("AIOFile closed")

        self.__file_obj = await self._run_in_thread(
            open, self.__fname, self.__open_mode,
        )

        return self.fileno()
Beispiel #23
0
    def exception(self) -> _Optional[BaseException]:

        if self._task is not None:
            raise _asyncio.InvalidStateError("ServerHandler still running")

        if self._exception is None:
            return None

        if isinstance(self._exception, _asyncio.CancelledError):
            raise self._exception

        return self._exception
Beispiel #24
0
    async def recv_obj(self):
        """
        recv_obj returns the landed result of a piece of back-script `code` sent with the triggered
        hosting conversation at remote site via HoCo.send_obj(code)

        Note this can only be called in `recv` stage, and from the aio task which created this
        conversation.

        """

        if not self._send_done_fut.done():
            raise asyncio.InvalidStateError("po co still in send stage")

        if self._recv_done_fut is None:
            raise asyncio.InvalidStateError("po co not in recv stage")

        assert self._begin_acked_fut.done(), "po co response not started ?!"

        hbic = self._hbic
        assert self is hbic._recver, "po co not current recver ?!"

        return await hbic._recv_one_obj(self.he)
Beispiel #25
0
    def result(self) -> Any:
        """Return the result of this assertion.

        The semantics is similar to that of the `result()` method of `asyncio.Task`
        (https://docs.python.org/3/library/asyncio-task.html#task-object):
        If the assertion is done, the result of the assertion coroutine is returned
        or the exception raised by the coroutine is re-raised.
        If the assertion is not done (in particular, if hasn't been started) then
        this method raises `asyncio.InvalidStateError`.
        """
        if not self._task:
            raise asyncio.InvalidStateError("Assertion not started")

        return self._task.result()
Beispiel #26
0
    def __aiter__(self) -> AsyncIterator[E]:
        """Return an asynchronous generator of events.

        It will yield events to `async for` loops in assertion coroutines.

        For a given assertion `A`, `A.__iter__()` is guaranteed to return
        the same asynchronous generator every time it's called.
        """
        if self._ready is None or self._processed is None:
            raise asyncio.InvalidStateError("Assertion not started")

        if self._generator is None:
            self._generator = self._create_generator()
        return self._generator
Beispiel #27
0
    def cancel_task(self, instance: TaskInstance):
        """
        Request cancellation of a specific instance of a scheduled task.

        This method will not immediately stop and delete the task. The cancellation will be queued
        in the asyncio event loop. You can await instance.wait() if you need to be sure the
        cancellation has completed.

        :param instance: The task instance (returned by :meth:`~.schedule_task_at` and
        :meth:`~.schedule_task_in`) to cancel.
        :raise asyncio.InvalidStateError: Task is already done, does not exist or was previously
        cancelled.
        """
        try:
            self.tasks[instance.task][instance.timestamp].async_task.cancel()
        except KeyError:
            raise asyncio.InvalidStateError(
                "Task {!s} does not exist, is finished or cancelled".format(
                    instance))
        except TypeError:
            raise asyncio.InvalidStateError(
                "Task was not started (??? should not happen?)".format(
                    instance))
Beispiel #28
0
    async def read(self) -> ResponseType:
        if self._status.done():
            await self._raise_for_status()
            raise asyncio.InvalidStateError(_RPC_ALREADY_FINISHED_DETAILS)

        response_message = await self._read()

        if response_message is None:
            # If the read operation failed, Core should explain why.
            await self._raise_for_status()
            # If no exception raised, there is something wrong internally.
            assert False, 'Read operation failed with StatusCode.OK'
        else:
            return response_message
Beispiel #29
0
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        hbic = self._hbic
        co = self._co

        if not hbic.is_connected():
            raise asyncio.InvalidStateError(
                f"hbic disconnected due to: {hbic.disc_reason!s}"
            )

        if not co._send_done_fut.done():
            await hbic._po_co_finish_send(co)

        recv_done_fut = co._recv_done_fut
        if recv_done_fut is not None:
            recv_done_fut.set_result(None)
Beispiel #30
0
    async def recv_data(
        self,
        bufs: Union[bytearray, memoryview,
                    # or sequence of them, i.e. streaming on-the-fly
                    Sequence[Union[bytearray, memoryview]], ],
    ):
        """
        recv_data receives the binary data/stream sent by calling PoCo.send_data()
        with the remote posting conversation which triggered this ho co.

        Note this can only be called in `recv` stage, and from the dedicated hosting aio task, i.e.
        from functions exposed to the hosting environment and called by the peer-scripting-code from
        the remote posting conversation which triggered this ho co.

        """

        if self._recv_done_fut.done():
            raise asyncio.InvalidStateError("ho co not in recv stage")

        hbic = self._hbic
        if self is not hbic._recver:
            raise asyncio.InvalidStateError("ho co not current recver")

        await hbic._recv_data(bufs)