This repository was archived by the owner on Mar 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
201 lines (184 loc) · 7.22 KB
/
Copy pathclient.rs
File metadata and controls
201 lines (184 loc) · 7.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! # Generic gRPC Client
//!
//! This module wraps a standard `tonic` client to provide a generic interface for
//! gRPC communication. It is agnostic to the specific Protobuf messages being exchanged.
//!
//! ## How it works
//!
//! The [`GrpcClient`] utilizes the [`super::codec::JsonCodec`] to handle serialization.
//! It does not need to know the structure of the data it is sending; it simply ensures
//! the connection is established and passes the `serde_json::Value` and `MethodDescriptor`
//! to the codec.
//!
//! ## Features
//!
//! * **Dynamic Pathing**: Constructs the HTTP/2 path (e.g., `/package.Service/Method`) at runtime.
//! * **Metadata Handling**: Converts standard Rust string tuples into Tonic's `MetadataMap` for headers.
//! * **Access Patterns**: Provides specific methods for Unary, Server Streaming, Client Streaming,
//! and Bidirectional Streaming calls.
use super::codec::JsonCodec;
use crate::BoxError;
use futures_util::Stream;
use http_body::Body as HttpBody;
use prost_reflect::MethodDescriptor;
use std::str::FromStr;
use tonic::{
client::GrpcService,
metadata::{
MetadataKey, MetadataValue,
errors::{InvalidMetadataKey, InvalidMetadataValue},
},
transport::Channel,
};
#[derive(thiserror::Error, Debug)]
pub enum GrpcRequestError {
#[error("Internal error, the client was not ready: '{0}'")]
ClientNotReady(#[source] BoxError),
#[error("Invalid metadata (header) key '{key}': '{source}'")]
InvalidMetadataKey {
key: String,
source: InvalidMetadataKey,
},
#[error("Invalid metadata (header) value for key '{key}': '{source}'")]
InvalidMetadataValue {
key: String,
source: InvalidMetadataValue,
},
}
/// A generic client for the gRPC Server Reflection Protocol.
#[derive(Debug, Clone)]
pub struct GrpcClient<S = Channel> {
client: tonic::client::Grpc<S>,
}
impl<S> GrpcClient<S>
where
S: GrpcService<tonic::body::Body>,
S::Error: Into<BoxError>,
S::ResponseBody: HttpBody<Data = tonic::codegen::Bytes> + Send + 'static,
<S::ResponseBody as HttpBody>::Error: Into<BoxError> + Send,
{
pub fn new(service: S) -> Self {
let client = tonic::client::Grpc::new(service);
Self { client }
}
/// Performs a Unary gRPC call (Single Request -> Single Response).
///
/// # Returns
/// * `Ok(Ok(Value))` - Successful RPC execution.
/// * `Ok(Err(Status))` - RPC executed, but server returned an error.
/// * `Err(ClientError)` - Failed to send request or connect.
pub async fn unary(
&mut self,
method: MethodDescriptor,
payload: serde_json::Value,
headers: Vec<(String, String)>,
) -> Result<Result<serde_json::Value, tonic::Status>, GrpcRequestError> {
self.client
.ready()
.await
.map_err(|e| GrpcRequestError::ClientNotReady(e.into()))?;
let codec = JsonCodec::new(method.input(), method.output());
let path = http_path(&method);
let request = build_request(payload, headers)?;
match self.client.unary(request, path, codec).await {
Ok(response) => Ok(Ok(response.into_inner())),
Err(status) => Ok(Err(status)),
}
}
/// Performs a Server Streaming gRPC call (Single Request -> Stream of Responses).
///
/// # Returns
///
/// * `Ok(Ok(Stream))` - Successful RPC execution.
/// * `Ok(Err(Status))` - RPC executed, but server returned an error.
/// * `Err(ClientError)` - Failed to send request or connect.
pub async fn server_streaming(
&mut self,
method: MethodDescriptor,
payload: serde_json::Value,
headers: Vec<(String, String)>,
) -> Result<Result<tonic::Streaming<serde_json::Value>, tonic::Status>, GrpcRequestError> {
self.client
.ready()
.await
.map_err(|e| GrpcRequestError::ClientNotReady(e.into()))?;
let codec = JsonCodec::new(method.input(), method.output());
let path = http_path(&method);
let request = build_request(payload, headers)?;
match self.client.server_streaming(request, path, codec).await {
Ok(response) => Ok(Ok(response.into_inner())),
Err(status) => Ok(Err(status)),
}
}
/// Performs a Client Streaming gRPC call (Stream of Requests -> Single Response).
///
/// # Returns
///
/// * `Ok(Ok(Value))` - Successful RPC execution.
/// * `Ok(Err(Status))` - RPC executed, but server returned an error.
/// * `Err(ClientError)` - Failed to send request or connect.
pub async fn client_streaming(
&mut self,
method: MethodDescriptor,
payload_stream: impl Stream<Item = serde_json::Value> + Send + 'static,
headers: Vec<(String, String)>,
) -> Result<Result<serde_json::Value, tonic::Status>, GrpcRequestError> {
self.client
.ready()
.await
.map_err(|e| GrpcRequestError::ClientNotReady(e.into()))?;
let codec = JsonCodec::new(method.input(), method.output());
let path = http_path(&method);
let request = build_request(payload_stream, headers)?;
match self.client.client_streaming(request, path, codec).await {
Ok(response) => Ok(Ok(response.into_inner())),
Err(status) => Ok(Err(status)),
}
}
/// Performs a Bidirectional Streaming gRPC call (Stream of Requests -> Stream of Responses).
///
/// # Returns
///
/// * `Ok(Ok(Stream))` - Successful RPC execution.
/// * `Ok(Err(Status))` - RPC executed, but server returned an error.
/// * `Err(ClientError)` - Failed to send request or connect.
pub async fn bidirectional_streaming(
&mut self,
method: MethodDescriptor,
payload_stream: impl Stream<Item = serde_json::Value> + Send + 'static,
headers: Vec<(String, String)>,
) -> Result<Result<tonic::Streaming<serde_json::Value>, tonic::Status>, GrpcRequestError> {
self.client
.ready()
.await
.map_err(|e| GrpcRequestError::ClientNotReady(e.into()))?;
let codec = JsonCodec::new(method.input(), method.output());
let path = http_path(&method);
let request = build_request(payload_stream, headers)?;
match self.client.streaming(request, path, codec).await {
Ok(response) => Ok(Ok(response.into_inner())),
Err(status) => Ok(Err(status)),
}
}
}
fn http_path(method: &MethodDescriptor) -> http::uri::PathAndQuery {
let path = format!("/{}/{}", method.parent_service().full_name(), method.name());
http::uri::PathAndQuery::from_str(&path).expect("valid gRPC path")
}
fn build_request<T>(
payload: T,
headers: Vec<(String, String)>,
) -> Result<tonic::Request<T>, GrpcRequestError> {
let mut request = tonic::Request::new(payload);
for (k, v) in headers {
let key =
MetadataKey::from_str(&k).map_err(|source| GrpcRequestError::InvalidMetadataKey {
key: k.clone(),
source,
})?;
let val = MetadataValue::from_str(&v)
.map_err(|source| GrpcRequestError::InvalidMetadataValue { key: k, source })?;
request.metadata_mut().insert(key, val);
}
Ok(request)
}