compio README

The project's README from github.com/compio-rs/compio. As one markdown file: README.md.


Compio

MIT licensed crates.io docs.rs Check Test Telegram Discord

A thread-per-core Rust runtime with IOCP/io_uring/polling inspired by monoio.

Quick start

Add compio as dependency:

cargo add compio --features macros,fs

Then use the high level APIs provided to perform filesystem & network IO:

use compio::{fs::File, io::AsyncReadAtExt};

#[compio::main]
async fn main() {
    let file = File::open("Cargo.toml").await.unwrap();
    let (read, buffer) = file.read_to_end_at(Vec::with_capacity(1024), 0).await.unwrap();
    assert_eq!(read, buffer.len());
    let buffer = String::from_utf8(buffer).unwrap();
    println!("{}", buffer);
}

It's also possible to use the low-level driver (the proactor, without async executor) manually. See driver example.

Observability

The console feature makes the runtime emit the tracing spans and events that tokio-console consumes, so compio applications can be inspected with it:

cargo add compio --features console
cargo add console-subscriber
# .cargo/config.toml
#
# `console-subscriber` refuses to run unless the runtime is known to be
# instrumented; this is the escape hatch it provides for runtimes other than
# tokio.
[build]
rustflags = ["--cfg", "console_without_tokio_unstable"]
console_subscriber::init();
compio::runtime::Runtime::new().unwrap().block_on(async {
    // ...
});

Then run tokio-console to watch tasks, poll times and waker activity. The console module docs describe what is reported and what is not.

The console example runs an echo server on a dispatcher, so that the console shows the tasks of a thread-per-core application spread over its worker threads, next to tasks that are wrong in the ways it warns about. It passes the cfg on the command line instead:

RUSTFLAGS="--cfg console_without_tokio_unstable" \
    cargo run --example console --features console,time,net,dispatcher,sync

Why the name?

The name comes from "completion-based IO", and follows the non-existent convention that an async runtime should be named with a suffix "io".

Comparison with other runtimes

Tokio

Tokio is a great generic-purpose async runtime. However, it is poll-based, and even uses undocumented APIs on Windows. We would like some new high-level APIs to perform IOCP/io_uring.

compio isn't tokio-based. This is mainly because tokio doesn't expose APIs to control mio, and mio doesn't expose APIs to control IOCP.

Monoio

Monoio focuses on Linux and io-uring, and fallbacks to mio on other platforms.

Glommio

Glommio doesn't support Windows.

Others

There are also lots of other great async runtimes. But most of them are (at the moment when compio was created) either poll-based, use io-uring unsoundly, or aren't cross-platform. We hope compio can fill this gap.

Contributing

There are opportunities to contribute to Compio at any level. It doesn't matter if you are just getting started with Rust or are the most weathered expert, we can use your help. If you have any question about Compio, feel free to join our telegram group. Before contributing, please checkout our contributing guide.

compio (compio-rs/compio)

Searching Database…

1.9K ·GitHub
Что это?Compio — асинхронный Rust-рантайм с моделью «поток на ядро», использующий бэкенды ввода-вывода на завершениях (IOCP на Windows, io_uring на Linux, polling в остальных случаях) вместо основанной на опросе модели, которую использует большинство рантаймов.
Это библиотека, которую я добавляю в свой Rust-проект, или отдельный сервер?Это библиотека Rust (крейт), которую вы добавляете как зависимость, чтобы получить асинхронный файловый и сетевой ввод-вывод, плюс низкоуровневый драйвер, которым можно пользоваться напрямую.
Как с него начать?Добавьте compio как зависимость в Cargo.toml, затем используйте его высокоуровневые асинхронные API для файлового и сетевого ввода-вывода или спускайтесь вручную к низкоуровневому драйверу proactor, если нужен больший контроль.
Нужно ли мне что-то, кроме Rust?Только Rust и крейт compio; на Linux он опирается на io_uring, на Windows — на IOCP, а на прочих платформах откатывается к polling, и всё это обрабатывается внутри.
Чем это отличается от простого использования Tokio?Tokio основан на опросе и на Windows опирается на недокументированные API, тогда как compio с нуля построен вокруг ввода-вывода на завершениях (IOCP/io_uring) и не построен поверх tokio или mio.
На кого нацелен compio и работает ли он кроссплатформенно, в отличие от некоторых альтернатив?Он нацелен на Rust-разработчиков, создающих высокопроизводительные асинхронные сетевые/файловые приложения и желающих получить по-настоящему кроссплатформенный рантайм на завершениях; в отличие от Monoio (сфокусирован на Linux/io_uring) или Glommio (без поддержки Windows), compio работает на Linux, Windows и macOS.
Почему он называется compio?Имя происходит от «completion-based IO» — в соответствии с традицией, что асинхронный рантайм должен иметь суффикс «-io».
Можно ли отлаживать и инспектировать запущенные задачи compio?Да, со включённой фичей console compio испускает tracing-спаны и события, которые умеет потреблять tokio-console, позволяя наблюдать задачи, время опросов и активность waker, в том числе в конфигурациях диспетчера с потоком на ядро.
Почему compio не построили поверх tokio или mio?Tokio не выставляет API для управления mio, а mio — API для управления IOCP, поэтому compio понадобился собственный фундамент на завершениях вместо переиспользования этих абстракций.
What are similar projects?libuv, tokio, muduo, swoole-src, hotpath-rs, conc, perry, libevent
Creator
compio-rs
Size
3.9 MB
Stars
1.9K
Age
3y
Commits · 90 Days