4

I'm trying to learn Rust, and trying to write some extremely simple web server code to do so.

I thought I had a good idea of the basics of lifetimes & borrowing in simple code, but I'm finding that either I'm missing a basic technique somewhere, or what I thought was a simple case is actually much more complicated for some reason.

What I'm essentially trying to do is this:

use std::env;
use std::convert::Infallible;
use std::net::SocketAddr;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};

// A demo web server: takes a message on the command-line, then
// serves it back to incoming requests.

#[tokio::main]
pub async fn main() {
    let args: Vec<String> = env::args().collect();
    let message = format!("Arguments were: {:?}", &args[1..]);
    serve_message(message).await;
}

pub async fn serve_message(message: String) {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    let make_svc = make_service_fn(|_conn| {
        async move {
            Ok::<_, Infallible>(service_fn(move |_: Request<Body>| async move {
                Ok::<_, Infallible>(
                    Response::new(Body::from(message))
                )
            }))
        }
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}

This fails to compile with:

error[E0507]: cannot move out of `message`, a captured variable in an `FnMut` closure
  --> src/main.rs:22:68
   |
17 |   pub async fn serve_message(message: String) {
   |                              ------- captured outer variable
...
22 |               Ok::<_, Infallible>(service_fn(move |_: Request<Body>| async move {
   |  ____________________________________________-----------------------_^
   | |                                            |
   | |                                            captured by this `FnMut` closure
23 | |                 Ok::<_, Infallible>(
24 | |                     Response::new(Body::from(message))
   | |                                              -------
   | |                                              |
   | |                                              variable moved due to use in generator
   | |                                              move occurs because `message` has type `String`, which does not implement the `Copy` trait
25 | |                 )
26 | |             }))
   | |_____________^ move out of `message` occurs here

error[E0507]: cannot move out of `message`, a captured variable in an `FnMut` closure
  --> src/main.rs:21:9
   |
17 |   pub async fn serve_message(message: String) {
   |                              ------- captured outer variable
...
20 |       let make_svc = make_service_fn(|_conn| {
   |                                      ------- captured by this `FnMut` closure
21 | /         async move {
22 | |             Ok::<_, Infallible>(service_fn(move |_: Request<Body>| async move {
23 | |                 Ok::<_, Infallible>(
24 | |                     Response::new(Body::from(message))
   | |                                              -------
   | |                                              |
   | |                                              variable moved due to use in generator
   | |                                              move occurs because `message` has type `String`, which does not implement the `Copy` trait
25 | |                 )
26 | |             }))
27 | |         }
   | |_________^ move out of `message` occurs here

I've tried a wide variety of more complex modifications of this, with cloning, ARCs, state into a struct with a handle impl, and lots of other approaches, but I'm struggling and each of them seems to bring me back to the same fundamental problem above. I'm clearly missing something essential about how async, closures & ownership interact, and the tools to manage that. I have seen How to re-use a value from the outer scope inside a closure in Rust? which is similar, but the only answer's example is a simpler demo that doesn't clearly translate to the larger problem - just adding .clone() as suggested everywhere doesn't seem sufficient for this case.

The part I find most confusing is that this is extremely similar to one of Hyper's own examples: https://docs.rs/hyper/latest/hyper/service/fn.make_service_fn.html#example. But that example doesn't seem to hit any issues, while this does.

What's the correct & idiomatic way to do this, why does it work, and what's the difference between this and that Hyper example case? Beginner-level explanations much appreciated.

3
  • Cloning/Arc should work. How did you try it? May 20 at 19:40
  • @ChayimFriedman, ok that's a useful clue! I've tried 10s of different ways though, I'm just very much out of my depth and not sure how they're meant to be used. All examples I can find are trivial and don't obviously map to slightly trickier cases like this for me. Can you share an example of how you'd use them in this scenario, and explain why?
    – Tim Perry
    May 21 at 16:39
  • I prefer that you will share your attempts and then I will explain what went wrong. May 21 at 16:47

1 Answer 1

1
+100

The reason that you are getting this error is that the message string is being moved into the closure that you pass to service_fn. In Rust, each value has a unique owner, and moving a value transfers its ownership. Once a value has been moved, it can no longer be used from the original location. See "Ownership and moves"

However, in your case, you want to use the message string in multiple responses, which means you need to share it between multiple closures. This is where Arc (Atomic Reference Counting) comes in handy.
An Arc<T> is a thread-safe reference-counted pointer that allows shared read access to a value of type T. It can be cloned to create a new pointer to the same value, increasing the reference count.

You can update your serve_message function to wrap the message in an Arc and then clone it for each request like this (playground):

use bytes::Bytes;
use hyper::{
    service::{make_service_fn, service_fn},
    Body, Error as HyperError, Request, Response, Server,
};
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;

pub async fn serve_message(message: String) {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    let message = Arc::new(Bytes::from(message));

    let make_svc = make_service_fn(move |_conn| {
        let message = Arc::clone(&message);
        async {
            Ok::<_, Infallible>(service_fn(move |_: Request<Body>| {
                let message = Bytes::copy_from_slice(&*Arc::clone(&message));
                async move { Ok::<_, HyperError>(Response::new(Body::from(message))) }
            }))
        }
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}

The way it works is:

  • Arc::new(message) creates a new Arc that owns the message. This is the only Arc that directly owns the message.
  • Each time make_service_fn is called, it clones the Arc (not the message itself), which increases the reference count but does not move the message.
  • Inside service_fn, we again clone the Arc for each request. This allows each request to have a reference to the message without taking ownership.
  • Finally, Response::new(Body::from((*Arc::clone(&message)).clone())) clones the Arc one more time to use the message in the response. This does not move the message and allows it to be used in subsequent responses.

Regarding the last point:

The code Response::new(Body::from(Arc::clone(&message).to_string())) would work as well, but there is a key difference to keep in mind.

When you use Arc::clone(&message).to_string(), you are creating a new String for every request. This can be inefficient if the message is large or if there are a lot of requests, because it involves allocating memory for a new String each time.

Instead, let message = Bytes::copy_from_slice(&*Arc::clone(&message)) is of type Bytes.

In this code, we're using Bytes::copy_from_slice(&*Arc::clone(&message)) to create a new Bytes instance from the shared Bytes for each request.
This is less efficient than sharing the Bytes directly (as we would ideally like to do), but it avoids the borrowing errors you were encountering earlier.

The breakdown is:

  • Arc::clone(&message) creates a new Arc that points to the same Bytes value that message points to. The type of Arc::clone(&message) is Arc<Bytes>.
  • &*Arc::clone(&message) dereferences the Arc<Bytes> to get a reference to the Bytes value it points to. The type of &*Arc::clone(&message) is &Bytes.
  • Bytes::copy_from_slice(&*Arc::clone(&message)) creates a new Bytes value that contains the same byte sequence as the Bytes value message points to. The type of Bytes::copy_from_slice(&*Arc::clone(&message)) is Bytes.

The Bytes::copy_from_slice function expects a reference to a byte slice (&[u8]), and &Bytes can be used as &[u8] because Bytes implements Deref<Target=[u8]>.

So the overall effect of Bytes::copy_from_slice(&*Arc::clone(&message)) is to create a new Bytes value that contains a copy of the bytes from the original Bytes value, allowing it to be used independently in the response body.


Dereferencing Arc<Bytes> to get a Bytes reference (&Bytes) doesn't work is because Body::from doesn't accept a &Bytes reference as a parameter.
While Rust's From trait often does work with references, in this case, the From trait is only implemented for the owned Bytes type and not for a reference to Bytes.

  • Body::from consumes its argument. It takes ownership of the provided value.
  • When you dereference Arc<Bytes>, you get a &Bytes (a reference to Bytes), not an owned Bytes.
  • A &Bytes is not the same thing as Bytes. They are different types. The former is a reference to a Bytes value, the latter is an owned Bytes value.
  • Because Body::from is not implemented for &Bytes, you can't pass a &Bytes to Body::from.

The Hyper example you linked creates an HTTP response with a body of type hyper::Body::empty(), which does not involve any borrowing from the outer scope.

In your code, you are trying to use a String (message) from the outer scope inside your service function, which leads to the borrowing issues you are encountering.

Your use case is different from the Hyper example because you want to share an owned String between multiple closures, which requires the use of Arc as explained above. The Arc allows multiple closures to have a read-only reference to the same String without taking ownership of it.

6
  • Phew, thank you, that's extremely helpful! There was still one tiny bug here, as the inner-most Arc::clone(&message) needs a .to_string(), but otherwise that all makes sense and it finally works now 👍.
    – Tim Perry
    May 22 at 17:27
  • @TimPerry But I thought the Body::from function in Hyper can accept anything that can be viewed as a byte slice (&[u8]), and Arc<String> satisfies that requirement because String itself implements AsRef<[u8]>. So when you do Body::from(Arc::clone(&message)), it should work because it can view the Arc<String> as a byte slice.
    – VonC
    May 22 at 18:03
  • No idea I'm afraid! In my case I get the trait From<Arc<String>> is not implemented for Body unless I use Arc::clone(&message).to_string() in there. Using the latest Hyper release - 0.14.26.
    – Tim Perry
    May 22 at 18:41
  • 1
    @TimPerry OK, I have updated the code, but using Byte instead of to_string(), to avoid creating a new String for every request.
    – VonC
    May 22 at 18:53
  • That change all sounds sensible, but the code still has the same issue: the trait From<Arc<bytes::Bytes>> is not implemented for Body. For Bytes 1 + Hyper 0.14.26.
    – Tim Perry
    May 23 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.