folk-plugin-grpc 0.6.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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! 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 folk_api::{InboundStream, StreamConn, StreamItem};
use http::uri::PathAndQuery;
use prost_reflect::{DescriptorPool, MessageDescriptor, MethodDescriptor};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::{OnceCell, mpsc};
use tokio_stream::StreamExt;
use tokio_stream::wrappers::ReceiverStream;
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, Streaming};
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}")))
}

/// Dynamic **server-streaming** call (phase 88b): one request, a stream of raw
/// response protobuf messages. Metadata and the deadline are applied as in
/// [`ResolvedClient::invoke`] — the deadline is propagated to the upstream via
/// `grpc-timeout`. The client-side deadline backstop lives one level up in
/// [`ResolvedClient::try_open_stream`] (via `with_stream_deadline`), which bounds
/// the whole stream when the server does not honour `grpc-timeout`; a stream with
/// **no** deadline runs until the caller cancels it by **dropping** the returned
/// [`Streaming`] (the handle bridge drops it on `folk_stream_close`). No retries:
/// a stream that already emitted messages cannot be replayed.
pub async fn call_server_streaming(
    channel: Channel,
    service: &str,
    method: &str,
    request: Bytes,
    metadata: &HashMap<String, Vec<String>>,
    deadline: Option<Duration>,
) -> Result<Streaming<Bytes>, Status> {
    let path = method_path(service, method)?;
    let mut req = tonic::Request::new(request);
    apply_metadata(req.metadata_mut(), metadata);
    if let Some(d) = deadline {
        if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
            req.metadata_mut().insert("grpc-timeout", v);
        }
    }

    let mut grpc = tonic::client::Grpc::new(channel);
    grpc.ready()
        .await
        .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
    let resp = grpc.server_streaming(req, path, BytesCodec).await?;
    Ok(resp.into_inner())
}

/// Build a tonic request from a request-message stream, applying metadata and the
/// deadline (as `grpc-timeout`) — shared by client-streaming and bidi.
fn streaming_request<S>(
    req_stream: S,
    metadata: &HashMap<String, Vec<String>>,
    deadline: Option<Duration>,
) -> tonic::Request<S> {
    let mut request = tonic::Request::new(req_stream);
    apply_metadata(request.metadata_mut(), metadata);
    if let Some(d) = deadline {
        if let Ok(v) = grpc_timeout_header(d).parse::<MetadataValue<Ascii>>() {
            request.metadata_mut().insert("grpc-timeout", v);
        }
    }
    request
}

/// Dynamic **client-streaming** call (phase 88b): a stream of requests, one
/// response. `req_stream` yields already-encoded protobuf messages.
pub async fn call_client_streaming<S>(
    channel: Channel,
    service: &str,
    method: &str,
    req_stream: S,
    metadata: &HashMap<String, Vec<String>>,
    deadline: Option<Duration>,
) -> Result<Bytes, Status>
where
    S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
{
    let path = method_path(service, method)?;
    let mut grpc = tonic::client::Grpc::new(channel);
    grpc.ready()
        .await
        .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
    let resp = grpc
        .client_streaming(
            streaming_request(req_stream, metadata, deadline),
            path,
            BytesCodec,
        )
        .await?;
    Ok(resp.into_inner())
}

/// Dynamic **bidirectional-streaming** call (phase 88b): a stream of requests and a
/// stream of responses. `req_stream` yields already-encoded protobuf messages.
pub async fn call_bidi_streaming<S>(
    channel: Channel,
    service: &str,
    method: &str,
    req_stream: S,
    metadata: &HashMap<String, Vec<String>>,
    deadline: Option<Duration>,
) -> Result<Streaming<Bytes>, Status>
where
    S: tokio_stream::Stream<Item = Bytes> + Send + 'static,
{
    let path = method_path(service, method)?;
    let mut grpc = tonic::client::Grpc::new(channel);
    grpc.ready()
        .await
        .map_err(|e| Status::unavailable(format!("channel not ready: {e}")))?;
    let resp = grpc
        .streaming(
            streaming_request(req_stream, metadata, deadline),
            path,
            BytesCodec,
        )
        .await?;
    Ok(resp.into_inner())
}

// ---------------------------------------------------------------------------
// 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>,
}

/// Which streaming shape `grpc.client.stream` should open.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StreamKind {
    /// One request → a stream of responses.
    #[default]
    ServerStreaming,
    /// A stream of requests → one response.
    ClientStreaming,
    /// A stream of requests ↔ a stream of responses.
    Bidi,
}

/// Envelope PHP sends to open a streaming call (`grpc.client.stream`, phase 88b).
/// Like [`ClientCallEnvelope`] plus `kind`; `message` carries the single initial
/// request for [`StreamKind::ServerStreaming`] and is unused (send messages via
/// `folk_stream_send`) for client-streaming / bidi.
#[derive(Debug, Deserialize)]
pub struct ClientStreamEnvelope {
    pub client: String,
    #[serde(default)]
    pub address: Option<String>,
    pub service: String,
    pub method: String,
    #[serde(default)]
    pub kind: StreamKind,
    #[serde(default)]
    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()),
        }
    }

    /// Open a **server-streaming** call (phase 88b). Returns a [`StreamConn`] whose
    /// inbound stream yields one JSON frame per upstream message: `{ "message": … }`
    /// for a decoded DTO, or `{ "__grpc_status", "__grpc_message" }` for a decode
    /// failure or a non-OK trailing status — the same convention the unary [`call`]
    /// uses, so the PHP side maps a status frame to `GrpcException`. Never fails at
    /// the handler level: setup errors (unknown client/method, bad request, connect)
    /// surface as a single status frame, so PHP's `foreach` always sees the outcome.
    ///
    /// [`call`]: Self::call
    pub async fn open_stream(&self, env: ClientStreamEnvelope) -> StreamConn {
        match self.try_open_stream(&env).await {
            Ok(conn) => conn,
            Err(status) => single_status_conn(status),
        }
    }

    async fn try_open_stream(&self, env: &ClientStreamEnvelope) -> Result<StreamConn, Value> {
        let client = self.clients.get(&env.client).ok_or_else(|| {
            status_json(
                Code::Unimplemented as i32 as u32,
                format!("unknown gRPC client '{}'", env.client),
            )
        })?;

        let method_desc =
            resolve_method(&client.pool, &env.service, &env.method).ok_or_else(|| {
                status_json(
                    Code::Unimplemented as i32 as u32,
                    format!(
                        "method {}/{} not in client '{}' descriptor pool",
                        env.service, env.method, env.client
                    ),
                )
            })?;

        let channel = client
            .channel(env.address.as_deref())
            .await
            .map_err(|e| 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);

        let output = method_desc.output();

        match env.kind {
            StreamKind::ServerStreaming => {
                let req_bytes = json_to_proto(&method_desc.input(), &env.message)
                    .map(Bytes::from)
                    .map_err(|e| {
                        status_json(
                            Code::InvalidArgument as i32 as u32,
                            format!("encode request: {e}"),
                        )
                    })?;
                let streaming = call_server_streaming(
                    channel,
                    &env.service,
                    &env.method,
                    req_bytes,
                    &env.metadata,
                    deadline,
                )
                .await
                .map_err(status_to_json)?;
                Ok(StreamConn::server_streaming(with_stream_deadline(
                    transcode_inbound(streaming, output),
                    deadline,
                )))
            }

            StreamKind::Bidi => {
                let (tx, req_stream) = outbound_stream(method_desc.input());
                let streaming = call_bidi_streaming(
                    channel,
                    &env.service,
                    &env.method,
                    req_stream,
                    &env.metadata,
                    deadline,
                )
                .await
                .map_err(status_to_json)?;
                Ok(StreamConn::duplex(
                    with_stream_deadline(transcode_inbound(streaming, output), deadline),
                    tx,
                ))
            }

            StreamKind::ClientStreaming => {
                // The single response is only available after the request stream
                // ends, so the call runs on a spawned task and delivers exactly one
                // inbound frame through a 1-slot channel.
                let (tx, req_stream) = outbound_stream(method_desc.input());
                let (frame_tx, frame_rx) = mpsc::channel::<StreamItem>(1);
                let service = env.service.clone();
                let method = env.method.clone();
                let metadata = env.metadata.clone();
                tokio::spawn(async move {
                    let frame = match call_client_streaming(
                        channel, &service, &method, req_stream, &metadata, deadline,
                    )
                    .await
                    {
                        Ok(resp) => Ok(message_or_status_frame(&output, &resp)),
                        Err(status) => Ok(status_frame_bytes(&status)),
                    };
                    let _ = frame_tx.send(frame).await;
                });
                let inbound: InboundStream = Box::pin(ReceiverStream::new(frame_rx));
                Ok(StreamConn::duplex(
                    with_stream_deadline(inbound, deadline),
                    tx,
                ))
            }
        }
    }
}

/// Bound an inbound stream by an absolute deadline (phase 88b). gRPC deadlines
/// apply to the whole RPC, streaming included, so when one is set the entire
/// stream must finish before it elapses; otherwise the stream ends with a single
/// `DEADLINE_EXCEEDED(4)` status frame (which PHP maps to `GrpcException`). The
/// `grpc-timeout` header is still sent upstream, but this is the client-side
/// backstop that fires when the server does not honour it. A stream with **no**
/// deadline is returned untouched — a long-lived stream must not be killed by a
/// backstop.
fn with_stream_deadline(inbound: InboundStream, deadline: Option<Duration>) -> InboundStream {
    let Some(d) = deadline else {
        return inbound;
    };
    let deadline_at = tokio::time::Instant::now() + d;
    let stream =
        futures_util::stream::unfold((inbound, false), move |(mut inner, done)| async move {
            if done {
                return None;
            }
            tokio::select! {
                biased;
                item = inner.next() => item.map(|x| (x, (inner, false))),
                () = tokio::time::sleep_until(deadline_at) => {
                    let frame = Bytes::from(
                        serde_json::to_vec(&status_json(
                            Code::DeadlineExceeded as i32 as u32,
                            "stream deadline exceeded",
                        ))
                        .unwrap_or_default(),
                    );
                    Some((Ok(frame), (inner, true)))
                }
            }
        });
    Box::pin(stream)
}

/// Map a tonic [`Status`] to the `{__grpc_status,…}` JSON PHP turns into an exception.
fn status_to_json(s: Status) -> Value {
    status_json(s.code() as i32 as u32, s.message().to_string())
}

/// Encode one response protobuf message as a `{ "message": DTO }` JSON frame, or a
/// status frame if it fails to decode (client-streaming's single response).
fn message_or_status_frame(output: &MessageDescriptor, proto: &[u8]) -> Bytes {
    let frame = match proto_to_json(output, proto) {
        Ok(v) => json!({ "message": v }),
        Err(e) => status_json(
            Code::Internal as i32 as u32,
            format!("decode stream message: {e}"),
        ),
    };
    Bytes::from(serde_json::to_vec(&frame).unwrap_or_default())
}

fn status_frame_bytes(status: &Status) -> Bytes {
    Bytes::from(serde_json::to_vec(&status_to_json(status.clone())).unwrap_or_default())
}

/// Adapt a tonic response [`Streaming`] into the bridge's inbound stream: one JSON
/// frame per message (`{ "message": … }`), a status frame on decode error or a
/// non-OK trailing status. Errors are frames, never `Err` — the bridge stays purely
/// data-carrying (mirrors the unary convention).
fn transcode_inbound(streaming: Streaming<Bytes>, output: MessageDescriptor) -> InboundStream {
    Box::pin(streaming.map(move |item| {
        let frame = match item {
            Ok(proto) => match proto_to_json(&output, &proto) {
                Ok(v) => json!({ "message": v }),
                Err(e) => status_json(
                    Code::Internal as i32 as u32,
                    format!("decode stream message: {e}"),
                ),
            },
            Err(status) => status_to_json(status),
        };
        Ok(Bytes::from(serde_json::to_vec(&frame).unwrap_or_default()))
    }))
}

/// Build the outbound half for client-streaming / bidi: a `mpsc::Sender` the bridge
/// pushes PHP-sent DTO-JSON into, and the tonic request stream that transcodes each
/// message JSON → protobuf. Messages that fail to encode are dropped with a warning
/// (a malformed DTO is a caller bug; dropping keeps the stream alive).
fn outbound_stream(
    input: MessageDescriptor,
) -> (
    tokio::sync::mpsc::Sender<Bytes>,
    impl tokio_stream::Stream<Item = Bytes> + Send + 'static,
) {
    let (tx, rx) = mpsc::channel::<Bytes>(16);
    let stream = ReceiverStream::new(rx).filter_map(move |json_bytes: Bytes| {
        let value: Value = match serde_json::from_slice(&json_bytes) {
            Ok(v) => v,
            Err(e) => {
                warn!(error = %e, "gRPC client stream: dropping unparsable outbound message");
                return None;
            }
        };
        match json_to_proto(&input, &value) {
            Ok(b) => Some(Bytes::from(b)),
            Err(e) => {
                warn!(error = %e, "gRPC client stream: dropping unencodable outbound message");
                None
            }
        }
    });
    (tx, stream)
}

/// A [`StreamConn`] that yields exactly one status frame then ends — used to
/// surface a setup failure (unknown client, connect error, …) to PHP's `foreach`.
fn single_status_conn(status: Value) -> StreamConn {
    let bytes = Bytes::from(serde_json::to_vec(&status).unwrap_or_default());
    let inbound: InboundStream = Box::pin(tokio_stream::once(Ok(bytes)));
    StreamConn::server_streaming(inbound)
}

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)
}