如何将异步/标准库 future 转换为 futures 0.1?

2023-12-14

我想使用async函数逐步解析入站流,但 actix-web 需要impl Future<Item = HttpResponse, Error = Error>作为返回值。

我如何转换返回的未来asyncactix-web 需要什么功能?

我正在使用 Rust 1.39 nightly 和 actix-web 1.0.7。

http_srv.rs :

use futures::compat::Stream01CompatExt;
use futures::future::{FutureExt, TryFutureExt};
use futures::stream::TryStreamExt;
use futures01::future::Future;
use futures01::stream::Stream;
use futures01::sync::mpsc; // for `try_next`

use actix_web::*;
use bytes::Bytes;
use futures_timer::Delay;
use std::time::Duration;

fn inbound(
    req: HttpRequest,
    stream: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
    let fut = async_inbound(&req, &stream);

    fut.unit_error().boxed_local().compat() // <--- compliation error here.
}

async fn async_inbound(req: &HttpRequest, stream: &web::Payload) -> HttpResponse {
    let mut compat_stream = stream.compat();
    loop {
        let result = compat_stream.try_next().await;
        if let Err(e) = result {
            warn!("Failed to read stream from {} : {}", req.path(), e);
            break;
        }

        if let Ok(option) = result {
            match option {
                None => {
                    info!("Request ends");
                    break;
                }
                Some(data) => {
                    println!("{:?}", data);
                }
            }
        }
    }
    HttpResponse::Ok().content_type("text/html").body("RESP")
}

pub fn start(port: u16) {
    info!("Starting HTTP server listening at port {} ...", port);

    let _ = HttpServer::new(|| {
        App::new()
            .wrap(middleware::DefaultHeaders::new().header(http::header::CACHE_CONTROL, "no-cache"))
            .wrap(middleware::Logger::default())
            .service(web::resource("/").route(web::put().to_async(inbound)))
    })
    .bind(format!("0.0.0.0:{}", port))
    .expect(&format!("Unable to bind on port {}", port))
    .run()
    .expect("Failed to start HTTP server");
}

Cargo.toml:

[dependencies]
log = "0.4.8"
env_logger = "0.6.2"
chrono = "0.4.8"
actix = "0.8.3"
bytes = "0.4.12"
actix-utils = "0.4.5"
futures-timer = "0.3"
futures01 = { package = "futures", version = "0.1", optional = false }

[dependencies.actix-web]
version = "1.0.7"
features = ["ssl"]

# https://rust-lang-nursery.github.io/futures-rs/blog/2019/04/18/compatibility-layer.html
# Rust’s futures ecosystem is currently split in two: 
# On the one hand we have the vibrant ecosystem built around [email protected] with its many libraries working on stable Rust 
# and on the other hand there’s std::future ecosystem with support for the ergonomic and powerful async/await language feature. 
# To bridge the gap between these two worlds we have introduced a compatibility layer as part of the [email protected] extension to std::future. 
[dependencies.futures-preview]
version = "0.3.0-alpha.18"
default-features = false
features = ["compat", "async-await", "nightly"]

编译错误:

error[E0271]: type mismatch resolving `<std::pin::Pin<std::boxed::Box<dyn core::future::future::Future<Output = std::result::Result<actix_http::response::Response, ()>>>> as core::future::future::Future>::Output == std::result::Result<_, actix_http::error::Error>`
  --> src/http_server.rs:39:55
   |
39 | fn inbound(req: HttpRequest, stream: web::Payload) -> impl Future<Item=HttpResponse, Error=Error> {
   |                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found struct `actix_http::error::Error`
   |
   = note: expected type `std::result::Result<actix_http::response::Response, ()>`
              found type `std::result::Result<_, actix_http::error::Error>`
   = note: required because of the requirements on the impl of `futures_core::future::TryFuture` for `std::pin::Pin<std::boxed::Box<dyn core::future::future::Future<Output = std::result::Result<actix_http::response::Response, ()>>>>`
   = note: the return type of a function must have a statically known size

std::future -> [email protected]转换步骤:

  • 未来需要TryFuture (Output = Result<T, E>)
  • 未来需要Unpin(您可以使用boxed组合器)
  • 最后,您可以调用compat组合器

Your inbound功能:

fn inbound(
    req: HttpRequest,
    stream: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
    let fut = async_inbound(&req, &stream);
    fut.unit_error().boxed_local().compat()
}

The inbound函数签名很好,但转换不行。

The async_inbound函数不是TryFuture(因为-> HttpResponse)。您正在尝试将其转换为unit_error组合器,但结果是Result<HttpResponse, ()>你想要Result<HttpResponse, Error>. Fixed inbound功能:

fn inbound(
    req: HttpRequest,
    stream: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
    let fut = async_inbound(req, stream);
    fut.boxed_local().compat()
}

Your async_inbound功能:

async fn async_inbound(req: &HttpRequest, stream: &web::Payload) -> HttpResponse {
    // ...
}

这里的第一个问题是替换-> HttpResponse with -> Result<HttpResponse>。另一个问题是你正在通过reg and stream引用。移动它们,因为不需要参考,您将需要'static. Fixed async_inbound功能:

async fn async_inbound(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse> {
    let mut compat_stream = stream.compat();

    while let Some(data) = compat_stream.try_next().await? {
        println!("{:?}", data);
    }

    Ok(HttpResponse::Ok().content_type("text/html").body("RESP"))
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将异步/标准库 future 转换为 futures 0.1? 的相关文章

随机推荐