actix-web: обработка асинхронных / будущих ответов с ограниченным временем жизни - PullRequest
1 голос
/ 11 июля 2019

Использование этого минимального асинхронного веб-сервера actix

use actix_web::{http, server, App, HttpRequest, HttpResponse,  Error}; // v. 0.7.19
use futures::Future; // v. 0.1.28

/// An Asynchronous response which will either "fail fast" on the outer `Result` or
/// return a future which may itself succeed or fail
/// The lifetime parameter is required to indicate that the future cannot outlive
/// the parameter  - the `req: &HttpRequest` - of the handler (`handle_request`)
type AsyncCResponse<'a> =
Result<Box<Future<Item = HttpResponse, Error = Error> + 'a>, Error>;

/// lifetimes have been elided but here the future in the `AsyncCResponse`
/// will have the same lifetime as the `req` HttpRequest
fn handle_request(req: &HttpRequest<()>) -> AsyncCResponse {
    // handle the request
    Ok(Box::new(futures::future::ok(HttpResponse::Ok().body("Hello World"))))
}

fn main() {
    // instantiation of an actix-web server
    server::new(move || {
        App::new()
            .resource("/", |r| {
                r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
            })
    });
}

Компиляция завершается с


error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:23:69
   |
23 |                 r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
   |                                                                     ^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 23:47...
  --> src/main.rs:23:47
   |
23 |                 r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
   |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:23:84
   |
23 |                 r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
   |                                                                                    ^
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the types are compatible:
           expected actix_web::handler::Responder
              found actix_web::handler::Responder

Определение f в actix-web:

/// Set handler function. Usually call to this method is last call
/// during route configuration, so it does not return reference to self.
pub fn f<F, R>(&mut self, handler: F)
where
    F: Fn(&HttpRequest<S>) -> R + 'static,
    R: Responder + 'static,
{
    self.handler = InnerHandler::new(handler);
}

Правильно ли я понимаю, что компиляция не удалась, потому что

  • определение f требует, чтобы обработчик F возвращал ответ с 'static продолжительностью жизни
  • когда ответ, возвращаемый данным обработчиком handle_request, имеет время жизни, связанное с временем жизни параметра HttpRequest?

Могу ли я что-то сделать, чтобы исправить это без изменения определения AsyncCResponse?

1 Ответ

0 голосов
/ 12 июля 2019

Простого решения не существует.

...