How to use the trio.move_on_after function in trio

To help you get started, we’ve selected a few trio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github goodboy / tractor / tests / test_cancellation.py View on Github external
async def test_cancel_infinite_streamer(start_method):

    # stream for at most 1 seconds
    with trio.move_on_after(1) as cancel_scope:
        async with tractor.open_nursery() as n:
            portal = await n.start_actor(
                'donny',
                rpc_module_paths=[__name__],
            )

            # this async for loop streams values from the above
            # async generator running in a separate process
            async for letter in await portal.run(__name__, 'stream_forever'):
                print(letter)

    # we support trio's cancellation system
    assert cancel_scope.cancelled_caught
    assert n.cancelled
github pgjones / hypercorn / tests / trio / test_h2.py View on Github external
async def test_post_response_keep_alive_timeout(nursery: trio._core._run.Nursery) -> None:
    config = Config()
    config.keep_alive_timeout = 0.01
    connection = MockConnection(config=config)
    nursery.start_soon(connection.server.handle_connection)
    stream_id = await connection.send_request(
        BASIC_HEADERS + [(":method", "GET"), (":path", "/1")], {}
    )
    await connection.end_stream(stream_id)
    async for event in connection.get_events():
        if isinstance(event, h2.events.StreamEnded):
            break  # Request ended
    with trio.move_on_after(2 * config.keep_alive_timeout):
        pass
    events = [event async for event in connection.get_events()]
    assert isinstance(events[-1], h2.events.ConnectionTerminated)
github caproto / caproto / caproto / trio / server.py View on Github external
async def wait(self, timeout=None):
        if timeout is not None:
            with trio.move_on_after(timeout):
                await super().wait()
                return True
            return False
        else:
            await super().wait()
            return True
github HyperionGray / starbelly / integration / __init__.py View on Github external
async def wrapper(*args, **kwargs):
            with trio.move_on_after(self._seconds) as cancel_scope:
                await fn(*args, **kwargs)
            if cancel_scope.cancelled_caught:
                pytest.fail('Test runtime exceeded the maximum {} seconds'
                    .format(self._seconds))
        return wrapper
github caproto / caproto / caproto / trio / client.py View on Github external
channels = OrderedDict()

        async def connect_outer(names):
            nonlocal channels

            async for addr, names in self.broadcaster.search_many(*names):
                for name in names:
                    channels[name] = await self.create_channel(name,
                                                               priority=priority)

            if wait_for_connection:
                for channel in channels.values():
                    await channel.wait_for_connection()

        if move_on_after is not None:
            with trio.move_on_after(move_on_after):
                async with trio.open_nursery() as nursery:
                    nursery.start_soon(connect_outer, names)
        else:
            async with trio.open_nursery() as nursery:
                nursery.start_soon(connect_outer, names)
        return channels
github goodboy / tractor / tractor / _ipc.py View on Github external
async def _reconnect(self) -> None:
        """Handle connection failures by polling until a reconnect can be
        established.
        """
        down = False
        while True:
            try:
                with trio.move_on_after(3) as cancel_scope:
                    await self.connect()
                cancelled = cancel_scope.cancelled_caught
                if cancelled:
                    log.warning(
                        "Reconnect timed out after 3 seconds, retrying...")
                    continue
                else:
                    log.warning("Stream connection re-established!")
                    # run any reconnection sequence
                    on_recon = self._recon_seq
                    if on_recon:
                        await on_recon(self)
                    break
            except (OSError, ConnectionRefusedError):
                if not down:
                    down = True
github caproto / caproto / caproto / trio / client.py View on Github external
for search_id, name in needs_search:
            self.unanswered_searches[search_id] = name

        results = defaultdict(list)

        while needs_search:
            self.log.debug('Searching for %r PVs....', len(needs_search))
            requests = (ca.SearchRequest(name, search_id,
                                         ca.DEFAULT_PROTOCOL_VERSION)
                        for search_id, name in needs_search)
            for batch in batch_requests(requests, SEARCH_MAX_DATAGRAM_BYTES):
                await self.send(self.ca_server_port,
                                ca.VersionRequest(0, ca.DEFAULT_PROTOCOL_VERSION),
                                *batch)

            with trio.move_on_after(1):
                await self.wait_on_new_command()

            results.clear()
            found = [(search_id, name) for search_id, name in needs_search
                     if search_id not in self.unanswered_searches]
            needs_search = [key for key in needs_search
                            if key not in found]
            for _search_id, name in found:
                address, timestamp = self.search_results[name]
                results[address].append(name)

            for names in results.values():
                yield (address, names)
github pypa / linehaul / linehaul / server.py View on Github external
for event in lr.receive_data(data):
                logger.log(log_SPEW, "{%s}: Received Event: %r", peer_id, event)
                await q.put(event)

            if not data:
                logger.debug("{%s}: Connection lost from %r.", peer_id, peer)
                lr.close()
                break
    except BufferTooLargeError:
        logger.debug("{%s}: Buffer too large; Dropping connection.", peer_id)
    except TruncatedLineError as exc:
        logger.debug("{%s}: Truncated line %r; Dropping connection.", peer_id, exc.line)
    except Exception:
        logger.exception("Unhandled error in connection:")
    finally:
        with trio.move_on_after(cleanup_timeout):
            await stream.aclose()
github goodboy / tractor / tractor / _portal.py View on Github external
async def aclose(self):
        """Cancel associated remote actor task and local memory channel
        on close.
        """
        if self._rx_chan._closed:
            log.warning(f"{self} is already closed")
            return
        cid = self._cid
        with trio.move_on_after(0.5) as cs:
            cs.shield = True
            log.warning(
                f"Cancelling stream {cid} to "
                f"{self._portal.channel.uid}")
            # NOTE: we're telling the far end actor to cancel a task
            # corresponding to *this actor*. The far end local channel
            # instance is passed to `Actor._cancel_task()` implicitly.
            await self._portal.run('self', '_cancel_task', cid=cid)

        if cs.cancelled_caught:
            # XXX: there's no way to know if the remote task was indeed
            # cancelled in the case where the connection is broken or
            # some other network error occurred.
            if not self._portal.channel.connected():
                log.warning(
                    "May have failed to cancel remote task "