callwire 2.0.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
use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};
use tokio::net::{TcpListener, TcpStream};
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>),
}

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

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

/// 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" {
        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.

    tokio::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;
    });
}

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

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

    loop {
        tokio::select! {
            res = crate::framing::read_frame(&mut reader) => {
                match res {
                    Ok(payload) => {
                        match crate::codec::unpack(&payload) {
                            Ok(msg) => {
                                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; }
            }
        }
    }
}

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 => {
            let payload = crate::codec::pack_error(msg.id, "TypeError", "missing func field").unwrap();
            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 {
        let payload = crate::codec::pack_error(
            msg.id,
            "NotFoundError",
            &format!("function '{}' not exported", func_name),
        ).unwrap();
        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;
                    }
                }
            }
        }
    }
}