ipckit 0.1.6

A cross-platform IPC (Inter-Process Communication) library for Rust and Python
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
//! Thread Channel for intra-process thread communication
//!
//! This module provides a high-performance channel for communication between threads
//! within the same process, using crossbeam-channel as the underlying implementation.
//!
//! # Example
//!
//! ```rust
//! use ipckit::ThreadChannel;
//! use std::thread;
//!
//! // Create an unbounded channel
//! let (tx, rx) = ThreadChannel::<String>::unbounded();
//!
//! thread::spawn(move || {
//!     tx.send("Hello from thread!".to_string()).unwrap();
//! });
//!
//! let msg = rx.recv().unwrap();
//! assert_eq!(msg, "Hello from thread!");
//! ```

use crate::error::{IpcError, Result};
use crate::graceful::{GracefulChannel, ShutdownState};
use crossbeam_channel::{self, Receiver, RecvTimeoutError, Sender, TryRecvError, TrySendError};
use std::sync::Arc;
use std::time::Duration;

/// A thread-safe channel sender for intra-process communication.
///
/// This is the sending half of a [`ThreadChannel`]. It can be cloned to create
/// multiple producers that send to the same channel.
#[derive(Debug)]
pub struct ThreadSender<T> {
    inner: Sender<T>,
    shutdown: Arc<ShutdownState>,
}

/// A thread-safe channel receiver for intra-process communication.
///
/// This is the receiving half of a [`ThreadChannel`]. It can be cloned to create
/// multiple consumers that receive from the same channel.
#[derive(Debug)]
pub struct ThreadReceiver<T> {
    inner: Receiver<T>,
    shutdown: Arc<ShutdownState>,
}

impl<T> Clone for ThreadSender<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            shutdown: Arc::clone(&self.shutdown),
        }
    }
}

impl<T> Clone for ThreadReceiver<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            shutdown: Arc::clone(&self.shutdown),
        }
    }
}

impl<T> ThreadSender<T> {
    /// Send a message through the channel.
    ///
    /// This method blocks if the channel is bounded and full.
    ///
    /// # Errors
    ///
    /// Returns `IpcError::Closed` if the channel has been shutdown or all receivers have been dropped.
    pub fn send(&self, msg: T) -> Result<()> {
        if self.shutdown.is_shutdown() {
            return Err(IpcError::Closed);
        }

        self.inner.send(msg).map_err(|_| IpcError::Closed)
    }

    /// Try to send a message without blocking.
    ///
    /// # Errors
    ///
    /// - `IpcError::Closed` if the channel has been shutdown or all receivers have been dropped.
    /// - `IpcError::WouldBlock` if the channel is full (bounded channels only).
    pub fn try_send(&self, msg: T) -> Result<()> {
        if self.shutdown.is_shutdown() {
            return Err(IpcError::Closed);
        }

        self.inner.try_send(msg).map_err(|e| match e {
            TrySendError::Full(_) => IpcError::WouldBlock,
            TrySendError::Disconnected(_) => IpcError::Closed,
        })
    }

    /// Send a message with a timeout.
    ///
    /// # Errors
    ///
    /// - `IpcError::Closed` if the channel has been shutdown or all receivers have been dropped.
    /// - `IpcError::Timeout` if the timeout expires before the message can be sent.
    pub fn send_timeout(&self, msg: T, timeout: Duration) -> Result<()> {
        if self.shutdown.is_shutdown() {
            return Err(IpcError::Closed);
        }

        self.inner.send_timeout(msg, timeout).map_err(|e| {
            if e.is_timeout() {
                IpcError::Timeout
            } else {
                IpcError::Closed
            }
        })
    }

    /// Check if the channel is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Check if the channel is full (always false for unbounded channels).
    pub fn is_full(&self) -> bool {
        self.inner.is_full()
    }

    /// Get the number of messages in the channel.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Get the capacity of the channel (None for unbounded channels).
    pub fn capacity(&self) -> Option<usize> {
        self.inner.capacity()
    }

    /// Check if the channel has been shutdown.
    pub fn is_shutdown(&self) -> bool {
        self.shutdown.is_shutdown()
    }

    /// Shutdown the channel.
    pub fn shutdown(&self) {
        self.shutdown.shutdown();
    }
}

impl<T> ThreadReceiver<T> {
    /// Receive a message from the channel.
    ///
    /// This method blocks until a message is available.
    ///
    /// # Errors
    ///
    /// Returns `IpcError::Closed` if the channel has been shutdown or all senders have been dropped.
    pub fn recv(&self) -> Result<T> {
        if self.shutdown.is_shutdown() {
            // Try to drain remaining messages first
            return self.inner.try_recv().map_err(|_| IpcError::Closed);
        }

        self.inner.recv().map_err(|_| IpcError::Closed)
    }

    /// Try to receive a message without blocking.
    ///
    /// # Errors
    ///
    /// - `IpcError::Closed` if the channel has been shutdown or all senders have been dropped.
    /// - `IpcError::WouldBlock` if no message is available.
    pub fn try_recv(&self) -> Result<T> {
        self.inner.try_recv().map_err(|e| match e {
            TryRecvError::Empty => IpcError::WouldBlock,
            TryRecvError::Disconnected => IpcError::Closed,
        })
    }

    /// Receive a message with a timeout.
    ///
    /// # Errors
    ///
    /// - `IpcError::Closed` if the channel has been shutdown or all senders have been dropped.
    /// - `IpcError::Timeout` if the timeout expires before a message is available.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<T> {
        if self.shutdown.is_shutdown() {
            return self.try_recv();
        }

        self.inner.recv_timeout(timeout).map_err(|e| match e {
            RecvTimeoutError::Timeout => IpcError::Timeout,
            RecvTimeoutError::Disconnected => IpcError::Closed,
        })
    }

    /// Check if the channel is empty.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get the number of messages in the channel.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Get the capacity of the channel (None for unbounded channels).
    pub fn capacity(&self) -> Option<usize> {
        self.inner.capacity()
    }

    /// Check if the channel has been shutdown.
    pub fn is_shutdown(&self) -> bool {
        self.shutdown.is_shutdown()
    }

    /// Shutdown the channel.
    pub fn shutdown(&self) {
        self.shutdown.shutdown();
    }

    /// Create an iterator over received messages.
    ///
    /// The iterator will block waiting for messages and will stop when the channel is closed.
    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
        std::iter::from_fn(move || self.recv().ok())
    }

    /// Create a non-blocking iterator over available messages.
    ///
    /// The iterator will return `None` when no more messages are immediately available.
    pub fn try_iter(&self) -> impl Iterator<Item = T> + '_ {
        std::iter::from_fn(move || self.try_recv().ok())
    }
}

/// A bidirectional thread channel that combines both sender and receiver.
///
/// This is useful when you need both send and receive capabilities in one place.
#[derive(Debug)]
pub struct ThreadChannel<T> {
    sender: ThreadSender<T>,
    receiver: ThreadReceiver<T>,
}

impl<T> ThreadChannel<T> {
    /// Create a new unbounded thread channel.
    ///
    /// An unbounded channel has no capacity limit and will never block on send.
    ///
    /// # Returns
    ///
    /// A tuple of (sender, receiver) for the channel.
    pub fn unbounded() -> (ThreadSender<T>, ThreadReceiver<T>) {
        let (tx, rx) = crossbeam_channel::unbounded();
        let shutdown = Arc::new(ShutdownState::new());

        let sender = ThreadSender {
            inner: tx,
            shutdown: Arc::clone(&shutdown),
        };

        let receiver = ThreadReceiver {
            inner: rx,
            shutdown,
        };

        (sender, receiver)
    }

    /// Create a new bounded thread channel with the specified capacity.
    ///
    /// A bounded channel will block on send when the channel is full.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The maximum number of messages the channel can hold.
    ///
    /// # Returns
    ///
    /// A tuple of (sender, receiver) for the channel.
    pub fn bounded(capacity: usize) -> (ThreadSender<T>, ThreadReceiver<T>) {
        let (tx, rx) = crossbeam_channel::bounded(capacity);
        let shutdown = Arc::new(ShutdownState::new());

        let sender = ThreadSender {
            inner: tx,
            shutdown: Arc::clone(&shutdown),
        };

        let receiver = ThreadReceiver {
            inner: rx,
            shutdown,
        };

        (sender, receiver)
    }

    /// Create a new bidirectional thread channel (unbounded).
    pub fn new_unbounded() -> Self {
        let (sender, receiver) = Self::unbounded();
        Self { sender, receiver }
    }

    /// Create a new bidirectional thread channel (bounded).
    pub fn new_bounded(capacity: usize) -> Self {
        let (sender, receiver) = Self::bounded(capacity);
        Self { sender, receiver }
    }

    /// Get a reference to the sender.
    pub fn sender(&self) -> &ThreadSender<T> {
        &self.sender
    }

    /// Get a reference to the receiver.
    pub fn receiver(&self) -> &ThreadReceiver<T> {
        &self.receiver
    }

    /// Clone the sender.
    pub fn clone_sender(&self) -> ThreadSender<T> {
        self.sender.clone()
    }

    /// Clone the receiver.
    pub fn clone_receiver(&self) -> ThreadReceiver<T> {
        self.receiver.clone()
    }

    /// Split the channel into sender and receiver.
    pub fn split(self) -> (ThreadSender<T>, ThreadReceiver<T>) {
        (self.sender, self.receiver)
    }
}

impl<T> GracefulChannel for ThreadChannel<T> {
    fn shutdown(&self) {
        self.sender.shutdown();
    }

    fn is_shutdown(&self) -> bool {
        self.sender.is_shutdown()
    }

    fn drain(&self) -> Result<()> {
        // For thread channels, drain means receiving all pending messages
        while self.receiver.try_recv().is_ok() {}
        Ok(())
    }

    fn shutdown_timeout(&self, timeout: Duration) -> Result<()> {
        self.shutdown();
        let start = std::time::Instant::now();

        while !self.receiver.is_empty() {
            if start.elapsed() >= timeout {
                return Err(IpcError::Timeout);
            }
            let _ = self.receiver.try_recv();
            std::thread::sleep(Duration::from_millis(1));
        }

        Ok(())
    }
}

impl<T> GracefulChannel for ThreadSender<T> {
    fn shutdown(&self) {
        self.shutdown.shutdown();
    }

    fn is_shutdown(&self) -> bool {
        self.shutdown.is_shutdown()
    }

    fn drain(&self) -> Result<()> {
        self.shutdown.wait_for_drain(None)
    }

    fn shutdown_timeout(&self, timeout: Duration) -> Result<()> {
        self.shutdown();
        self.shutdown.wait_for_drain(Some(timeout))
    }
}

impl<T> GracefulChannel for ThreadReceiver<T> {
    fn shutdown(&self) {
        self.shutdown.shutdown();
    }

    fn is_shutdown(&self) -> bool {
        self.shutdown.is_shutdown()
    }

    fn drain(&self) -> Result<()> {
        while self.try_recv().is_ok() {}
        Ok(())
    }

    fn shutdown_timeout(&self, timeout: Duration) -> Result<()> {
        self.shutdown();
        let start = std::time::Instant::now();

        while !self.is_empty() {
            if start.elapsed() >= timeout {
                return Err(IpcError::Timeout);
            }
            let _ = self.try_recv();
            std::thread::sleep(Duration::from_millis(1));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_unbounded_channel() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        tx.send(42).unwrap();
        tx.send(43).unwrap();

        assert_eq!(rx.recv().unwrap(), 42);
        assert_eq!(rx.recv().unwrap(), 43);
    }

    #[test]
    fn test_bounded_channel() {
        let (tx, rx) = ThreadChannel::<i32>::bounded(2);

        tx.send(1).unwrap();
        tx.send(2).unwrap();

        // Channel is full, try_send should fail
        assert!(matches!(tx.try_send(3), Err(IpcError::WouldBlock)));

        assert_eq!(rx.recv().unwrap(), 1);

        // Now we can send again
        tx.send(3).unwrap();

        assert_eq!(rx.recv().unwrap(), 2);
        assert_eq!(rx.recv().unwrap(), 3);
    }

    #[test]
    fn test_multi_producer() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();
        let tx2 = tx.clone();

        let h1 = thread::spawn(move || {
            for i in 0..5 {
                tx.send(i).unwrap();
            }
        });

        let h2 = thread::spawn(move || {
            for i in 5..10 {
                tx2.send(i).unwrap();
            }
        });

        h1.join().unwrap();
        h2.join().unwrap();

        let mut received: Vec<i32> = rx.try_iter().collect();
        received.sort();

        assert_eq!(received, (0..10).collect::<Vec<_>>());
    }

    #[test]
    fn test_multi_consumer() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();
        let rx2 = rx.clone();

        for i in 0..10 {
            tx.send(i).unwrap();
        }
        drop(tx);

        let h1 = thread::spawn(move || {
            let mut received = Vec::new();
            while let Ok(v) = rx.recv() {
                received.push(v);
            }
            received
        });

        let h2 = thread::spawn(move || {
            let mut received = Vec::new();
            while let Ok(v) = rx2.recv() {
                received.push(v);
            }
            received
        });

        let r1 = h1.join().unwrap();
        let r2 = h2.join().unwrap();

        let mut all: Vec<i32> = r1.into_iter().chain(r2).collect();
        all.sort();

        assert_eq!(all, (0..10).collect::<Vec<_>>());
    }

    #[test]
    fn test_shutdown() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        tx.send(1).unwrap();
        tx.shutdown();

        // Should fail after shutdown
        assert!(matches!(tx.send(2), Err(IpcError::Closed)));

        // Can still receive pending messages
        assert_eq!(rx.recv().unwrap(), 1);
    }

    #[test]
    fn test_recv_timeout() {
        let (_tx, rx) = ThreadChannel::<i32>::unbounded();

        let result = rx.recv_timeout(Duration::from_millis(50));
        assert!(matches!(result, Err(IpcError::Timeout)));
    }

    #[test]
    fn test_send_timeout() {
        let (tx, _rx) = ThreadChannel::<i32>::bounded(1);

        tx.send(1).unwrap();

        let result = tx.send_timeout(2, Duration::from_millis(50));
        assert!(matches!(result, Err(IpcError::Timeout)));
    }

    #[test]
    fn test_try_recv() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        assert!(matches!(rx.try_recv(), Err(IpcError::WouldBlock)));

        tx.send(42).unwrap();

        assert_eq!(rx.try_recv().unwrap(), 42);
        assert!(matches!(rx.try_recv(), Err(IpcError::WouldBlock)));
    }

    #[test]
    fn test_channel_capacity() {
        let (tx, rx) = ThreadChannel::<i32>::bounded(5);

        assert_eq!(tx.capacity(), Some(5));
        assert_eq!(rx.capacity(), Some(5));
        assert!(tx.is_empty());
        assert!(!tx.is_full());

        for i in 0..5 {
            tx.send(i).unwrap();
        }

        assert!(tx.is_full());
        assert!(!tx.is_empty());
        assert_eq!(tx.len(), 5);
    }

    #[test]
    fn test_unbounded_capacity() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        assert_eq!(tx.capacity(), None);
        assert_eq!(rx.capacity(), None);
        assert!(!tx.is_full()); // Unbounded is never full
    }

    #[test]
    fn test_graceful_channel_trait() {
        let channel = ThreadChannel::<i32>::new_unbounded();

        assert!(!channel.is_shutdown());

        channel.sender().send(1).unwrap();
        channel.sender().send(2).unwrap();

        channel.shutdown();

        assert!(channel.is_shutdown());

        // Drain remaining messages
        channel.drain().unwrap();

        assert!(channel.receiver().is_empty());
    }

    #[test]
    fn test_iter() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        tx.send(1).unwrap();
        tx.send(2).unwrap();
        tx.send(3).unwrap();
        drop(tx);

        let collected: Vec<i32> = rx.iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }

    #[test]
    fn test_try_iter() {
        let (tx, rx) = ThreadChannel::<i32>::unbounded();

        tx.send(1).unwrap();
        tx.send(2).unwrap();

        let collected: Vec<i32> = rx.try_iter().collect();
        assert_eq!(collected, vec![1, 2]);

        // try_iter doesn't block, so we can continue
        tx.send(3).unwrap();
        assert_eq!(rx.recv().unwrap(), 3);
    }
}