TonIO
TonIO is a multi-threaded async runtime for free-threaded Python, built in Rust on top of the mio crate, and inspired by tinyio, trio and tokio.
Warning: TonIO is currently a work in progress. The APIs are subject to breaking changes.
Note: TonIO is available on free-threaded Python only. Windows is supported on a best-effort basis.
TonIO supports both using yield and the more canonical async/await notations, with the latter being available as part of the tonio.colored module. Following code snippets show both the usages.
Warning: despite the fact TonIO supportsasyncandawaitnotations, it's not compatible with anyasyncioobject like futures and tasks. The TonIO-Monkey project provides patches for some popularasynciopackages.
In a nutshell
|
|
|
Usage
Entrypoint
Every TonIO program consists of an entrypoint, which should be passed to the run method:
|
|
|
TonIO also provides a main decorator, thus we can rewrite the previous example as:
|
|
|
Note: as you can see thecoloredmodule provides the additionalyield_nowcoroutine, a quick way to define a suspension point, given you cannot justyieldas in the non-colored notation.
Note: bothrunandmaincan only be called once per program. To run the runtime multiple times in the same program, follow the section below.
Manually managing the runtime
TonIO also provides the runtime function, to manually manage the runtime lifecycle:
import tonio
def _run1():
...
async def _run2():
...
def main():
runtime = tonio.runtime()
runtime.run_until_complete(_run1())
runtime.run_until_complete(_run2())
Runtime options
The run, main and runtime methods accept options, specifically:
| option name | description | default |
| --- | --- | --- |
| context | enable contextvars usage in coroutines | False |
| signals | list of signals to listen to | |
| threads | Number of runtime threads | # of CPU cores |
| blocking_threadpool_size | Maximum number of blocking threads | 128 |
| blocking_threadpool_idle_ttl | Idle timeout for blocking threads (in seconds) | 30 |
Events
The core object in TonIO is Event. It's basically a wrapper around an atomic boolean flag, initialised with False. Event provides the following methods:
is_set(): return the value of the flagset(): set the flag toTrueclear(): set the flag toFalsewait(timeout=None): returns a coroutine you can yield on that unblocks when the flag is set toTrueor the timeout expires. Timeout is in seconds.
|
|
|
Waiters
Event.wait returns a Waiter, the object the runtime actually suspends on. Waiters can be combined: w1 & w2 unblocks when both are set, w1 | w2 when either is. When the operands carry timeouts, & keeps the longest and | the shortest.
Waiters can also be built directly from events with Waiter(ev1, ev2) (all) and Waiter.any(ev1, ev2). Both accept a timeout that applies to the waiter as a whole, and expressed in microseconds.
|
|
|
Result
Result is a thread-safe slot to hand values across coroutines, typically paired with an Event. store(value) writes it and fetch() reads it back. Built with a size, it holds that many slots, store(value, index) fills one and fetch() returns them as a list.
Spawning tasks
TonIO provides the spawn method to schedule new coroutines onto the runtime:
|
|
|
Coroutines passed to spawn get scheduled onto the runtime immediately. Using yield or await on the return value of spawn just waits for the coroutines to complete and retrieve the results.
When results are not needed, spawn.without_results waits for completion without collecting them. spawn.without_tracking schedules the coroutines and returns nothing at all, for fire-and-forget work.
Blocking tasks
TonIO provides the spawn_blocking method to schedule blocking operations onto the runtime:
|
|
|
Running tasks from synchronous contexts
TonIO provides the block_on method to spawn coroutines from a synchronous context. It works the same way of spawn, except it accepts a single coroutine and it blocks the current thread until the coroutine is completed.
Warning: using block_on from within a coroutine might produce a runtime deadlock.
Map utilities
TonIO provides the map and map_blocking utilities to spawn the same operation with an iterable of parameters:
|
|
|
Completion-based iterators
TonIO provides the as_completed utility to iterate over task results based on completion order:
|
|
|
Scopes and cancellations
TonIO provides a scope context, that lets you cancel work spawned within it:
|
|
|
When you yield on the scope, it will wait for all the spawned coroutines to end. If the scope was canceled, then all the pending coroutines will be canceled. By default, an exception in the scope context won't cancel the scope itself. If you want those exceptions to cancel the scope, you can pass cancel_on_exc=True to scope.
Note: as you can see, the colored version ofscopedoesn't require to beawaited, as it will yield when exiting the context.
Select first completing task
TonIO also provides a select utility to cancel remaining work on the first completing task:
|
|
|
select also accepts waiters, so an Event.wait() can race against coroutines.
Time-related functions
tonio.time.time(): a function returning the runtime's clock (in seconds, microsecond resolution)tonio.time.sleep(delay): a coroutine you can yield on to sleep (delay is in seconds)tonio.time.timeout(coro, timeout): a coroutine you can yield on returning a tuple(output, success). If the coroutine succeeds in the given time then the pair(output, True)is returned. Otherwise this will return(None, False).
Note:time.sleepis also exported to the maintoniomodule.
Note: all of the above functions are also present in tonio.colored.time module.
Scheduling work
TonIO provides the time.interval function to create interval objects you can yield on a scheduled basis:
|
|
|
The interval method first argument is the interval in seconds resolution, and the method also accepts an optional at argument, to delay the first execution at a specific time (from the runtime's clock perspective):
from tonio import time
tick every 500ms, with the first tick happening in 5 seconds from now
interval = time.interval(0.5, time.time() + 5)
Synchronization primitives
Synchronization primitives are exposed in the tonio.sync module.
Lock
Implements a classic mutex, or a non-reentrant, single-owner lock for coroutines:
|
|
|
The Lock object also implements an or_raise method, that will immediately fail when the lock cannot be acquired:
from tonio.exceptions import WouldBlock
try:
with lock.or_raise():
...
except WouldBlock:
...
Semaphore
A semaphore for coroutines:
|
|
|
As for locks, the Semaphore object also implements an or_raise method, that will immediately fail when the lock cannot be acquired:
from tonio.exceptions import WouldBlock
try:
with semaphore.or_raise():
...
except WouldBlock:
...
The Semaphore object also implements a tokens method, that returns the number of available tokens.
Barrier
A barrier for coroutines:
|
|
|
The Barrier object also implements a value method, which returns the current value of the barrier.
Channels
Multi-producer multi-consumer channels for inter-coroutine communication.
The tonio.sync.channel module provides both a channel and an unbounded constructors.
The main difference between bounded and unbounded channels, as the names suggest, is that while the first will suspend sending messages once the specified length is reached, and it will resume accepting messages once the existing buffer is consumed, the latter will always accept new messages. That's also why, the sender part of a bounded channel is async, while in the unbounded is not.
##### Bounded channel
|
|
|
##### Unbounded channel
|
|
|
##### Non-blocking operations
Receivers of both channel kinds offer receive_nowait, a synchronous variant that never suspends: it returns the message or one of the Empty and Closed sentinels. Bounded senders, the only suspending ones, offer send_nowait in the same way: it returns None on success or one of the Full and Closed sentinels. The sentinels are available as attributes on the objects exposing them:
sender, receiver = channel.channel(8)
if sender.send_nowait(message) is sender.Full:
...
if (message := receiver.receive_nowait()) is receiver.Empty:
...
The same objects also expose try_send and try_receive, which raise instead: WouldBlock when the channel is full or empty, BrokenPipeError when it's closed.
Markers
The mark module provides decorator shortcuts for spawn_blocking and Semaphore:
|
|
|
Network module
Network primitives are exposed under the tonio.net module.
Streams
The high-level network primitives in TonIO are centered around the SocketStream and SocketListener objects.
The SocketListener object implements an accept coroutine which returns a SocketStream object.
The SocketStream object implements the send_all and receive_some coroutines to send and receive data, and a send_eof method to shutdown the sending side.
Both objects implement a close method to shutdown the underlying socket.
You can create and interact with the above objects using some high-level helpers in the net module, specifically:
open_tcp_stream: a coroutine to open aSocketStreamconnected to a TCP endpointopen_unix_socket: a coroutine to open aSocketStreamconnected to a Unix socketopen_tcp_listeners: a coroutine to initialiseSocketListenerobjectsopen_unix_listener: a coroutine to initialise aSocketListeneron a Unix socket pathserve_listeners: a coroutine to spawnSocketListeneraccept loops targeting a handlerserve_tcp: a coroutine that joinsopen_tcp_listenersandserve_listenersin one callserve_unix: a coroutine that joinsopen_unix_listenerandserve_listenersin one call
|
|
|
Unix domain sockets use the same objects, with serve_unix and open_unix_socket:
|
|
|
##### Readiness and non-blocking operations
SocketStream also exposes its readiness state, for code that wants to decide when to read or write rather than just block on it:
wait_readable(timeout=None)andwait_writable(timeout=None): coroutines that suspend until the socket is ready, returningFalseif the timeout (in seconds) expires firstreceive_some_nowait(max_bytes=None): a synchronous receive, returning theNotReadysentinel (available asstream.NotReady) when no data is availabletry_receive_some(max_bytes=None): same, but raisingWouldBlockinsteadwatch_readable()andwatch_writable(): context managers producing a watcher, whosewaiter()method returns aWaiter(orNonewhen ready) you can combine with others, and whoseready()method tells whether the socket is ready
|
|
|
TLS streams
TonIO implement TLS wrappers around the streaming APIs through primitives in the tonio.net.tls module.
TonIO provides the TLSStream and TLSListener object wrappers and the following high-level helpers:
open_tls_over_tcp_stream: a coroutine to open aTLSStreamwrapping a TCPSocketStreamopen_tls_over_tcp_listeners: a coroutine to initialiseTLSListenerobjectsserve_tls_over_tcp: a coroutine that joinsopen_tls_over_tcp_listenersandserve_listenersin one call
Low-level sockets
The tonio.net.socket module provides TonIO's basic low-level networking API.
Generally, the API exposed by this module mirrors the standard library socket module.
TonIO socket objects are overall very similar to the standard library socket objects, with the main difference being that blocking methods become coroutines.
|
|
|
Filesystem module
TonIO's fs module exposes async API for filesystem operations (that are run in the blocking thread-pool).
It provides open, a Path class mirroring pathlib.Path, and wrap_file to
adopt an already-open file object.
|
|
|
Operations that touch the filesystem are asynchronous; everything else stays synchronous.
Note: methods returning several paths (iterdir,glob,rglob,walk) are resolved in a single hop and give back alist. Sincewalkis fully materialised, mutating itsdirnamesdoes not prune the traversal, unlikepathlib.Path.walk.
Reading a file line by line differs between the two flavours. The await syntax supports async for
and async with, neither of which the yield syntax can express:
|
|
|
Subprocesses
TonIO exposes two coroutines to run child processes: run_process for the common
"run it and collect the outcome" case, and open_process for interacting with a process while it
runs. Both spawn the process on the blocking thread-pool.
run_process returns a subprocess.CompletedProcess and accepts:
stdin: bytes to feed to the child (defaults tob'', meaning "close stdin immediately"), or a file descriptor/subprocessconstantcapture_stdout/capture_stderr: when true, the relevant stream is collected and available on the resultcheck: when true (the default), a non-zero exit code raisessubprocess.CalledProcessError
subprocess.Popen.
|
|
|
open_process returns a Process object instead, giving access to the running child. Passing
subprocess.PIPE for stdin, stdout or stderr exposes the corresponding pipe as a stream on the
process object, implementing the same send_all and receive_some coroutines of network streams:
|
|
|
The Process object exposes:
argsandpid: the command and the process identifierstdin,stdout,stderr: the piped streams, orNonewhen not pipedstdio: a(stdin, stdout)tuple, when both are pipedreturncodeandpoll(): the exit code, orNonewhile the process is still runningwait: a coroutine waiting for the process to exit, returning its exit codesend_signal,terminate,kill: synchronous methods to signal the process
Note: unlikerun_process,open_processdoes not reap the child for you: remember towaiton it — possibly after akill— otherwise the child outlives your task.
Note: processes in TonIO only communicate over unbuffered byte streams: theuniversal_newlines,text,encoding,errorsandbufsizeoptions ofsubprocessare not supported.
Note: on Windows, due to the platform's lack of features, the subprocess readiness implementation falls back to the blocking thread-pool. Thus, waiting on a process or read/write operations on pipes can't be interrupted while blocked: cancellations take effect only once the OS call returns.
Driving your own I/O
The io module exposes the primitives TonIO's own sockets, pipes and processes are built on, so you can plug any file descriptor the platform poller understands into the runtime, with the same readiness model.
register puts a descriptor under the poller's watch, for both reading and writing, and returns a ScheduledIO object. The registration is edge-triggered and lasts until you close it. The descriptor itself is neither owned nor switched to non-blocking mode: that's up to you.
Readiness is consumed in user space through a small protocol: arm_r (or arm_w) returns None if the descriptor is known to be ready, otherwise a Waiter to suspend on. Once ready, you perform the actual system call. If it would block anyway, clear_r (or clear_w) drops the stale readiness, so the next arm_r suspends again.
|
|
|
arm_r and arm_w accept a timeout in seconds. An expired waiter just resumes, so a further arm_* call tells whether the descriptor got ready in the meantime. Readiness also covers hang-ups and errors: you'll be woken up when the peer goes away, and the following system call will report it.
consume_r and consume_w drain a direction's readiness and tell whether it was set, for descriptors signalling through readiness alone.
Descriptor streams
FdStream wraps a pipe-like descriptor into the same stream interface of the network module, taking ownership of it. It provides the send_all and receive_some coroutines, fileno and close, the latter also invoked when leaving a with block. This is what the pipes of Process objects are.
|
|
|
Concurrent operations on the same direction of a stream raise WouldBlock, and a broken pipe surfaces as ResourceBroken.
Note: on Windows FdStream falls back to the blocking thread-pool, with the same limitations described for subprocesses.
Signals
TonIO provides a context manager to catch signals.
The usage of such context manager requires to first configure the runtime to listen for such signals:
|
|
|
Exceptions
The tonio.exceptions module exposes:
CancelledError: raised inside a coroutine when it gets cancelledTimeoutError: raised when a timed operation expiresWouldBlock: raised by theor_raiseandtry_*variants when the operation cannot complete immediatelyResourceBroken: raised by streams when the underlying transport is unusable
Note:CancelledErrorandTimeoutErrorderive fromBaseException, so they pass throughexcept Exceptionclauses.
Testing
TonIO ships with a pytest plugin, which runs tests marked with the tonio marker on the runtime:
|
|
|
The marker can also be applied at module level with pytestmark = pytest.mark.tonio, or at class level.
To avoid marking tests entirely, the plugin also provides an auto mode, in which every async test gets run on the TonIO runtime. Auto mode can be enabled with the tonio_mode option in the pytest configuration:
[tool.pytest.ini_options]
tonio_mode = 'auto'
Async fixtures
For asynchronous fixtures where setup and teardown are required, the two syntaxes differ.
##### await syntax
Async fixtures involved in TonIO tests run on the runtime. Coroutine fixtures simply return their value, while async generator fixtures can yield it and run teardown code after the yield:
import pytest
from tonio.colored.net import open_tcp_stream
@pytest.fixture
async def connection():
stream = await open_tcp_stream(host='127.0.0.1', port=8000)
yield stream
stream.close()
##### yield syntax
Given non-colored TonIO coroutines are indistinguishable from standard pytest generator fixtures, the plugin never runs generator fixtures on the runtime. This is usually not a limitation: since yield syntax tests already run as coroutines, simple setup can just happen within the test itself:
import pytest
from tonio.net import open_tcp_stream
def _connect():
stream = yield open_tcp_stream(host='127.0.0.1', port=8000)
return stream
@pytest.mark.tonio
def test_conn():
stream = yield _connect()
yield stream.send_all(b'ping')
When an actual teardown is required, the plugin provides the tonio_run fixture, which runs the given coroutine on the runtime:
@pytest.fixture
def connection(tonio_run):
stream = tonio_run(_connect())
def _disconnect():
yield stream.send_all(b'bye')
stream.close()
yield stream
tonio_run(_disconnect())
Runtime configuration in pytest
The TonIO runtime is always initialised once per test session, with context enabled and 2 threads. Runtime options can be customized overriding the session-scoped tonio_runtime_options fixture, for example in conftest.py:
import pytest
@pytest.fixture(scope='session')
def tonio_runtime_options():
return {'threads': 4}
The runtime object itself is available to tests and fixtures via the session-scoped tonio_runtime fixture.
Libraries built on TonIO
In addition to the patches provided by the TonIO-Monkey project, the following libraries target TonIO natively:
- httpunk: a low-level async HTTP library
- punkreq: a high-level async HTTP client
- punkasgi: an ASGI server built on TonIO
License
TonIO is released under the BSD License.