Tower Service Implementation Referencing Self

⚓ rust    📅 2025-05-18    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

I'm writing a tower::Service implementation for a Rust Lambda function utilizing the lambda_runtime crate and I'm having difficulty with the Future type on the service.

To make things much easier to reason about and work with, I have a struct which contains config data that I've defined a function on:

use lambda_runtime::LambdaEvent;

pub struct LambdaService {
    config: LambdaServiceConfig,
}

pub struct LambdaServiceConfig;

#[derive(Debug, Serialize, Deserialize)]
pub struct LambdaResponse;

impl LambdaService {
    pub async fn on_event(&self, event: LambdaEvent<serde_json::Value>) -> anyhow::Result<Option<LambdaResponse>> {
        Ok(None)
    }
}

I now need to implement tower::Service for it:

impl Service<LambdaEvent<serde_json::Value>> for LambdaService {
    type Response = Option<LambdaResponse>;
    type Error = anyhow::Error;
    type Future = Pin<Box<dyn Future<Output=Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: LambdaEvent<serde_json::Value>) -> Self::Future {
        Box::pin(self.on_event(req))
    }
}

This yields a compiler error:

error: lifetime may not live long enough
  --> crates/api-lambda/src/lib.rs:20:9
   |
19 |     fn call(&mut self, req: LambdaEvent<serde_json::Value>) -> Self::Future {
   |             - let's call the lifetime of this reference `'1`
20 |         Box::pin(self.on_event(req))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`

I think I understand why the issue is manifesting, self needs to be 'static? Obviously I don't see any way of making self 'static, so what are my options to work around this?

2 posts - 2 participants

Read full topic

🏷️ rust_feed