Skip to main content

folk_plugin_grpc/
service.rs

1use std::io::{Read as _, Write as _};
2use std::pin::Pin;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicUsize, Ordering};
5use std::task::{Context, Poll};
6
7use axum::extract::State;
8use axum::response::IntoResponse;
9use base64::Engine;
10use bytes::{Bytes, BytesMut};
11use folk_api::{Executor, ResponseChunk};
12use http::{HeaderMap, HeaderValue, Response};
13use http_body::Frame;
14use http_body_util::BodyExt;
15use prost::Message as _;
16use prost_reflect::{
17    DescriptorPool, DeserializeOptions, DynamicMessage, MessageDescriptor, MethodDescriptor,
18    SerializeOptions,
19};
20use tokio::sync::mpsc;
21use tracing::debug;
22
23use crate::metrics::{GrpcMetrics, RequestTracker};
24
25#[derive(serde::Serialize, serde::Deserialize, Debug)]
26pub struct GrpcEnvelope {
27    pub service: String,
28    pub method: String,
29    pub payload: Vec<u8>,
30    pub metadata: std::collections::HashMap<String, String>,
31}
32
33const B64: base64::engine::general_purpose::GeneralPurpose =
34    base64::engine::general_purpose::STANDARD;
35
36#[derive(Clone)]
37pub struct GrpcState {
38    pub executor: Arc<dyn Executor>,
39    pub max_recv_message_size: usize,
40    pub max_send_message_size: usize,
41    pub compression: bool,
42    pub metrics: Option<GrpcMetrics>,
43    /// Descriptor pool for proto↔native transcoding (phase 87). `Some` only when
44    /// `[grpc] transcode = true` and a pool was built (from `proto` and/or
45    /// `descriptor_set`). `None` ⇒ raw passthrough: incoming bytes are base64'd to
46    /// PHP and the response base64 is returned verbatim (legacy behaviour, BC).
47    pub descriptors: Option<Arc<DescriptorPool>>,
48}
49
50pub async fn grpc_handler(
51    State(state): State<GrpcState>,
52    req: axum::extract::Request,
53) -> impl IntoResponse {
54    let tracker = state.metrics.as_ref().map(|m| m.track_start());
55
56    let path = req.uri().path().to_string();
57
58    let parts: Vec<&str> = path.trim_start_matches('/').splitn(2, '/').collect();
59    let (service, method) = match parts.as_slice() {
60        [s, m] => (s.to_string(), m.to_string()),
61        _ => {
62            if let Some(t) = tracker {
63                t.finish("", "", 12, 0, 0);
64            }
65            return grpc_response(Bytes::new(), 12, "unimplemented: bad path", false);
66        }
67    };
68
69    // Check if client accepts gzip
70    let client_accepts_gzip = state.compression
71        && req
72            .headers()
73            .get("grpc-accept-encoding")
74            .and_then(|v| v.to_str().ok())
75            .is_some_and(|v| v.split(',').any(|e| e.trim() == "gzip"));
76
77    // Collect application metadata as a multimap (repeated header keys preserved,
78    // #fix) and split out call-info headers (phase 87 mid-tier Context):
79    //   - grpc-timeout → relative deadline in seconds (advisory)
80    //   - :authority   → authority()
81    // Transport/pseudo headers are dropped from the app metadata.
82    let mut metadata: std::collections::HashMap<String, Vec<String>> =
83        std::collections::HashMap::new();
84    let mut timeout_seconds: Option<f64> = None;
85    for (k, v) in req.headers().iter() {
86        let key = k.as_str();
87        let Ok(val) = v.to_str() else { continue };
88        if key == "grpc-timeout" {
89            timeout_seconds = parse_grpc_timeout(val);
90            continue;
91        }
92        if key.starts_with(':')
93            || key == "content-type"
94            || key == "te"
95            || key == "user-agent"
96            || key == "grpc-encoding"
97            || key == "grpc-accept-encoding"
98        {
99            continue;
100        }
101        metadata
102            .entry(key.to_string())
103            .or_default()
104            .push(val.to_string());
105    }
106
107    // `:authority` is folded into the request URI by hyper; fall back to Host.
108    let authority: Option<String> = req
109        .uri()
110        .authority()
111        .map(|a| a.as_str().to_string())
112        .or_else(|| {
113            req.headers()
114                .get("host")
115                .and_then(|v| v.to_str().ok())
116                .map(str::to_string)
117        });
118
119    // Peer address from tonic's connect-info (advisory; behind a proxy this is the
120    // proxy's address — the real client arrives via X-Forwarded-For, like HTTP).
121    let peer_address: Option<String> = req
122        .extensions()
123        .get::<tonic::transport::server::TcpConnectInfo>()
124        .and_then(|ci| ci.remote_addr())
125        .map(|addr| addr.to_string());
126
127    // Correlation id for this call (UUID v7). The HTTP path gets one from the
128    // bridge; the gRPC path did not — generate one here so PHP logs can correlate.
129    let request_id = uuid::Uuid::now_v7().to_string();
130
131    // Client-streaming / bidi (phase 94, #92): the PHP handler consumes a stream
132    // of inbound request messages. Detect the method kind BEFORE buffering the
133    // body — these calls stream the body in incrementally rather than collecting
134    // it. Only reachable in transcode mode (passthrough can't detect the kind — a
135    // documented v1 limitation shared with server-streaming).
136    if let Some(m) = state.descriptors.as_ref().and_then(|pool| {
137        pool.get_service_by_name(&service)
138            .and_then(|svc| svc.methods().find(|mm| mm.name() == method))
139            .filter(prost_reflect::MethodDescriptor::is_client_streaming)
140    }) {
141        return serve_inbound_streaming(
142            &state,
143            req,
144            service,
145            method,
146            m,
147            metadata,
148            timeout_seconds,
149            authority,
150            peer_address,
151            request_id,
152            client_accepts_gzip,
153            tracker,
154        )
155        .await;
156    }
157
158    let body_bytes = match req.into_body().collect().await {
159        Ok(collected) => collected.to_bytes(),
160        Err(e) => {
161            if let Some(t) = tracker {
162                t.finish(&service, &method, 13, 0, 0);
163            }
164            return grpc_response(Bytes::new(), 13, &format!("body: {e}"), false);
165        }
166    };
167
168    if body_bytes.len() < 5 {
169        if let Some(t) = tracker {
170            t.finish(&service, &method, 13, 0, 0);
171        }
172        return grpc_response(Bytes::new(), 13, "incomplete gRPC frame", false);
173    }
174
175    // Parse gRPC frame: [compression_flag(1)][length(4)][payload]
176    let compressed = body_bytes[0] == 1;
177    let raw_payload = body_bytes.slice(5..);
178
179    // Decompress incoming if needed (size-limited to prevent zip bombs)
180    let proto_bytes = if compressed {
181        match gzip_decompress(&raw_payload, state.max_recv_message_size) {
182            Ok(decompressed) => Bytes::from(decompressed),
183            Err(e) => {
184                if let Some(t) = tracker {
185                    t.finish(&service, &method, 8, raw_payload.len(), 0);
186                }
187                return grpc_response(
188                    Bytes::new(),
189                    8, // RESOURCE_EXHAUSTED
190                    &format!("decompress: {e}"),
191                    false,
192                );
193            }
194        }
195    } else {
196        raw_payload
197    };
198
199    let recv_bytes = proto_bytes.len();
200
201    // Enforce max incoming message size (uncompressed payloads)
202    if recv_bytes > state.max_recv_message_size {
203        if let Some(t) = tracker {
204            t.finish(&service, &method, 8, recv_bytes, 0);
205        }
206        return grpc_response(
207            Bytes::new(),
208            8, // RESOURCE_EXHAUSTED
209            &format!(
210                "received message larger than max ({recv_bytes} vs {} bytes)",
211                state.max_recv_message_size
212            ),
213            false,
214        );
215    }
216
217    debug!(service, method, payload_len = recv_bytes, "gRPC call");
218
219    // Resolve the method descriptor when transcoding is enabled. A method absent
220    // from the pool is UNIMPLEMENTED (12) — the client asked for something the
221    // configured protos don't describe.
222    let method_desc = match &state.descriptors {
223        Some(pool) => match pool
224            .get_service_by_name(&service)
225            .and_then(|svc| svc.methods().find(|m| m.name() == method))
226        {
227            Some(m) => Some(m),
228            None => {
229                if let Some(t) = tracker {
230                    t.finish(&service, &method, 12, recv_bytes, 0);
231                }
232                return grpc_response(
233                    Bytes::new(),
234                    12,
235                    "unimplemented: method not in descriptor pool",
236                    false,
237                );
238            }
239        },
240        None => None,
241    };
242
243    // Build the worker payload. Transcode mode decodes the incoming protobuf into
244    // a structured JSON message (`message` + `encoding: "json"`); passthrough mode
245    // forwards the raw bytes as base64 (`payload`) — the legacy contract.
246    let payload_value = if let Some(m) = &method_desc {
247        let message = match proto_to_json(&m.input(), &proto_bytes) {
248            Ok(v) => v,
249            Err(e) => {
250                if let Some(t) = tracker {
251                    t.finish(&service, &method, 3, recv_bytes, 0);
252                }
253                // INVALID_ARGUMENT: the bytes don't match the declared message.
254                return grpc_response(Bytes::new(), 3, &format!("transcode request: {e}"), false);
255            }
256        };
257        serde_json::json!({
258            "service": service,
259            "method": method,
260            "message": message,
261            "encoding": "json",
262            "metadata": metadata,
263            "request_id": request_id,
264            "timeout_seconds": timeout_seconds,
265            "peer_address": peer_address,
266            "authority": authority,
267        })
268    } else {
269        serde_json::json!({
270            "service": service,
271            "method": method,
272            "payload": B64.encode(&proto_bytes),
273            "metadata": metadata,
274            "request_id": request_id,
275            "timeout_seconds": timeout_seconds,
276            "peer_address": peer_address,
277            "authority": authority,
278        })
279    };
280
281    // Server-streaming (phase 88b, #32): the PHP handler yields N response
282    // messages. Only reachable in transcode mode — passthrough has no descriptor
283    // to detect the method kind, so a streaming method configured without protos
284    // falls through to the unary path (documented v1 limitation). Reuses the
285    // `ResponseChunk` stream (`execute_streamed`): each `Return` is one message.
286    if let Some(m) = &method_desc {
287        if m.is_server_streaming() {
288            return serve_server_streaming(
289                &state,
290                service,
291                method,
292                payload_value,
293                m.output(),
294                client_accepts_gzip,
295                recv_bytes,
296                tracker,
297            )
298            .await;
299        }
300    }
301
302    let response_value = match state
303        .executor
304        .execute_value("grpc.call", payload_value)
305        .await
306    {
307        Ok(v) => v,
308        Err(e) => {
309            if let Some(t) = tracker {
310                t.finish(&service, &method, 13, recv_bytes, 0);
311            }
312            return grpc_response(Bytes::new(), 13, &format!("worker: {e}"), false);
313        }
314    };
315
316    // Business status set by PHP via $context->setStatus($code, $msg) arrives
317    // as {__grpc_status, __grpc_message}. The code is already a canonical gRPC
318    // code (google.rpc.Code) — pass it through, clamped to the valid range.
319    if let serde_json::Value::Object(map) = &response_value {
320        if let Some(status_val) = map.get("__grpc_status") {
321            let code = status_val
322                .as_u64()
323                .filter(|c| *c <= 16)
324                .map_or(13, |c| c as u32);
325            let message = map
326                .get("__grpc_message")
327                .and_then(|v| v.as_str())
328                .unwrap_or("")
329                .to_string();
330            debug!(service, method, code, "gRPC business status from handler");
331            if let Some(t) = tracker {
332                t.finish(&service, &method, code, recv_bytes, 0);
333            }
334            return grpc_response(Bytes::new(), code, &message, false);
335        }
336    }
337
338    // Produce response protobuf bytes. Transcode mode expects a structured message
339    // under `__message` and re-encodes it via the output descriptor; passthrough
340    // mode expects base64 (a bare string, or `__result`/`result`).
341    let proto_response: Vec<u8> = if let Some(m) = &method_desc {
342        let message = match &response_value {
343            serde_json::Value::Object(map) => map.get("__message"),
344            _ => None,
345        };
346        let Some(message) = message else {
347            if let Some(t) = tracker {
348                t.finish(&service, &method, 13, recv_bytes, 0);
349            }
350            return grpc_response(
351                Bytes::new(),
352                13,
353                "transcode handler returned no message",
354                false,
355            );
356        };
357        match json_to_proto(&m.output(), message) {
358            Ok(bytes) => bytes,
359            Err(e) => {
360                if let Some(t) = tracker {
361                    t.finish(&service, &method, 13, recv_bytes, 0);
362                }
363                return grpc_response(Bytes::new(), 13, &format!("transcode response: {e}"), false);
364            }
365        }
366    } else {
367        // Extract response: a string directly, or wrapped in {"__result": "..."}
368        let response_str = match &response_value {
369            serde_json::Value::String(s) => s.clone(),
370            serde_json::Value::Object(map) => {
371                if let Some(serde_json::Value::String(s)) = map.get("__result") {
372                    s.clone()
373                } else if let Some(serde_json::Value::String(s)) = map.get("result") {
374                    s.clone()
375                } else {
376                    if let Some(t) = tracker {
377                        t.finish(&service, &method, 13, recv_bytes, 0);
378                    }
379                    return grpc_response(
380                        Bytes::new(),
381                        13,
382                        &format!("unexpected response: {response_value}"),
383                        false,
384                    );
385                }
386            }
387            other => {
388                if let Some(t) = tracker {
389                    t.finish(&service, &method, 13, recv_bytes, 0);
390                }
391                return grpc_response(
392                    Bytes::new(),
393                    13,
394                    &format!("unexpected response type: {other}"),
395                    false,
396                );
397            }
398        };
399
400        // Decode base64 protobuf bytes
401        match B64.decode(&response_str) {
402            Ok(bytes) => bytes,
403            Err(e) => {
404                tracing::warn!(error = %e, "base64 decode failed for gRPC response, returning INTERNAL");
405                if let Some(t) = tracker {
406                    t.finish(&service, &method, 13, recv_bytes, 0);
407                }
408                return grpc_response(
409                    Bytes::new(),
410                    13, // INTERNAL
411                    "PHP worker returned invalid base64 response",
412                    false,
413                );
414            }
415        }
416    };
417
418    let sent_bytes = proto_response.len();
419
420    // Enforce max outgoing message size
421    if sent_bytes > state.max_send_message_size {
422        if let Some(t) = tracker {
423            t.finish(&service, &method, 8, recv_bytes, sent_bytes);
424        }
425        return grpc_response(
426            Bytes::new(),
427            8, // RESOURCE_EXHAUSTED
428            &format!(
429                "response larger than max ({sent_bytes} vs {} bytes)",
430                state.max_send_message_size
431            ),
432            false,
433        );
434    }
435
436    // Build gRPC-framed response (optionally compressed)
437    if client_accepts_gzip {
438        if let Ok(compressed_data) = gzip_compress(&proto_response) {
439            let mut framed = Vec::with_capacity(5 + compressed_data.len());
440            framed.push(1u8); // compression flag
441            framed.extend_from_slice(&(compressed_data.len() as u32).to_be_bytes());
442            framed.extend_from_slice(&compressed_data);
443            if let Some(t) = tracker {
444                t.finish(&service, &method, 0, recv_bytes, sent_bytes);
445            }
446            return grpc_response(Bytes::from(framed), 0, "", true);
447        }
448    }
449
450    let mut framed = Vec::with_capacity(5 + proto_response.len());
451    framed.push(0u8);
452    framed.extend_from_slice(&(proto_response.len() as u32).to_be_bytes());
453    framed.extend_from_slice(&proto_response);
454
455    if let Some(t) = tracker {
456        t.finish(&service, &method, 0, recv_bytes, sent_bytes);
457    }
458    grpc_response(Bytes::from(framed), 0, "", false)
459}
460
461/// Parse a gRPC `grpc-timeout` header value into a relative deadline in seconds.
462///
463/// Format is ASCII digits followed by a single unit char: `H`ours, `M`inutes,
464/// `S`econds, `m`illis, `u`micros, `n`anos (grpc-over-HTTP2 spec). Returns `None`
465/// for a malformed value — the deadline is advisory, so a bad header is ignored
466/// rather than failing the call.
467pub fn parse_grpc_timeout(v: &str) -> Option<f64> {
468    let v = v.trim();
469    if v.len() < 2 {
470        return None;
471    }
472    let (num, unit) = v.split_at(v.len() - 1);
473    let n: f64 = num.parse().ok()?;
474    let secs = match unit {
475        "H" => n * 3600.0,
476        "M" => n * 60.0,
477        "S" => n,
478        "m" => n / 1_000.0,
479        "u" => n / 1_000_000.0,
480        "n" => n / 1_000_000_000.0,
481        _ => return None,
482    };
483    Some(secs)
484}
485
486/// Decode protobuf bytes into a canonical-JSON value (proto→native, request
487/// side). Errors if the bytes don't match `desc` or can't be serialized.
488pub fn proto_to_json(desc: &MessageDescriptor, bytes: &[u8]) -> anyhow::Result<serde_json::Value> {
489    let dynamic = DynamicMessage::decode(desc.clone(), bytes)?;
490    let value = dynamic.serialize_with_options(
491        serde_json::value::Serializer,
492        &transcode_serialize_options(),
493    )?;
494    Ok(value)
495}
496
497/// Encode a canonical-JSON value into protobuf bytes (native→proto, response
498/// side). Errors if the value doesn't fit `desc`.
499pub fn json_to_proto(
500    desc: &MessageDescriptor,
501    value: &serde_json::Value,
502) -> anyhow::Result<Vec<u8>> {
503    let dynamic = DynamicMessage::deserialize_with_options(
504        desc.clone(),
505        value,
506        &transcode_deserialize_options(),
507    )?;
508    Ok(dynamic.encode_to_vec())
509}
510
511/// Serialize options for proto→native (request). `use_proto_field_name` keeps
512/// snake_case keys matching generated DTO properties; `use_enum_numbers` emits
513/// enums as ints so PHP `enum: int` can `tryFrom` them (not the enum name);
514/// 64-bit ints stay JSON numbers (not canonical-JSON strings) so PHP receives
515/// plain `int` (uint64 > 2^63 edge is documented). bytes are still emitted as
516/// base64 (decision 3).
517fn transcode_serialize_options() -> SerializeOptions {
518    SerializeOptions::new()
519        .use_proto_field_name(true)
520        .use_enum_numbers(true)
521        .stringify_64_bit_integers(false)
522}
523
524/// Deserialize options for native→proto (response). Accepts both snake_case and
525/// camelCase field names (protobuf JSON); unknown fields are ignored so a DTO
526/// that omits or adds keys is tolerated rather than rejected.
527fn transcode_deserialize_options() -> DeserializeOptions {
528    DeserializeOptions::new().deny_unknown_fields(false)
529}
530
531/// Build the gRPC trailer map (`grpc-status` + optional `grpc-message`) that
532/// terminates every response — unary and streaming alike.
533fn grpc_trailers(status: u32, message: &str) -> HeaderMap {
534    let mut trailers = HeaderMap::new();
535    trailers.insert("grpc-status", HeaderValue::from(status));
536    if !message.is_empty() {
537        if let Ok(v) = HeaderValue::from_str(message) {
538            trailers.insert("grpc-message", v);
539        }
540    }
541    trailers
542}
543
544/// Frame one protobuf message as a length-prefixed gRPC data frame
545/// (`[compression_flag(1)][length(4, BE)][payload]`), gzip-compressing the
546/// payload when the client accepted gzip and compression succeeds.
547fn frame_message(proto: &[u8], gzip: bool) -> Bytes {
548    if gzip {
549        if let Ok(compressed) = gzip_compress(proto) {
550            let mut framed = Vec::with_capacity(5 + compressed.len());
551            framed.push(1u8);
552            framed.extend_from_slice(&(compressed.len() as u32).to_be_bytes());
553            framed.extend_from_slice(&compressed);
554            return Bytes::from(framed);
555        }
556    }
557    let mut framed = Vec::with_capacity(5 + proto.len());
558    framed.push(0u8);
559    framed.extend_from_slice(&(proto.len() as u32).to_be_bytes());
560    framed.extend_from_slice(proto);
561    Bytes::from(framed)
562}
563
564fn grpc_response(data: Bytes, status: u32, message: &str, gzip: bool) -> Response<GrpcBody> {
565    let mut builder = Response::builder()
566        .status(200)
567        .header("content-type", "application/grpc");
568
569    if gzip {
570        builder = builder.header("grpc-encoding", "gzip");
571    }
572
573    builder
574        .body(GrpcBody::Single {
575            data: Some(data),
576            trailers: Some(grpc_trailers(status, message)),
577        })
578        .unwrap()
579}
580
581/// Drive a server-streaming (phase 88b, #32) gRPC call: the PHP handler yields
582/// `N` response messages, delivered here as a stream of [`ResponseChunk`]s from
583/// [`Executor::execute_streamed`]. Each `Return` becomes one gRPC data frame;
584/// the stream terminates with OK trailers (or an error/business status).
585///
586/// A setup failure (worker never started) collapses to a single-frame error
587/// response — mirroring the unary path — so the handler never emits `Err`.
588#[allow(clippy::too_many_arguments)]
589async fn serve_server_streaming(
590    state: &GrpcState,
591    service: String,
592    method: String,
593    payload_value: serde_json::Value,
594    output: MessageDescriptor,
595    gzip: bool,
596    recv_bytes: usize,
597    tracker: Option<RequestTracker>,
598) -> Response<GrpcBody> {
599    let rx = match state
600        .executor
601        .execute_streamed("grpc.call", payload_value)
602        .await
603    {
604        Ok((rx, _id)) => rx,
605        Err(e) => {
606            if let Some(t) = tracker {
607                t.finish(&service, &method, 13, recv_bytes, 0);
608            }
609            return grpc_response(Bytes::new(), 13, &format!("worker: {e}"), false);
610        }
611    };
612
613    let body = GrpcBody::Stream(Box::new(GrpcStreamBody {
614        rx,
615        output,
616        gzip,
617        max_send: state.max_send_message_size,
618        service,
619        method,
620        recv_bytes,
621        recv_counter: None,
622        sent_bytes: 0,
623        tracker,
624        done: false,
625    }));
626
627    let mut builder = Response::builder()
628        .status(200)
629        .header("content-type", "application/grpc");
630    if gzip {
631        builder = builder.header("grpc-encoding", "gzip");
632    }
633    builder.body(body).unwrap()
634}
635
636/// Drive a **client-streaming** or **bidi** (phase 94, #92) gRPC call: the PHP
637/// handler consumes a stream of inbound request messages (`iterable $requests`).
638///
639/// Unlike unary/server-streaming (which buffer the single request), the incoming
640/// HTTP/2 body is read incrementally: a spawned task de-frames each gRPC message,
641/// transcodes it to one JSON message, and hands it to the worker through
642/// [`Executor::execute_streamed_with_body`]; PHP pulls them with `folk_grpc_recv`.
643/// Client-streaming produces a single response (buffered `GrpcBody::Single`, like
644/// unary); bidi produces a message stream (reusing [`GrpcStreamBody`]).
645#[allow(clippy::too_many_arguments)]
646async fn serve_inbound_streaming(
647    state: &GrpcState,
648    req: axum::extract::Request,
649    service: String,
650    method: String,
651    method_desc: MethodDescriptor,
652    metadata: std::collections::HashMap<String, Vec<String>>,
653    timeout_seconds: Option<f64>,
654    authority: Option<String>,
655    peer_address: Option<String>,
656    request_id: String,
657    client_accepts_gzip: bool,
658    tracker: Option<RequestTracker>,
659) -> Response<GrpcBody> {
660    let is_bidi = method_desc.is_server_streaming();
661    let input = method_desc.input();
662    let output = method_desc.output();
663
664    // No `message` — inbound messages arrive on the stream, not the payload. The
665    // `client_streaming` marker tells the PHP router to build an `iterable`.
666    let payload_value = serde_json::json!({
667        "service": service,
668        "method": method,
669        "encoding": "json",
670        "client_streaming": true,
671        "server_streaming": is_bidi,
672        "metadata": metadata,
673        "request_id": request_id,
674        "timeout_seconds": timeout_seconds,
675        "peer_address": peer_address,
676        "authority": authority,
677    });
678
679    // Reader task: de-frame the request body incrementally and feed one JSON
680    // message per gRPC frame into `body_rx`. Channel close (drop) = end-of-stream.
681    let (body_tx, body_rx) = mpsc::channel::<Bytes>(16);
682    let recv_counter = Arc::new(AtomicUsize::new(0));
683    let input_for_reader = input.clone();
684    let recv_for_reader = recv_counter.clone();
685    let max_recv = state.max_recv_message_size;
686    tokio::spawn(async move {
687        let mut body = req.into_body();
688        let mut buf = BytesMut::new();
689        'outer: loop {
690            match body.frame().await {
691                Some(Ok(frame)) => {
692                    let Ok(data) = frame.into_data() else {
693                        continue; // trailers/other non-data frame — ignore
694                    };
695                    buf.extend_from_slice(&data);
696                    loop {
697                        match take_inbound_message(&mut buf, &input_for_reader, max_recv) {
698                            Ok(Some((json, n))) => {
699                                recv_for_reader.fetch_add(n, Ordering::Relaxed);
700                                if body_tx.send(Bytes::from(json)).await.is_err() {
701                                    break 'outer; // worker/handler gone
702                                }
703                            }
704                            Ok(None) => break, // need more bytes for the next frame
705                            Err(e) => {
706                                tracing::warn!(error = %e, "gRPC inbound frame rejected; ending request stream");
707                                break 'outer;
708                            }
709                        }
710                    }
711                }
712                Some(Err(e)) => {
713                    tracing::debug!(error = %e, "gRPC request body error; ending request stream");
714                    break;
715                }
716                None => break, // clean end-of-body: client half-closed
717            }
718        }
719        drop(body_tx); // EOF → folk_grpc_recv returns null
720    });
721
722    let rx = match state
723        .executor
724        .execute_streamed_with_body("grpc.call", payload_value, body_rx)
725        .await
726    {
727        Ok((rx, _id)) => rx,
728        Err(e) => {
729            if let Some(t) = tracker {
730                t.finish(
731                    &service,
732                    &method,
733                    13,
734                    recv_counter.load(Ordering::Relaxed),
735                    0,
736                );
737            }
738            return grpc_response(Bytes::new(), 13, &format!("worker: {e}"), false);
739        }
740    };
741
742    if is_bidi {
743        // Bidi: N responses — reuse the server-streaming body, with the live
744        // inbound counter so metrics see the request bytes read after this point.
745        let body = GrpcBody::Stream(Box::new(GrpcStreamBody {
746            rx,
747            output,
748            gzip: client_accepts_gzip,
749            max_send: state.max_send_message_size,
750            service,
751            method,
752            recv_bytes: 0,
753            recv_counter: Some(recv_counter),
754            sent_bytes: 0,
755            tracker,
756            done: false,
757        }));
758        let mut builder = Response::builder()
759            .status(200)
760            .header("content-type", "application/grpc");
761        if client_accepts_gzip {
762            builder = builder.header("grpc-encoding", "gzip");
763        }
764        return builder.body(body).unwrap();
765    }
766
767    // Client-streaming: exactly one response message (or a status/error), drained
768    // from the response stream and returned as a single buffered frame, like unary.
769    let mut rx = rx;
770    let (data, code, message, gzip, sent): (Bytes, u32, String, bool, usize) = loop {
771        match rx.recv().await {
772            Some(ResponseChunk::Return(value)) => {
773                let Some(map) = value.as_object() else {
774                    continue;
775                };
776                if let Some(status_val) = map.get("__grpc_status") {
777                    let code = status_val
778                        .as_u64()
779                        .filter(|c| *c <= 16)
780                        .map_or(13, |c| c as u32);
781                    let msg = map
782                        .get("__grpc_message")
783                        .and_then(|v| v.as_str())
784                        .unwrap_or("")
785                        .to_string();
786                    break (Bytes::new(), code, msg, false, 0);
787                }
788                let Some(message) = map.get("__message") else {
789                    continue; // e.g. {__result: null} — not a response message
790                };
791                match json_to_proto(&output, message) {
792                    Ok(proto) => {
793                        if proto.len() > state.max_send_message_size {
794                            break (
795                                Bytes::new(),
796                                8, // RESOURCE_EXHAUSTED
797                                format!(
798                                    "response larger than max ({} vs {} bytes)",
799                                    proto.len(),
800                                    state.max_send_message_size
801                                ),
802                                false,
803                                0,
804                            );
805                        }
806                        let sent = proto.len();
807                        break (
808                            frame_message(&proto, client_accepts_gzip),
809                            0,
810                            String::new(),
811                            client_accepts_gzip,
812                            sent,
813                        );
814                    }
815                    Err(e) => {
816                        break (
817                            Bytes::new(),
818                            13,
819                            format!("transcode response: {e}"),
820                            false,
821                            0,
822                        );
823                    }
824                }
825            }
826            Some(ResponseChunk::Error(e)) => break (Bytes::new(), 13, e.message, false, 0),
827            Some(ResponseChunk::End) | None => {
828                break (
829                    Bytes::new(),
830                    13,
831                    "client-streaming handler returned no message".to_string(),
832                    false,
833                    0,
834                );
835            }
836            Some(_) => continue, // Headers/Body not part of the gRPC message protocol
837        }
838    };
839
840    if let Some(t) = tracker {
841        t.finish(
842            &service,
843            &method,
844            code,
845            recv_counter.load(Ordering::Relaxed),
846            sent,
847        );
848    }
849    grpc_response(data, code, &message, gzip)
850}
851
852/// Pull one complete gRPC message from `buf` (length-prefixed
853/// `[flag(1)][len(4, BE)][payload]`), transcoding it to a JSON message via
854/// `input`. Returns `Ok(Some((json_bytes, proto_len)))` on a complete frame,
855/// `Ok(None)` when more bytes are needed, or `Err` on an oversized / undecodable
856/// frame. Bytes are consumed from `buf` only when a full frame is returned.
857fn take_inbound_message(
858    buf: &mut BytesMut,
859    input: &MessageDescriptor,
860    max_recv: usize,
861) -> anyhow::Result<Option<(Vec<u8>, usize)>> {
862    if buf.len() < 5 {
863        return Ok(None);
864    }
865    let compressed = buf[0] == 1;
866    let len = u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]) as usize;
867    if len > max_recv {
868        anyhow::bail!("received message larger than max ({len} vs {max_recv} bytes)");
869    }
870    if buf.len() < 5 + len {
871        return Ok(None); // incomplete frame — wait for more body bytes
872    }
873    let _prefix = buf.split_to(5);
874    let payload = buf.split_to(len).freeze();
875    let proto = if compressed {
876        Bytes::from(gzip_decompress(&payload, max_recv)?)
877    } else {
878        payload
879    };
880    let value = proto_to_json(input, &proto)?;
881    let json = serde_json::to_vec(&value)?;
882    Ok(Some((json, proto.len())))
883}
884
885fn gzip_decompress(data: &[u8], limit: usize) -> std::io::Result<Vec<u8>> {
886    let decoder = flate2::read::GzDecoder::new(data);
887    let mut out = Vec::new();
888    decoder.take(limit as u64 + 1).read_to_end(&mut out)?;
889    if out.len() > limit {
890        return Err(std::io::Error::new(
891            std::io::ErrorKind::InvalidData,
892            format!("decompressed message exceeds limit ({limit} bytes)"),
893        ));
894    }
895    Ok(out)
896}
897
898fn gzip_compress(data: &[u8]) -> std::io::Result<Vec<u8>> {
899    let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
900    encoder.write_all(data)?;
901    encoder.finish()
902}
903
904/// gRPC response body. Either a single buffered data frame followed by trailers
905/// (unary — the phase 87/88 path), or a live stream that pulls PHP-yielded
906/// messages off a [`ResponseChunk`] channel and frames them one at a time
907/// (server-streaming — phase 88b, #32).
908pub enum GrpcBody {
909    /// One optional data frame, then trailers. Used by every unary response and
910    /// by every error/status shortcut (`grpc_response`).
911    Single {
912        data: Option<Bytes>,
913        trailers: Option<HeaderMap>,
914    },
915    /// A multi-frame server-streaming response.
916    Stream(Box<GrpcStreamBody>),
917}
918
919impl http_body::Body for GrpcBody {
920    type Data = Bytes;
921    type Error = std::convert::Infallible;
922
923    fn poll_frame(
924        self: Pin<&mut Self>,
925        cx: &mut Context<'_>,
926    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
927        match self.get_mut() {
928            GrpcBody::Single { data, trailers } => {
929                if let Some(data) = data.take() {
930                    if !data.is_empty() {
931                        return Poll::Ready(Some(Ok(Frame::data(data))));
932                    }
933                }
934                if let Some(trailers) = trailers.take() {
935                    return Poll::Ready(Some(Ok(Frame::trailers(trailers))));
936                }
937                Poll::Ready(None)
938            }
939            GrpcBody::Stream(body) => body.poll_frame(cx),
940        }
941    }
942}
943
944/// Streaming half of [`GrpcBody`]. Drains a [`ResponseChunk`] receiver fed by the
945/// PHP worker (one `Return` per `yield`), transcodes each message via the output
946/// descriptor, and emits it as a length-prefixed gRPC data frame. The stream
947/// ends with trailers: OK on `End`/channel-close, a business status when the
948/// handler set one (`__grpc_status`), or INTERNAL on a worker error / transcode
949/// failure.
950pub struct GrpcStreamBody {
951    rx: mpsc::Receiver<ResponseChunk>,
952    output: MessageDescriptor,
953    gzip: bool,
954    max_send: usize,
955    service: String,
956    method: String,
957    recv_bytes: usize,
958    /// Live inbound-byte counter for bidi (phase 94): the request reader task
959    /// increments it as it de-frames incoming messages, and [`Self::finish`]
960    /// reads it for metrics. `None` for server-streaming (one buffered request,
961    /// so `recv_bytes` is already final).
962    recv_counter: Option<Arc<AtomicUsize>>,
963    sent_bytes: usize,
964    tracker: Option<RequestTracker>,
965    done: bool,
966}
967
968impl GrpcStreamBody {
969    /// Terminate the stream: record metrics and emit the trailing status frame.
970    /// After this the body yields `None`.
971    fn finish(
972        &mut self,
973        code: u32,
974        message: &str,
975    ) -> Poll<Option<Result<Frame<Bytes>, std::convert::Infallible>>> {
976        self.done = true;
977        if let Some(t) = self.tracker.take() {
978            let recv = self.recv_bytes
979                + self
980                    .recv_counter
981                    .as_ref()
982                    .map_or(0, |c| c.load(Ordering::Relaxed));
983            t.finish(&self.service, &self.method, code, recv, self.sent_bytes);
984        }
985        Poll::Ready(Some(Ok(Frame::trailers(grpc_trailers(code, message)))))
986    }
987
988    fn poll_frame(
989        &mut self,
990        cx: &mut Context<'_>,
991    ) -> Poll<Option<Result<Frame<Bytes>, std::convert::Infallible>>> {
992        if self.done {
993            return Poll::Ready(None);
994        }
995        loop {
996            match self.rx.poll_recv(cx) {
997                Poll::Ready(Some(ResponseChunk::Return(value))) => {
998                    let Some(map) = value.as_object() else {
999                        // A bare (non-object) Return is not a valid streamed
1000                        // message — the yield convention is always a `{__message}`
1001                        // / `{__grpc_status}` object. Ignore and keep draining.
1002                        continue;
1003                    };
1004
1005                    // A business status set by the handler ({__grpc_status,
1006                    // __grpc_message}) closes the stream (convention shared with
1007                    // the unary path), rather than being framed as a message.
1008                    if let Some(status_val) = map.get("__grpc_status") {
1009                        let code = status_val
1010                            .as_u64()
1011                            .filter(|c| *c <= 16)
1012                            .map_or(13, |c| c as u32);
1013                        let message = map
1014                            .get("__grpc_message")
1015                            .and_then(|v| v.as_str())
1016                            .unwrap_or("")
1017                            .to_string();
1018                        return self.finish(code, &message);
1019                    }
1020
1021                    // A streamed message is exactly `{__message: dto}` (symmetric
1022                    // with the unary handler return). Any other object — notably
1023                    // the `{__result: null}` a void/empty generator return
1024                    // finalises to when it yielded nothing — is not a message;
1025                    // ignore it and let the channel close into an OK trailer.
1026                    let Some(message) = map.get("__message") else {
1027                        continue;
1028                    };
1029
1030                    match json_to_proto(&self.output, message) {
1031                        Ok(proto) => {
1032                            if proto.len() > self.max_send {
1033                                return self.finish(
1034                                    8, // RESOURCE_EXHAUSTED
1035                                    &format!(
1036                                        "response larger than max ({} vs {} bytes)",
1037                                        proto.len(),
1038                                        self.max_send
1039                                    ),
1040                                );
1041                            }
1042                            self.sent_bytes += proto.len();
1043                            let framed = frame_message(&proto, self.gzip);
1044                            return Poll::Ready(Some(Ok(Frame::data(framed))));
1045                        }
1046                        Err(e) => {
1047                            return self.finish(13, &format!("transcode response: {e}"));
1048                        }
1049                    }
1050                }
1051                Poll::Ready(Some(ResponseChunk::Error(e))) => {
1052                    return self.finish(13, &e.message);
1053                }
1054                Poll::Ready(Some(ResponseChunk::End)) => {
1055                    return self.finish(0, "");
1056                }
1057                // Headers/Body chunks are not part of the gRPC message protocol —
1058                // ignore them and keep pulling.
1059                Poll::Ready(Some(_)) => continue,
1060                Poll::Ready(None) => return self.finish(0, ""),
1061                Poll::Pending => return Poll::Pending,
1062            }
1063        }
1064    }
1065}