grpc / grpc/grpc-rust

How does tonic library dynamically set up custom middleware

Open
#1,800 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
12.5k
Forks
1.3k
Avg merge
4d 7h
Merged PRs (30d)
24

Description

```
pub struct GrpcStruct
where
F: tonic::service::interceptor::Interceptor + Clone + Send + Sync + 'static,
{
middleware: Vec,
}

Setting the layer manually is fine

let ss = self.middleware[0].clone();
let ss1 = self.middleware[1].clone();
let ss2 = self.middleware[2].clone();

tonic::transport::Server::builder()
.layer(interceptor(ss))
.layer(interceptor(ss1))
.layer(interceptor(ss2))
.add_service(srv)
.serve(address)
.await
.unwrap();

// But change to dynamic add, will report an error, the error at the bottom

let mut app = tonic::transport::Server::builder();
for mid in self.middleware.iter() {
app = app.layer(interceptor(mid.clone()));
}
app.add_service(srv).serve(address).await.unwrap();

```

Report an error:
![image](https://github.com/user-attachments/assets/7ad905a9-97e8-439b-821c-d1928edab9ee)

Contributor guide

Open the contributing guide

Research direction

Reproduce the shown tonic::transport::Server builder example and inspect the compiler error for the looped .layer(interceptor(mid.clone())) calls. Compare it with the manually chained version and consult tonic's Server builder and layer type constraints; done means the middleware can be assembled dynamically without the reported error.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.