use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use bytes::{Buf, BufMut, Bytes};
use folk_api::{InboundStream, StreamConn, StreamItem};
use http::uri::PathAndQuery;
use prost_reflect::{DescriptorPool, MessageDescriptor, MethodDescriptor};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::{OnceCell, mpsc};
use tokio_stream::StreamExt;
use tokio_stream::wrappers::ReceiverStream;
use tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
use tonic::metadata::{Ascii, MetadataKey, MetadataValue};
use tonic::transport::{
Certificate, Channel, ClientTlsConfig as TonicClientTls, Endpoint, Identity,
};
use tonic::{Code, Status, Streaming};
use tracing::{debug, warn};
use crate::config::{ClientConfig, ClientTlsConfig, RetryConfig};
use crate::service::{json_to_proto, proto_to_json};
#[derive(Default, Clone, Copy)]
pub struct BytesCodec;
impl Codec for BytesCodec {
type Encode = Bytes;
type Decode = Bytes;
type Encoder = BytesCodec;
type Decoder = BytesCodec;
fn encoder(&mut self) -> Self::Encoder {
BytesCodec
}
fn decoder(&mut self) -> Self::Decoder {
BytesCodec
}
}
impl Encoder for BytesCodec {
type Item = Bytes;
type Error = Status;
fn encode(&mut self, item: Bytes, dst: &mut EncodeBuf<'_>) -> Result<(), Status> {
dst.put(item);
Ok(())
}
}
impl Decoder for BytesCodec {
type Item = Bytes;
type Error = Status;
fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Bytes>, Status> {
let len = src.remaining();
Ok(Some(src.copy_to_bytes(len)))
}
}
pub async fn call_unary(
channel: Channel,
service: &str,
method: &str,
request: Bytes,
) -> Result<Bytes, Status> {
let mut grpc = tonic::client::Grpc::new(channel);
grpc.ready()
.await
.map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
let path = method_path(service, method)?;
let response = grpc
.unary(tonic::Request::new(request), path, BytesCodec)
.await?;
Ok(response.into_inner())
}
fn method_path(service: &str, method: &str) -> Result<PathAndQuery, Status> {
format!("/{service}/{method}")
.parse()
.map_err(|e| Status::internal(format!("invalid method path: {e}")))
}
pub async fn call_server_streaming(
channel: Channel,
service: &str,
method: &str,
request: Bytes,
metadata: &HashMap<String, Vec<String>>,
deadline: Option<Duration>,
) -> Result<Streaming<Bytes>, Status> {
let path = method_path(service, method)?;
let mut req = tonic::Request::new(request);
apply_metadata(req.metadata_mut(), metadata);
if let Some(d) = deadline {
if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
req.metadata_mut().insert("grpc-timeout", v);
}
}
let mut grpc = tonic::client::Grpc::new(channel);
grpc.ready()
.await
.map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
let resp = grpc.server_streaming(req, path, BytesCodec).await?;
Ok(resp.into_inner())
}
fn streaming_request<S>(
req_stream: S,
metadata: &HashMap<String, Vec<String>>,
deadline: Option<Duration>,
) -> tonic::Request<S> {
let mut request = tonic::Request::new(req_stream);
apply_metadata(request.metadata_mut(), metadata);
if let Some(d) = deadline {
if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
request.metadata_mut().insert("grpc-timeout", v);
}
}
request
}
pub async fn call_client_streaming<S>(
channel: Channel,
service: &str,
method: &str,
req_stream: S,
metadata: &HashMap<String, Vec<String>>,
deadline: Option<Duration>,
) -> Result<Bytes, Status>
where
S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
{
let path = method_path(service, method)?;
let mut grpc = tonic::client::Grpc::new(channel);
grpc.ready()
.await
.map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
let resp = grpc
.client_streaming(
streaming_request(req_stream, metadata, deadline),
path,
BytesCodec,
)
.await?;
Ok(resp.into_inner())
}
pub async fn call_bidi_streaming<S>(
channel: Channel,
service: &str,
method: &str,
req_stream: S,
metadata: &HashMap<String, Vec<String>>,
deadline: Option<Duration>,
) -> Result<Streaming<Bytes>, Status>
where
S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
{
let path = method_path(service, method)?;
let mut grpc = tonic::client::Grpc::new(channel);
grpc.ready()
.await
.map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
let resp = grpc
.streaming(
streaming_request(req_stream, metadata, deadline),
path,
BytesCodec,
)
.await?;
Ok(resp.into_inner())
}
#[derive(Debug, Deserialize)]
pub struct ClientCallEnvelope {
pub client: String,
#[serde(default)]
pub address: Option<String>,
pub service: String,
pub method: String,
pub message: Value,
#[serde(default)]
pub metadata: HashMap<String, Vec<String>>,
#[serde(default)]
pub deadline_seconds: Option<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StreamKind {
#[default]
ServerStreaming,
ClientStreaming,
Bidi,
}
#[derive(Debug, Deserialize)]
pub struct ClientStreamEnvelope {
pub client: String,
#[serde(default)]
pub address: Option<String>,
pub service: String,
pub method: String,
#[serde(default)]
pub kind: StreamKind,
#[serde(default)]
pub message: Value,
#[serde(default)]
pub metadata: HashMap<String, Vec<String>>,
#[serde(default)]
pub deadline_seconds: Option<f64>,
}
fn status_json(code: u32, message: impl Into<String>) -> Value {
json!({ "__grpc_status": code, "__grpc_message": message.into() })
}
pub struct ClientRegistry {
clients: HashMap<String, ResolvedClient>,
}
impl ClientRegistry {
pub fn build(configs: &HashMap<String, ClientConfig>) -> Self {
let mut clients = HashMap::new();
for (name, cfg) in configs {
match crate::plugin::build_descriptor_pool(&cfg.proto, cfg.descriptor_set.as_deref()) {
Ok(pool) => {
clients.insert(
name.clone(),
ResolvedClient::new(Arc::new(pool), cfg.clone()),
);
}
Err(e) => warn!(
client = %name,
error = %e,
"gRPC client: descriptor pool build failed; client unavailable"
),
}
}
Self { clients }
}
pub fn is_empty(&self) -> bool {
self.clients.is_empty()
}
pub fn len(&self) -> usize {
self.clients.len()
}
pub async fn call(&self, env: ClientCallEnvelope) -> Value {
let Some(client) = self.clients.get(&env.client) else {
return status_json(
Code::Unimplemented as i32 as u32,
format!("unknown gRPC client '{}'", env.client),
);
};
let Some(method_desc) = resolve_method(&client.pool, &env.service, &env.method) else {
return status_json(
Code::Unimplemented as i32 as u32,
format!(
"method {}/{} not in client '{}' descriptor pool",
env.service, env.method, env.client
),
);
};
let req_bytes = match json_to_proto(&method_desc.input(), &env.message) {
Ok(b) => Bytes::from(b),
Err(e) => {
return status_json(
Code::InvalidArgument as i32 as u32,
format!("encode request: {e}"),
);
}
};
let channel = match client.channel(env.address.as_deref()).await {
Ok(c) => c,
Err(e) => {
return status_json(Code::Unavailable as i32 as u32, format!("connect: {e}"));
}
};
let deadline = env
.deadline_seconds
.filter(|s| *s > 0.0)
.map(Duration::from_secs_f64)
.or(client.default_deadline);
match client
.invoke(
channel,
&env.service,
&env.method,
req_bytes,
&env.metadata,
deadline,
)
.await
{
Ok(resp_bytes) => match proto_to_json(&method_desc.output(), &resp_bytes) {
Ok(v) => json!({ "message": v }),
Err(e) => status_json(
Code::Internal as i32 as u32,
format!("decode response: {e}"),
),
},
Err(status) => status_json(status.code() as i32 as u32, status.message().to_string()),
}
}
pub async fn open_stream(&self, env: ClientStreamEnvelope) -> StreamConn {
match self.try_open_stream(&env).await {
Ok(conn) => conn,
Err(status) => single_status_conn(status),
}
}
async fn try_open_stream(&self, env: &ClientStreamEnvelope) -> Result<StreamConn, Value> {
let client = self.clients.get(&env.client).ok_or_else(|| {
status_json(
Code::Unimplemented as i32 as u32,
format!("unknown gRPC client '{}'", env.client),
)
})?;
let method_desc =
resolve_method(&client.pool, &env.service, &env.method).ok_or_else(|| {
status_json(
Code::Unimplemented as i32 as u32,
format!(
"method {}/{} not in client '{}' descriptor pool",
env.service, env.method, env.client
),
)
})?;
let channel = client
.channel(env.address.as_deref())
.await
.map_err(|e| status_json(Code::Unavailable as i32 as u32, format!("connect: {e}")))?;
let deadline = env
.deadline_seconds
.filter(|s| *s > 0.0)
.map(Duration::from_secs_f64)
.or(client.default_deadline);
let output = method_desc.output();
match env.kind {
StreamKind::ServerStreaming => {
let req_bytes = json_to_proto(&method_desc.input(), &env.message)
.map(Bytes::from)
.map_err(|e| {
status_json(
Code::InvalidArgument as i32 as u32,
format!("encode request: {e}"),
)
})?;
let streaming = call_server_streaming(
channel,
&env.service,
&env.method,
req_bytes,
&env.metadata,
deadline,
)
.await
.map_err(status_to_json)?;
Ok(StreamConn::server_streaming(with_stream_deadline(
transcode_inbound(streaming, output),
deadline,
)))
}
StreamKind::Bidi => {
let (tx, req_stream) = outbound_stream(method_desc.input());
let streaming = call_bidi_streaming(
channel,
&env.service,
&env.method,
req_stream,
&env.metadata,
deadline,
)
.await
.map_err(status_to_json)?;
Ok(StreamConn::duplex(
with_stream_deadline(transcode_inbound(streaming, output), deadline),
tx,
))
}
StreamKind::ClientStreaming => {
let (tx, req_stream) = outbound_stream(method_desc.input());
let (frame_tx, frame_rx) = mpsc::channel::<StreamItem>(1);
let service = env.service.clone();
let method = env.method.clone();
let metadata = env.metadata.clone();
tokio::spawn(async move {
let frame = match call_client_streaming(
channel, &service, &method, req_stream, &metadata, deadline,
)
.await
{
Ok(resp) => Ok(message_or_status_frame(&output, &resp)),
Err(status) => Ok(status_frame_bytes(&status)),
};
let _ = frame_tx.send(frame).await;
});
let inbound: InboundStream = Box::pin(ReceiverStream::new(frame_rx));
Ok(StreamConn::duplex(
with_stream_deadline(inbound, deadline),
tx,
))
}
}
}
}
fn with_stream_deadline(inbound: InboundStream, deadline: Option<Duration>) -> InboundStream {
let Some(d) = deadline else {
return inbound;
};
let deadline_at = tokio::time::Instant::now() + d;
let stream =
futures_util::stream::unfold((inbound, false), move |(mut inner, done)| async move {
if done {
return None;
}
tokio::select! {
biased;
item = inner.next() => item.map(|x| (x, (inner, false))),
() = tokio::time::sleep_until(deadline_at) => {
let frame = Bytes::from(
serde_json::to_vec(&status_json(
Code::DeadlineExceeded as i32 as u32,
"stream deadline exceeded",
))
.unwrap_or_default(),
);
Some((Ok(frame), (inner, true)))
}
}
});
Box::pin(stream)
}
fn status_to_json(s: Status) -> Value {
status_json(s.code() as i32 as u32, s.message().to_string())
}
fn message_or_status_frame(output: &MessageDescriptor, proto: &[u8]) -> Bytes {
let frame = match proto_to_json(output, proto) {
Ok(v) => json!({ "message": v }),
Err(e) => status_json(
Code::Internal as i32 as u32,
format!("decode stream message: {e}"),
),
};
Bytes::from(serde_json::to_vec(&frame).unwrap_or_default())
}
fn status_frame_bytes(status: &Status) -> Bytes {
Bytes::from(serde_json::to_vec(&status_to_json(status.clone())).unwrap_or_default())
}
fn transcode_inbound(streaming: Streaming<Bytes>, output: MessageDescriptor) -> InboundStream {
Box::pin(streaming.map(move |item| {
let frame = match item {
Ok(proto) => match proto_to_json(&output, &proto) {
Ok(v) => json!({ "message": v }),
Err(e) => status_json(
Code::Internal as i32 as u32,
format!("decode stream message: {e}"),
),
},
Err(status) => status_to_json(status),
};
Ok(Bytes::from(serde_json::to_vec(&frame).unwrap_or_default()))
}))
}
fn outbound_stream(
input: MessageDescriptor,
) -> (
tokio::sync::mpsc::Sender<Bytes>,
impl tokio_stream::Stream<Item = Bytes> + Send + 'static,
) {
let (tx, rx) = mpsc::channel::<Bytes>(16);
let stream = ReceiverStream::new(rx).filter_map(move |json_bytes: Bytes| {
let value: Value = match serde_json::from_slice(&json_bytes) {
Ok(v) => v,
Err(e) => {
warn!(error = %e, "gRPC client stream: dropping unparsable outbound message");
return None;
}
};
match json_to_proto(&input, &value) {
Ok(b) => Some(Bytes::from(b)),
Err(e) => {
warn!(error = %e, "gRPC client stream: dropping unencodable outbound message");
None
}
}
});
(tx, stream)
}
fn single_status_conn(status: Value) -> StreamConn {
let bytes = Bytes::from(serde_json::to_vec(&status).unwrap_or_default());
let inbound: InboundStream = Box::pin(tokio_stream::once(Ok(bytes)));
StreamConn::server_streaming(inbound)
}
fn resolve_method(pool: &DescriptorPool, service: &str, method: &str) -> Option<MethodDescriptor> {
pool.get_service_by_name(service)?
.methods()
.find(|m| m.name() == method)
}
struct ResolvedClient {
pool: Arc<DescriptorPool>,
addresses: Vec<String>,
tls: Option<ClientTlsConfig>,
default_deadline: Option<Duration>,
retries: Option<RetryConfig>,
channel: OnceCell<Channel>,
}
impl ResolvedClient {
fn new(pool: Arc<DescriptorPool>, cfg: ClientConfig) -> Self {
Self {
pool,
addresses: cfg.address,
tls: cfg.tls,
default_deadline: cfg.deadline,
retries: cfg.retries,
channel: OnceCell::new(),
}
}
fn endpoint(&self, address: &str) -> Result<Endpoint, Status> {
let scheme = if self.tls.is_some() { "https" } else { "http" };
let uri = format!("{scheme}://{address}");
let mut ep = Channel::from_shared(uri)
.map_err(|e| Status::internal(format!("invalid upstream address '{address}': {e}")))?
.keep_alive_while_idle(true);
if let Some(tls) = &self.tls {
ep = ep
.tls_config(build_tls(tls)?)
.map_err(|e| Status::internal(format!("upstream TLS config: {e}")))?;
}
Ok(ep)
}
async fn channel(&self, override_addr: Option<&str>) -> Result<Channel, Status> {
if let Some(addr) = override_addr {
return Ok(self.endpoint(addr)?.connect_lazy());
}
self.channel
.get_or_try_init(|| async { self.build_default_channel() })
.await
.cloned()
}
fn build_default_channel(&self) -> Result<Channel, Status> {
if self.addresses.is_empty() {
return Err(Status::internal("gRPC client has no configured address"));
}
if self.addresses.len() == 1 {
return Ok(self.endpoint(&self.addresses[0])?.connect_lazy());
}
let mut endpoints = Vec::with_capacity(self.addresses.len());
for addr in &self.addresses {
endpoints.push(self.endpoint(addr)?);
}
Ok(Channel::balance_list(endpoints.into_iter()))
}
async fn invoke(
&self,
channel: Channel,
service: &str,
method: &str,
req_bytes: Bytes,
metadata: &HashMap<String, Vec<String>>,
deadline: Option<Duration>,
) -> Result<Bytes, Status> {
let max_attempts = self.retries.as_ref().map_or(1, |r| r.max_attempts.max(1));
let base_backoff = self.retries.as_ref().map_or(Duration::ZERO, |r| r.backoff);
let path = method_path(service, method)?;
let mut attempt = 0;
loop {
attempt += 1;
let mut request = tonic::Request::new(req_bytes.clone());
apply_metadata(request.metadata_mut(), metadata);
if let Some(d) = deadline {
if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
request.metadata_mut().insert("grpc-timeout", v);
}
}
let channel = channel.clone();
let path = path.clone();
let fut = async move {
let mut grpc = tonic::client::Grpc::new(channel);
grpc.ready()
.await
.map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
grpc.unary(request, path, BytesCodec).await
};
let result = match deadline {
Some(d) => {
let backstop = d + Duration::from_millis(250);
match tokio::time::timeout(backstop, fut).await {
Ok(Ok(resp)) => Ok(resp),
Ok(Err(status)) if status.code() == Code::Cancelled => {
Err(Status::deadline_exceeded("client deadline exceeded"))
}
Ok(Err(status)) => Err(status),
Err(_) => Err(Status::deadline_exceeded("client deadline exceeded")),
}
}
None => fut.await,
};
match result {
Ok(resp) => return Ok(resp.into_inner()),
Err(status) => {
let transient = status.code() == Code::Unavailable;
if transient && attempt < max_attempts {
let factor = 2u32.pow((attempt - 1).min(10));
let backoff = base_backoff * factor;
debug!(
attempt,
max_attempts,
?backoff,
"gRPC client: retrying transient failure"
);
if !backoff.is_zero() {
tokio::time::sleep(backoff).await;
}
continue;
}
return Err(status);
}
}
}
}
}
fn grpc_timeout_header(d: Duration) -> String {
let millis = d.as_millis();
if millis <= 99_999_999 {
format!("{millis}m")
} else {
format!("{}S", d.as_secs().min(99_999_999))
}
}
fn apply_metadata(map: &mut tonic::metadata::MetadataMap, metadata: &HashMap<String, Vec<String>>) {
for (key, values) in metadata {
if key.ends_with("-bin") {
debug!(key = %key, "gRPC client: skipping binary metadata (unsupported in v1)");
continue;
}
let Ok(mkey) = key.parse::<MetadataKey<Ascii>>() else {
debug!(key = %key, "gRPC client: skipping invalid metadata key");
continue;
};
for value in values {
match MetadataValue::try_from(value) {
Ok(mval) => {
map.append(mkey.clone(), mval);
}
Err(_) => debug!(key = %key, "gRPC client: skipping invalid metadata value"),
}
}
}
}
fn build_tls(tls: &ClientTlsConfig) -> Result<TonicClientTls, Status> {
let mut cfg = TonicClientTls::new();
if let Some(ca) = &tls.ca {
let pem = std::fs::read(ca)
.map_err(|e| Status::internal(format!("read CA {}: {e}", ca.display())))?;
cfg = cfg.ca_certificate(Certificate::from_pem(pem));
}
if let (Some(cert), Some(key)) = (&tls.cert, &tls.key) {
let cert_pem = std::fs::read(cert)
.map_err(|e| Status::internal(format!("read client cert {}: {e}", cert.display())))?;
let key_pem = std::fs::read(key)
.map_err(|e| Status::internal(format!("read client key {}: {e}", key.display())))?;
cfg = cfg.identity(Identity::from_pem(cert_pem, key_pem));
}
if let Some(domain) = &tls.domain {
cfg = cfg.domain_name(domain);
}
Ok(cfg)
}