Pyjo.Reactor.Trio - Low-level event reactor on Trio¶
from Pyjo.Reactor.Trio import Trio
# Watch if handle becomes readable or writable
reactor = Trio()
reactor.io(first, lambda reactor, writable: print(
'First handle is writable' if writable else 'First handle is readable'
))
# Or import the module, as in Google Python Style Guide
import Pyjo.Reactor.Trio
# Watch if handle becomes readable or writable
reactor = Pyjo.Reactor.Trio.new()
reactor.io(first, lambda reactor, writable: print(
'First handle is writable' if writable else 'First handle is readable'
))
# Change to watching only if handle becomes writable
reactor.watch(first, False, True)
# Watch a file descriptor if it becomes readable
reactor.io(fd, lambda reactor, writable: print(
'Second handle is writable' if writable else 'Second handle is readable'
)).watch(fd, True, False)
# Add a timer
def timeout(reactor):
reactor.remove(first)
reactor.remove(fd)
print('Timeout!')
reactor.timer(15, timeout)
# Start reactor if necessary
if not reactor.is_running:
reactor.start()
Pyjo.Reactor.Trio is a low-level event reactor based on
Trio, the async library of structured
concurrency. It watches handles and runs timers in a run of Trio, so the
tasks of Trio run along with it. PYJO_REACTOR selects it for
Pyjo.IOLoop:
PYJO_REACTOR=Pyjo.Reactor.Trio
Inside a run of Trio that runs already, as of trio.run(), the reactor
watches its handles and timers in that run, with tasks of its own, and
is_running is true there:
start() and one_tick()
return right away, as Trio does not nest its runs, a promise of Pyjoyment is
awaited in a task of Trio, Pyjo.Promise.Pyjo_Promise.wait() returns at
once, and a blocking request of Pyjo.UserAgent raises
RuntimeError. A coroutine of Pyjoyment, as an async def action,
is a task of that run, where it can await anything of Trio. An exception of a
callback that no error event handles ends that run with
trio.TrioInternalError, as Trio does for a crashed system task.
Outside of a run of Trio, start() and
one_tick() run a run of Trio of the reactor itself,
in the guest mode of Trio, which ends when they return, unless coroutines that
it runs are not done yet, which it keeps until they are, or until
close() cancels them, as the end of a with block
does. While it lives, the thread cannot start another run of Trio, as of
trio.run(). Each thread has runs of its own, as the workers of
Pyjo.Server.Prethread, and the child of a fork, as a worker of
Pyjo.Server.Prefork, leaves the run of its parent. The run of the
reactor leaves the signals and signal.set_wakeup_fd() to the program, as
the servers of Pyjoyment set them.
The events come in the order of Pyjo.Reactor.Poll: the handles that are
ready, in the order in which they were added, and then the timers that are
due, with the callbacks of next_tick()
that the handles added. On Windows, Trio watches sockets only.
Events¶
Pyjo.Reactor.Trio inherits all events from Pyjo.Reactor.Poll.
See also¶
Pyjo.Reactor.Poll, Pyjoyment, https://github.com/pyjoyment/Pyjoyment.
Classes¶
- class Pyjo.Reactor.Trio.Pyjo_Reactor_Trio[source]¶
Pyjo.Reactor.Trioinherits all methods fromPyjo.Reactor.Polland implements the following new ones.- again(id: str, after: float | None = None) None[source]¶
reactor.again(id) reactor.again(id, 0.5)
Restart timer and optionally change the invocation time. Note that this method requires an active timer.
- awaitable(promise: Any) Awaitable[None][source]¶
awaitable = reactor.awaitable(promise)
Return what
await promisewaits on in a task of Trio, which completes when the promise is fulfilled or rejected. Outside a task of Trio, as in a coroutine thatPyjo.Stepsdrives, it is the one of the base class, which yields the promise to whoever drives the coroutine.
- close() None[source]¶
reactor.close()
End the run of Trio of the reactor itself, after the coroutines that are left in it are cancelled, as the end of a
withblock does; a run of the application is left to it.
- event_loop_modules = ('trio',)¶
modules = reactor.event_loop_modules
The names of the modules of the event loop that the reactor runs on, as
('trio',), whose code a finalizer of the garbage collector may interrupt. The cleanup of a stream, a server or a user agent that is freed in a frame of such a module, or of a module of a class of the reactor, waits for the next tick of the reactor, so that it does not change the structures that the event loop is changing. Defaults to().class Pyjo_Reactor_MyLoop(Pyjo.Reactor.Poll.object): event_loop_modules = ('myloop',)
- io(handle: Handle, cb: IOCallback) Self[source]¶
reactor = reactor.io(handle, cb)
Watch handle for I/O events, invoking the callback whenever handle becomes readable or writable.
# Callback will be executed twice if handle becomes readable and writable def cb(reactor, writable): if writable: print('Handle is writable') else: print('Handle is readable') reactor.io(handle, cb)
- property is_running: bool[source]¶
boolean = reactor.is_running
Check if reactor is running, also inside a run of Trio that runs already, which watches its handles and timers.
- one_tick() None[source]¶
reactor.one_tick()
Run reactor until an event occurs or no events are being watched anymore, or return right away inside a run of Trio that runs already.
# Don't block longer than 0.5 seconds id = reactor.timer(0.5, lambda reactor: None) reactor.one_tick() reactor.remove(id)
- remove(remove: Handle | str) bool[source]¶
boolean = reactor.remove(handle) boolean = reactor.remove(id)
Remove handle or timer.
- run_coroutine(coro: Coroutine[Any, Any, Any], resolve: Callable[[Any], Any], reject: Callable[[Any], Any]) None[source]¶
reactor.run_coroutine(coro, resolve, reject)
Run a coroutine as a task of the run of Trio, where it can await anything of Trio, and call
resolvewith what it returns orrejectwith the exception it raises, or withtrio.Cancelledwhen the run ends before it. A coroutine that is not done is something to watch, so thatstart()does not stop before it, and each step of the coroutine is an event, which endsone_tick().
- start() None[source]¶
reactor.start()
Start watching for I/O and timer events, this will block until
stop()is called or no events are being watched anymore, or return right away inside a run of Trio that runs already.# Start reactor only if it is not running already if not reactor.is_running: reactor.start()
- watch(handle: Handle, read: bool, write: bool) Self[source]¶
reactor = reactor.watch(handle, readable, writable)
Change I/O events to watch handle for with true and false values. Note that this method requires an active I/O watcher.
# Watch only for readable events reactor.watch(handle, True, False) # Watch only for writable events reactor.watch(handle, False, True) # Watch for readable and writable events reactor.watch(handle, True, True) # Pause watching for events reactor.watch(handle, False, False)
Examples
examples/hello_world_trio.py runs Pyjo.HelloWorld on the server of
Pyjoyment on Trio until the signal INT or TERM, in a with block,
which closes the listen sockets of the server at its end:
import os # The reactor of Pyjoyment on Trio, selected before Pyjo.IOLoop is loaded os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Trio' import Pyjo.HelloWorld # noqa: E402 import Pyjo.Server.Daemon # noqa: E402 # The server of Pyjoyment on Trio, until the signal INT or TERM, which closes its listen sockets at the end of the block with Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://*:3000']) as daemon: daemon.run()
$ python examples/hello_world_trio.py
Web application available at http://127.0.0.1:3000
$ curl http://127.0.0.1:3000/
Your Pyjo is working!
examples/trio_nursery.py is a program of Trio, whose run has the server
of Pyjoyment and two tasks of a nursery that request it, with a stream of Trio
and with the user agent of Pyjoyment, whose promise a task of Trio awaits:
import os # The reactor of Pyjoyment on Trio, selected before Pyjo.IOLoop is loaded os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Trio' import Pyjo.HelloWorld # noqa: E402 import Pyjo.Server.Daemon # noqa: E402 import Pyjo.UserAgent # noqa: E402 import trio # noqa: E402 # A task with a stream of Trio, which reads the status line of the response async def stream(port, results): async with await trio.open_tcp_stream('127.0.0.1', port) as stream: await stream.send_all(b'GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n') data = b'' while b'\r\n' not in data: data += await stream.receive_some() results['trio'] = data.split(b'\r\n')[0].decode() # A task with the user agent of Pyjoyment, which awaits the promise of its request async def user_agent(port, results): with Pyjo.UserAgent.new() as ua: tx = await ua.get_p(f'http://127.0.0.1:{port}/') results['Pyjo.UserAgent'] = f'{tx.res.code} {tx.res.text}' # The server of Pyjoyment in the run of Trio of the program, on a port that the system picks, with two tasks of a nursery # that request it, and its listen sockets closed at the end of the block async def main(): results = {} with Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://127.0.0.1'], silent=True) as daemon: port = daemon.start().ports()[0] async with trio.open_nursery() as nursery: nursery.start_soon(stream, port, results) nursery.start_soon(user_agent, port, results) for name in ('trio', 'Pyjo.UserAgent'): print(f'{name}: {results[name]}') trio.run(main)
$ python examples/trio_nursery.py
trio: HTTP/1.1 200 OK
Pyjo.UserAgent: 200 Your Pyjo is working!
examples/loopback_trio.py is a server of Pyjoyment and its user agent on
Trio, a blocking request, which runs the event loop until the response, and
the class of the reactor and the async library that its callbacks run in:
import os # The reactor of Pyjoyment on Trio, selected before Pyjo.IOLoop is loaded os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Trio' import Pyjo.HelloWorld # noqa: E402 import Pyjo.IOLoop # noqa: E402 import Pyjo.Server.Daemon # noqa: E402 import Pyjo.UserAgent # noqa: E402 import sniffio # noqa: E402 # The async library that a callback of the reactor runs in, as a library of Trio would detect it libraries = [] def detect(loop): try: libraries.append(sniffio.current_async_library()) except sniffio.AsyncLibraryNotFoundError: libraries.append('none') # The server, on a port that the system picks, and the user agent, in the same event loop, which close their sockets at # the end of the block with ( Pyjo.Server.Daemon.new(app=Pyjo.HelloWorld.new(), listen=['http://127.0.0.1'], silent=True) as daemon, Pyjo.UserAgent.new(ioloop=Pyjo.IOLoop.singleton) as ua, ): # A blocking request, which runs the event loop of the server on Trio until the response Pyjo.IOLoop.next_tick(detect) tx = ua.get(f'http://127.0.0.1:{daemon.start().ports()[0]}/') print(type(Pyjo.IOLoop.singleton.reactor).__name__, *libraries) print(tx.result.code, tx.result.text)
$ python examples/loopback_trio.py
Pyjo_Reactor_Trio trio
200 Your Pyjo is working!
examples/echo_client_trio.py is the echo client of the tutorial of Trio, with
its sender and receiver in a nursery, and an echo server of
Pyjo.IOLoop in the same run of Trio. The sender waits for the echo of
each message, and closes its side of the connection after the last one, which
the server closes the connection at:
import os # The reactor of Pyjoyment on Trio, selected before Pyjo.IOLoop is loaded os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Trio' import Pyjo.IOLoop # noqa: E402 import Pyjo.Promise # noqa: E402 from itertools import count # noqa: E402 import trio # noqa: E402 MESSAGES = [b'async can sometimes be confusing,', b'but I believe in you!'] CONNECTION_COUNTER = count() # The echo server of Pyjoyment, which writes back what it reads, until the client closes the connection def echo_server(closed): def accept(loop, stream, id): ident = next(CONNECTION_COUNTER) print(f'echo_server {ident}: started') @stream.on def read(stream, data): print(f'echo_server {ident}: received data {data!r}') stream.write(data) @stream.on def close(stream): print(f'echo_server {ident}: connection closed') closed.resolve() return Pyjo.IOLoop.server(accept, address='127.0.0.1') # The echo client of the tutorial of Trio, whose sender waits for the echo of each message before the next one and # closes its side of the connection after the last one, as the stream of Pyjoyment closes at the end of the data async def sender(client_stream, echoed): print('sender: started!') for data in MESSAGES: print(f'sender: sending {data!r}') await client_stream.send_all(data) await echoed.receive() await client_stream.send_eof() async def receiver(client_stream, echoed): print('receiver: started!') async for data in client_stream: print(f'receiver: got data {data!r}') await echoed.send(data) print('receiver: connection closed') # The server of Pyjoyment in the run of Trio of the program, on a port that the system picks, and the client in a # nursery, until the server closed the connection, and the listen socket of the server removed at the end async def parent(): closed = Pyjo.Promise.new() id = echo_server(closed) port = Pyjo.IOLoop.acceptor(id).port print(f'parent: connecting to 127.0.0.1:{port}') client_stream = await trio.open_tcp_stream('127.0.0.1', port) send_echoed, receive_echoed = trio.open_memory_channel(0) async with client_stream, send_echoed, receive_echoed: async with trio.open_nursery() as nursery: print('parent: spawning sender...') nursery.start_soon(sender, client_stream, receive_echoed) print('parent: spawning receiver...') nursery.start_soon(receiver, client_stream, send_echoed) await closed Pyjo.IOLoop.remove(id) trio.run(parent)
The tasks run concurrently, so the order of their lines differs between the runs:
$ python examples/echo_client_trio.py
parent: connecting to 127.0.0.1:60341
parent: spawning sender...
parent: spawning receiver...
echo_server 0: started
receiver: started!
sender: started!
sender: sending b'async can sometimes be confusing,'
echo_server 0: received data b'async can sometimes be confusing,'
receiver: got data b'async can sometimes be confusing,'
sender: sending b'but I believe in you!'
echo_server 0: received data b'but I believe in you!'
receiver: got data b'but I believe in you!'
echo_server 0: connection closed
receiver: connection closed
examples/echo_server_trio.py is the echo server of the tutorial of Trio, with
trio.serve_tcp in a nursery, and an echo client of Pyjo.IOLoop,
whose promise a task of Trio awaits:
import os # The reactor of Pyjoyment on Trio, selected before Pyjo.IOLoop is loaded os.environ['PYJO_REACTOR'] = 'Pyjo.Reactor.Trio' import Pyjo.IOLoop # noqa: E402 import Pyjo.Promise # noqa: E402 from functools import partial # noqa: E402 from itertools import count # noqa: E402 import trio # noqa: E402 MESSAGES = [b'async can sometimes be confusing,', b'but I believe in you!'] CONNECTION_COUNTER = count() # The echo server of the tutorial of Trio, until the client closes the connection async def echo_server(server_stream): ident = next(CONNECTION_COUNTER) print(f'echo_server {ident}: started') try: async for data in server_stream: print(f'echo_server {ident}: received data {data!r}') await server_stream.send_all(data) print(f'echo_server {ident}: connection closed') except Exception as exc: print(f'echo_server {ident}: crashed: {exc!r}') # The echo client of Pyjoyment, which writes each message after the echo of the one before and closes the connection # after the last one, and its promise, which a task of Trio awaits def echo_client(port): promise = Pyjo.Promise.new() messages = list(MESSAGES) echo = b'' @Pyjo.IOLoop.client(address='127.0.0.1', port=port) def client(loop, err, stream): if err is not None: return promise.reject(err) def send(): print(f'client: sending {messages[0]!r}') stream.write(messages[0]) @stream.on def read(stream, data): nonlocal echo echo += data if len(echo) < len(messages[0]): return print(f'client: got data {echo!r}') echo = b'' messages.pop(0) if messages: send() else: stream.close_gracefully() @stream.on def close(stream): print('client: connection closed') promise.resolve() send() return promise # The server of Trio in a nursery, on a port that the system picks, with its connections in a nursery of their own, so # that its listen socket closes after the client and the echo server ends with the connection async def main(): async with trio.open_nursery() as handler_nursery: async with trio.open_nursery() as nursery: listeners = await nursery.start( partial(trio.serve_tcp, echo_server, 0, host='127.0.0.1', handler_nursery=handler_nursery) ) await echo_client(listeners[0].socket.getsockname()[1]) nursery.cancel_scope.cancel() trio.run(main)
$ python examples/echo_server_trio.py
echo_server 0: started
client: sending b'async can sometimes be confusing,'
echo_server 0: received data b'async can sometimes be confusing,'
client: got data b'async can sometimes be confusing,'
client: sending b'but I believe in you!'
echo_server 0: received data b'but I believe in you!'
client: got data b'but I believe in you!'
client: connection closed
echo_server 0: connection closed