grpc / grpc/grpc-rust

Adding an IntoResponse trait

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

Description

## Feature Request

### Crates

tonic-build

### Motivation

When using a generated client, you can pass either a `Message` or a `Request`, as the client accepts `impl IntoRequest`. This makes things more ergonomic when you don't have any headers/options to attach.

The generated server code lacks a similar IntoResponse and IntoStreamingResponse trait, so all responses need to be wrapped in Response::new(). This makes things a bit more cumbersome, and inconsistent with the client side of things (I remember being a bit confused by this when I started using Tonic).

Are there any technical limitations or other reasons that would prevent adding such functionality in the next breaking update?

(Apologies if this has been discussed before. I found a brief mention on https://github.com/hyperium/tonic/pull/66#issuecomment-545213939 but couldn't see an issue for this specifically)

### Proposal

Adding a similar trait:

```rust
pub trait IntoResponse {
fn into_response(self) -> Response;
}

impl IntoResponse for T {
fn into_response(self) -> Response {
Response::new(self)
}
}

impl IntoResponse for Response {
fn into_response(self) -> Response {
self
}
}

async fn some_method(...) -> Result, tonic::Status> {
Ok(Response::new(SomeMessage {}))
}

async fn some_method(...) -> Result, tonic::Status> {
Ok(SomeMessage {})
}
```

prost-build would presumably need to be updated to change the signature of the generated methods, and call .into_response() inside call().

One potential downside is increased compile time due to the extra type inferences, but such a cost is already paid when compiling the client.

If this is something you'd be amenable to, I can look into it further.

### Alternatives

https://github.com/hyperium/tonic/pull/1064 would continue to require manual wrapping, but would reduce the keystrokes required to do so.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.