endpoint-libs 4.2.1

Launch MCP services fast: describe endpoints once in RON, and endpoint-gen generates the Rust models, docs and MCP tool schemas that this crate serves over WebSocket RPC, with roles and typed errors built in.
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
//! Per-connection outbound queue.
//!
//! The bound is the number of queued messages. A [`Sender`] does not reserve
//! a slot of its own. `futures::channel::mpsc` does (`buffer + num_senders`),
//! and `drop_conn_on_buffer_full` would then fire at a different depth than
//! the one [`crate::libs::ws::WsServerConfig::message_buffer_size`] names.
//!
//! [`Sender::try_send`] reports [`TrySendError::Full`] and
//! [`TrySendError::Closed`]. [`Sender::try_send_batch`] admits all frames at
//! once or leaves the queue unchanged. [`Receiver::recv`] yields `None` once
//! every sender is gone and the queue is empty, which the session classifies
//! as `Outbound::Closed`. Sends are synchronous, and a capacity of zero
//! never accepts a message.

use alloc::collections::VecDeque;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll, Waker};

use eko::thread::Mutex;

/// The shared queue. One mutex covers the buffer, the sender count and the
/// parked receiver, so a send cannot land between the empty check and the
/// waker store.
struct Inner<T> {
    queue: VecDeque<T>,
    capacity: usize,
    senders: usize,
    receiver_alive: bool,
    recv_waker: Option<Waker>,
}

/// Sending half of a [`channel`].
///
/// Cloning does not consume capacity. Dropping the last clone is what lets
/// [`Receiver::recv`] return `None`.
#[must_use = "dropping the sender closes the queue once the last one is gone"]
pub struct Sender<T> {
    shared: Arc<Mutex<Inner<T>>>,
}

/// Receiving half of a [`channel`].
///
/// Not cloneable. The session loop is the only reader.
#[must_use = "dropping the receiver closes the queue"]
pub struct Receiver<T> {
    shared: Arc<Mutex<Inner<T>>>,
}

/// [`Sender::try_send`] could not accept the message. The message comes back
/// with the error.
#[derive(Debug)]
pub enum TrySendError<T> {
    /// `len == capacity`. A cloned sender does not make this less likely.
    Full(T),
    /// The [`Receiver`] has been dropped. This is reported even when the
    /// buffer still has room, and even when it is already full.
    Closed(T),
}

/// A batch could not be queued atomically. The entire batch is returned.
#[derive(Debug)]
pub enum TrySendBatchError<T> {
    /// The [`Receiver`] has been dropped. This takes precedence over capacity.
    Closed(Vec<T>),
    /// The batch itself is larger than the queue's total capacity.
    TooLarge(Vec<T>),
    /// The batch would fit in an empty queue but not in the remaining slots.
    Full(Vec<T>),
}

impl<T> TrySendBatchError<T> {
    /// The batch that was not queued.
    pub fn into_inner(self) -> Vec<T> {
        match self {
            Self::Closed(batch) | Self::TooLarge(batch) | Self::Full(batch) => batch,
        }
    }
}

/// [`Receiver::try_recv`] found nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TryRecvError {
    /// No message yet, and a sender still exists.
    Empty,
    /// No message, and every sender has been dropped.
    Disconnected,
}

impl<T> TrySendError<T> {
    /// The message that was not queued.
    pub fn into_inner(self) -> T {
        match self {
            TrySendError::Full(value) | TrySendError::Closed(value) => value,
        }
    }
}

impl<T> core::fmt::Display for TrySendError<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TrySendError::Full(_) => f.write_str("outbound queue full"),
            TrySendError::Closed(_) => f.write_str("outbound queue closed"),
        }
    }
}

impl<T: core::fmt::Debug> core::error::Error for TrySendError<T> {}

impl core::fmt::Display for TryRecvError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            TryRecvError::Empty => f.write_str("outbound queue empty"),
            TryRecvError::Disconnected => f.write_str("outbound queue disconnected"),
        }
    }
}

impl core::error::Error for TryRecvError {}

/// Create a bounded queue. `capacity` is the maximum number of queued
/// messages, not a per-sender allowance. Zero accepts nothing via
/// [`Sender::try_send`].
pub fn channel<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
    let shared = Arc::new(Mutex::new(Inner {
        queue: VecDeque::new(),
        capacity,
        senders: 1,
        receiver_alive: true,
        recv_waker: None,
    }));
    (
        Sender {
            shared: Arc::clone(&shared),
        },
        Receiver { shared },
    )
}

impl<T> Clone for Sender<T> {
    fn clone(&self) -> Self {
        self.shared.lock().senders += 1;
        Self {
            shared: Arc::clone(&self.shared),
        }
    }
}

impl<T> Drop for Sender<T> {
    fn drop(&mut self) {
        let waker = {
            let mut inner = self.shared.lock();
            inner.senders -= 1;
            if inner.senders == 0 {
                inner.recv_waker.take()
            } else {
                None
            }
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }
}

impl<T> Sender<T> {
    /// Queue `value`, or give it back.
    ///
    /// A full buffer and a dropped receiver are different answers.
    /// [`TrySendError::Closed`] wins when both are true, so a late send after
    /// teardown is not reported as backpressure.
    pub fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
        let waker = {
            let mut inner = self.shared.lock();
            if !inner.receiver_alive {
                return Err(TrySendError::Closed(value));
            }
            if inner.queue.len() >= inner.capacity {
                return Err(TrySendError::Full(value));
            }
            inner.queue.push_back(value);
            inner.recv_waker.take()
        };
        if let Some(waker) = waker {
            waker.wake();
        }
        Ok(())
    }

    /// Queue every value in order, or return the entire batch unchanged.
    ///
    /// A dropped receiver takes precedence over both capacity errors. An
    /// empty batch succeeds while the receiver is alive.
    pub fn try_send_batch(&self, batch: Vec<T>) -> Result<(), TrySendBatchError<T>> {
        let waker = {
            let mut inner = self.shared.lock();
            if !inner.receiver_alive {
                return Err(TrySendBatchError::Closed(batch));
            }
            if batch.is_empty() {
                return Ok(());
            }
            if batch.len() > inner.capacity {
                return Err(TrySendBatchError::TooLarge(batch));
            }
            if batch.len() > inner.capacity - inner.queue.len() {
                return Err(TrySendBatchError::Full(batch));
            }
            inner.queue.extend(batch);
            inner.recv_waker.take()
        };
        if let Some(waker) = waker {
            waker.wake();
        }
        Ok(())
    }
}

impl<T> Drop for Receiver<T> {
    fn drop(&mut self) {
        self.shared.lock().receiver_alive = false;
    }
}

impl<T> Receiver<T> {
    /// The next message, if one is already queued.
    pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
        let mut inner = self.shared.lock();
        match inner.pop() {
            Pop::Value(value) => Ok(value),
            Pop::Empty => Err(TryRecvError::Empty),
            Pop::Closed => Err(TryRecvError::Disconnected),
        }
    }

    /// The next message, or `None` when every sender is gone and the queue
    /// is empty. Queued messages are delivered first.
    ///
    /// Cancel-safe: a message is removed only when this returns `Ready`.
    pub fn recv(&mut self) -> Recv<'_, T> {
        Recv { receiver: self }
    }
}

enum Pop<T> {
    Value(T),
    Empty,
    Closed,
}

impl<T> Inner<T> {
    fn pop(&mut self) -> Pop<T> {
        if let Some(value) = self.queue.pop_front() {
            Pop::Value(value)
        } else if self.senders == 0 {
            Pop::Closed
        } else {
            Pop::Empty
        }
    }
}

/// Future from [`Receiver::recv`].
pub struct Recv<'a, T> {
    receiver: &'a mut Receiver<T>,
}

impl<T> Future for Recv<'_, T> {
    type Output = Option<T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
        let this = self.get_mut();
        let mut inner = this.receiver.shared.lock();
        match inner.pop() {
            Pop::Value(value) => Poll::Ready(Some(value)),
            Pop::Closed => Poll::Ready(None),
            Pop::Empty => {
                match inner.recv_waker {
                    Some(ref parked) if parked.will_wake(cx.waker()) => {}
                    _ => inner.recv_waker = Some(cx.waker().clone()),
                }
                Poll::Pending
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::task::{Context, Poll, Wake, Waker};

    use super::{TryRecvError, TrySendBatchError, TrySendError, channel};

    struct Flag(AtomicBool);

    impl Wake for Flag {
        fn wake(self: Arc<Self>) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    fn flag_waker() -> (Arc<Flag>, Waker) {
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let waker = Waker::from(Arc::clone(&flag));
        (flag, waker)
    }

    #[test]
    fn sends_leave_in_arrival_order() {
        let (tx, mut rx) = channel(4);
        let tx2 = tx.clone();
        tx.try_send(1).unwrap();
        tx2.try_send(2).unwrap();
        tx.try_send(3).unwrap();
        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);
        assert_eq!(rx.try_recv().unwrap(), 3);
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
    }

    #[test]
    fn batch_admission_is_atomic_and_preserves_order() {
        let (tx, mut rx) = channel(4);
        tx.try_send(0).unwrap();

        let result = tx.try_send_batch(vec![1, 2, 3, 4]);
        let Err(TrySendBatchError::Full(batch)) = result else {
            panic!("expected Full, got {result:?}");
        };
        assert_eq!(batch, [1, 2, 3, 4]);
        assert_eq!(rx.try_recv(), Ok(0));
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));

        tx.try_send(0).unwrap();
        let result = tx.try_send_batch(vec![1, 2, 3, 4, 5]);
        let Err(TrySendBatchError::TooLarge(batch)) = result else {
            panic!("expected TooLarge, got {result:?}");
        };
        assert_eq!(batch, [1, 2, 3, 4, 5]);
        assert_eq!(rx.try_recv(), Ok(0));
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));

        tx.try_send(0).unwrap();
        tx.try_send_batch(vec![1, 2, 3]).unwrap();
        for expected in 0..4 {
            assert_eq!(rx.try_recv(), Ok(expected));
        }
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
    }

    #[test]
    fn batch_rejects_closed_receiver_before_capacity_checks() {
        let (tx, rx) = channel(1);
        tx.try_send(0).unwrap();
        drop(rx);

        let error = tx.try_send_batch(vec![1, 2]).unwrap_err();
        assert!(matches!(&error, TrySendBatchError::Closed(_)));
        assert_eq!(error.into_inner(), [1, 2]);
    }

    #[test]
    fn batch_wakes_a_parked_receiver_when_frames_are_admitted() {
        let (tx, mut rx) = channel(2);
        let (flag, waker) = flag_waker();
        let mut cx = Context::from_waker(&waker);
        {
            let mut recv = std::pin::pin!(rx.recv());
            assert!(recv.as_mut().poll(&mut cx).is_pending());
            tx.try_send_batch(Vec::new()).unwrap();
            assert!(!flag.0.load(Ordering::SeqCst));

            tx.try_send_batch(vec![4, 5]).unwrap();
            assert!(flag.0.load(Ordering::SeqCst));
            assert_eq!(recv.as_mut().poll(&mut cx), Poll::Ready(Some(4)));
        }
        assert_eq!(rx.try_recv(), Ok(5));
    }

    #[test]
    fn cloned_senders_do_not_add_capacity() {
        let (tx, _rx) = channel(1);
        let second = tx.clone();
        let third = tx.clone();
        tx.try_send(1).unwrap();
        assert!(matches!(second.try_send(2), Err(TrySendError::Full(2))));
        assert!(matches!(third.try_send(3), Err(TrySendError::Full(3))));
    }

    #[test]
    fn a_dropped_receiver_is_closed_even_when_full() {
        let (tx, rx) = channel(1);
        tx.try_send(1).unwrap();
        drop(rx);
        assert!(matches!(tx.try_send(2), Err(TrySendError::Closed(2))));
        assert_eq!(tx.try_send(3).unwrap_err().into_inner(), 3);
    }

    #[test]
    fn a_dropped_receiver_is_closed_while_there_is_room() {
        let (tx, rx) = channel(4);
        drop(rx);
        assert!(matches!(tx.try_send(1), Err(TrySendError::Closed(1))));
    }

    #[test]
    fn zero_capacity_rejects_while_the_receiver_lives() {
        let (tx, rx) = channel::<u8>(0);
        assert!(matches!(tx.try_send(1), Err(TrySendError::Full(1))));
        drop(rx);
        assert!(matches!(tx.try_send(1), Err(TrySendError::Closed(1))));
    }

    #[test]
    fn empty_while_a_sender_lives_and_disconnected_after_the_last_drop() {
        let (tx, mut rx) = channel::<u8>(1);
        let extra = tx.clone();
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
        drop(tx);
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
        drop(extra);
        assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
    }

    #[test]
    fn queued_messages_are_read_before_close() {
        let (tx, mut rx) = channel(2);
        tx.try_send(1).unwrap();
        tx.try_send(2).unwrap();
        drop(tx);
        assert_eq!(rx.try_recv().unwrap(), 1);
        assert_eq!(rx.try_recv().unwrap(), 2);
        assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));

        let waker = flag_waker().1;
        let mut cx = Context::from_waker(&waker);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(None)));
    }

    #[test]
    fn a_message_sent_before_recv_is_ready_without_parking() {
        let (tx, mut rx) = channel(1);
        tx.try_send(9).unwrap();
        let waker = flag_waker().1;
        let mut cx = Context::from_waker(&waker);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(Some(9))));
    }

    #[test]
    fn a_parked_recv_wakes_when_a_message_arrives() {
        let (tx, mut rx) = channel(1);
        let (flag, waker) = flag_waker();
        let mut cx = Context::from_waker(&waker);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(recv.as_mut().poll(&mut cx).is_pending());
        assert!(!flag.0.load(Ordering::SeqCst));
        tx.try_send(7).unwrap();
        assert!(flag.0.load(Ordering::SeqCst));
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(Some(7))));
    }

    #[test]
    fn the_receiver_parks_again_after_taking_a_message() {
        let (tx, mut rx) = channel(2);
        let (flag, waker) = flag_waker();
        let mut cx = Context::from_waker(&waker);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(recv.as_mut().poll(&mut cx).is_pending());
        tx.try_send(1).unwrap();
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(Some(1))));

        flag.0.store(false, Ordering::SeqCst);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(recv.as_mut().poll(&mut cx).is_pending());
        tx.try_send(2).unwrap();
        assert!(flag.0.load(Ordering::SeqCst));
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(Some(2))));
    }

    #[test]
    fn a_parked_recv_completes_when_the_last_sender_drops() {
        let (tx, mut rx) = channel::<u8>(1);
        let extra = tx.clone();
        drop(tx);
        let (flag, waker) = flag_waker();
        let mut cx = Context::from_waker(&waker);
        let mut recv = std::pin::pin!(rx.recv());
        assert!(recv.as_mut().poll(&mut cx).is_pending());
        drop(extra);
        assert!(flag.0.load(Ordering::SeqCst));
        assert!(matches!(recv.as_mut().poll(&mut cx), Poll::Ready(None)));
    }

    #[test]
    fn dropping_one_sender_does_not_close() {
        let (tx, mut rx) = channel(1);
        let extra = tx.clone();
        drop(tx);
        extra.try_send(4).unwrap();
        assert_eq!(rx.try_recv().unwrap(), 4);
        assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
    }
}