hyperium/hyper

remove static lifetimes

Closed this issue · 6 comments

I'm trying to use hyper, but it seems to require I put config data into 'static objects.
Is this a hard requirement?

Example:

  1. read config data
  2. do some init work
  3. call start_http2(&config)
  4. Server::http(handler) == FAIL?

The root cause seems to be this:
impl<'a, H: Handler + 'static> Server<'a, H, HttpListener>

Doesn't that force the handler to have a 'static lifetime?

pub fn start_http2(config: &BTreeMap<String, String>) {

let handler = move |req: Request, res: Response| {
    proxy2(&req, &res, &config);
};
let server = Server::http(handler);
let _guard = server.listen("127.0.0.1:1337").unwrap();

}

src/main.rs:261:19: 263:6 error: cannot infer an appropriate lifetime for capture of config by closure due to conflicting requirements
src/main.rs:261 let handler = |req: Request, res: Response| {
src/main.rs:262 proxy2(&req, &res, &config);
src/main.rs:263 };
src/main.rs:265:18: 265:24 note: first, the lifetime cannot outlive the expression at 265:17...
src/main.rs:265 let _guard = server.listen("127.0.0.1:1337").unwrap();
^~~~~~
src/main.rs:265:18: 265:24 note: ...so that captured variable config does not outlive the enclosing closure
src/main.rs:265 let _guard = server.listen("127.0.0.1:1337").unwrap();
^~~~~~
src/main.rs:265:18: 265:49 note: but, the lifetime must be valid for the method call at 265:17...
src/main.rs:265 let _guard = server.listen("127.0.0.1:1337").unwrap();
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/main.rs:265:18: 265:49 note: ...so that captured variable config does not outlive the enclosing closure
src/main.rs:265 let _guard = server.listen("127.0.0.1:1337").unwrap();

Well, the Handler needs to be Send and Sync. That includes any references it has. This is because the Handler is shared among multiple threads. Perhaps with the recent-ish Send changes, it doesn't have to be 'static, but it may need to be.

@reem you tend to know more about these kinds of things

reem commented

When a new version of thread::scoped lands, we will be able to remove the 'static bound, but for now we need 'static to be able to use Handler within hyper's internal thread pool.

By the looks of the Leak/thread::scoped discussion and the time to 1.0, it seems unlikely that the new API will look like the old one, so we will also have to provide a different Server API for non-'static handlers.

This seems like it could be solved with the crossbeam crate.

Though, as reem said, it'll still likely need a new server API.

Handler on master does not require 'static.