我们一起聊聊如何编写异步运行时通用库?

开发 前端
在Cargo.toml中,你可以简单地将common-async-runtime作为依赖项包含进来。这使得你的库代码很“纯粹”,因为现在选择异步运行时是由下游控制的。与方法1类似,这个crate可以在没有任何异步运行时的情况下编译,这很简洁!​

如果你正在用Rust编写异步应用程序,在某些情况下,你可能希望将代码分成几个子crate。这样做的好处是:

  • 更好的封装,在子系统之间有一个crate边界,可以产生更清晰的代码和定义更良好的API。不再需要这样写:pub(crate)。
  • 更快的编译,通过将一个大crate分解成几个独立的小crate,它们可以并发地编译。

使用一个异步运行时,编写异步运行时通用库的好处是什么?

  • 可移植性,你可以很容易地切换到不同的异步运行时或wasm。
  • 保证正确性,针对tokio和async-std,测试一个库就可以发现更多的bug,包括并发bug(由于任务执行顺序模糊)和“未定义行为”(由于误解异步运行时实现细节)

下面使用三种方法来实现异步运行时通用库。

方法1,定义自己的异步运行时Trait

使用futures crate,可以编写非常通用的库代码,但是time,sleep或timeout等操作必须依赖于异步运行时。这时,你可以定义自己的AsyncRuntime trait,并要求下游实现它。

use std::{future::Future, time::Duration};

pub trait AsyncRuntime: Send + Sync + 'static {
    type Delay: Future<Output = ()> + Send;

    // 返回值必须是一个Future
    fn sleep(duration: Duration) -> Self::Delay;
}

可以像这样使用上面的库代码:

async fn operation<R: AsyncRuntime>() {
    R::sleep(Duration::from_millis(1)).await;
}

下面是它如何实现的:

pub struct TokioRuntime;

impl AsyncRuntime for TokioRuntime {
    type Delay = tokio::time::Sleep;

    fn sleep(duration: Duration) -> Self::Delay {
        tokio::time::sleep(duration)
    }
}

#[tokio::main]
async fn main() {
    operation::<TokioRuntime>().await;
    println!("Hello, world!");
}

方法2,在内部抽象异步运行时并公开特性标志

为了处理网络连接或文件句柄,我们可以使用AsyncRead / AsyncWrite trait:

#[async_trait]
pub(crate) trait AsyncRuntime: Send + Sync + 'static {
    type Connection: AsyncRead + AsyncWrite + Send + Sync + 'static;

    async fn connect(addr: SocketAddr) -> std::io::Result<Self::Connection>;
}

可以像这样使用上面的库代码:

async fn operation<R: AsyncRuntime>(conn: &mut R::Connection) 
where
    R::Connection: Unpin,
{
    conn.write(b"some bytes").await;
}

然后为每个异步运行时定义一个模块:

#[cfg(feature = "runtime-async-std")]
mod async_std_impl;
#[cfg(feature = "runtime-async-std")]
use async_std_impl::*;

#[cfg(feature = "runtime-tokio")]
mod tokio_impl;
#[cfg(feature = "runtime-tokio")]
use tokio_impl::*;

tokio_impl模块:

mod tokio_impl {
    use std::net::SocketAddr;

    use async_trait::async_trait;
    use crate::AsyncRuntime;

    pub struct TokioRuntime;

    #[async_trait]
    impl AsyncRuntime for TokioRuntime {
        type Connection = tokio::net::TcpStream;

        async fn connect(addr: SocketAddr) -> std::io::Result<Self::Connection> {
            tokio::net::TcpStream::connect(addr).await
        }
    }
}

main函数代码:

#[tokio::main]
async fn main() {
    let mut conn =
        TokioRuntime::connect(SocketAddr::new(IpAddr::from_str("0.0.0.0").unwrap(), 8080))
            .await
            .unwrap();
    operation::<TokioRuntime>(&mut conn).await;
    println!("Hello, world!");
}

方法3,维护一个异步运行时抽象库

基本上,将使用的所有异步运行时api写成一个包装器库。这样做可能很繁琐,但也有一个好处,即可以在一个地方为项目指定与异步运行时的所有交互,这对于调试或跟踪非常方便。

例如,我们定义异步运行时抽象库的名字为:common-async-runtime,它的异步任务处理代码如下:

// common-async-runtime/tokio_task.rs

pub use tokio::task::{JoinHandle as TaskHandle};

pub fn spawn_task<F, T>(future: F) -> TaskHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    tokio::task::spawn(future)
}

async-std的任务API与Tokio略有不同,这需要一些样板文件:

// common-async-runtime/async_std_task.rs

pub struct TaskHandle<T>(async_std::task::JoinHandle<T>);

pub fn spawn_task<F, T>(future: F) -> TaskHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
{
    TaskHandle(async_std::task::spawn(future))
}

#[derive(Debug)]
pub struct JoinError;

impl std::error::Error for JoinError {}

impl<T> Future for TaskHandle<T> {
    type Output = Result<T, JoinError>;

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        match self.0.poll_unpin(cx) {
            std::task::Poll::Ready(res) => std::task::Poll::Ready(Ok(res)),
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

在Cargo.toml中,你可以简单地将common-async-runtime作为依赖项包含进来。这使得你的库代码很“纯粹”,因为现在选择异步运行时是由下游控制的。与方法1类似,这个crate可以在没有任何异步运行时的情况下编译,这很简洁!

责任编辑:武晓燕 来源: coding到灯火阑珊
相关推荐

2023-11-29 07:10:50

python协程异步编程

2023-04-03 00:09:13

2021-08-27 07:06:10

IOJava抽象

2024-02-20 21:34:16

循环GolangGo

2023-07-04 08:06:40

数据库容器公有云

2023-08-10 08:28:46

网络编程通信

2022-05-24 08:21:16

数据安全API

2023-08-04 08:20:56

DockerfileDocker工具

2023-09-10 21:42:31

2023-06-30 08:18:51

敏捷开发模式

2022-12-05 09:10:21

2021-11-04 06:58:31

CSS性能设备

2023-11-06 07:21:02

DBaaSApachealpha版本

2022-08-30 13:48:16

LinuxMySQL内存

2022-02-14 07:03:31

网站安全MFA

2022-11-12 12:33:38

CSS预处理器Sass

2022-10-28 07:27:17

Netty异步Future

2023-12-28 09:55:08

队列数据结构存储

2022-04-06 08:23:57

指针函数代码

2023-07-27 07:46:51

SAFe团队测试
点赞
收藏

51CTO技术栈公众号