Struggle with async function lifetime issue

I am writing a toy program for learning networking and server, and in a simple struct I have lifetimes issues. The error "self has an anonymous lifetime '_ but it needs to satisfy a 'static lifetime requirement" popped when trying to compile. While I understand that I need to add 'static to self I don't understand why. I isolated the problem it's from the lock() call on the mutex. Do I need the Pin ?

pub type PtrMtx<T> = Arc<Mutex<T>>;
pub struct Server {
    sessions: PtrMtx<Vec<Session>>, 
    connected: PtrMtx<HashMap<Uuid, Option<SessionId>>>,
}

impl Server {
    pub fn new() -> Self {
        Server {
            sessions: ptr_mtx(vec![]),
            connected: ptr_mtx(HashMap::new()),
        }
    }

    pub async fn handle(&self, mut stream: TcpStream) -> Result<(), BoxError> {
        let length_delimited =
            FramedRead::new(stream, LengthDelimitedCodec::new());
        let mut deserialized =
            tokio_serde::SymmetricallyFramed::new(length_delimited, SymmetricalBincode::<Message>::default());

        if let Some(message) = deserialized.try_next().await? {
            // first message from a client
            match message.action {
                Input::CreateSession(password) => {
                    let id = Uuid::new_v4();
                    self.sessions.lock()?.push( // if commented it compiles
                        Session::new(id, format!("Session of {}", id), password)
                    )
                }
                _ => {}
            }
        }
        Ok(())
    }
}

And the error :

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
   --> src/server/mod.rs:99:25
    |
99  |       pub async fn handle(&self, mut stream: TcpStream) -> Result<(), BoxError> {
    |  _________________________^^^^^_________________________________________________-
    | |                         |
    | |                         this data with an anonymous lifetime `'_`...
    | |                         ...is captured here...
100 | |         let length_delimited =
101 | |             FramedRead::new(stream, LengthDelimitedCodec::new());
102 | |         let mut deserialized =
...   |
118 | |         Ok(())
119 | |     }
    | |_____- ...and is required to live as long as `'static` here

Since you haven't posted the full error, I don't know in detail what is going on, but the following two articles are relevant to your question:

Sorry, I added the error information !

Oh, damn, that's tricky. It is because the error returned by Mutex::lock is a PoisonGuard, and it contains the locked guard, so when you return the error with ? it is turned into a BoxError, and the boxed error requires the error to be 'static, but the error contains a reference to self.

Typically you unwrap poison errors, which avoids this issue. They can only happen if your program panicks while it holds the lock and then tries to lock it again.

2 Likes

Thanks a lot! Glad I asked because I couldn't have resolved it myself..

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.