Skip to content

Add services dynamically with tonic #886

@Miaxos

Description

@Miaxos

Feature Request

Hello 👋!

Thread from discord which motivated this issue creation: https://discord.com/channels/500028886025895936/628706823104626710/930507181516795944

Motivation

I want to dynamically add services where those services would be initialized later.

For instance, let's suppose we want a Builder pattern to create GRPC services based on a Shared Context where you could register your Service creation function.

struct GRPCDriver<C, Se>
where
    C: BusinessContext + Send + Sync + 'static,
    Se: Service<hyper::Request<Body>, Response = Response<BoxBody>>
        + NamedService
        + Clone
        + Send
        + 'static,
    Se::Future: Send + 'static,
    Se::Error: Into<TonicError> + Send,
{
    // Here we have our "service factory" which create services based on a Shared Context
    grpc_services: Vec<Box<dyn Fn(Arc<C>) -> Se + Send>>,
    ..
}

impl<C, Se> GRPCDriver<C, Se>
where
    C: BusinessContext + Send + Sync + 'static,
    Se: Service<Request<Body>, Response = Response<BoxBody>>
        + NamedService
        + Clone
        + Send
        + 'static,
    Se::Future: Send + 'static,
    Se::Error: Into<TonicError> + Send,
{

   // Here the function which will run the server and services initialization.
  async fn run_driver_without_context(self, context: Arc<C>) -> anyhow::Result<()> {

    let grpc_services: Vec<Box<dyn Fn(Arc<C>) -> Se + Send>> = self.grpc_services;
    let mut server = TonicServer::builder();

    for service in grpc_services {
        server = server.add_service(service(Arc::clone(&context)));
        // Here types are fucked up because the compiler can't infer the right type for server.
    }

    server.await

  }
}

It won't work due to the typing of the successive add_service call.

Proposal

Not really :(

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