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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use std::io::{Read as _, Write as _};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::extract::State;
use axum::response::IntoResponse;
use base64::Engine;
use bytes::Bytes;
use folk_api::Executor;
use http::{HeaderMap, HeaderValue, Response};
use http_body::Frame;
use http_body_util::BodyExt;
use prost::Message as _;
use prost_reflect::{
    DescriptorPool, DeserializeOptions, DynamicMessage, MessageDescriptor, SerializeOptions,
};
use tracing::debug;

use crate::metrics::GrpcMetrics;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct GrpcEnvelope {
    pub service: String,
    pub method: String,
    pub payload: Vec<u8>,
    pub metadata: std::collections::HashMap<String, String>,
}

const B64: base64::engine::general_purpose::GeneralPurpose =
    base64::engine::general_purpose::STANDARD;

#[derive(Clone)]
pub struct GrpcState {
    pub executor: Arc<dyn Executor>,
    pub max_recv_message_size: usize,
    pub max_send_message_size: usize,
    pub compression: bool,
    pub metrics: Option<GrpcMetrics>,
    /// Descriptor pool for proto↔native transcoding (phase 87). `Some` only when
    /// `[grpc] transcode = true` and a pool was built (from `proto` and/or
    /// `descriptor_set`). `None` ⇒ raw passthrough: incoming bytes are base64'd to
    /// PHP and the response base64 is returned verbatim (legacy behaviour, BC).
    pub descriptors: Option<Arc<DescriptorPool>>,
}

pub async fn grpc_handler(
    State(state): State<GrpcState>,
    req: axum::extract::Request,
) -> impl IntoResponse {
    let tracker = state.metrics.as_ref().map(|m| m.track_start());

    let path = req.uri().path().to_string();

    let parts: Vec<&str> = path.trim_start_matches('/').splitn(2, '/').collect();
    let (service, method) = match parts.as_slice() {
        [s, m] => (s.to_string(), m.to_string()),
        _ => {
            if let Some(t) = tracker {
                t.finish("", "", 12, 0, 0);
            }
            return grpc_response(Bytes::new(), 12, "unimplemented: bad path", false);
        }
    };

    // Check if client accepts gzip
    let client_accepts_gzip = state.compression
        && req
            .headers()
            .get("grpc-accept-encoding")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.split(',').any(|e| e.trim() == "gzip"));

    // Collect application metadata as a multimap (repeated header keys preserved,
    // #fix) and split out call-info headers (phase 87 mid-tier Context):
    //   - grpc-timeout → relative deadline in seconds (advisory)
    //   - :authority   → authority()
    // Transport/pseudo headers are dropped from the app metadata.
    let mut metadata: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    let mut timeout_seconds: Option<f64> = None;
    for (k, v) in req.headers().iter() {
        let key = k.as_str();
        let Ok(val) = v.to_str() else { continue };
        if key == "grpc-timeout" {
            timeout_seconds = parse_grpc_timeout(val);
            continue;
        }
        if key.starts_with(':')
            || key == "content-type"
            || key == "te"
            || key == "user-agent"
            || key == "grpc-encoding"
            || key == "grpc-accept-encoding"
        {
            continue;
        }
        metadata
            .entry(key.to_string())
            .or_default()
            .push(val.to_string());
    }

    // `:authority` is folded into the request URI by hyper; fall back to Host.
    let authority: Option<String> = req
        .uri()
        .authority()
        .map(|a| a.as_str().to_string())
        .or_else(|| {
            req.headers()
                .get("host")
                .and_then(|v| v.to_str().ok())
                .map(str::to_string)
        });

    // Peer address from tonic's connect-info (advisory; behind a proxy this is the
    // proxy's address — the real client arrives via X-Forwarded-For, like HTTP).
    let peer_address: Option<String> = req
        .extensions()
        .get::<tonic::transport::server::TcpConnectInfo>()
        .and_then(|ci| ci.remote_addr())
        .map(|addr| addr.to_string());

    // Correlation id for this call (UUID v7). The HTTP path gets one from the
    // bridge; the gRPC path did not — generate one here so PHP logs can correlate.
    let request_id = uuid::Uuid::now_v7().to_string();

    let body_bytes = match req.into_body().collect().await {
        Ok(collected) => collected.to_bytes(),
        Err(e) => {
            if let Some(t) = tracker {
                t.finish(&service, &method, 13, 0, 0);
            }
            return grpc_response(Bytes::new(), 13, &format!("body: {e}"), false);
        }
    };

    if body_bytes.len() < 5 {
        if let Some(t) = tracker {
            t.finish(&service, &method, 13, 0, 0);
        }
        return grpc_response(Bytes::new(), 13, "incomplete gRPC frame", false);
    }

    // Parse gRPC frame: [compression_flag(1)][length(4)][payload]
    let compressed = body_bytes[0] == 1;
    let raw_payload = body_bytes.slice(5..);

    // Decompress incoming if needed (size-limited to prevent zip bombs)
    let proto_bytes = if compressed {
        match gzip_decompress(&raw_payload, state.max_recv_message_size) {
            Ok(decompressed) => Bytes::from(decompressed),
            Err(e) => {
                if let Some(t) = tracker {
                    t.finish(&service, &method, 8, raw_payload.len(), 0);
                }
                return grpc_response(
                    Bytes::new(),
                    8, // RESOURCE_EXHAUSTED
                    &format!("decompress: {e}"),
                    false,
                );
            }
        }
    } else {
        raw_payload
    };

    let recv_bytes = proto_bytes.len();

    // Enforce max incoming message size (uncompressed payloads)
    if recv_bytes > state.max_recv_message_size {
        if let Some(t) = tracker {
            t.finish(&service, &method, 8, recv_bytes, 0);
        }
        return grpc_response(
            Bytes::new(),
            8, // RESOURCE_EXHAUSTED
            &format!(
                "received message larger than max ({recv_bytes} vs {} bytes)",
                state.max_recv_message_size
            ),
            false,
        );
    }

    debug!(service, method, payload_len = recv_bytes, "gRPC call");

    // Resolve the method descriptor when transcoding is enabled. A method absent
    // from the pool is UNIMPLEMENTED (12) — the client asked for something the
    // configured protos don't describe.
    let method_desc = match &state.descriptors {
        Some(pool) => match pool
            .get_service_by_name(&service)
            .and_then(|svc| svc.methods().find(|m| m.name() == method))
        {
            Some(m) => Some(m),
            None => {
                if let Some(t) = tracker {
                    t.finish(&service, &method, 12, recv_bytes, 0);
                }
                return grpc_response(
                    Bytes::new(),
                    12,
                    "unimplemented: method not in descriptor pool",
                    false,
                );
            }
        },
        None => None,
    };

    // Build the worker payload. Transcode mode decodes the incoming protobuf into
    // a structured JSON message (`message` + `encoding: "json"`); passthrough mode
    // forwards the raw bytes as base64 (`payload`) — the legacy contract.
    let payload_value = if let Some(m) = &method_desc {
        let message = match proto_to_json(&m.input(), &proto_bytes) {
            Ok(v) => v,
            Err(e) => {
                if let Some(t) = tracker {
                    t.finish(&service, &method, 3, recv_bytes, 0);
                }
                // INVALID_ARGUMENT: the bytes don't match the declared message.
                return grpc_response(Bytes::new(), 3, &format!("transcode request: {e}"), false);
            }
        };
        serde_json::json!({
            "service": service,
            "method": method,
            "message": message,
            "encoding": "json",
            "metadata": metadata,
            "request_id": request_id,
            "timeout_seconds": timeout_seconds,
            "peer_address": peer_address,
            "authority": authority,
        })
    } else {
        serde_json::json!({
            "service": service,
            "method": method,
            "payload": B64.encode(&proto_bytes),
            "metadata": metadata,
            "request_id": request_id,
            "timeout_seconds": timeout_seconds,
            "peer_address": peer_address,
            "authority": authority,
        })
    };

    let response_value = match state
        .executor
        .execute_value("grpc.call", payload_value)
        .await
    {
        Ok(v) => v,
        Err(e) => {
            if let Some(t) = tracker {
                t.finish(&service, &method, 13, recv_bytes, 0);
            }
            return grpc_response(Bytes::new(), 13, &format!("worker: {e}"), false);
        }
    };

    // Business status set by PHP via $context->setStatus($code, $msg) arrives
    // as {__grpc_status, __grpc_message}. The code is already a canonical gRPC
    // code (google.rpc.Code) — pass it through, clamped to the valid range.
    if let serde_json::Value::Object(map) = &response_value {
        if let Some(status_val) = map.get("__grpc_status") {
            let code = status_val
                .as_u64()
                .filter(|c| *c <= 16)
                .map_or(13, |c| c as u32);
            let message = map
                .get("__grpc_message")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            debug!(service, method, code, "gRPC business status from handler");
            if let Some(t) = tracker {
                t.finish(&service, &method, code, recv_bytes, 0);
            }
            return grpc_response(Bytes::new(), code, &message, false);
        }
    }

    // Produce response protobuf bytes. Transcode mode expects a structured message
    // under `__message` and re-encodes it via the output descriptor; passthrough
    // mode expects base64 (a bare string, or `__result`/`result`).
    let proto_response: Vec<u8> = if let Some(m) = &method_desc {
        let message = match &response_value {
            serde_json::Value::Object(map) => map.get("__message"),
            _ => None,
        };
        let Some(message) = message else {
            if let Some(t) = tracker {
                t.finish(&service, &method, 13, recv_bytes, 0);
            }
            return grpc_response(
                Bytes::new(),
                13,
                "transcode handler returned no message",
                false,
            );
        };
        match json_to_proto(&m.output(), message) {
            Ok(bytes) => bytes,
            Err(e) => {
                if let Some(t) = tracker {
                    t.finish(&service, &method, 13, recv_bytes, 0);
                }
                return grpc_response(Bytes::new(), 13, &format!("transcode response: {e}"), false);
            }
        }
    } else {
        // Extract response: a string directly, or wrapped in {"__result": "..."}
        let response_str = match &response_value {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Object(map) => {
                if let Some(serde_json::Value::String(s)) = map.get("__result") {
                    s.clone()
                } else if let Some(serde_json::Value::String(s)) = map.get("result") {
                    s.clone()
                } else {
                    if let Some(t) = tracker {
                        t.finish(&service, &method, 13, recv_bytes, 0);
                    }
                    return grpc_response(
                        Bytes::new(),
                        13,
                        &format!("unexpected response: {response_value}"),
                        false,
                    );
                }
            }
            other => {
                if let Some(t) = tracker {
                    t.finish(&service, &method, 13, recv_bytes, 0);
                }
                return grpc_response(
                    Bytes::new(),
                    13,
                    &format!("unexpected response type: {other}"),
                    false,
                );
            }
        };

        // Decode base64 protobuf bytes
        match B64.decode(&response_str) {
            Ok(bytes) => bytes,
            Err(e) => {
                tracing::warn!(error = %e, "base64 decode failed for gRPC response, returning INTERNAL");
                if let Some(t) = tracker {
                    t.finish(&service, &method, 13, recv_bytes, 0);
                }
                return grpc_response(
                    Bytes::new(),
                    13, // INTERNAL
                    "PHP worker returned invalid base64 response",
                    false,
                );
            }
        }
    };

    let sent_bytes = proto_response.len();

    // Enforce max outgoing message size
    if sent_bytes > state.max_send_message_size {
        if let Some(t) = tracker {
            t.finish(&service, &method, 8, recv_bytes, sent_bytes);
        }
        return grpc_response(
            Bytes::new(),
            8, // RESOURCE_EXHAUSTED
            &format!(
                "response larger than max ({sent_bytes} vs {} bytes)",
                state.max_send_message_size
            ),
            false,
        );
    }

    // Build gRPC-framed response (optionally compressed)
    if client_accepts_gzip {
        if let Ok(compressed_data) = gzip_compress(&proto_response) {
            let mut framed = Vec::with_capacity(5 + compressed_data.len());
            framed.push(1u8); // compression flag
            framed.extend_from_slice(&(compressed_data.len() as u32).to_be_bytes());
            framed.extend_from_slice(&compressed_data);
            if let Some(t) = tracker {
                t.finish(&service, &method, 0, recv_bytes, sent_bytes);
            }
            return grpc_response(Bytes::from(framed), 0, "", true);
        }
    }

    let mut framed = Vec::with_capacity(5 + proto_response.len());
    framed.push(0u8);
    framed.extend_from_slice(&(proto_response.len() as u32).to_be_bytes());
    framed.extend_from_slice(&proto_response);

    if let Some(t) = tracker {
        t.finish(&service, &method, 0, recv_bytes, sent_bytes);
    }
    grpc_response(Bytes::from(framed), 0, "", false)
}

/// Parse a gRPC `grpc-timeout` header value into a relative deadline in seconds.
///
/// Format is ASCII digits followed by a single unit char: `H`ours, `M`inutes,
/// `S`econds, `m`illis, `u`micros, `n`anos (grpc-over-HTTP2 spec). Returns `None`
/// for a malformed value — the deadline is advisory, so a bad header is ignored
/// rather than failing the call.
pub fn parse_grpc_timeout(v: &str) -> Option<f64> {
    let v = v.trim();
    if v.len() < 2 {
        return None;
    }
    let (num, unit) = v.split_at(v.len() - 1);
    let n: f64 = num.parse().ok()?;
    let secs = match unit {
        "H" => n * 3600.0,
        "M" => n * 60.0,
        "S" => n,
        "m" => n / 1_000.0,
        "u" => n / 1_000_000.0,
        "n" => n / 1_000_000_000.0,
        _ => return None,
    };
    Some(secs)
}

/// Decode protobuf bytes into a canonical-JSON value (proto→native, request
/// side). Errors if the bytes don't match `desc` or can't be serialized.
pub fn proto_to_json(desc: &MessageDescriptor, bytes: &[u8]) -> anyhow::Result<serde_json::Value> {
    let dynamic = DynamicMessage::decode(desc.clone(), bytes)?;
    let value = dynamic.serialize_with_options(
        serde_json::value::Serializer,
        &transcode_serialize_options(),
    )?;
    Ok(value)
}

/// Encode a canonical-JSON value into protobuf bytes (native→proto, response
/// side). Errors if the value doesn't fit `desc`.
pub fn json_to_proto(
    desc: &MessageDescriptor,
    value: &serde_json::Value,
) -> anyhow::Result<Vec<u8>> {
    let dynamic = DynamicMessage::deserialize_with_options(
        desc.clone(),
        value,
        &transcode_deserialize_options(),
    )?;
    Ok(dynamic.encode_to_vec())
}

/// Serialize options for proto→native (request). `use_proto_field_name` keeps
/// snake_case keys matching generated DTO properties; `use_enum_numbers` emits
/// enums as ints so PHP `enum: int` can `tryFrom` them (not the enum name);
/// 64-bit ints stay JSON numbers (not canonical-JSON strings) so PHP receives
/// plain `int` (uint64 > 2^63 edge is documented). bytes are still emitted as
/// base64 (decision 3).
fn transcode_serialize_options() -> SerializeOptions {
    SerializeOptions::new()
        .use_proto_field_name(true)
        .use_enum_numbers(true)
        .stringify_64_bit_integers(false)
}

/// Deserialize options for native→proto (response). Accepts both snake_case and
/// camelCase field names (protobuf JSON); unknown fields are ignored so a DTO
/// that omits or adds keys is tolerated rather than rejected.
fn transcode_deserialize_options() -> DeserializeOptions {
    DeserializeOptions::new().deny_unknown_fields(false)
}

fn grpc_response(data: Bytes, status: u32, message: &str, gzip: bool) -> Response<GrpcBody> {
    let mut trailers = HeaderMap::new();
    trailers.insert("grpc-status", HeaderValue::from(status));
    if !message.is_empty() {
        if let Ok(v) = HeaderValue::from_str(message) {
            trailers.insert("grpc-message", v);
        }
    }

    let mut builder = Response::builder()
        .status(200)
        .header("content-type", "application/grpc");

    if gzip {
        builder = builder.header("grpc-encoding", "gzip");
    }

    builder
        .body(GrpcBody {
            data: Some(data),
            trailers: Some(trailers),
        })
        .unwrap()
}

fn gzip_decompress(data: &[u8], limit: usize) -> std::io::Result<Vec<u8>> {
    let decoder = flate2::read::GzDecoder::new(data);
    let mut out = Vec::new();
    decoder.take(limit as u64 + 1).read_to_end(&mut out)?;
    if out.len() > limit {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("decompressed message exceeds limit ({limit} bytes)"),
        ));
    }
    Ok(out)
}

fn gzip_compress(data: &[u8]) -> std::io::Result<Vec<u8>> {
    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
    encoder.write_all(data)?;
    encoder.finish()
}

/// Custom body type that sends data followed by gRPC trailers.
pub struct GrpcBody {
    data: Option<Bytes>,
    trailers: Option<HeaderMap>,
}

impl http_body::Body for GrpcBody {
    type Data = Bytes;
    type Error = std::convert::Infallible;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        if let Some(data) = self.data.take() {
            if !data.is_empty() {
                return Poll::Ready(Some(Ok(Frame::data(data))));
            }
        }
        if let Some(trailers) = self.trailers.take() {
            return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
        }
        Poll::Ready(None)
    }
}