Skip to main content

folk_plugin_grpc/
client.rs

1//! gRPC **client** transport (phase 88): let PHP call upstream gRPC services with
2//! Folk acting as the client. Folk encodes the request and decodes the response
3//! itself (prost-reflect against the *client* descriptor pool), so tonic must not
4//! do any message (de)serialization — it only owns gRPC framing/compression and
5//! the HTTP/2 channel. The [`BytesCodec`] below is what makes that possible: a
6//! codec that passes raw protobuf bytes through untouched in both directions.
7//!
8//! This is the reverse of the server path ([`crate::service`]): there we
9//! `proto_to_json` the request and `json_to_proto` the response; here we
10//! `json_to_proto` the request and `proto_to_json` the response — the same
11//! `prost-reflect` machinery from phase 87, run the other way.
12//!
13//! ## Per-worker channel pool
14//!
15//! Channels are created **lazily on first use inside the RPC handler**, which runs
16//! on the worker's tokio runtime (`folk_call` → `TOKIO_HANDLE.block_on`). Creating
17//! them there — not at plugin boot — binds each channel to the runtime that will
18//! poll it (phase 79 fork model): every worker gets its own pool, and a respawned
19//! worker rebuilds it. This mirrors how memory/embedded jobs drivers are
20//! per-process (phase 85).
21
22use 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// ---------------------------------------------------------------------------
47// Raw-bytes codec
48// ---------------------------------------------------------------------------
49
50/// A gRPC codec that passes raw protobuf bytes through untouched.
51///
52/// tonic normally (de)serializes messages via prost; we do that ourselves with
53/// prost-reflect, so the codec's job is reduced to moving already-encoded bytes
54/// in and out of tonic's framing. `Encode` and `Decode` are both [`Bytes`].
55#[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        // tonic strips gRPC framing and hands us exactly one message's bytes,
89        // calling `decode` once per framed message. Consume all of it — an empty
90        // message (all-default protobuf) is a valid `Some(empty)`, not `None`.
91        let len = src.remaining();
92        Ok(Some(src.copy_to_bytes(len)))
93    }
94}
95
96/// Perform a dynamic unary gRPC call over `channel` with no message
97/// (de)serialization by tonic. `request` is already-encoded protobuf; the return
98/// is the raw response protobuf. Used by the PoC test and by [`ResolvedClient`].
99pub 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
122/// Dynamic **server-streaming** call (phase 88b): one request, a stream of raw
123/// response protobuf messages. Metadata and the deadline are applied as in
124/// [`ResolvedClient::invoke`] — the deadline is propagated to the upstream via
125/// `grpc-timeout`. The client-side deadline backstop lives one level up in
126/// [`ResolvedClient::try_open_stream`] (via `with_stream_deadline`), which bounds
127/// the whole stream when the server does not honour `grpc-timeout`; a stream with
128/// **no** deadline runs until the caller cancels it by **dropping** the returned
129/// [`Streaming`] (the handle bridge drops it on `folk_stream_close`). No retries:
130/// a stream that already emitted messages cannot be replayed.
131pub 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
156/// Build a tonic request from a request-message stream, applying metadata and the
157/// deadline (as `grpc-timeout`) — shared by client-streaming and bidi.
158fn 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
173/// Dynamic **client-streaming** call (phase 88b): a stream of requests, one
174/// response. `req_stream` yields already-encoded protobuf messages.
175pub 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
201/// Dynamic **bidirectional-streaming** call (phase 88b): a stream of requests and a
202/// stream of responses. `req_stream` yields already-encoded protobuf messages.
203pub 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// ---------------------------------------------------------------------------
230// Call envelope (PHP → Rust, JSON over the `grpc.client.call` RPC method)
231// ---------------------------------------------------------------------------
232
233/// Envelope PHP sends to invoke an upstream. `client` names a `[grpc.clients.<name>]`
234/// entry (resolves the descriptor pool, TLS, default deadline, retries); `address`
235/// optionally overrides the endpoint for this call. `message` is the request DTO as
236/// canonical JSON; it is transcoded to protobuf against the client's pool.
237#[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/// Which streaming shape `grpc.client.stream` should open.
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
253#[serde(rename_all = "snake_case")]
254pub enum StreamKind {
255    /// One request → a stream of responses.
256    #[default]
257    ServerStreaming,
258    /// A stream of requests → one response.
259    ClientStreaming,
260    /// A stream of requests ↔ a stream of responses.
261    Bidi,
262}
263
264/// Envelope PHP sends to open a streaming call (`grpc.client.stream`, phase 88b).
265/// Like [`ClientCallEnvelope`] plus `kind`; `message` carries the single initial
266/// request for [`StreamKind::ServerStreaming`] and is unused (send messages via
267/// `folk_stream_send`) for client-streaming / bidi.
268#[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
285/// Build the `{__grpc_status, __grpc_message}` object PHP maps to `GrpcException`.
286fn status_json(code: u32, message: impl Into<String>) -> Value {
287    json!({ "__grpc_status": code, "__grpc_message": message.into() })
288}
289
290// ---------------------------------------------------------------------------
291// Client registry + resolved clients
292// ---------------------------------------------------------------------------
293
294/// Per-worker registry of configured upstream clients, keyed by `[grpc.clients.<name>]`
295/// name. Built once per worker `run()`; each entry lazily opens its channel on first
296/// call. Clients whose descriptor pool fails to build are logged and omitted (a call
297/// to them returns `UNIMPLEMENTED`), rather than crashing the worker.
298pub struct ClientRegistry {
299    clients: HashMap<String, ResolvedClient>,
300}
301
302impl ClientRegistry {
303    /// Build the registry from `[grpc.clients.*]`. Never fails as a whole: a client
304    /// with no usable descriptors is skipped with a warning.
305    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    /// Execute one `grpc.client.call`. Returns a JSON value: `{ "message": <DTO> }`
334    /// on success, or `{ "__grpc_status", "__grpc_message" }` for any gRPC/transport
335    /// failure (business status passed through; transport → `UNAVAILABLE(14)`;
336    /// client deadline → `DEADLINE_EXCEEDED(4)`). Never returns `Err` for a call
337    /// outcome — only truly internal encode failures surface as a status too.
338    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        // Resolve the method against THIS client's descriptor pool.
347        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        // Encode request DTO → protobuf.
358        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        // Resolve the channel (cached default, or a one-off for an address override).
369        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    /// Open a **server-streaming** call (phase 88b). Returns a [`StreamConn`] whose
405    /// inbound stream yields one JSON frame per upstream message: `{ "message": … }`
406    /// for a decoded DTO, or `{ "__grpc_status", "__grpc_message" }` for a decode
407    /// failure or a non-OK trailing status — the same convention the unary [`call`]
408    /// uses, so the PHP side maps a status frame to `GrpcException`. Never fails at
409    /// the handler level: setup errors (unknown client/method, bad request, connect)
410    /// surface as a single status frame, so PHP's `foreach` always sees the outcome.
411    ///
412    /// [`call`]: Self::call
413    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                // The single response is only available after the request stream
498                // ends, so the call runs on a spawned task and delivers exactly one
499                // inbound frame through a 1-slot channel.
500                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
526/// Bound an inbound stream by an absolute deadline (phase 88b). gRPC deadlines
527/// apply to the whole RPC, streaming included, so when one is set the entire
528/// stream must finish before it elapses; otherwise the stream ends with a single
529/// `DEADLINE_EXCEEDED(4)` status frame (which PHP maps to `GrpcException`). The
530/// `grpc-timeout` header is still sent upstream, but this is the client-side
531/// backstop that fires when the server does not honour it. A stream with **no**
532/// deadline is returned untouched — a long-lived stream must not be killed by a
533/// backstop.
534fn 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
562/// Map a tonic [`Status`] to the `{__grpc_status,…}` JSON PHP turns into an exception.
563fn status_to_json(s: Status) -> Value {
564    status_json(s.code() as i32 as u32, s.message().to_string())
565}
566
567/// Encode one response protobuf message as a `{ "message": DTO }` JSON frame, or a
568/// status frame if it fails to decode (client-streaming's single response).
569fn 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
584/// Adapt a tonic response [`Streaming`] into the bridge's inbound stream: one JSON
585/// frame per message (`{ "message": … }`), a status frame on decode error or a
586/// non-OK trailing status. Errors are frames, never `Err` — the bridge stays purely
587/// data-carrying (mirrors the unary convention).
588fn 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
604/// Build the outbound half for client-streaming / bidi: a `mpsc::Sender` the bridge
605/// pushes PHP-sent DTO-JSON into, and the tonic request stream that transcodes each
606/// message JSON → protobuf. Messages that fail to encode are dropped with a warning
607/// (a malformed DTO is a caller bug; dropping keeps the stream alive).
608fn 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
634/// A [`StreamConn`] that yields exactly one status frame then ends — used to
635/// surface a setup failure (unknown client, connect error, …) to PHP's `foreach`.
636fn 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
648/// One resolved upstream: descriptor pool + endpoint(s) + call policy, plus a
649/// lazily-opened (per-worker) default channel.
650struct ResolvedClient {
651    pool: Arc<DescriptorPool>,
652    addresses: Vec<String>,
653    tls: Option<ClientTlsConfig>,
654    default_deadline: Option<Duration>,
655    retries: Option<RetryConfig>,
656    /// Lazily-initialized default channel (single endpoint, or LB across all
657    /// addresses). Created on first call inside the worker runtime.
658    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    /// Build a tonic [`Endpoint`] for one `host:port`, applying upstream TLS/mTLS.
674    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    /// Resolve the channel for a call: a per-call one-off for an explicit address
690    /// override, otherwise the cached default channel (built once per worker).
691    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    /// Build the default channel: `connect_lazy` for a single address, or tonic's
702    /// round-robin `balance_list` across several (client-side LB, phase 88 §1.4).
703    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    /// Unary call with outbound metadata, deadline, and retry-on-transient. Retries
718    /// apply **only** to `UNAVAILABLE` (transport) — never to a business status, so a
719    /// non-idempotent call that already ran is not silently duplicated.
720    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            // Propagate the deadline to the upstream via the `grpc-timeout` header so
741            // a well-behaved server can enforce it too (and shed load early). Set it
742            // manually rather than via tonic's `set_timeout`: the latter also makes
743            // the tonic client self-cancel on expiry with CANCELLED, which races —
744            // and loses to — the authoritative local timeout below. A stray existing
745            // `grpc-timeout` from app metadata is overwritten by our computed value.
746            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            // Deadline handling. The propagated `grpc-timeout` above makes tonic's
763            // own client enforce the deadline — but it surfaces expiry as CANCELLED,
764            // so we normalize that to DEADLINE_EXCEEDED for a consistent code 4 (we
765            // never cancel a call for any other reason, so CANCELLED-under-deadline is
766            // always the deadline). A local `tokio::time::timeout` with a small grace
767            // is the backstop that guarantees the *worker* thread is never blocked
768            // past the deadline even if tonic's timer somehow doesn't fire.
769            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
809/// Format a deadline as a gRPC `grpc-timeout` header value (`<int><unit>`, max 8
810/// digits per the grpc-over-HTTP2 spec). Uses milliseconds when they fit in 8
811/// digits (< ~27h), else falls back to whole seconds — enough range for any sane
812/// deadline. The inverse of [`crate::service::parse_grpc_timeout`].
813fn 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
822/// Apply outbound application metadata (a multimap) to a request. ASCII keys/values
823/// only; `-bin` keys and malformed entries are skipped (binary metadata needs
824/// base64 framing — out of scope for unary v1).
825fn 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
846/// Translate a [`ClientTlsConfig`] into tonic's client TLS config.
847fn 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}