callwire 2.2.0

High-performance bidirectional RPC over TCP with MessagePack framing — Go, Python, Rust interop
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
use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use rmpv::Value;
use crate::codec::WireMessage;
use crate::errors::{CallwireError, Result};

pub type BoxFuture<'a, T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
pub type BoxStream<'a, T> = std::pin::Pin<Box<dyn futures_util::Stream<Item = T> + Send + 'a>>;

pub enum RegistryEntry {
    Unary(Arc<dyn Fn(Value) -> BoxFuture<'static, std::result::Result<Value, CallwireError>> + Send + Sync>),
    Stream(Arc<dyn Fn(Value) -> BoxFuture<'static, std::result::Result<BoxStream<'static, std::result::Result<Value, CallwireError>>, CallwireError>> + Send + Sync>),
    ClientStream(Arc<dyn Fn(BoxStream<'static, Value>) -> BoxFuture<'static, std::result::Result<Value, CallwireError>> + Send + Sync>),
    Bidi(Arc<dyn Fn(BoxStream<'static, Value>) -> BoxFuture<'static, std::result::Result<BoxStream<'static, std::result::Result<Value, CallwireError>>, CallwireError>> + Send + Sync>),
}

impl Clone for RegistryEntry {
    fn clone(&self) -> Self {
        match self {
            RegistryEntry::Unary(f) => RegistryEntry::Unary(f.clone()),
            RegistryEntry::Stream(f) => RegistryEntry::Stream(f.clone()),
            RegistryEntry::ClientStream(f) => RegistryEntry::ClientStream(f.clone()),
            RegistryEntry::Bidi(f) => RegistryEntry::Bidi(f.clone()),
        }
    }
}

/// Signal sent through the per-call input channel for client-streaming/bidi calls.
enum StreamInputMsg {
    Chunk(Value),
    Close,
}

/// Minimal adapter turning an `mpsc::Receiver<Value>` into a `futures_util::Stream`.
struct ReceiverValueStream(mpsc::Receiver<Value>);

impl futures_util::Stream for ReceiverValueStream {
    type Item = Value;
    fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Value>> {
        self.0.poll_recv(cx)
    }
}

pub(crate) static REGISTRY: LazyLock<Mutex<HashMap<String, RegistryEntry>>> = LazyLock::new(|| {
    Mutex::new(HashMap::new())
});

/// Shutdown sender for the auto-serve loop. When `Some`, a server is running.
static AUTO_SERVE_TX: LazyLock<Mutex<Option<tokio::sync::watch::Sender<bool>>>> = LazyLock::new(|| {
    Mutex::new(None)
});

pub trait ToWireError {
    fn to_wire_error(self) -> CallwireError;
}

impl ToWireError for CallwireError {
    fn to_wire_error(self) -> CallwireError {
        self
    }
}

impl ToWireError for String {
    fn to_wire_error(self) -> CallwireError {
        CallwireError {
            error_type: "Error".to_string(),
            message: self,
        }
    }
}

impl ToWireError for &str {
    fn to_wire_error(self) -> CallwireError {
        CallwireError {
            error_type: "Error".to_string(),
            message: self.to_string(),
        }
    }
}

impl ToWireError for std::convert::Infallible {
    fn to_wire_error(self) -> CallwireError {
        unreachable!()
    }
}

pub fn register_unary<F, Args, Resp, Err>(name: &str, func: F)
where
    F: Fn(Args) -> std::result::Result<Resp, Err> + Send + Sync + 'static,
    Args: serde::de::DeserializeOwned + Send + 'static,
    Resp: serde::Serialize + Send + 'static,
    Err: ToWireError + Send + 'static,
{
    let func = Arc::new(func);
    let wrapped = Arc::new(move |args_val: Value| {
        let func = func.clone();
        Box::pin(async move {
            let clean_args = match args_val {
                Value::Array(ref vec) if vec.is_empty() => Value::Nil,
                other => other,
            };
            let args: Args = rmpv::ext::from_value(clean_args)
                .map_err(|e| CallwireError {
                    error_type: "TypeError".to_string(),
                    message: format!("Argument deserialization failed: {}", e),
                })?;
            match func(args) {
                Ok(resp) => {
                    let bytes = crate::codec::to_vec_map(&resp).map_err(|e| CallwireError {
                        error_type: "SerializationError".to_string(),
                        message: e.to_string(),
                    })?;
                    rmp_serde::from_slice(&bytes).map_err(|e| CallwireError {
                        error_type: "SerializationError".to_string(),
                        message: e.to_string(),
                    })
                }
                Err(err) => Err(err.to_wire_error()),
            }
        }) as BoxFuture<'static, std::result::Result<Value, CallwireError>>
    });
    
    REGISTRY.lock().unwrap().insert(name.to_string(), RegistryEntry::Unary(wrapped));
    spawn_auto_serve_if_idle();
}

pub fn register_stream<F, Args, S, Item, Err, SErr>(name: &str, func: F)
where
    F: Fn(Args) -> std::result::Result<S, Err> + Send + Sync + 'static,
    Args: serde::de::DeserializeOwned + Send + 'static,
    S: futures_util::Stream<Item = std::result::Result<Item, SErr>> + Send + 'static,
    Item: serde::Serialize + Send + 'static,
    Err: ToWireError + Send + 'static,
    SErr: ToWireError + Send + 'static,
{
    let func = Arc::new(func);
    let wrapped = Arc::new(move |args_val: Value| {
        let func = func.clone();
        Box::pin(async move {
            let clean_args = match args_val {
                Value::Array(ref vec) if vec.is_empty() => Value::Nil,
                other => other,
            };
            let args: Args = match rmpv::ext::from_value(clean_args) {
                Ok(args) => args,
                Err(e) => return Err(CallwireError {
                    error_type: "TypeError".to_string(),
                    message: format!("Argument deserialization failed: {}", e),
                }),
            };
            match func(args) {
                Ok(stream) => {
                    use futures_util::StreamExt;
                    let mapped_stream = stream.map(|res| {
                        match res {
                            Ok(item) => {
                                let bytes = match crate::codec::to_vec_map(&item) {
                                    Ok(b) => b,
                                    Err(e) => return Err(CallwireError {
                                        error_type: "SerializationError".to_string(),
                                        message: e.to_string(),
                                    }),
                                };
                                rmp_serde::from_slice(&bytes).map_err(|e| CallwireError {
                                    error_type: "SerializationError".to_string(),
                                    message: e.to_string(),
                                })
                            }
                            Err(e) => Err(e.to_wire_error()),
                        }
                    });
                    let boxed: BoxStream<'static, std::result::Result<Value, CallwireError>> = Box::pin(mapped_stream);
                    Ok(boxed)
                }
                Err(err) => Err(err.to_wire_error()),
            }
        }) as BoxFuture<'static, std::result::Result<BoxStream<'static, std::result::Result<Value, CallwireError>>, CallwireError>>
    });
    
    REGISTRY.lock().unwrap().insert(name.to_string(), RegistryEntry::Stream(wrapped));
    spawn_auto_serve_if_idle();
}

pub fn register_client_stream<F, Args, Resp, Err>(name: &str, func: F)
where
    F: Fn(BoxStream<'static, Args>) -> std::result::Result<Resp, Err> + Send + Sync + 'static,
    Args: serde::de::DeserializeOwned + Send + 'static,
    Resp: serde::Serialize + Send + 'static,
    Err: ToWireError + Send + 'static,
{
    let func = Arc::new(func);
    let wrapped = Arc::new(move |value_stream: BoxStream<'static, Value>| {
        let func = func.clone();
        Box::pin(async move {
            use futures_util::StreamExt;
            let args_stream: BoxStream<'static, Args> = Box::pin(value_stream.filter_map(|v| async move {
                rmpv::ext::from_value(v).ok()
            }));
            match func(args_stream) {
                Ok(resp) => {
                    let bytes = crate::codec::to_vec_map(&resp).map_err(|e| CallwireError {
                        error_type: "SerializationError".to_string(),
                        message: e.to_string(),
                    })?;
                    rmp_serde::from_slice(&bytes).map_err(|e| CallwireError {
                        error_type: "SerializationError".to_string(),
                        message: e.to_string(),
                    })
                }
                Err(err) => Err(err.to_wire_error()),
            }
        }) as BoxFuture<'static, std::result::Result<Value, CallwireError>>
    });

    REGISTRY.lock().unwrap().insert(name.to_string(), RegistryEntry::ClientStream(wrapped));
    spawn_auto_serve_if_idle();
}

pub fn register_bidi<F, Args, S, Item, Err, SErr>(name: &str, func: F)
where
    F: Fn(BoxStream<'static, Args>) -> std::result::Result<S, Err> + Send + Sync + 'static,
    Args: serde::de::DeserializeOwned + Send + 'static,
    S: futures_util::Stream<Item = std::result::Result<Item, SErr>> + Send + 'static,
    Item: serde::Serialize + Send + 'static,
    Err: ToWireError + Send + 'static,
    SErr: ToWireError + Send + 'static,
{
    let func = Arc::new(func);
    let wrapped = Arc::new(move |value_stream: BoxStream<'static, Value>| {
        let func = func.clone();
        Box::pin(async move {
            use futures_util::StreamExt;
            let args_stream: BoxStream<'static, Args> = Box::pin(value_stream.filter_map(|v| async move {
                rmpv::ext::from_value(v).ok()
            }));
            match func(args_stream) {
                Ok(stream) => {
                    let mapped_stream = stream.map(|res| {
                        match res {
                            Ok(item) => {
                                let bytes = match crate::codec::to_vec_map(&item) {
                                    Ok(b) => b,
                                    Err(e) => return Err(CallwireError {
                                        error_type: "SerializationError".to_string(),
                                        message: e.to_string(),
                                    }),
                                };
                                rmp_serde::from_slice(&bytes).map_err(|e| CallwireError {
                                    error_type: "SerializationError".to_string(),
                                    message: e.to_string(),
                                })
                            }
                            Err(e) => Err(e.to_wire_error()),
                        }
                    });
                    let boxed: BoxStream<'static, std::result::Result<Value, CallwireError>> = Box::pin(mapped_stream);
                    Ok(boxed)
                }
                Err(err) => Err(err.to_wire_error()),
            }
        }) as BoxFuture<'static, std::result::Result<BoxStream<'static, std::result::Result<Value, CallwireError>>, CallwireError>>
    });

    REGISTRY.lock().unwrap().insert(name.to_string(), RegistryEntry::Bidi(wrapped));
    spawn_auto_serve_if_idle();
}

/// Internal: check if a server is already running; if not, spawn one.
/// Called from register_* functions. Does NOT block — the caller must use
/// [`wait_serving`] if it needs to know when the listener is bound.
fn spawn_auto_serve_if_idle() {
    let mut tx_guard = AUTO_SERVE_TX.lock().unwrap();
    if tx_guard.is_some() {
        // Already running.
        return;
    }
    if std::env::var("CALLWIRE_AUTO").unwrap_or_default() == "0"
        || std::env::var("CALLWIRE_SPAWNED").as_deref() == Ok("1")
    {
        return;
    }

    let host = std::env::var("CALLWIRE_HOST").unwrap_or_else(|_| "localhost".to_string());
    let port = std::env::var("CALLWIRE_PORT").unwrap_or_else(|_| "9090".to_string());
    let addr = format!("{}:{}", host, port);

    let (tx, rx) = tokio::sync::watch::channel(false);
    *tx_guard = Some(tx);
    drop(tx_guard); // Release lock before spawning.

    match tokio::runtime::Handle::try_current() {
        Ok(handle) => {
            handle.spawn(async move {
                let listener = match TcpListener::bind(&addr).await {
                    Ok(l) => l,
                    Err(e) => {
                        eprintln!("callwire: auto-serve on {} failed to bind: {}", addr, e);
                        return;
                    }
                };
                run_accept_loop(listener, rx).await;
            });
        }
        Err(_) => {
            // Spawn a background OS thread with its own Tokio runtime if no global runtime exists.
            std::thread::spawn(move || {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                rt.block_on(async {
                    let listener = match TcpListener::bind(&addr).await {
                        Ok(l) => l,
                        Err(e) => {
                            eprintln!("callwire: auto-serve on {} failed to bind: {}", addr, e);
                            return;
                        }
                    };
                    run_accept_loop(listener, rx).await;
                });
            });
        }
    }
}

/// Start the auto-serve server and wait until the TCP listener is bound.
/// Returns when the listener is ready to accept connections.
/// This is a no-op if the server is already running.
pub async fn auto_serve() {
    {
        let guard = AUTO_SERVE_TX.lock().unwrap();
        if guard.is_some() {
            return;
        }
    }

    if std::env::var("CALLWIRE_AUTO").unwrap_or_default() == "0" {
        return;
    }

    let host = std::env::var("CALLWIRE_HOST").unwrap_or_else(|_| "localhost".to_string());
    let port = std::env::var("CALLWIRE_PORT").unwrap_or_else(|_| "9090".to_string());
    let addr = format!("{}:{}", host, port);

    // Bind the listener before storing the sender so callers know it's ready.
    let listener = match TcpListener::bind(&addr).await {
        Ok(l) => l,
        Err(e) => {
            eprintln!("callwire: auto-serve on {} failed to bind: {}", addr, e);
            return;
        }
    };

    let (tx, rx) = tokio::sync::watch::channel(false);
    {
        let mut guard = AUTO_SERVE_TX.lock().unwrap();
        if guard.is_some() {
            // Another task raced us and already bound — drop ours.
            return;
        }
        *guard = Some(tx);
    }

    tokio::spawn(run_accept_loop(listener, rx));
}

/// Explicitly start a server on `addr`, waiting until the listener is bound.
/// Returns a [`ServerHandle`] that can be used to shut it down.
pub async fn serve_on(addr: &str) -> Result<ServerHandle> {
    let listener = TcpListener::bind(addr).await?;
    let (tx, rx) = tokio::sync::watch::channel(false);
    tokio::spawn(run_accept_loop(listener, rx));
    Ok(ServerHandle { tx })
}

/// A handle to a running server. Drop or call `.close()` to stop it.
pub struct ServerHandle {
    pub(crate) tx: tokio::sync::watch::Sender<bool>,
}

impl ServerHandle {
    pub fn close(self) {
        let _ = self.tx.send(true);
    }
}

/// Shut down the global auto-serve server.
pub fn close() {
    let mut guard = AUTO_SERVE_TX.lock().unwrap();
    if let Some(tx) = guard.take() {
        let _ = tx.send(true);
    }
}

/// Serve forever on `addr` (no built-in shutdown).
pub async fn serve<A: tokio::net::ToSocketAddrs>(addr: A) -> Result<()> {
    let listener = TcpListener::bind(addr).await?;
    let (_tx, rx) = tokio::sync::watch::channel(false);
    run_accept_loop(listener, rx).await;
    Ok(())
}

pub(crate) async fn run_accept_loop(listener: TcpListener, mut rx: tokio::sync::watch::Receiver<bool>) {
    loop {
        tokio::select! {
            res = listener.accept() => {
                match res {
                    Ok((socket, _)) => {
                        tokio::spawn(handle_connection(socket, rx.clone()));
                    }
                    Err(_) => break,
                }
            }
            _ = rx.changed() => {
                if *rx.borrow() { break; }
            }
        }
    }
}

async fn handle_connection(socket: TcpStream, mut shutdown_rx: tokio::sync::watch::Receiver<bool>) {
    let (mut reader, stream_writer) = socket.into_split();
    let writer = Arc::new(tokio::sync::Mutex::new(stream_writer));
    // bool = is_bidi: client-stream calls must terminate with stream_close,
    // bidi calls must terminate with stream_end — the two are not interchangeable.
    let stream_inputs: Arc<Mutex<HashMap<u64, (mpsc::Sender<StreamInputMsg>, bool)>>> =
        Arc::new(Mutex::new(HashMap::new()));

    loop {
        tokio::select! {
            res = crate::framing::read_frame(&mut reader) => {
                match res {
                    Ok(payload) => {
                        match crate::codec::unpack(&payload) {
                            Ok(msg) => {
                                let msg_type = msg.msg_type.as_str();

                                // Route follow-up frames of an in-progress streaming-input call
                                if msg_type == "stream_chunk" || msg_type == "stream_close" || msg_type == "stream_end" {
                                    let entry = {
                                        let inputs = stream_inputs.lock().unwrap();
                                        inputs.get(&msg.id).cloned()
                                    };
                                    if let Some((sender, is_bidi)) = entry {
                                        if msg_type == "stream_chunk" {
                                            let _ = sender.send(StreamInputMsg::Chunk(msg.result.unwrap_or(Value::Nil))).await;
                                        } else {
                                            let expected = if is_bidi { "stream_end" } else { "stream_close" };
                                            if msg_type != expected {
                                                if let Ok(payload) = crate::codec::pack_error(
                                                    msg.id,
                                                    "ProtocolError",
                                                    &format!("expected '{}' to terminate this call, got '{}'", expected, msg_type),
                                                ) {
                                                    let mut w = writer.lock().await;
                                                    let _ = crate::framing::write_frame(&mut *w, &payload).await;
                                                }
                                            }
                                            // Forward Close regardless of mismatch so the handler
                                            // unblocks instead of hanging after a malformed terminator.
                                            let _ = sender.send(StreamInputMsg::Close).await;
                                            stream_inputs.lock().unwrap().remove(&msg.id);
                                        }
                                    }
                                    continue;
                                }

                                if msg_type != "request" {
                                    continue;
                                }

                                let is_bidi = msg.stream.unwrap_or(false);
                                let func_name = msg.func.clone().unwrap_or_default();

                                let entry = {
                                    let reg = REGISTRY.lock().unwrap();
                                    reg.get(&func_name).cloned()
                                };

                                match entry {
                                    Some(RegistryEntry::Bidi(_)) if is_bidi => {
                                        let (tx, rx) = mpsc::channel(256);
                                        let id = msg.id;
                                        stream_inputs.lock().unwrap().insert(id, (tx, true));
                                        let writer_clone = writer.clone();
                                        let inputs_clone = stream_inputs.clone();
                                        tokio::spawn(async move {
                                            dispatch_bidi(writer_clone, msg, rx).await;
                                            inputs_clone.lock().unwrap().remove(&id);
                                        });
                                    }
                                    Some(RegistryEntry::ClientStream(_)) if !is_bidi => {
                                        let (tx, rx) = mpsc::channel(256);
                                        stream_inputs.lock().unwrap().insert(msg.id, (tx, false));
                                        let writer_clone = writer.clone();
                                        let inputs_clone = stream_inputs.clone();
                                        let id = msg.id;
                                        tokio::spawn(async move {
                                            dispatch_client_stream(writer_clone, msg, rx).await;
                                            inputs_clone.lock().unwrap().remove(&id);
                                        });
                                    }
                                    _ => {
                                        let writer_clone = writer.clone();
                                        tokio::spawn(async move {
                                            dispatch(writer_clone, msg).await;
                                        });
                                    }
                                }
                            }
                            Err(_) => {
                                // ignore malformed frame
                            }
                        }
                    }
                    Err(_) => break,
                }
            }
            _ = shutdown_rx.changed() => {
                if *shutdown_rx.borrow() { break; }
            }
        }
    }

    // Connection is closing: drop all pending stream_inputs senders so that any
    // in-progress dispatch_client_stream/dispatch_bidi task blocked on
    // input_rx.recv() gets None and unblocks instead of hanging forever.
    stream_inputs.lock().unwrap().clear();
}

async fn dispatch(writer: Arc<tokio::sync::Mutex<tokio::net::tcp::OwnedWriteHalf>>, msg: WireMessage) {
    let func_name = match &msg.func {
        Some(f) => f.clone(),
        None => {
            if let Ok(payload) = crate::codec::pack_error(msg.id, "TypeError", "missing func field") {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
            return;
        }
    };

    let entry = {
        let reg = REGISTRY.lock().unwrap();
        reg.get(&func_name).cloned()
    };

    let Some(entry) = entry else {
        if let Ok(payload) = crate::codec::pack_error(
            msg.id,
            "NotFoundError",
            &format!("function '{}' not exported", func_name),
        ) {
            let mut w = writer.lock().await;
            let _ = crate::framing::write_frame(&mut *w, &payload).await;
        }
        return;
    };

    let args = msg.args.unwrap_or(Value::Nil);

    match entry {
        RegistryEntry::Unary(handler) => {
            match handler(args).await {
                Ok(res) => {
                    if let Ok(payload) = crate::codec::pack_response(msg.id, &res) {
                        let mut w = writer.lock().await;
                        let _ = crate::framing::write_frame(&mut *w, &payload).await;
                    }
                }
                Err(err) => {
                    if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                        let mut w = writer.lock().await;
                        let _ = crate::framing::write_frame(&mut *w, &payload).await;
                    }
                }
            }
        }
        RegistryEntry::Stream(handler) => {
            match handler(args).await {
                Ok(mut stream) => {
                    use futures_util::StreamExt;
                    while let Some(res) = stream.next().await {
                        match res {
                            Ok(val) => {
                                if let Ok(payload) = crate::codec::pack_stream_chunk(msg.id, &val) {
                                    let mut w = writer.lock().await;
                                    if crate::framing::write_frame(&mut *w, &payload).await.is_err() {
                                        return;
                                    }
                                }
                            }
                            Err(err) => {
                                if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                                    let mut w = writer.lock().await;
                                    let _ = crate::framing::write_frame(&mut *w, &payload).await;
                                }
                                return;
                            }
                        }
                    }
                    if let Ok(payload) = crate::codec::pack_stream_end(msg.id) {
                        let mut w = writer.lock().await;
                        let _ = crate::framing::write_frame(&mut *w, &payload).await;
                    }
                }
                Err(err) => {
                    if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                        let mut w = writer.lock().await;
                        let _ = crate::framing::write_frame(&mut *w, &payload).await;
                    }
                }
            }
        }
        RegistryEntry::ClientStream(_) | RegistryEntry::Bidi(_) => {
            // Streaming-input calls are routed to dispatch_client_stream/dispatch_bidi
            // by handle_connection before reaching here — this arm should be unreachable
            // in normal operation, but guards against a stray unary/bidi mismatch.
            if let Ok(payload) = crate::codec::pack_error(
                msg.id,
                "TypeError",
                "function requires client-streaming or bidi-streaming call, not unary",
            ) {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
        }
    }
}

async fn dispatch_client_stream(
    writer: Arc<tokio::sync::Mutex<tokio::net::tcp::OwnedWriteHalf>>,
    msg: WireMessage,
    mut input_rx: mpsc::Receiver<StreamInputMsg>,
) {
    let func_name = msg.func.clone().unwrap_or_default();
    let entry = {
        let reg = REGISTRY.lock().unwrap();
        reg.get(&func_name).cloned()
    };

    let Some(RegistryEntry::ClientStream(handler)) = entry else {
        if let Ok(payload) = crate::codec::pack_error(
            msg.id,
            "NotFoundError",
            &format!("function '{}' not exported as client-stream", func_name),
        ) {
            let mut w = writer.lock().await;
            let _ = crate::framing::write_frame(&mut *w, &payload).await;
        }
        return;
    };

    let (value_tx, value_rx) = mpsc::channel::<Value>(256);
    tokio::spawn(async move {
        while let Some(signal) = input_rx.recv().await {
            match signal {
                StreamInputMsg::Chunk(v) => {
                    if value_tx.send(v).await.is_err() {
                        break;
                    }
                }
                StreamInputMsg::Close => break,
            }
        }
    });

    let value_stream: BoxStream<'static, Value> = Box::pin(ReceiverValueStream(value_rx));

    match handler(value_stream).await {
        Ok(res) => {
            if let Ok(payload) = crate::codec::pack_response(msg.id, &res) {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
        }
        Err(err) => {
            if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
        }
    }
}

async fn dispatch_bidi(
    writer: Arc<tokio::sync::Mutex<tokio::net::tcp::OwnedWriteHalf>>,
    msg: WireMessage,
    mut input_rx: mpsc::Receiver<StreamInputMsg>,
) {
    let func_name = msg.func.clone().unwrap_or_default();
    let entry = {
        let reg = REGISTRY.lock().unwrap();
        reg.get(&func_name).cloned()
    };

    let Some(RegistryEntry::Bidi(handler)) = entry else {
        if let Ok(payload) = crate::codec::pack_error(
            msg.id,
            "NotFoundError",
            &format!("function '{}' not exported as bidi-stream", func_name),
        ) {
            let mut w = writer.lock().await;
            let _ = crate::framing::write_frame(&mut *w, &payload).await;
        }
        return;
    };

    let (value_tx, value_rx) = mpsc::channel::<Value>(256);
    tokio::spawn(async move {
        while let Some(signal) = input_rx.recv().await {
            match signal {
                StreamInputMsg::Chunk(v) => {
                    if value_tx.send(v).await.is_err() {
                        break;
                    }
                }
                StreamInputMsg::Close => break,
            }
        }
    });

    let value_stream: BoxStream<'static, Value> = Box::pin(ReceiverValueStream(value_rx));

    match handler(value_stream).await {
        Ok(mut out_stream) => {
            use futures_util::StreamExt;
            while let Some(res) = out_stream.next().await {
                match res {
                    Ok(val) => {
                        if let Ok(payload) = crate::codec::pack_stream_chunk(msg.id, &val) {
                            let mut w = writer.lock().await;
                            if crate::framing::write_frame(&mut *w, &payload).await.is_err() {
                                return;
                            }
                        }
                    }
                    Err(err) => {
                        if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                            let mut w = writer.lock().await;
                            let _ = crate::framing::write_frame(&mut *w, &payload).await;
                        }
                        return;
                    }
                }
            }
            if let Ok(payload) = crate::codec::pack_stream_end(msg.id) {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
        }
        Err(err) => {
            if let Ok(payload) = crate::codec::pack_error(msg.id, &err.error_type, &err.message) {
                let mut w = writer.lock().await;
                let _ = crate::framing::write_frame(&mut *w, &payload).await;
            }
        }
    }
}