folk_plugin_grpc/config.rs
1use std::collections::HashMap;
2use std::net::SocketAddr;
3use std::path::PathBuf;
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7
8/// gRPC plugin configuration.
9///
10/// ```toml
11/// [grpc]
12/// listen = "0.0.0.0:50051"
13/// proto = ["proto/service.proto"]
14/// max_recv_message_size = "4mb"
15/// max_send_message_size = "4mb"
16/// timeout = "30s"
17/// max_concurrent_streams = 200
18///
19/// [grpc.keepalive]
20/// interval = "60s"
21/// timeout = "20s"
22///
23/// compression = true
24///
25/// [grpc.tls]
26/// cert = "/path/to/cert.pem"
27/// key = "/path/to/key.pem"
28/// ```
29#[derive(Debug, Clone, Serialize, Deserialize)]
30#[serde(default)]
31pub struct GrpcConfig {
32 /// Listening address for the gRPC **server**. Optional (phase 88): the server
33 /// binds only when this is set. Omitting `[grpc] listen` while configuring
34 /// `[grpc.clients.*]` yields a **client-only** deployment — Folk calls upstreams
35 /// but exposes no gRPC server. Every server config sets this explicitly, so
36 /// making it optional is backward-compatible in practice.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub listen: Option<SocketAddr>,
39 /// Proto files (or directories) for gRPC reflection and — when
40 /// [`transcode`](Self::transcode) is on — proto↔native transcoding. A
41 /// directory entry is scanned recursively for `*.proto`. Imports are
42 /// resolved automatically. When empty, reflection is disabled.
43 #[serde(default)]
44 pub proto: Vec<String>,
45 /// Optional path to a prebuilt encoded `FileDescriptorSet` bundle (e.g.
46 /// `all.pb` produced by `protoc --descriptor_set_out` or another Folk build).
47 /// Merged into the descriptor pool alongside [`proto`](Self::proto) — useful
48 /// for making extra types (notably ones packed in `Any`) resolvable without
49 /// listing every `.proto`. Requires [`transcode`](Self::transcode).
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub descriptor_set: Option<String>,
52 /// Transcode proto↔native on the request path (phase 87). Default `false`:
53 /// the plugin passes raw protobuf bytes through to PHP unchanged (legacy
54 /// behaviour, zero regression). When `true` and a descriptor pool is
55 /// available, incoming messages are decoded to a structured payload and
56 /// responses re-encoded, so PHP handlers work with generated DTOs.
57 #[serde(default)]
58 pub transcode: bool,
59 /// Maximum incoming message size. Accepts: "4mb", "512kb", or raw bytes as integer.
60 /// Default: 4 MiB.
61 #[serde(with = "human_bytes")]
62 pub max_recv_message_size: usize,
63 /// Maximum outgoing message size. Accepts: "4mb", "512kb", or raw bytes as integer.
64 /// Default: 4 MiB.
65 #[serde(with = "human_bytes")]
66 pub max_send_message_size: usize,
67 /// Server-wide RPC timeout. Default: none (no timeout).
68 #[serde(
69 default,
70 with = "humantime_serde",
71 skip_serializing_if = "Option::is_none"
72 )]
73 pub timeout: Option<Duration>,
74 /// Maximum HTTP/2 concurrent streams per connection.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub max_concurrent_streams: Option<u32>,
77 /// HTTP/2 keepalive configuration.
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub keepalive: Option<KeepaliveConfig>,
80 /// TLS configuration. If set, the server uses TLS (rustls).
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub tls: Option<TlsConfig>,
83 /// Enable gzip compression for gRPC messages. Default: false.
84 #[serde(default)]
85 pub compression: bool,
86 /// Named upstream gRPC **clients** (phase 88). Each entry `[grpc.clients.<name>]`
87 /// carries its own `proto` contracts (own descriptor pool), `address`(es), TLS,
88 /// deadline and retry policy. Independent of the server side — a config with only
89 /// `[grpc.clients.*]` (no `listen`) is a valid client-only deployment.
90 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
91 pub clients: HashMap<String, ClientConfig>,
92}
93
94/// TLS certificate + key paths.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct TlsConfig {
97 /// Path to PEM-encoded certificate chain.
98 pub cert: PathBuf,
99 /// Path to PEM-encoded private key.
100 pub key: PathBuf,
101}
102
103/// Configuration for one named upstream gRPC client (`[grpc.clients.<name>]`).
104///
105/// Each client is self-contained: its own proto contracts build its own descriptor
106/// pool (so two upstreams may declare same-named messages without colliding), its
107/// own endpoint address(es), TLS to the upstream, and call policy (deadline/retries).
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct ClientConfig {
110 /// Upstream address(es), `host:port`. A single string or a list; multiple
111 /// addresses enable client-side round-robin load balancing (phase 88 §1.4).
112 #[serde(deserialize_with = "one_or_many", default)]
113 pub address: Vec<String>,
114 /// Proto contracts for THIS upstream (files or directories, scanned
115 /// recursively). Builds this client's descriptor pool via the same path as the
116 /// server side (`build_descriptor_pool`). Imports resolve automatically.
117 #[serde(default)]
118 pub proto: Vec<String>,
119 /// Optional prebuilt `FileDescriptorSet` bundle merged into this client's pool
120 /// (same role as the server's `descriptor_set` — resolve `Any`/extra types).
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub descriptor_set: Option<String>,
123 /// TLS/mTLS to the upstream. Distinct from the server listener's TLS.
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub tls: Option<ClientTlsConfig>,
126 /// Default per-call deadline. A call may override it; if neither is set the
127 /// call has no client-imposed deadline (the worker still blocks — document).
128 #[serde(
129 default,
130 with = "humantime_serde",
131 skip_serializing_if = "Option::is_none"
132 )]
133 pub deadline: Option<Duration>,
134 /// Retry policy for transient/network failures (never for a business status).
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub retries: Option<RetryConfig>,
137}
138
139/// Upstream TLS/mTLS settings for a gRPC client.
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct ClientTlsConfig {
142 /// PEM CA certificate(s) to verify the upstream. When omitted, the platform's
143 /// system roots are used.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub ca: Option<PathBuf>,
146 /// PEM client certificate for mTLS (presenting an identity to the upstream).
147 /// Requires [`key`](Self::key).
148 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub cert: Option<PathBuf>,
150 /// PEM client private key for mTLS. Requires [`cert`](Self::cert).
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub key: Option<PathBuf>,
153 /// SNI / domain name to validate the upstream certificate against, when it
154 /// differs from the address host (e.g. behind a load balancer).
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub domain: Option<String>,
157}
158
159/// Retry policy for a gRPC client (phase 88 §1.4).
160///
161/// Applies only to transient/transport failures (`UNAVAILABLE`, connect timeout)
162/// and never to a business status returned by the upstream — retrying a
163/// non-idempotent call that already executed would double it.
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct RetryConfig {
166 /// Maximum total attempts, including the first. `1` (or absent policy) = no
167 /// retry. Default when the section is present: 3.
168 #[serde(default = "default_max_attempts")]
169 pub max_attempts: u32,
170 /// Base backoff between attempts; grows exponentially (`base * 2^(n-1)`).
171 /// Default: 100ms.
172 #[serde(default = "default_backoff", with = "humantime_serde")]
173 pub backoff: Duration,
174}
175
176fn default_max_attempts() -> u32 {
177 3
178}
179
180fn default_backoff() -> Duration {
181 Duration::from_millis(100)
182}
183
184/// Deserialize `address` accepting either a single `"host:port"` string or a list
185/// `["a:1", "b:2"]` — both yield a `Vec<String>`.
186fn one_or_many<'de, D>(de: D) -> Result<Vec<String>, D::Error>
187where
188 D: serde::Deserializer<'de>,
189{
190 #[derive(Deserialize)]
191 #[serde(untagged)]
192 enum OneOrMany {
193 One(String),
194 Many(Vec<String>),
195 }
196 Ok(match OneOrMany::deserialize(de)? {
197 OneOrMany::One(s) => vec![s],
198 OneOrMany::Many(v) => v,
199 })
200}
201
202/// HTTP/2 keepalive settings.
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct KeepaliveConfig {
205 /// HTTP/2 PING interval. Default: 60s.
206 #[serde(with = "humantime_serde")]
207 pub interval: Duration,
208 /// PING response timeout. Default: 20s.
209 #[serde(with = "humantime_serde")]
210 pub timeout: Duration,
211}
212
213impl Default for GrpcConfig {
214 fn default() -> Self {
215 Self {
216 listen: None,
217 proto: vec![],
218 descriptor_set: None,
219 transcode: false,
220 max_recv_message_size: 4 * 1024 * 1024, // 4 MiB
221 max_send_message_size: 4 * 1024 * 1024, // 4 MiB
222 timeout: None,
223 max_concurrent_streams: None,
224 keepalive: None,
225 tls: None,
226 compression: false,
227 clients: HashMap::new(),
228 }
229 }
230}
231
232pub fn parse_byte_size(s: &str) -> Result<usize, String> {
233 let s = s.trim().to_lowercase();
234
235 if let Ok(n) = s.parse::<usize>() {
236 return Ok(n);
237 }
238
239 let (num_part, multiplier) = if let Some(n) = s.strip_suffix("gib") {
240 (n, 1024 * 1024 * 1024)
241 } else if let Some(n) = s.strip_suffix("gb") {
242 (n, 1024 * 1024 * 1024)
243 } else if let Some(n) = s.strip_suffix("mib") {
244 (n, 1024 * 1024)
245 } else if let Some(n) = s.strip_suffix("mb") {
246 (n, 1024 * 1024)
247 } else if let Some(n) = s.strip_suffix("kib") {
248 (n, 1024)
249 } else if let Some(n) = s.strip_suffix("kb") {
250 (n, 1024)
251 } else if let Some(n) = s.strip_suffix("b") {
252 (n, 1)
253 } else {
254 return Err(format!("invalid byte size: {s:?}"));
255 };
256
257 let num: usize = num_part
258 .trim()
259 .parse()
260 .map_err(|_| format!("invalid byte size number: {num_part:?}"))?;
261
262 Ok(num * multiplier)
263}
264
265mod human_bytes {
266 use serde::{Deserialize, Deserializer, Serializer, de};
267
268 pub fn serialize<S: Serializer>(value: &usize, ser: S) -> Result<S::Ok, S::Error> {
269 ser.serialize_u64(*value as u64)
270 }
271
272 pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<usize, D::Error> {
273 #[derive(Deserialize)]
274 #[serde(untagged)]
275 enum ByteSize {
276 Str(String),
277 Num(usize),
278 }
279
280 match ByteSize::deserialize(de)? {
281 ByteSize::Num(n) => Ok(n),
282 ByteSize::Str(s) => super::parse_byte_size(&s).map_err(de::Error::custom),
283 }
284 }
285}