kyron-foundation 0.0.1

kyron: foundational components for runtime
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
//
// Copyright (c) 2025 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache License Version 2.0 which is available at
// <https://www.apache.org/licenses/LICENSE-2.0>
//
// SPDX-License-Identifier: Apache-2.0
//

use crate::prelude::*;
use crate::{prelude::FoundationAtomicBool, types::CommonErrors};

use super::queue::Queue;
use std::sync::{Arc, Condvar, Mutex};

///
/// Implements the **threadsafe** FIFO queue that triggers consumer once new data is added. This is MPSC implementation
///
pub struct TriggerQueue<T> {
    mtx: Mutex<Queue<T>>,
    cv: Condvar,
    state: FoundationAtomicBool, // true when sleeping, used to not do notify (syscall) when consumer is anyway not waiting on it
    has_consumer: FoundationAtomicBool,
}

unsafe impl<T: Send> Send for TriggerQueue<T> {}
unsafe impl<T> Sync for TriggerQueue<T> {}

pub struct TriggerQueueConsumer<T> {
    queue: Arc<TriggerQueue<T>>,
}

impl<T> TriggerQueueConsumer<T> {
    ///
    /// Pops single element from queue if present
    ///
    pub fn pop(&self) -> Option<T> {
        self.queue.pop()
    }

    ///
    /// Pops up to `container.size()` elements from the queue using single lock operation. This helps to minimize number of OS calls if you have a local storage
    ///
    pub fn pop_into_vec(&self, container: &mut Vec<T>) {
        self.queue.pop_into_vec(container)
    }

    ///
    /// Pops an item from a queue once it's available, otherwise it does block up to `dur`.
    ///
    pub fn pop_blocking_with_timeout(&self, dur: ::core::time::Duration) -> Result<T, CommonErrors> {
        self.queue.pop_blocking_with_timeout(dur)
    }

    ///
    /// Pops an item from a queue once it's available, otherwise it does block and wait until elem is present
    ///
    pub fn pop_blocking(&self) -> T {
        self.queue.pop_blocking()
    }

    ///
    /// Returns max number of elements queue can hold
    ///
    pub fn capacity(&self) -> usize {
        self.queue.capacity()
    }
}

impl<T> Drop for TriggerQueueConsumer<T> {
    fn drop(&mut self) {
        self.queue.has_consumer.store(false, ::core::sync::atomic::Ordering::SeqCst);
    }
}

impl<T> TriggerQueue<T> {
    ///
    /// Creates queue with `count` size, must be power of two
    ///
    pub fn new(count: usize) -> Self {
        Self {
            mtx: Mutex::new(Queue::new(count)),
            cv: Condvar::new(),
            state: FoundationAtomicBool::new(false),
            has_consumer: FoundationAtomicBool::new(false),
        }
    }

    ///
    /// Returns max number of elements queue can hold
    ///
    pub fn capacity(&self) -> usize {
        self.mtx.lock().unwrap().capacity()
    }

    ///
    /// Returns  consumer if there is non existing already
    ///
    pub fn get_consumer(self: &Arc<Self>) -> Option<TriggerQueueConsumer<T>> {
        match self.has_consumer.compare_exchange(
            false,
            true,
            ::core::sync::atomic::Ordering::SeqCst,
            ::core::sync::atomic::Ordering::SeqCst,
        ) {
            Ok(_) => Some(TriggerQueueConsumer { queue: self.clone() }),
            Err(_) => None,
        }
    }
    ///
    /// Push data into a queue and notify consumer only if it does already wait on being notified.
    ///
    pub fn push(&self, value: T) -> bool {
        let mut data = self.mtx.lock().unwrap();
        let ret = data.push(value);

        if !ret {
            return false;
        }

        if self.state.load(::core::sync::atomic::Ordering::Relaxed) {
            drop(data);
            self.cv.notify_one();
        }

        ret
    }

    fn pop(&self) -> Option<T> {
        self.mtx.lock().unwrap().pop()
    }

    fn pop_into_vec(&self, container: &mut Vec<T>) {
        let mut data = self.mtx.lock().unwrap();

        loop {
            if container.is_full() {
                return;
            }

            let val = data.pop();
            if val.is_none() {
                return;
            }

            container.push(val.unwrap()).unwrap(); // There is still a place as it was checked above
        }
    }

    fn pop_blocking_with_timeout(&self, dur: ::core::time::Duration) -> Result<T, CommonErrors> {
        let data = self.mtx.lock().unwrap();

        self.state.store(true, ::core::sync::atomic::Ordering::Relaxed);
        let mut res = self.cv.wait_timeout_while(data, dur, |guard| guard.is_empty()).unwrap();
        self.state.store(false, ::core::sync::atomic::Ordering::Relaxed);

        if res.1.timed_out() {
            Err(CommonErrors::Timeout)
        } else {
            Ok(res.0.pop().unwrap()) // As we did not timed out and we are single consumer, there must be value inside
        }
    }

    fn pop_blocking(&self) -> T {
        let data = self.mtx.lock().unwrap();

        self.state.store(true, ::core::sync::atomic::Ordering::Relaxed);
        let mut res = self.cv.wait_while(data, |guard| guard.is_empty()).unwrap();
        self.state.store(false, ::core::sync::atomic::Ordering::Relaxed);

        res.pop().unwrap() // As queue is not empty and we are single consumer, there must be value inside
    }
}

#[cfg(test)]
#[cfg(not(loom))]
mod tests {
    use crate::prelude::vector_extension::VectorExtension;

    use super::*;
    use core::sync::atomic::Ordering;
    use core::time::Duration;
    use std::sync::Arc;
    use std::thread;

    pub fn collect_from_iterator<I, T>(iter: I, size: usize) -> Vec<T>
    where
        I: IntoIterator<Item = T>,
    {
        let mut result = Vec::new_in_global(size);

        for item in iter {
            result.push(item).unwrap();
        }

        result
    }

    #[test]
    fn test_pop_empty_queue() {
        let queue = TriggerQueue::<i32>::new(128);
        assert_eq!(queue.pop(), None);
    }

    #[test]
    fn test_pop_single_element() {
        let queue = TriggerQueue::<i32>::new(128);
        queue.push(42);
        assert_eq!(queue.pop(), Some(42));
        // Queue should be empty after pop
        assert_eq!(queue.pop(), None);
    }

    #[test]
    fn test_push_pop_multiple_elements() {
        let queue = TriggerQueue::<i32>::new(128);

        // Push multiple elements
        queue.push(1);
        queue.push(2);
        queue.push(3);

        // Pop them in FIFO order
        assert_eq!(queue.pop(), Some(1));
        assert_eq!(queue.pop(), Some(2));
        assert_eq!(queue.pop(), Some(3));
        assert_eq!(queue.pop(), None);
    }

    #[test]
    fn test_pop_into_vec_empty_queue() {
        let queue = TriggerQueue::<i32>::new(128);
        let mut vec = Vec::new_in_global(128);
        queue.pop_into_vec(&mut vec);
        assert!(vec.is_empty());
    }

    #[test]
    fn test_pop_into_vec_partial_fill() {
        let queue = TriggerQueue::<i32>::new(128);

        // Push elements
        queue.push(1);
        queue.push(2);

        // Create a vector with capacity for more elements
        let mut vec = Vec::new_in_global(128);
        queue.pop_into_vec(&mut vec);

        // Should contain exactly the elements pushed
        assert_eq!(vec, collect_from_iterator(1..3, 128));

        // Queue should be empty now
        assert_eq!(queue.pop(), None);
    }

    #[test]
    fn test_pop_into_vec_full_container() {
        let queue = TriggerQueue::<i32>::new(128);

        for i in 1..=10 {
            queue.push(i);
        }

        let mut vec = Vec::new_in_global(10);
        queue.pop_into_vec(&mut vec);

        // Should take as many elements as possible
        assert_eq!(vec.len(), 10);
        assert_eq!(vec, collect_from_iterator(1..11, 10));

        // Queue should be empty
        assert_eq!(queue.pop(), None);
    }

    #[test]
    fn test_pop_blocking_with_timeout_empty_queue() {
        let queue = TriggerQueue::<i32>::new(128);

        // Should timeout when queue is empty
        let result = queue.pop_blocking_with_timeout(Duration::from_millis(50));
        assert!(matches!(result, Err(CommonErrors::Timeout)));
    }

    #[test]
    fn test_pop_blocking_with_timeout_immediate_data() {
        let queue = TriggerQueue::<i32>::new(128);

        // Push data before blocking pop
        queue.push(42);

        // Should return immediately with the data
        let result = queue.pop_blocking_with_timeout(Duration::from_secs(1));
        assert_eq!(result, Ok(42));
    }

    #[test]
    fn test_pop_blocking_with_timeout_data_arrives() {
        let queue = Arc::new(TriggerQueue::<i32>::new(128));
        let queue_clone = Arc::clone(&queue);

        // Spawn thread that will push data after a delay
        let handle = thread::spawn(move || {
            thread::sleep(Duration::from_millis(100));
            queue_clone.push(42)
        });

        // This should wait and then receive the data
        let result = queue.pop_blocking_with_timeout(Duration::from_secs(1));
        assert_eq!(result, Ok(42));

        handle.join().unwrap();
    }

    #[test]
    fn test_concurrent_push_pop() {
        let queue = Arc::new(TriggerQueue::<i32>::new(128));
        let queue_clone = Arc::clone(&queue);

        const NUM_ITEMS: i32 = 1000;
        let mut i = 0;
        // Spawn producer thread
        let producer = thread::spawn(move || {
            while i < NUM_ITEMS {
                if queue_clone.push(i) {
                    i += 1;
                }

                // Small delay to test interleaving
                if i % 100 == 0 {
                    thread::sleep(Duration::from_millis(1));
                }
            }
        });

        // Consumer thread
        let consumer = thread::spawn(move || {
            let mut received = 0;
            let mut sum = 0;

            while received < NUM_ITEMS {
                match queue.pop_blocking_with_timeout(Duration::from_millis(100)) {
                    Ok(val) => {
                        sum += val;
                        received += 1;
                    }
                    Err(CommonErrors::Timeout) => continue,
                    Err(_) => panic!("Unexpected error"),
                }
            }
            sum
        });

        producer.join().unwrap();
        let sum = consumer.join().unwrap();

        // Expected sum of 0..NUM_ITEMS
        let expected_sum: i32 = (0..NUM_ITEMS).sum();
        assert_eq!(sum, expected_sum);
    }

    #[test]
    fn test_pop_into_vec_concurrent() {
        let queue = Arc::new(TriggerQueue::<i32>::new(128));
        let queue_clone1 = Arc::clone(&queue);
        let queue_clone2 = Arc::clone(&queue);

        const NUM_PRODUCERS: usize = 5;
        const ITEMS_PER_PRODUCER: i32 = 200;

        // Spawn multiple producer threads
        let mut handles = Vec::new_in_global(NUM_PRODUCERS);
        for p in 0..NUM_PRODUCERS {
            let q = Arc::clone(&queue_clone1);
            let handle = thread::spawn(move || {
                for i in 0..ITEMS_PER_PRODUCER {
                    loop {
                        let success = q.push(p as i32 * ITEMS_PER_PRODUCER + i);
                        if success {
                            break;
                        }

                        thread::sleep(Duration::from_millis(10));
                    }
                }
            });
            handles.push(handle).unwrap();
        }

        // Consumer thread using pop_into_vec
        let consumer = thread::spawn(move || {
            let expected_total = NUM_PRODUCERS as i32 * ITEMS_PER_PRODUCER;
            let mut all_received = Vec::new_in_global(expected_total as usize);

            while all_received.len() < expected_total as usize {
                let mut batch = Vec::new_in_global(50);
                queue_clone2.pop_into_vec(&mut batch);

                if !batch.is_empty() {
                    for e in batch.as_slice() {
                        all_received.push(*e).unwrap();
                    }
                } else {
                    thread::sleep(Duration::from_millis(10));
                }
            }

            all_received
        });

        while !handles.is_empty() {
            handles.pop().unwrap().join().unwrap();
        }

        // Get consumer result
        let received = consumer.join().unwrap();

        // Check that we received exactly the expected number of items
        assert_eq!(received.len(), (NUM_PRODUCERS as i32 * ITEMS_PER_PRODUCER) as usize);

        // Check that all values are present
        let mut received_sorted = received;
        received_sorted.sort();
        let expected: Vec<i32> = collect_from_iterator(
            0..(NUM_PRODUCERS as i32 * ITEMS_PER_PRODUCER),
            (NUM_PRODUCERS as i32 * ITEMS_PER_PRODUCER) as usize,
        );
        assert_eq!(received_sorted, expected);
    }

    #[test]
    fn test_state_transitions() {
        let queue = TriggerQueue::<i32>::new(128);

        // Initially state should be false (not sleeping)
        assert!(!queue.state.load(Ordering::SeqCst));

        // Set up a thread that will wait
        let queue_arc = Arc::new(queue);
        let queue_clone = Arc::clone(&queue_arc);

        let handle = thread::spawn(move || {
            // Should set state to true before waiting
            let result = queue_clone.pop_blocking_with_timeout(Duration::from_millis(500));

            // After timeout, state should be false again
            assert!(!queue_clone.state.load(Ordering::SeqCst));

            result
        });

        // Give the thread time to enter waiting state
        thread::sleep(Duration::from_millis(100));

        // State should be true (sleeping)
        assert!(queue_arc.state.load(Ordering::SeqCst));

        // Wait for thread to finish
        let _ = handle.join().unwrap();
    }

    #[test]
    fn test_multiple_waiters() {
        let queue = Arc::new(TriggerQueue::<i32>::new(128));
        let queue_clone1 = Arc::clone(&queue);
        let queue_clone2 = Arc::clone(&queue);

        // Create two waiting threads
        let handle1 = thread::spawn(move || queue_clone1.pop_blocking_with_timeout(Duration::from_millis(500)));

        let handle2 = thread::spawn(move || queue_clone2.pop_blocking_with_timeout(Duration::from_millis(500)));

        // Give threads time to start waiting
        thread::sleep(Duration::from_millis(50));

        // Push two items
        queue.push(1);
        queue.push(2);

        // Both threads should get an item
        let result1 = handle1.join().unwrap();
        let result2 = handle2.join().unwrap();

        // We can't guarantee which thread gets which value due to scheduling,
        // but both should get a value
        assert!(result1.is_ok());
        assert!(result2.is_ok());

        // The values should be 1 and 2
        let mut values = vec![result1.unwrap(), result2.unwrap()];
        values.sort();
        assert_eq!(values, vec![1, 2]);
    }

    #[test]
    fn test_zero_timeout() {
        let queue = TriggerQueue::<i32>::new(128);

        // Push an item
        queue.push(42);

        // Zero timeout should work if data is available
        let result = queue.pop_blocking_with_timeout(Duration::from_secs(0));
        assert_eq!(result, Ok(42));

        // Zero timeout should fail immediately if no data
        let result = queue.pop_blocking_with_timeout(Duration::from_secs(0));
        assert!(matches!(result, Err(CommonErrors::Timeout)));
    }

    #[test]
    fn test_consumer_drop_allows_new_consumer() {
        let queue = Arc::new(TriggerQueue::<i32>::new(32));

        // Create a scope to contain our first consumer
        {
            let consumer = queue.get_consumer();
            assert!(consumer.is_some());
            // Consumer will be dropped when it goes out of scope
        }

        // We should be able to get a new consumer
        let new_consumer = queue.get_consumer();
        assert!(new_consumer.is_some());
    }

    #[test]
    fn test_thread_safe_consumer_handoff() {
        let queue = Arc::new(TriggerQueue::<i32>::new(32));

        // Thread 1 gets consumer then releases it
        let queue_clone1 = Arc::clone(&queue);
        let handle1 = thread::spawn(move || {
            let consumer = queue_clone1.get_consumer().unwrap();

            // Push some data
            queue_clone1.push(1);
            queue_clone1.push(2);

            // Use the consumer to read data
            assert_eq!(consumer.queue.pop(), Some(1));

            // Now drop the consumer explicitly
            drop(consumer);
        });

        // Wait for thread 1 to complete
        handle1.join().unwrap();

        // Thread 2 should now be able to get the consumer
        let queue_clone2 = Arc::clone(&queue);
        let handle2 = thread::spawn(move || {
            let consumer = queue_clone2.get_consumer();
            assert!(consumer.is_some());
            let consumer = consumer.unwrap();

            // Should be able to read the remaining data
            assert_eq!(consumer.queue.pop(), Some(2));
        });

        handle2.join().unwrap();
    }
}