Actix Web的生命周期问题

时间:2018-11-25 07:36:31

标签: rust lifetime rust-actix

我正在用Actix-web实现中间件,并且存在无法解决的寿命问题。

extern crate actix_web;

use actix_web::actix::{Actor, Addr, Context, System};
use actix_web::middleware::Middleware;
use actix_web::{http, server, App, HttpRequest, Responder};
use std::collections::HashMap;

pub struct CacheActor {
    caches: HashMap<String, String>,
}

impl CacheActor {
    pub fn new() -> Self {
        CacheActor {
            caches: HashMap::new(),
        }
    }
}

impl Actor for CacheActor {
    type Context = Context<Self>;
}

fn create_resource(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
    unimplemented!();
    format!("Unimplemented")
}

fn list_resources(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
    unimplemented!();
    format!("Unimplemented")
}

pub trait TusMiddlewareTrait {
    fn with_tus(self, addr: &Addr<CacheActor>) -> App;
}

impl TusMiddlewareTrait for App {
    fn with_tus(self, addr: &Addr<CacheActor>) -> App {
        self.route("/files", http::Method::GET, |req| list_resources(req, addr))
            .route("/files", http::Method::POST, |req| {
                create_resource(req, addr)
            })
    }
}

fn main() {
    let system = System::new("Example");
    let cache_addr = CacheActor::new().start();

    server::new(|| App::new().with_tus(&cache_addr))
        .bind("127.0.0.1:8080")
        .unwrap()
        .run();

    system.run();
}

我得到的错误如下,

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/tus/middleware.rs:84:49
   |
84 |             .route("/files", http::Method::GET, |req| list_resources(req, addr))
   |                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 81:5...
  --> src/tus/middleware.rs:81:5
   |
81 | /     fn with_tus(self, addr: &actix::Addr<cache::CacheActor>) -> App {
82 | |         self.middleware(TusMiddleware)
83 | |             .route("/files", http::Method::OPTIONS, tus_information)
84 | |             .route("/files", http::Method::GET, |req| list_resources(req, addr))
...  |
87 | |             })
88 | |     }
   | |_____^
   = note: ...so that the types are compatible:
           expected &&actix::address::Addr<tus::cache::CacheActor>
              found &&actix::address::Addr<tus::cache::CacheActor>
   = note: but, the lifetime must be valid for the static lifetime...

据我了解,我正在传递cache_addr作为对with_tus函数的引用。在route中的每个闭包中,addr也是一个引用。

我不明白为什么编译器会说the lifetime cannot outlive the anonymous lifetime #1。据我所知,cache_addr的生命周期仍然长于闭包。生命周期应覆盖到system.run()行。有人可以启发我吗?

修改

我将上面的代码更新为MCVE(至少可以简单地复制整个代码并运行商品构建,同时仍保留相同的错误消息)。我不能在生锈的操场上运行它。目前,它不支持actix条板箱。我尝试进一步减少它,但这给了我一个不同的错误。抱歉,Rust我还很陌生。

我的问题有两个,一个是我想了解告诉我的错误是什么。其次,我想知道如何使用actix正确地执行此操作,因此为什么示例代码依赖于actix

1 个答案:

答案 0 :(得分:0)

看看App::route signature

pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
where
    F: WithFactory<T, S, R>,
    R: Responder + 'static,
    T: FromRequest<S> + 'static,

F的泛型依赖于TR,而它们又有'static的生存期要求。

您的闭包捕获了&Addr<CacheActor>生命周期内无效的'static,并生成了错误。

我看到的一种可能性是直接从docs使用App“状态”:

  

应用程序状态与同一应用程序中的所有路由和资源共享。使用http actor时,可以使用HttpRequest :: state()以只读方式访问状态,但是可以使用RefCell的内部可变性来实现状态可变性。状态也可用于路由匹配谓词和中间件。

在这种情况下,应该类似于:

extern crate actix_web;

use actix_web::actix::{Actor, Addr, Context, System};
use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
use std::collections::HashMap;
use actix_web::dev::Handler;

#[derive(Clone)]
pub struct CacheActor {
    caches: HashMap<String, String>,
}

impl CacheActor {
    pub fn new() -> Self {
        CacheActor {
            caches: HashMap::new(),
        }
    }
}

impl Actor for CacheActor {
    type Context = Context<Self>;
}

impl<S> Handler<S> for CacheActor {
    type Result = String;

    fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
        unimplemented!();
    }
}

fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
    Ok(HttpResponse::Found()
        .header(http::header::LOCATION, format!("hello {}", req.path()))
        .finish())
}

fn main() {
    let system = System::new("Example");

    server::new(|| {
        let cache_addr = CacheActor::new().start();
        App::with_state(cache_addr)
            .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
    })
    .bind("127.0.0.1:8080")
    .unwrap()
    .run();

    system.run();
}