folk-plugin-grpc 0.5.0

gRPC plugin for Folk — unary server + client (call upstreams from PHP) via tonic
Documentation
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! gRPC **client** transport (phase 88): let PHP call upstream gRPC services with
//! Folk acting as the client. Folk encodes the request and decodes the response
//! itself (prost-reflect against the *client* descriptor pool), so tonic must not
//! do any message (de)serialization — it only owns gRPC framing/compression and
//! the HTTP/2 channel. The [`BytesCodec`] below is what makes that possible: a
//! codec that passes raw protobuf bytes through untouched in both directions.
//!
//! This is the reverse of the server path ([`crate::service`]): there we
//! `proto_to_json` the request and `json_to_proto` the response; here we
//! `json_to_proto` the request and `proto_to_json` the response — the same
//! `prost-reflect` machinery from phase 87, run the other way.
//!
//! ## Per-worker channel pool
//!
//! Channels are created **lazily on first use inside the RPC handler**, which runs
//! on the worker's tokio runtime (`folk_call` → `TOKIO_HANDLE.block_on`). Creating
//! them there — not at plugin boot — binds each channel to the runtime that will
//! poll it (phase 79 fork model): every worker gets its own pool, and a respawned
//! worker rebuilds it. This mirrors how memory/embedded jobs drivers are
//! per-process (phase 85).

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use bytes::{Buf, BufMut, Bytes};
use http::uri::PathAndQuery;
use prost_reflect::{DescriptorPool, MethodDescriptor};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::OnceCell;
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};
use tracing::{debug, warn};

use crate::config::{ClientConfig, ClientTlsConfig, RetryConfig};
use crate::service::{json_to_proto, proto_to_json};

// ---------------------------------------------------------------------------
// Raw-bytes codec
// ---------------------------------------------------------------------------

/// A gRPC codec that passes raw protobuf bytes through untouched.
///
/// tonic normally (de)serializes messages via prost; we do that ourselves with
/// prost-reflect, so the codec's job is reduced to moving already-encoded bytes
/// in and out of tonic's framing. `Encode` and `Decode` are both [`Bytes`].
#[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> {
        // tonic strips gRPC framing and hands us exactly one message's bytes,
        // calling `decode` once per framed message. Consume all of it — an empty
        // message (all-default protobuf) is a valid `Some(empty)`, not `None`.
        let len = src.remaining();
        Ok(Some(src.copy_to_bytes(len)))
    }
}

/// Perform a dynamic unary gRPC call over `channel` with no message
/// (de)serialization by tonic. `request` is already-encoded protobuf; the return
/// is the raw response protobuf. Used by the PoC test and by [`ResolvedClient`].
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}")))
}

// ---------------------------------------------------------------------------
// Call envelope (PHP → Rust, JSON over the `grpc.client.call` RPC method)
// ---------------------------------------------------------------------------

/// Envelope PHP sends to invoke an upstream. `client` names a `[grpc.clients.<name>]`
/// entry (resolves the descriptor pool, TLS, default deadline, retries); `address`
/// optionally overrides the endpoint for this call. `message` is the request DTO as
/// canonical JSON; it is transcoded to protobuf against the client's pool.
#[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>,
}

/// Build the `{__grpc_status, __grpc_message}` object PHP maps to `GrpcException`.
fn status_json(code: u32, message: impl Into<String>) -> Value {
    json!({ "__grpc_status": code, "__grpc_message": message.into() })
}

// ---------------------------------------------------------------------------
// Client registry + resolved clients
// ---------------------------------------------------------------------------

/// Per-worker registry of configured upstream clients, keyed by `[grpc.clients.<name>]`
/// name. Built once per worker `run()`; each entry lazily opens its channel on first
/// call. Clients whose descriptor pool fails to build are logged and omitted (a call
/// to them returns `UNIMPLEMENTED`), rather than crashing the worker.
pub struct ClientRegistry {
    clients: HashMap<String, ResolvedClient>,
}

impl ClientRegistry {
    /// Build the registry from `[grpc.clients.*]`. Never fails as a whole: a client
    /// with no usable descriptors is skipped with a warning.
    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()
    }

    /// Execute one `grpc.client.call`. Returns a JSON value: `{ "message": <DTO> }`
    /// on success, or `{ "__grpc_status", "__grpc_message" }` for any gRPC/transport
    /// failure (business status passed through; transport → `UNAVAILABLE(14)`;
    /// client deadline → `DEADLINE_EXCEEDED(4)`). Never returns `Err` for a call
    /// outcome — only truly internal encode failures surface as a status too.
    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),
            );
        };

        // Resolve the method against THIS client's descriptor pool.
        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
                ),
            );
        };

        // Encode request DTO → protobuf.
        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}"),
                );
            }
        };

        // Resolve the channel (cached default, or a one-off for an address override).
        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()),
        }
    }
}

fn resolve_method(pool: &DescriptorPool, service: &str, method: &str) -> Option<MethodDescriptor> {
    pool.get_service_by_name(service)?
        .methods()
        .find(|m| m.name() == method)
}

/// One resolved upstream: descriptor pool + endpoint(s) + call policy, plus a
/// lazily-opened (per-worker) default channel.
struct ResolvedClient {
    pool: Arc<DescriptorPool>,
    addresses: Vec<String>,
    tls: Option<ClientTlsConfig>,
    default_deadline: Option<Duration>,
    retries: Option<RetryConfig>,
    /// Lazily-initialized default channel (single endpoint, or LB across all
    /// addresses). Created on first call inside the worker runtime.
    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(),
        }
    }

    /// Build a tonic [`Endpoint`] for one `host:port`, applying upstream TLS/mTLS.
    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)
    }

    /// Resolve the channel for a call: a per-call one-off for an explicit address
    /// override, otherwise the cached default channel (built once per worker).
    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()
    }

    /// Build the default channel: `connect_lazy` for a single address, or tonic's
    /// round-robin `balance_list` across several (client-side LB, phase 88 §1.4).
    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()))
    }

    /// Unary call with outbound metadata, deadline, and retry-on-transient. Retries
    /// apply **only** to `UNAVAILABLE` (transport) — never to a business status, so a
    /// non-idempotent call that already ran is not silently duplicated.
    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);

            // Propagate the deadline to the upstream via the `grpc-timeout` header so
            // a well-behaved server can enforce it too (and shed load early). Set it
            // manually rather than via tonic's `set_timeout`: the latter also makes
            // the tonic client self-cancel on expiry with CANCELLED, which races —
            // and loses to — the authoritative local timeout below. A stray existing
            // `grpc-timeout` from app metadata is overwritten by our computed value.
            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
            };

            // Deadline handling. The propagated `grpc-timeout` above makes tonic's
            // own client enforce the deadline — but it surfaces expiry as CANCELLED,
            // so we normalize that to DEADLINE_EXCEEDED for a consistent code 4 (we
            // never cancel a call for any other reason, so CANCELLED-under-deadline is
            // always the deadline). A local `tokio::time::timeout` with a small grace
            // is the backstop that guarantees the *worker* thread is never blocked
            // past the deadline even if tonic's timer somehow doesn't fire.
            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);
                }
            }
        }
    }
}

/// Format a deadline as a gRPC `grpc-timeout` header value (`<int><unit>`, max 8
/// digits per the grpc-over-HTTP2 spec). Uses milliseconds when they fit in 8
/// digits (< ~27h), else falls back to whole seconds — enough range for any sane
/// deadline. The inverse of [`crate::service::parse_grpc_timeout`].
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))
    }
}

/// Apply outbound application metadata (a multimap) to a request. ASCII keys/values
/// only; `-bin` keys and malformed entries are skipped (binary metadata needs
/// base64 framing — out of scope for unary v1).
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"),
            }
        }
    }
}

/// Translate a [`ClientTlsConfig`] into tonic's client TLS config.
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)
}