How to use the trio.Event 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 ethereum / trinity / tests-trio / p2p-trio / test_service.py View on Github external
async def test_trio_service_lifecycle_run_and_clean_exit():
    trigger_exit = trio.Event()

    @as_service
    async def ServiceTest(manager):
        await trigger_exit.wait()

    service = ServiceTest()
    manager = Manager(service)

    await do_service_lifecycle_check(
        manager=manager,
        manager_run_fn=manager.run,
        trigger_exit_condition_fn=trigger_exit.set,
        should_be_cancelled=False,
    )
github ethereum / trinity / p2p / discovery.py View on Github external
async def wait_neighbours(self, remote: NodeAPI) -> Tuple[NodeAPI, ...]:
        """Wait for a neihgbours packet from the given node.

        Returns the list of neighbours received.
        """
        event = trio.Event()
        neighbours: List[NodeAPI] = []

        def process(response: List[NodeAPI]) -> None:
            neighbours.extend(response)
            # This callback is expected to be called multiple times because nodes usually
            # split the neighbours replies into multiple packets, so we only call event.set() once
            # we've received enough neighbours.
            if len(neighbours) >= constants.KADEMLIA_BUCKET_SIZE:
                event.set()

        with self.neighbours_callbacks.acquire(remote, process):
            with trio.move_on_after(constants.KADEMLIA_REQUEST_TIMEOUT) as cancel_scope:
                await event.wait()
                self.logger.debug2('got expected neighbours response from %s', remote)
            if cancel_scope.cancelled_caught:
                self.logger.debug2(
github python-trio / trio-amqp / trio_amqp / protocol.py View on Github external
async def __aenter__(self):
        self.connecting = trio.Event()
        self.connection_closed = trio.Event()
        self.state = CONNECTING
        self.version_major = None
        self.version_minor = None
        self.server_properties = None
        self.server_mechanisms = None
        self.server_locales = None
        self.server_heartbeat = None
        self.channels = {}
        self.server_frame_max = None
        self.server_channel_max = None
        self.channels_ids_ceil = 0
        self.channels_ids_free = set()
        self._send_send_channel, self._send_receive_channel = trio.open_memory_channel(1)

        if self._ssl:
github goodboy / tractor / tractor / _actor.py View on Github external
def register_actor(
        self, uid: Tuple[str, str], sockaddr: Tuple[str, int]
    ) -> None:
        name, uuid = uid
        self._registry[uid] = sockaddr

        # pop and signal all waiter events
        events = self._waiters.pop(name, ())
        self._waiters.setdefault(name, []).append(uid)
        for event in events:
            if isinstance(event, trio.Event):
                event.set()
github M-o-a-T / qbroker / trio_qbroker / broker.py View on Github external
async procedure that runs while attempting to
                    reconnect.
                cfg:
                    Configuration. See :obj:`qbroker.config.DEFAULT_CONFIG`
                    for the defaults.
            """

        self.app = app
        self.args = args

        if nursery is None:
            raise RuntimeError("I need a nursery")
        self.nursery = nursery
        self._queue = trio.Queue(999)
        self._stop = trio.Event()
        self._connected = trio.Event()
        self.nursery.start_soon(self._queue_run)
        self.hidden = hidden
        self._idle = None  # cancel scope of backgound while-disconnected task
        self.idle_proc = idle_proc

        self.uuid = uuidstr()

        if 'cfg' in cfg:
            cfg = cfg['cfg']
        if 'amqp' in cfg:
            cfg = cfg['amqp']
        self.cfg = combine_dict(cfg, DEFAULT_CONFIG)

        self._endpoints = {}
        self._reg_endpoints = set()
github ethereum / lahja / lahja / trio / endpoint.py View on Github external
def __init__(
        self,
        local_name: str,
        conn: ConnectionAPI,
        subscriptions_changed: ConditionAPI,
        new_msg_func: Callable[[Broadcast], Awaitable[Any]],
    ) -> None:
        super().__init__(local_name, conn, new_msg_func)

        self._notify_lock = trio.Lock()  # type: ignore

        self._received_response = trio.Condition()  # type: ignore
        self._received_subscription = trio.Condition()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore

        self._received_subscription = subscriptions_changed

        self._subscriptions_initialized = trio.Event()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore
        self._ready = trio.Event()  # type: ignore
github ethereum / lahja / lahja / tools / engine.py View on Github external
async def run_with_timeout(
        self, coro: Callable[..., Awaitable[Any]], *args: Any, timeout: int
    ) -> None:
        try:
            await asyncio.wait_for(coro(*args), timeout=timeout)
        except asyncio.TimeoutError as err:
            raise TimeoutError from err

    async def sleep(self, seconds: float) -> None:
        await asyncio.sleep(seconds)


class TrioEngine(EngineAPI):
    endpoint_class = TrioEndpoint
    Event = cast(Type[EventAPI], trio.Event)

    async def run_drivers(self, *drivers: Driver) -> None:
        async with trio.open_nursery() as nursery:
            for driver in drivers:
                nursery.start_soon(driver, self)

    async def run_with_timeout(
        self, coro: Callable[..., Awaitable[Any]], *args: Any, timeout: int
    ) -> None:
        try:
            with trio.fail_after(timeout):
                await coro(*args)
        except trio.TooSlowError as err:
            raise TimeoutError from err

    async def sleep(self, seconds: float) -> None:
github ethereum / lahja / lahja / trio / endpoint.py View on Github external
) -> None:
        super().__init__(local_name, conn, new_msg_func)

        self._notify_lock = trio.Lock()  # type: ignore

        self._received_response = trio.Condition()  # type: ignore
        self._received_subscription = trio.Condition()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore

        self._received_subscription = subscriptions_changed

        self._subscriptions_initialized = trio.Event()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore
        self._ready = trio.Event()  # type: ignore
github M-o-a-T / qbroker / trio_qbroker / conn.py View on Github external
async def connect(self, broker):
        self.broker = weakref.ref(broker)
        self.is_disconnected = trio.Event()

        timeout = self.cfg.timeout.connect
        if not timeout:
            timeout = math.inf
        with trio.open_cancel_scope() as scope:
            scope.timeout = timeout
            async with trio_amqp.connect_amqp(**self.cfg.server) as amqp:
                scope.timeout = math.inf

                self.amqp = amqp
                nursery = self.nursery
                try:
                    for _ in range(self.rpc_workers):
                        await nursery.start(self._work_rpc)
                    for _ in range(self.alert_workers):
                        await nursery.start(self._work_alert)