folk-plugin-grpc 0.7.0

gRPC plugin for Folk — unary server + client (call upstreams from PHP) via tonic
Documentation
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::time::Duration;

use serde::{Deserialize, Serialize};

/// gRPC plugin configuration.
///
/// ```toml
/// [grpc]
/// listen = "0.0.0.0:50051"
/// proto = ["proto/service.proto"]
/// max_recv_message_size = "4mb"
/// max_send_message_size = "4mb"
/// timeout = "30s"
/// max_concurrent_streams = 200
///
/// [grpc.keepalive]
/// interval = "60s"
/// timeout = "20s"
///
/// compression = true
///
/// [grpc.tls]
/// cert = "/path/to/cert.pem"
/// key = "/path/to/key.pem"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GrpcConfig {
    /// Listening address for the gRPC **server**. Optional (phase 88): the server
    /// binds only when this is set. Omitting `[grpc] listen` while configuring
    /// `[grpc.clients.*]` yields a **client-only** deployment — Folk calls upstreams
    /// but exposes no gRPC server. Every server config sets this explicitly, so
    /// making it optional is backward-compatible in practice.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub listen: Option<SocketAddr>,
    /// Proto files (or directories) for gRPC reflection and — when
    /// [`transcode`](Self::transcode) is on — proto↔native transcoding. A
    /// directory entry is scanned recursively for `*.proto`. Imports are
    /// resolved automatically. When empty, reflection is disabled.
    #[serde(default)]
    pub proto: Vec<String>,
    /// Optional path to a prebuilt encoded `FileDescriptorSet` bundle (e.g.
    /// `all.pb` produced by `protoc --descriptor_set_out` or another Folk build).
    /// Merged into the descriptor pool alongside [`proto`](Self::proto) — useful
    /// for making extra types (notably ones packed in `Any`) resolvable without
    /// listing every `.proto`. Requires [`transcode`](Self::transcode).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub descriptor_set: Option<String>,
    /// Transcode proto↔native on the request path (phase 87). Default `false`:
    /// the plugin passes raw protobuf bytes through to PHP unchanged (legacy
    /// behaviour, zero regression). When `true` and a descriptor pool is
    /// available, incoming messages are decoded to a structured payload and
    /// responses re-encoded, so PHP handlers work with generated DTOs.
    #[serde(default)]
    pub transcode: bool,
    /// Maximum incoming message size. Accepts: "4mb", "512kb", or raw bytes as integer.
    /// Default: 4 MiB.
    #[serde(with = "human_bytes")]
    pub max_recv_message_size: usize,
    /// Maximum outgoing message size. Accepts: "4mb", "512kb", or raw bytes as integer.
    /// Default: 4 MiB.
    #[serde(with = "human_bytes")]
    pub max_send_message_size: usize,
    /// Server-wide RPC timeout. Default: none (no timeout).
    #[serde(
        default,
        with = "humantime_serde",
        skip_serializing_if = "Option::is_none"
    )]
    pub timeout: Option<Duration>,
    /// Maximum HTTP/2 concurrent streams per connection.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_concurrent_streams: Option<u32>,
    /// HTTP/2 keepalive configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keepalive: Option<KeepaliveConfig>,
    /// TLS configuration. If set, the server uses TLS (rustls).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tls: Option<TlsConfig>,
    /// Enable gzip compression for gRPC messages. Default: false.
    #[serde(default)]
    pub compression: bool,
    /// Named upstream gRPC **clients** (phase 88). Each entry `[grpc.clients.<name>]`
    /// carries its own `proto` contracts (own descriptor pool), `address`(es), TLS,
    /// deadline and retry policy. Independent of the server side — a config with only
    /// `[grpc.clients.*]` (no `listen`) is a valid client-only deployment.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub clients: HashMap<String, ClientConfig>,
}

/// TLS certificate + key paths.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TlsConfig {
    /// Path to PEM-encoded certificate chain.
    pub cert: PathBuf,
    /// Path to PEM-encoded private key.
    pub key: PathBuf,
}

/// Configuration for one named upstream gRPC client (`[grpc.clients.<name>]`).
///
/// Each client is self-contained: its own proto contracts build its own descriptor
/// pool (so two upstreams may declare same-named messages without colliding), its
/// own endpoint address(es), TLS to the upstream, and call policy (deadline/retries).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
    /// Upstream address(es), `host:port`. A single string or a list; multiple
    /// addresses enable client-side round-robin load balancing (phase 88 §1.4).
    #[serde(deserialize_with = "one_or_many", default)]
    pub address: Vec<String>,
    /// Proto contracts for THIS upstream (files or directories, scanned
    /// recursively). Builds this client's descriptor pool via the same path as the
    /// server side (`build_descriptor_pool`). Imports resolve automatically.
    #[serde(default)]
    pub proto: Vec<String>,
    /// Optional prebuilt `FileDescriptorSet` bundle merged into this client's pool
    /// (same role as the server's `descriptor_set` — resolve `Any`/extra types).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub descriptor_set: Option<String>,
    /// TLS/mTLS to the upstream. Distinct from the server listener's TLS.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tls: Option<ClientTlsConfig>,
    /// Default per-call deadline. A call may override it; if neither is set the
    /// call has no client-imposed deadline (the worker still blocks — document).
    #[serde(
        default,
        with = "humantime_serde",
        skip_serializing_if = "Option::is_none"
    )]
    pub deadline: Option<Duration>,
    /// Retry policy for transient/network failures (never for a business status).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retries: Option<RetryConfig>,
}

/// Upstream TLS/mTLS settings for a gRPC client.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientTlsConfig {
    /// PEM CA certificate(s) to verify the upstream. When omitted, the platform's
    /// system roots are used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca: Option<PathBuf>,
    /// PEM client certificate for mTLS (presenting an identity to the upstream).
    /// Requires [`key`](Self::key).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cert: Option<PathBuf>,
    /// PEM client private key for mTLS. Requires [`cert`](Self::cert).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<PathBuf>,
    /// SNI / domain name to validate the upstream certificate against, when it
    /// differs from the address host (e.g. behind a load balancer).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}

/// Retry policy for a gRPC client (phase 88 §1.4).
///
/// Applies only to transient/transport failures (`UNAVAILABLE`, connect timeout)
/// and never to a business status returned by the upstream — retrying a
/// non-idempotent call that already executed would double it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum total attempts, including the first. `1` (or absent policy) = no
    /// retry. Default when the section is present: 3.
    #[serde(default = "default_max_attempts")]
    pub max_attempts: u32,
    /// Base backoff between attempts; grows exponentially (`base * 2^(n-1)`).
    /// Default: 100ms.
    #[serde(default = "default_backoff", with = "humantime_serde")]
    pub backoff: Duration,
}

fn default_max_attempts() -> u32 {
    3
}

fn default_backoff() -> Duration {
    Duration::from_millis(100)
}

/// Deserialize `address` accepting either a single `"host:port"` string or a list
/// `["a:1", "b:2"]` — both yield a `Vec<String>`.
fn one_or_many<'de, D>(de: D) -> Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany {
        One(String),
        Many(Vec<String>),
    }
    Ok(match OneOrMany::deserialize(de)? {
        OneOrMany::One(s) => vec![s],
        OneOrMany::Many(v) => v,
    })
}

/// HTTP/2 keepalive settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeepaliveConfig {
    /// HTTP/2 PING interval. Default: 60s.
    #[serde(with = "humantime_serde")]
    pub interval: Duration,
    /// PING response timeout. Default: 20s.
    #[serde(with = "humantime_serde")]
    pub timeout: Duration,
}

impl Default for GrpcConfig {
    fn default() -> Self {
        Self {
            listen: None,
            proto: vec![],
            descriptor_set: None,
            transcode: false,
            max_recv_message_size: 4 * 1024 * 1024, // 4 MiB
            max_send_message_size: 4 * 1024 * 1024, // 4 MiB
            timeout: None,
            max_concurrent_streams: None,
            keepalive: None,
            tls: None,
            compression: false,
            clients: HashMap::new(),
        }
    }
}

pub fn parse_byte_size(s: &str) -> Result<usize, String> {
    let s = s.trim().to_lowercase();

    if let Ok(n) = s.parse::<usize>() {
        return Ok(n);
    }

    let (num_part, multiplier) = if let Some(n) = s.strip_suffix("gib") {
        (n, 1024 * 1024 * 1024)
    } else if let Some(n) = s.strip_suffix("gb") {
        (n, 1024 * 1024 * 1024)
    } else if let Some(n) = s.strip_suffix("mib") {
        (n, 1024 * 1024)
    } else if let Some(n) = s.strip_suffix("mb") {
        (n, 1024 * 1024)
    } else if let Some(n) = s.strip_suffix("kib") {
        (n, 1024)
    } else if let Some(n) = s.strip_suffix("kb") {
        (n, 1024)
    } else if let Some(n) = s.strip_suffix("b") {
        (n, 1)
    } else {
        return Err(format!("invalid byte size: {s:?}"));
    };

    let num: usize = num_part
        .trim()
        .parse()
        .map_err(|_| format!("invalid byte size number: {num_part:?}"))?;

    Ok(num * multiplier)
}

mod human_bytes {
    use serde::{Deserialize, Deserializer, Serializer, de};

    pub fn serialize<S: Serializer>(value: &usize, ser: S) -> Result<S::Ok, S::Error> {
        ser.serialize_u64(*value as u64)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<usize, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum ByteSize {
            Str(String),
            Num(usize),
        }

        match ByteSize::deserialize(de)? {
            ByteSize::Num(n) => Ok(n),
            ByteSize::Str(s) => super::parse_byte_size(&s).map_err(de::Error::custom),
        }
    }
}