Skip to content

How to specify static service methods? #2668

@ghost

Description

I added lifetime to custom service to trait to indicate static lifetime but still fails. Why?
I know I call self.kool() before the async but can we not call it inside async with explicit static lifetime.

use std::env::var;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::Future;
use hyper::service::Service;
use hyper::{Body, Request, Response, StatusCode};
use mongodb::options::ClientOptions;

pub struct MakeSvc<'a> {
    pub(crate) _lifetime: PhantomData<&'a ()>
}

#[derive(Clone)]
pub struct Svc<'a> {
    pub m: mongodb::Client,
    pub(crate) _lifetime: PhantomData<&'a ()>
}

impl <'a> Svc<'a> {
    pub async fn kool(&'a self)->i32{
        99
    }
}

impl<'a,T> Service<T> for MakeSvc<'a>{
    type Response = Svc<'a>;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
    fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
    fn call(&mut self, _: T) -> Self::Future {
        let fut = async move {
            let mongo_url = var("MONGO").unwrap_or("mongodb://localhost:27017".to_string());
            let client_options = ClientOptions::parse(mongo_url).await.unwrap();
            let m = mongodb::Client::with_options(client_options).unwrap();
            Ok(Svc { m,  _lifetime: Default::default() })
        };
        Box::pin(fut)
    }
}

impl<'a> Service<Request<Body>> for Svc<'a> {
    type Response = Response<Body>;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>  +'a + Send>>;
    fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let res = async move {
            match (req.method(), req.uri().path()) {
                _ => {
                    self.kool();
                    Ok(Response::builder()
                        .status(StatusCode::NOT_FOUND)
                        .body("sorry".into())
                        .unwrap())
                }
            }
        };
        Box::pin(res)
    }
}
[dependencies]
tokio = { version = "1.8.0", features = ["full"] }
hyper = {version="0.14.13",features=["full"]}
tower = {version="0.4.8", features=["full"]}
mongodb = {version="2.0.1"}
futures = "0.3.15"

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions