1use std::collections::HashMap;
23use std::sync::Arc;
24use std::time::Duration;
25
26use bytes::{Buf, BufMut, Bytes};
27use folk_api::{InboundStream, StreamConn, StreamItem};
28use http::uri::PathAndQuery;
29use prost_reflect::{DescriptorPool, MessageDescriptor, MethodDescriptor};
30use serde::Deserialize;
31use serde_json::{Value, json};
32use tokio::sync::{OnceCell, mpsc};
33use tokio_stream::StreamExt;
34use tokio_stream::wrappers::ReceiverStream;
35use tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
36use tonic::metadata::{Ascii, MetadataKey, MetadataValue};
37use tonic::transport::{
38 Certificate, Channel, ClientTlsConfig as TonicClientTls, Endpoint, Identity,
39};
40use tonic::{Code, Status, Streaming};
41use tracing::{debug, warn};
42
43use crate::config::{ClientConfig, ClientTlsConfig, RetryConfig};
44use crate::service::{json_to_proto, proto_to_json};
45
46#[derive(Default, Clone, Copy)]
56pub struct BytesCodec;
57
58impl Codec for BytesCodec {
59 type Encode = Bytes;
60 type Decode = Bytes;
61 type Encoder = BytesCodec;
62 type Decoder = BytesCodec;
63
64 fn encoder(&mut self) -> Self::Encoder {
65 BytesCodec
66 }
67
68 fn decoder(&mut self) -> Self::Decoder {
69 BytesCodec
70 }
71}
72
73impl Encoder for BytesCodec {
74 type Item = Bytes;
75 type Error = Status;
76
77 fn encode(&mut self, item: Bytes, dst: &mut EncodeBuf<'_>) -> Result<(), Status> {
78 dst.put(item);
79 Ok(())
80 }
81}
82
83impl Decoder for BytesCodec {
84 type Item = Bytes;
85 type Error = Status;
86
87 fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Bytes>, Status> {
88 let len = src.remaining();
92 Ok(Some(src.copy_to_bytes(len)))
93 }
94}
95
96pub async fn call_unary(
100 channel: Channel,
101 service: &str,
102 method: &str,
103 request: Bytes,
104) -> Result<Bytes, Status> {
105 let mut grpc = tonic::client::Grpc::new(channel);
106 grpc.ready()
107 .await
108 .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
109 let path = method_path(service, method)?;
110 let response = grpc
111 .unary(tonic::Request::new(request), path, BytesCodec)
112 .await?;
113 Ok(response.into_inner())
114}
115
116fn method_path(service: &str, method: &str) -> Result<PathAndQuery, Status> {
117 format!("/{service}/{method}")
118 .parse()
119 .map_err(|e| Status::internal(format!("invalid method path: {e}")))
120}
121
122pub async fn call_server_streaming(
132 channel: Channel,
133 service: &str,
134 method: &str,
135 request: Bytes,
136 metadata: &HashMap<String, Vec<String>>,
137 deadline: Option<Duration>,
138) -> Result<Streaming<Bytes>, Status> {
139 let path = method_path(service, method)?;
140 let mut req = tonic::Request::new(request);
141 apply_metadata(req.metadata_mut(), metadata);
142 if let Some(d) = deadline {
143 if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
144 req.metadata_mut().insert("grpc-timeout", v);
145 }
146 }
147
148 let mut grpc = tonic::client::Grpc::new(channel);
149 grpc.ready()
150 .await
151 .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
152 let resp = grpc.server_streaming(req, path, BytesCodec).await?;
153 Ok(resp.into_inner())
154}
155
156fn streaming_request<S>(
159 req_stream: S,
160 metadata: &HashMap<String, Vec<String>>,
161 deadline: Option<Duration>,
162) -> tonic::Request<S> {
163 let mut request = tonic::Request::new(req_stream);
164 apply_metadata(request.metadata_mut(), metadata);
165 if let Some(d) = deadline {
166 if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
167 request.metadata_mut().insert("grpc-timeout", v);
168 }
169 }
170 request
171}
172
173pub async fn call_client_streaming<S>(
176 channel: Channel,
177 service: &str,
178 method: &str,
179 req_stream: S,
180 metadata: &HashMap<String, Vec<String>>,
181 deadline: Option<Duration>,
182) -> Result<Bytes, Status>
183where
184 S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
185{
186 let path = method_path(service, method)?;
187 let mut grpc = tonic::client::Grpc::new(channel);
188 grpc.ready()
189 .await
190 .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
191 let resp = grpc
192 .client_streaming(
193 streaming_request(req_stream, metadata, deadline),
194 path,
195 BytesCodec,
196 )
197 .await?;
198 Ok(resp.into_inner())
199}
200
201pub async fn call_bidi_streaming<S>(
204 channel: Channel,
205 service: &str,
206 method: &str,
207 req_stream: S,
208 metadata: &HashMap<String, Vec<String>>,
209 deadline: Option<Duration>,
210) -> Result<Streaming<Bytes>, Status>
211where
212 S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
213{
214 let path = method_path(service, method)?;
215 let mut grpc = tonic::client::Grpc::new(channel);
216 grpc.ready()
217 .await
218 .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
219 let resp = grpc
220 .streaming(
221 streaming_request(req_stream, metadata, deadline),
222 path,
223 BytesCodec,
224 )
225 .await?;
226 Ok(resp.into_inner())
227}
228
229#[derive(Debug, Deserialize)]
238pub struct ClientCallEnvelope {
239 pub client: String,
240 #[serde(default)]
241 pub address: Option<String>,
242 pub service: String,
243 pub method: String,
244 pub message: Value,
245 #[serde(default)]
246 pub metadata: HashMap<String, Vec<String>>,
247 #[serde(default)]
248 pub deadline_seconds: Option<f64>,
249}
250
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
253#[serde(rename_all = "snake_case")]
254pub enum StreamKind {
255 #[default]
257 ServerStreaming,
258 ClientStreaming,
260 Bidi,
262}
263
264#[derive(Debug, Deserialize)]
269pub struct ClientStreamEnvelope {
270 pub client: String,
271 #[serde(default)]
272 pub address: Option<String>,
273 pub service: String,
274 pub method: String,
275 #[serde(default)]
276 pub kind: StreamKind,
277 #[serde(default)]
278 pub message: Value,
279 #[serde(default)]
280 pub metadata: HashMap<String, Vec<String>>,
281 #[serde(default)]
282 pub deadline_seconds: Option<f64>,
283}
284
285fn status_json(code: u32, message: impl Into<String>) -> Value {
287 json!({ "__grpc_status": code, "__grpc_message": message.into() })
288}
289
290pub struct ClientRegistry {
299 clients: HashMap<String, ResolvedClient>,
300}
301
302impl ClientRegistry {
303 pub fn build(configs: &HashMap<String, ClientConfig>) -> Self {
306 let mut clients = HashMap::new();
307 for (name, cfg) in configs {
308 match crate::plugin::build_descriptor_pool(&cfg.proto, cfg.descriptor_set.as_deref()) {
309 Ok(pool) => {
310 clients.insert(
311 name.clone(),
312 ResolvedClient::new(Arc::new(pool), cfg.clone()),
313 );
314 }
315 Err(e) => warn!(
316 client = %name,
317 error = %e,
318 "gRPC client: descriptor pool build failed; client unavailable"
319 ),
320 }
321 }
322 Self { clients }
323 }
324
325 pub fn is_empty(&self) -> bool {
326 self.clients.is_empty()
327 }
328
329 pub fn len(&self) -> usize {
330 self.clients.len()
331 }
332
333 pub async fn call(&self, env: ClientCallEnvelope) -> Value {
339 let Some(client) = self.clients.get(&env.client) else {
340 return status_json(
341 Code::Unimplemented as i32 as u32,
342 format!("unknown gRPC client '{}'", env.client),
343 );
344 };
345
346 let Some(method_desc) = resolve_method(&client.pool, &env.service, &env.method) else {
348 return status_json(
349 Code::Unimplemented as i32 as u32,
350 format!(
351 "method {}/{} not in client '{}' descriptor pool",
352 env.service, env.method, env.client
353 ),
354 );
355 };
356
357 let req_bytes = match json_to_proto(&method_desc.input(), &env.message) {
359 Ok(b) => Bytes::from(b),
360 Err(e) => {
361 return status_json(
362 Code::InvalidArgument as i32 as u32,
363 format!("encode request: {e}"),
364 );
365 }
366 };
367
368 let channel = match client.channel(env.address.as_deref()).await {
370 Ok(c) => c,
371 Err(e) => {
372 return status_json(Code::Unavailable as i32 as u32, format!("connect: {e}"));
373 }
374 };
375
376 let deadline = env
377 .deadline_seconds
378 .filter(|s| *s > 0.0)
379 .map(Duration::from_secs_f64)
380 .or(client.default_deadline);
381
382 match client
383 .invoke(
384 channel,
385 &env.service,
386 &env.method,
387 req_bytes,
388 &env.metadata,
389 deadline,
390 )
391 .await
392 {
393 Ok(resp_bytes) => match proto_to_json(&method_desc.output(), &resp_bytes) {
394 Ok(v) => json!({ "message": v }),
395 Err(e) => status_json(
396 Code::Internal as i32 as u32,
397 format!("decode response: {e}"),
398 ),
399 },
400 Err(status) => status_json(status.code() as i32 as u32, status.message().to_string()),
401 }
402 }
403
404 pub async fn open_stream(&self, env: ClientStreamEnvelope) -> StreamConn {
414 match self.try_open_stream(&env).await {
415 Ok(conn) => conn,
416 Err(status) => single_status_conn(status),
417 }
418 }
419
420 async fn try_open_stream(&self, env: &ClientStreamEnvelope) -> Result<StreamConn, Value> {
421 let client = self.clients.get(&env.client).ok_or_else(|| {
422 status_json(
423 Code::Unimplemented as i32 as u32,
424 format!("unknown gRPC client '{}'", env.client),
425 )
426 })?;
427
428 let method_desc =
429 resolve_method(&client.pool, &env.service, &env.method).ok_or_else(|| {
430 status_json(
431 Code::Unimplemented as i32 as u32,
432 format!(
433 "method {}/{} not in client '{}' descriptor pool",
434 env.service, env.method, env.client
435 ),
436 )
437 })?;
438
439 let channel = client
440 .channel(env.address.as_deref())
441 .await
442 .map_err(|e| status_json(Code::Unavailable as i32 as u32, format!("connect: {e}")))?;
443
444 let deadline = env
445 .deadline_seconds
446 .filter(|s| *s > 0.0)
447 .map(Duration::from_secs_f64)
448 .or(client.default_deadline);
449
450 let output = method_desc.output();
451
452 match env.kind {
453 StreamKind::ServerStreaming => {
454 let req_bytes = json_to_proto(&method_desc.input(), &env.message)
455 .map(Bytes::from)
456 .map_err(|e| {
457 status_json(
458 Code::InvalidArgument as i32 as u32,
459 format!("encode request: {e}"),
460 )
461 })?;
462 let streaming = call_server_streaming(
463 channel,
464 &env.service,
465 &env.method,
466 req_bytes,
467 &env.metadata,
468 deadline,
469 )
470 .await
471 .map_err(status_to_json)?;
472 Ok(StreamConn::server_streaming(with_stream_deadline(
473 transcode_inbound(streaming, output),
474 deadline,
475 )))
476 }
477
478 StreamKind::Bidi => {
479 let (tx, req_stream) = outbound_stream(method_desc.input());
480 let streaming = call_bidi_streaming(
481 channel,
482 &env.service,
483 &env.method,
484 req_stream,
485 &env.metadata,
486 deadline,
487 )
488 .await
489 .map_err(status_to_json)?;
490 Ok(StreamConn::duplex(
491 with_stream_deadline(transcode_inbound(streaming, output), deadline),
492 tx,
493 ))
494 }
495
496 StreamKind::ClientStreaming => {
497 let (tx, req_stream) = outbound_stream(method_desc.input());
501 let (frame_tx, frame_rx) = mpsc::channel::<StreamItem>(1);
502 let service = env.service.clone();
503 let method = env.method.clone();
504 let metadata = env.metadata.clone();
505 tokio::spawn(async move {
506 let frame = match call_client_streaming(
507 channel, &service, &method, req_stream, &metadata, deadline,
508 )
509 .await
510 {
511 Ok(resp) => Ok(message_or_status_frame(&output, &resp)),
512 Err(status) => Ok(status_frame_bytes(&status)),
513 };
514 let _ = frame_tx.send(frame).await;
515 });
516 let inbound: InboundStream = Box::pin(ReceiverStream::new(frame_rx));
517 Ok(StreamConn::duplex(
518 with_stream_deadline(inbound, deadline),
519 tx,
520 ))
521 }
522 }
523 }
524}
525
526fn with_stream_deadline(inbound: InboundStream, deadline: Option<Duration>) -> InboundStream {
535 let Some(d) = deadline else {
536 return inbound;
537 };
538 let deadline_at = tokio::time::Instant::now() + d;
539 let stream =
540 futures_util::stream::unfold((inbound, false), move |(mut inner, done)| async move {
541 if done {
542 return None;
543 }
544 tokio::select! {
545 biased;
546 item = inner.next() => item.map(|x| (x, (inner, false))),
547 () = tokio::time::sleep_until(deadline_at) => {
548 let frame = Bytes::from(
549 serde_json::to_vec(&status_json(
550 Code::DeadlineExceeded as i32 as u32,
551 "stream deadline exceeded",
552 ))
553 .unwrap_or_default(),
554 );
555 Some((Ok(frame), (inner, true)))
556 }
557 }
558 });
559 Box::pin(stream)
560}
561
562fn status_to_json(s: Status) -> Value {
564 status_json(s.code() as i32 as u32, s.message().to_string())
565}
566
567fn message_or_status_frame(output: &MessageDescriptor, proto: &[u8]) -> Bytes {
570 let frame = match proto_to_json(output, proto) {
571 Ok(v) => json!({ "message": v }),
572 Err(e) => status_json(
573 Code::Internal as i32 as u32,
574 format!("decode stream message: {e}"),
575 ),
576 };
577 Bytes::from(serde_json::to_vec(&frame).unwrap_or_default())
578}
579
580fn status_frame_bytes(status: &Status) -> Bytes {
581 Bytes::from(serde_json::to_vec(&status_to_json(status.clone())).unwrap_or_default())
582}
583
584fn transcode_inbound(streaming: Streaming<Bytes>, output: MessageDescriptor) -> InboundStream {
589 Box::pin(streaming.map(move |item| {
590 let frame = match item {
591 Ok(proto) => match proto_to_json(&output, &proto) {
592 Ok(v) => json!({ "message": v }),
593 Err(e) => status_json(
594 Code::Internal as i32 as u32,
595 format!("decode stream message: {e}"),
596 ),
597 },
598 Err(status) => status_to_json(status),
599 };
600 Ok(Bytes::from(serde_json::to_vec(&frame).unwrap_or_default()))
601 }))
602}
603
604fn outbound_stream(
609 input: MessageDescriptor,
610) -> (
611 tokio::sync::mpsc::Sender<Bytes>,
612 impl tokio_stream::Stream<Item = Bytes> + Send + 'static,
613) {
614 let (tx, rx) = mpsc::channel::<Bytes>(16);
615 let stream = ReceiverStream::new(rx).filter_map(move |json_bytes: Bytes| {
616 let value: Value = match serde_json::from_slice(&json_bytes) {
617 Ok(v) => v,
618 Err(e) => {
619 warn!(error = %e, "gRPC client stream: dropping unparsable outbound message");
620 return None;
621 }
622 };
623 match json_to_proto(&input, &value) {
624 Ok(b) => Some(Bytes::from(b)),
625 Err(e) => {
626 warn!(error = %e, "gRPC client stream: dropping unencodable outbound message");
627 None
628 }
629 }
630 });
631 (tx, stream)
632}
633
634fn single_status_conn(status: Value) -> StreamConn {
637 let bytes = Bytes::from(serde_json::to_vec(&status).unwrap_or_default());
638 let inbound: InboundStream = Box::pin(tokio_stream::once(Ok(bytes)));
639 StreamConn::server_streaming(inbound)
640}
641
642fn resolve_method(pool: &DescriptorPool, service: &str, method: &str) -> Option<MethodDescriptor> {
643 pool.get_service_by_name(service)?
644 .methods()
645 .find(|m| m.name() == method)
646}
647
648struct ResolvedClient {
651 pool: Arc<DescriptorPool>,
652 addresses: Vec<String>,
653 tls: Option<ClientTlsConfig>,
654 default_deadline: Option<Duration>,
655 retries: Option<RetryConfig>,
656 channel: OnceCell<Channel>,
659}
660
661impl ResolvedClient {
662 fn new(pool: Arc<DescriptorPool>, cfg: ClientConfig) -> Self {
663 Self {
664 pool,
665 addresses: cfg.address,
666 tls: cfg.tls,
667 default_deadline: cfg.deadline,
668 retries: cfg.retries,
669 channel: OnceCell::new(),
670 }
671 }
672
673 fn endpoint(&self, address: &str) -> Result<Endpoint, Status> {
675 let scheme = if self.tls.is_some() { "https" } else { "http" };
676 let uri = format!("{scheme}://{address}");
677 let mut ep = Channel::from_shared(uri)
678 .map_err(|e| Status::internal(format!("invalid upstream address '{address}': {e}")))?
679 .keep_alive_while_idle(true);
680
681 if let Some(tls) = &self.tls {
682 ep = ep
683 .tls_config(build_tls(tls)?)
684 .map_err(|e| Status::internal(format!("upstream TLS config: {e}")))?;
685 }
686 Ok(ep)
687 }
688
689 async fn channel(&self, override_addr: Option<&str>) -> Result<Channel, Status> {
692 if let Some(addr) = override_addr {
693 return Ok(self.endpoint(addr)?.connect_lazy());
694 }
695 self.channel
696 .get_or_try_init(|| async { self.build_default_channel() })
697 .await
698 .cloned()
699 }
700
701 fn build_default_channel(&self) -> Result<Channel, Status> {
704 if self.addresses.is_empty() {
705 return Err(Status::internal("gRPC client has no configured address"));
706 }
707 if self.addresses.len() == 1 {
708 return Ok(self.endpoint(&self.addresses[0])?.connect_lazy());
709 }
710 let mut endpoints = Vec::with_capacity(self.addresses.len());
711 for addr in &self.addresses {
712 endpoints.push(self.endpoint(addr)?);
713 }
714 Ok(Channel::balance_list(endpoints.into_iter()))
715 }
716
717 async fn invoke(
721 &self,
722 channel: Channel,
723 service: &str,
724 method: &str,
725 req_bytes: Bytes,
726 metadata: &HashMap<String, Vec<String>>,
727 deadline: Option<Duration>,
728 ) -> Result<Bytes, Status> {
729 let max_attempts = self.retries.as_ref().map_or(1, |r| r.max_attempts.max(1));
730 let base_backoff = self.retries.as_ref().map_or(Duration::ZERO, |r| r.backoff);
731 let path = method_path(service, method)?;
732
733 let mut attempt = 0;
734 loop {
735 attempt += 1;
736
737 let mut request = tonic::Request::new(req_bytes.clone());
738 apply_metadata(request.metadata_mut(), metadata);
739
740 if let Some(d) = deadline {
747 if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
748 request.metadata_mut().insert("grpc-timeout", v);
749 }
750 }
751
752 let channel = channel.clone();
753 let path = path.clone();
754 let fut = async move {
755 let mut grpc = tonic::client::Grpc::new(channel);
756 grpc.ready()
757 .await
758 .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
759 grpc.unary(request, path, BytesCodec).await
760 };
761
762 let result = match deadline {
770 Some(d) => {
771 let backstop = d + Duration::from_millis(250);
772 match tokio::time::timeout(backstop, fut).await {
773 Ok(Ok(resp)) => Ok(resp),
774 Ok(Err(status)) if status.code() == Code::Cancelled => {
775 Err(Status::deadline_exceeded("client deadline exceeded"))
776 }
777 Ok(Err(status)) => Err(status),
778 Err(_) => Err(Status::deadline_exceeded("client deadline exceeded")),
779 }
780 }
781 None => fut.await,
782 };
783
784 match result {
785 Ok(resp) => return Ok(resp.into_inner()),
786 Err(status) => {
787 let transient = status.code() == Code::Unavailable;
788 if transient && attempt < max_attempts {
789 let factor = 2u32.pow((attempt - 1).min(10));
790 let backoff = base_backoff * factor;
791 debug!(
792 attempt,
793 max_attempts,
794 ?backoff,
795 "gRPC client: retrying transient failure"
796 );
797 if !backoff.is_zero() {
798 tokio::time::sleep(backoff).await;
799 }
800 continue;
801 }
802 return Err(status);
803 }
804 }
805 }
806 }
807}
808
809fn grpc_timeout_header(d: Duration) -> String {
814 let millis = d.as_millis();
815 if millis <= 99_999_999 {
816 format!("{millis}m")
817 } else {
818 format!("{}S", d.as_secs().min(99_999_999))
819 }
820}
821
822fn apply_metadata(map: &mut tonic::metadata::MetadataMap, metadata: &HashMap<String, Vec<String>>) {
826 for (key, values) in metadata {
827 if key.ends_with("-bin") {
828 debug!(key = %key, "gRPC client: skipping binary metadata (unsupported in v1)");
829 continue;
830 }
831 let Ok(mkey) = key.parse::<MetadataKey<Ascii>>() else {
832 debug!(key = %key, "gRPC client: skipping invalid metadata key");
833 continue;
834 };
835 for value in values {
836 match MetadataValue::try_from(value) {
837 Ok(mval) => {
838 map.append(mkey.clone(), mval);
839 }
840 Err(_) => debug!(key = %key, "gRPC client: skipping invalid metadata value"),
841 }
842 }
843 }
844}
845
846fn build_tls(tls: &ClientTlsConfig) -> Result<TonicClientTls, Status> {
848 let mut cfg = TonicClientTls::new();
849 if let Some(ca) = &tls.ca {
850 let pem = std::fs::read(ca)
851 .map_err(|e| Status::internal(format!("read CA {}: {e}", ca.display())))?;
852 cfg = cfg.ca_certificate(Certificate::from_pem(pem));
853 }
854 if let (Some(cert), Some(key)) = (&tls.cert, &tls.key) {
855 let cert_pem = std::fs::read(cert)
856 .map_err(|e| Status::internal(format!("read client cert {}: {e}", cert.display())))?;
857 let key_pem = std::fs::read(key)
858 .map_err(|e| Status::internal(format!("read client key {}: {e}", key.display())))?;
859 cfg = cfg.identity(Identity::from_pem(cert_pem, key_pem));
860 }
861 if let Some(domain) = &tls.domain {
862 cfg = cfg.domain_name(domain);
863 }
864 Ok(cfg)
865}