commonware-utils 2026.7.0

Leverage common functionality across multiple primitives.
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
//! Utilities for graceful channel shutdown handling.
//!
//! When actors communicate via channels, senders may outlive receivers during shutdown.
//! This module provides extension traits and helpers that handle disconnection gracefully
//! rather than panicking.
//!
//! # Example
//!
//! ```ignore
//! use commonware_utils::channel::fallible::FallibleExt;
//!
//! // Fire-and-forget: silently ignore disconnection
//! sender.send_lossy(Message::Shutdown);
//!
//! // Request-response: return None on disconnection
//! let result = sender.request(|tx| Message::Query { responder: tx }).await;
//! ```

use super::{
    mpsc, oneshot,
    reservation::{Reservation, ReservationExt},
};
use std::future::Future;

/// Extension trait for channel operations that may fail due to disconnection.
///
/// Use these methods when the receiver may be dropped during shutdown
/// and you want to handle that gracefully rather than panicking.
pub trait FallibleExt<T> {
    /// Send a message, returning `true` if successful.
    ///
    /// Use this for fire-and-forget messages where the receiver
    /// may have been dropped during shutdown. The return value can
    /// be ignored if the caller doesn't need to know whether the
    /// send succeeded.
    fn send_lossy(&self, msg: T) -> bool;

    /// Send a request message containing a oneshot responder and await the response.
    ///
    /// Returns `None` if:
    /// - The receiver has been dropped (send fails)
    /// - The responder is dropped without sending (receive fails)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let dialable: Option<Vec<PublicKey>> = sender
    ///     .request(|tx| Message::Dialable { responder: tx })
    ///     .await;
    /// ```
    fn request<R, F>(&self, make_msg: F) -> impl Future<Output = Option<R>> + Send
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;

    /// Send a request and return the provided default on failure.
    ///
    /// This is a convenience wrapper around [`request`](Self::request) for cases
    /// where you have a sensible default value.
    fn request_or<R, F>(&self, make_msg: F, default: R) -> impl Future<Output = R> + Send
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;

    /// Send a request and return `R::default()` on failure.
    ///
    /// This is a convenience wrapper around [`request`](Self::request) for types
    /// that implement [`Default`].
    fn request_or_default<R, F>(&self, make_msg: F) -> impl Future<Output = R> + Send
    where
        R: Default + Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;
}

impl<T: Send> FallibleExt<T> for mpsc::UnboundedSender<T> {
    fn send_lossy(&self, msg: T) -> bool {
        self.send(msg).is_ok()
    }

    async fn request<R, F>(&self, make_msg: F) -> Option<R>
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        let (tx, rx) = oneshot::channel();
        if self.send(make_msg(tx)).is_err() {
            return None;
        }
        rx.await.ok()
    }

    async fn request_or<R, F>(&self, make_msg: F, default: R) -> R
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        self.request(make_msg).await.unwrap_or(default)
    }

    async fn request_or_default<R, F>(&self, make_msg: F) -> R
    where
        R: Default + Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        self.request(make_msg).await.unwrap_or_default()
    }
}

/// Extension trait for bounded channel operations that may fail due to disconnection.
///
/// Similar to [`FallibleExt`] but for bounded channels where send operations are async.
pub trait AsyncFallibleExt<T> {
    /// Send a message asynchronously, returning `true` if successful.
    ///
    /// Use this for fire-and-forget messages where the receiver
    /// may have been dropped during shutdown. The return value can
    /// be ignored if the caller doesn't need to know whether the
    /// send succeeded.
    fn send_lossy(&self, msg: T) -> impl Future<Output = bool> + Send;

    /// Try to send a message without blocking, returning `true` if successful.
    ///
    /// Use this for fire-and-forget messages where you don't want to wait
    /// if the channel is full. Returns `false` if the channel is full or
    /// disconnected.
    fn try_send_lossy(&self, msg: T) -> bool;

    /// Attempts to send immediately, reserving the message when the channel is full.
    ///
    /// Returns `None` if the value was sent immediately or the receiver has been dropped.
    #[must_use = "await and send any reservation"]
    fn send_or_reserve_lossy(&self, msg: T) -> Option<Reservation<T>>
    where
        T: 'static;

    /// Send a request message containing a oneshot responder and await the response.
    ///
    /// Returns `None` if:
    /// - The receiver has been dropped (send fails)
    /// - The responder is dropped without sending (receive fails)
    fn request<R, F>(&self, make_msg: F) -> impl Future<Output = Option<R>> + Send
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;

    /// Send a request and return the provided default on failure.
    fn request_or<R, F>(&self, make_msg: F, default: R) -> impl Future<Output = R> + Send
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;

    /// Send a request and return `R::default()` on failure.
    fn request_or_default<R, F>(&self, make_msg: F) -> impl Future<Output = R> + Send
    where
        R: Default + Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send;
}

impl<T: Send> AsyncFallibleExt<T> for mpsc::Sender<T> {
    async fn send_lossy(&self, msg: T) -> bool {
        self.send(msg).await.is_ok()
    }

    fn try_send_lossy(&self, msg: T) -> bool {
        self.try_send(msg).is_ok()
    }

    fn send_or_reserve_lossy(&self, msg: T) -> Option<Reservation<T>>
    where
        T: 'static,
    {
        self.send_or_reserve(msg).ok().flatten()
    }

    async fn request<R, F>(&self, make_msg: F) -> Option<R>
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        let (tx, rx) = oneshot::channel();
        if self.send(make_msg(tx)).await.is_err() {
            return None;
        }
        rx.await.ok()
    }

    async fn request_or<R, F>(&self, make_msg: F, default: R) -> R
    where
        R: Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        self.request(make_msg).await.unwrap_or(default)
    }

    async fn request_or_default<R, F>(&self, make_msg: F) -> R
    where
        R: Default + Send,
        F: FnOnce(oneshot::Sender<R>) -> T + Send,
    {
        self.request(make_msg).await.unwrap_or_default()
    }
}

/// Extension trait for oneshot sender operations that may fail due to disconnection.
///
/// Use this when the receiver may have been dropped during shutdown
/// and you want to handle that gracefully rather than panicking.
pub trait OneshotExt<T> {
    /// Send a value, returning `true` if successful.
    ///
    /// Use this for fire-and-forget responses where the requester
    /// may have been dropped during shutdown. The return value can
    /// be ignored if the caller doesn't need to know whether the
    /// send succeeded.
    ///
    /// Consumes the sender.
    fn send_lossy(self, msg: T) -> bool;
}

impl<T> OneshotExt<T> for oneshot::Sender<T> {
    fn send_lossy(self, msg: T) -> bool {
        self.send(msg).is_ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use commonware_macros::test_async;

    #[derive(Debug)]
    #[allow(dead_code)]
    enum TestMessage {
        FireAndForget(u32),
        Request {
            responder: oneshot::Sender<String>,
        },
        RequestBool {
            responder: oneshot::Sender<bool>,
        },
        RequestVec {
            responder: oneshot::Sender<Vec<u32>>,
        },
    }

    #[test]
    fn test_send_lossy_success() {
        let (tx, mut rx) = mpsc::unbounded_channel();
        assert!(tx.send_lossy(TestMessage::FireAndForget(42)));

        // Message should be received
        assert!(matches!(rx.try_recv(), Ok(TestMessage::FireAndForget(42))));
    }

    #[test]
    fn test_send_lossy_disconnected() {
        let (tx, rx) = mpsc::unbounded_channel::<TestMessage>();
        drop(rx);

        // Should not panic, returns false
        assert!(!tx.send_lossy(TestMessage::FireAndForget(42)));
    }

    #[test_async]
    async fn test_request_send_disconnected() {
        let (tx, rx) = mpsc::unbounded_channel::<TestMessage>();
        drop(rx);

        let result: Option<String> = tx
            .request(|responder| TestMessage::Request { responder })
            .await;

        assert_eq!(result, None);
    }

    #[test_async]
    async fn test_request_or_disconnected() {
        let (tx, rx) = mpsc::unbounded_channel::<TestMessage>();
        drop(rx);

        let result = tx
            .request_or(|responder| TestMessage::RequestBool { responder }, false)
            .await;

        assert!(!result);
    }

    #[test_async]
    async fn test_request_or_default_disconnected() {
        let (tx, rx) = mpsc::unbounded_channel::<TestMessage>();
        drop(rx);

        let result: Vec<u32> = tx
            .request_or_default(|responder| TestMessage::RequestVec { responder })
            .await;

        assert!(result.is_empty());
    }

    // AsyncFallibleExt tests for bounded channels

    #[test_async]
    async fn test_async_send_lossy_success() {
        let (tx, mut rx) = mpsc::channel(1);
        assert!(tx.send_lossy(TestMessage::FireAndForget(42)).await);

        // Message should be received
        assert!(matches!(rx.try_recv(), Ok(TestMessage::FireAndForget(42))));
    }

    #[test_async]
    async fn test_async_send_lossy_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        // Should not panic, returns false
        assert!(!tx.send_lossy(TestMessage::FireAndForget(42)).await);
    }

    #[test_async]
    async fn test_async_request_send_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        let result: Option<String> =
            AsyncFallibleExt::request(&tx, |responder| TestMessage::Request { responder }).await;

        assert_eq!(result, None);
    }

    #[test_async]
    async fn test_async_request_or_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        let result = AsyncFallibleExt::request_or(
            &tx,
            |responder| TestMessage::RequestBool { responder },
            false,
        )
        .await;

        assert!(!result);
    }

    #[test_async]
    async fn test_async_request_or_default_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        let result: Vec<u32> = AsyncFallibleExt::request_or_default(&tx, |responder| {
            TestMessage::RequestVec { responder }
        })
        .await;

        assert!(result.is_empty());
    }

    // try_send_lossy tests

    #[test]
    fn test_try_send_lossy_success() {
        let (tx, mut rx) = mpsc::channel(1);
        assert!(tx.try_send_lossy(TestMessage::FireAndForget(42)));

        // Message should be received
        assert!(matches!(rx.try_recv(), Ok(TestMessage::FireAndForget(42))));
    }

    #[test]
    fn test_try_send_lossy_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        // Should not panic, returns false
        assert!(!tx.try_send_lossy(TestMessage::FireAndForget(42)));
    }

    // send_or_reserve_lossy tests

    #[test]
    fn test_send_or_reserve_lossy_success() {
        let (tx, mut rx) = mpsc::channel(1);

        assert!(tx
            .send_or_reserve_lossy(TestMessage::FireAndForget(42))
            .is_none());
        assert!(matches!(rx.try_recv(), Ok(TestMessage::FireAndForget(42))));
    }

    #[test]
    fn test_send_or_reserve_lossy_disconnected() {
        let (tx, rx) = mpsc::channel::<TestMessage>(1);
        drop(rx);

        assert!(tx
            .send_or_reserve_lossy(TestMessage::FireAndForget(42))
            .is_none());
    }

    #[test_async]
    async fn test_send_or_reserve_lossy_reserves_when_full() {
        let (tx, mut rx) = mpsc::channel(1);
        tx.try_send(TestMessage::FireAndForget(1)).unwrap();

        let reservation = tx
            .send_or_reserve_lossy(TestMessage::FireAndForget(2))
            .expect("receiver should be open");

        assert!(matches!(
            rx.recv().await,
            Some(TestMessage::FireAndForget(1))
        ));
        reservation.await.unwrap().send();
        assert!(matches!(
            rx.recv().await,
            Some(TestMessage::FireAndForget(2))
        ));
    }

    #[test_async]
    async fn test_send_or_reserve_lossy_reserved_disconnected() {
        let (tx, rx) = mpsc::channel(1);
        tx.try_send(TestMessage::FireAndForget(1)).unwrap();

        let reservation = tx
            .send_or_reserve_lossy(TestMessage::FireAndForget(2))
            .expect("receiver should be open");
        drop(rx);

        assert!(reservation.await.is_err());
    }

    // OneshotExt tests

    #[test]
    fn test_oneshot_send_lossy_success() {
        let (tx, mut rx) = oneshot::channel::<u32>();
        assert!(tx.send_lossy(42));
        assert_eq!(rx.try_recv(), Ok(42));
    }

    #[test]
    fn test_oneshot_send_lossy_disconnected() {
        let (tx, rx) = oneshot::channel::<u32>();
        drop(rx);
        assert!(!tx.send_lossy(42));
    }
}