hyperium / tonic

A native gRPC client & server implementation with async/await support.
https://docs.rs/tonic
MIT License
9.76k stars 997 forks source link

What's the idiomatic way of passing data from a layer to the actual service implementation? #839

Open sonthonaxrk opened 2 years ago

sonthonaxrk commented 2 years ago

I'm looking at this example where you use a tower layer to do some async processing before a request (in my case I want to check if a use is authenticated).

However, one problem I'm facing with the tower layer is that _I don't know how to pass the result to the Service. In the example below, you can do some 'extra work', but you just pass the request further up the stack of layers. For instance, I want to be able to pass a user ID up the stack.

https://github.com/hyperium/tonic/blob/master/examples/src/tower/server.rs#L105

In the above example, you pass a hyper::Request, which doesn't really have anyway of attaching metadata (beyond something silly like adding it to the headers).

LucioFranco commented 2 years ago

It should be possible to write an example for this I think

davidpdrsn commented 2 years ago

You can set your data in a http::Request extension and then extract it in your RPC via tonic::Request::extension.

Tonic automatically copies http extensions into grpc extensions.