Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
timeoutQueue_test.cc
Go to the documentation of this file.
1
11# include <gtest/gtest.h>
12# include <stdexcept>
13# include <atomic>
14# include <chrono>
15# include <thread>
16# include <vector>
17# include <mutex>
18# include <condition_variable>
19# include <memory>
20# include <timeoutQueue.H>
21
22using namespace std;
23
24// Global queue (singleton)
25static TimeoutQueue* g_queue = nullptr;
26
27// Helper to get the current time plus milliseconds
28static Time time_from_now_ms(int ms)
29{
31}
32
40static bool wait_for_status(
41 const TimeoutQueue::Event* event,
43 const chrono::milliseconds timeout)
44{
45 const auto deadline = chrono::steady_clock::now() + timeout;
46 while (chrono::steady_clock::now() < deadline)
47 {
48 if (event->get_execution_status() == expected)
49 return true;
50 this_thread::sleep_for(chrono::milliseconds(10));
51 }
52 return event->get_execution_status() == expected;
53}
54
69template <typename Pred>
70static bool wait_until(Pred pred, const chrono::milliseconds timeout)
71{
72 const auto deadline = chrono::steady_clock::now() + timeout;
73 while (chrono::steady_clock::now() < deadline)
74 {
75 if (pred())
76 return true;
77 this_thread::sleep_for(chrono::milliseconds(2));
78 }
79 return pred();
80}
81
82// Test event that tracks execution
84{
85public:
86 atomic<bool> executed{false};
87 atomic<int> execution_count{0};
88 function<void()> callback;
89
90 TestEvent(const Time& t) : Event(t) {}
91 TestEvent(const Time& t, function<void()> cb) : Event(t), callback(move(cb)) {}
92
93 void EventFct() override
94 {
95 executed = true;
97 if (callback) callback();
98 }
99};
100
101// Test event that signals a condition variable
103{
104public:
105 mutex& mtx;
106 condition_variable& cv;
107 bool& flag;
108
109 SignalingEvent(const Time& t, mutex& m, condition_variable& c, bool& f)
110 : Event(t), mtx(m), cv(c), flag(f) {}
111
112 void EventFct() override
113 {
114 lock_guard<mutex> lock(mtx);
115 flag = true;
116 cv.notify_all();
117 }
118};
119
120// Test event that records execution time
122{
123public:
124 chrono::steady_clock::time_point scheduled_at;
125 chrono::steady_clock::time_point executed_at;
126 atomic<bool> executed{false};
127
128 TimingEvent(const Time& t) : Event(t), scheduled_at(chrono::steady_clock::now()) {}
129
130 void EventFct() override
131 {
132 executed_at = chrono::steady_clock::now();
133 executed = true;
134 }
135
136 [[nodiscard]] int elapsed_ms() const
137 {
138 return chrono::duration_cast<chrono::milliseconds>(
139 executed_at - scheduled_at).count();
140 }
141};
142
143// Test event that can reschedule itself
145{
146public:
151 atomic<int> execution_count{0};
152
153 ReschedulingEvent(const Time& t, TimeoutQueue* q, int max_resc,
154 int step_ms = 50)
155 : Event(t), queue(q), reschedule_count(0), max_reschedules(max_resc),
156 reschedule_step_ms(step_ms) {}
157
158 void EventFct() override
159 {
162 {
165 }
166 }
167};
168
169// =============================================================================
170// Test Environment - manages the singleton TimeoutQueue
171// =============================================================================
172
173class TimeoutQueueEnvironment : public ::testing::Environment
174{
175public:
176 void SetUp() override
177 {
178 g_queue = new TimeoutQueue();
179 }
180
181 void TearDown() override
182 {
183 if (g_queue)
184 {
185 g_queue->shutdown();
186 this_thread::sleep_for(chrono::milliseconds(100));
187 delete g_queue;
188 g_queue = nullptr;
189 }
190 }
191};
192
193// =============================================================================
194// Basic Functionality Tests
195// =============================================================================
196
197TEST(TimeoutQueueTest, ScheduleAndExecuteSingleEvent)
198{
199 mutex mtx;
200 condition_variable cv;
201 bool executed = false;
202
203 bool completed = false;
204 bool callback_done = false;
205
206 auto* event = new SignalingEvent(time_from_now_ms(100), mtx, cv, executed);
207 event->set_completion_callback([&](TimeoutQueue::Event*, TimeoutQueue::Event::Execution_Status status) {
208 lock_guard<mutex> lock(mtx);
210 callback_done = true;
211 cv.notify_all();
212 });
213 g_queue->schedule_event(event);
214
215 unique_lock<mutex> lock(mtx);
216 ASSERT_TRUE(cv.wait_for(lock, chrono::milliseconds(500),
217 [&]{ return callback_done; }));
218 EXPECT_TRUE(executed);
219 EXPECT_TRUE(completed);
220
221 delete event;
222}
223
224TEST(TimeoutQueueTest, EventExecutionStatus)
225{
226 const auto completion_timeout = chrono::seconds(30);
227
228 auto* event = new TestEvent(time_from_now_ms(50));
229
230 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::Out_Queue);
231
232 g_queue->schedule_event(event);
233 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::In_Queue);
234
235 // Wait on the lifecycle state instead of a fixed sleep. A fixed delay is
236 // unreliable on heavily loaded CI runners where the worker thread may not run
237 // within the window, leaving the event unexecuted (and turning the following
238 // delete into a use-after-free). wait_for_status returns as soon as the event
239 // completes and only blocks longer when scheduling is genuinely delayed. Once
240 // the status is Executed the worker no longer references the event (no
241 // completion callback is set), so deleting it afterwards is safe.
242 const bool executed =
243 wait_for_status(event, TimeoutQueue::Event::Executed, completion_timeout);
244 if (not executed)
245 {
246 // The worker never ran the event: it is still In_Queue (or Executing).
247 // Deleting it directly would abort, so hand it back to the queue for a
248 // safe teardown before failing.
249 const auto status = event->get_execution_status();
250 TimeoutQueue::Event* pending = event;
251 try
252 {
254 }
255 catch (const invalid_argument&)
256 {
257 // The worker executed the event between the timeout check and this
258 // call, so it is no longer in the registry; delete it ourselves.
259 delete event;
260 }
261 ADD_FAILURE() << "event did not reach Executed before timeout; "
262 << "last status was " << status;
263 return;
264 }
265
266 EXPECT_TRUE(event->executed);
267
268 delete event;
269}
270
271TEST(TimeoutQueueTest, ScheduleWithExplicitTime)
272{
273 const auto completion_timeout = chrono::seconds(30);
274
275 auto* event = new TestEvent(time_from_now_ms(1000)); // Will be overridden
276 Time trigger_time = time_from_now_ms(50);
277
278 g_queue->schedule_event(trigger_time, event);
279
280 // Wait on the lifecycle state rather than a fixed sleep: the worker thread may
281 // not run within a fixed window on a loaded CI runner, which would both fail
282 // the assertion and turn the delete below into a use-after-free.
283 const bool executed =
284 wait_for_status(event, TimeoutQueue::Event::Executed, completion_timeout);
285 if (not executed)
286 {
287 const auto status = event->get_execution_status();
288 TimeoutQueue::Event* pending = event;
289 try
290 {
292 }
293 catch (const invalid_argument&)
294 {
295 delete event;
296 }
297 ADD_FAILURE() << "event did not reach Executed before timeout; "
298 << "last status was " << status;
299 return;
300 }
301
302 EXPECT_TRUE(event->executed);
303
304 delete event;
305}
306
307TEST(TimeoutQueueTest, GetAbsoluteTime)
308{
309 Time t = time_from_now_ms(100);
310 auto* event = new TestEvent(t);
311
312 Time event_time = event->getAbsoluteTime();
313 EXPECT_EQ(event_time.tv_sec, t.tv_sec);
314 EXPECT_EQ(event_time.tv_nsec, t.tv_nsec);
315
316 delete event;
317}
318
319// =============================================================================
320// Cancellation Tests
321// =============================================================================
322
323TEST(TimeoutQueueTest, CancelEventBeforeExecution)
324{
325 auto* event = new TestEvent(time_from_now_ms(500));
326
327 g_queue->schedule_event(event);
328 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::In_Queue);
329
330 bool canceled = g_queue->cancel_event(event);
331 EXPECT_TRUE(canceled);
332 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::Canceled);
333
334 this_thread::sleep_for(chrono::milliseconds(100));
335 EXPECT_FALSE(event->executed);
336
337 delete event;
338}
339
340TEST(TimeoutQueueTest, CancelEventNotInQueue)
341{
342 auto* event = new TestEvent(time_from_now_ms(100));
343
344 // Now returns false if event is not in registry
345 EXPECT_FALSE(g_queue->cancel_event(event));
346
347 delete event;
348}
349
350TEST(TimeoutQueueTest, CancelDeleteEvent)
351{
353
354 g_queue->schedule_event(event);
356
357 EXPECT_EQ(event, nullptr);
358}
359
360TEST(TimeoutQueueTest, CancelDeleteNullEvent)
361{
362 TimeoutQueue::Event* event = nullptr;
363 EXPECT_NO_THROW(g_queue->cancel_delete_event(event));
364 EXPECT_EQ(event, nullptr);
365}
366
367// =============================================================================
368// Rescheduling Tests
369// =============================================================================
370
371TEST(TimeoutQueueTest, RescheduleEvent)
372{
373 const int original_delay_ms = 60000;
374 const int rescheduled_delay_ms = 200;
375 const auto completion_timeout = chrono::seconds(30);
376
377 auto* event = new TimingEvent(time_from_now_ms(original_delay_ms));
378 g_queue->schedule_event(event);
379 this_thread::sleep_for(chrono::milliseconds(100));
380
381 g_queue->reschedule_event(time_from_now_ms(rescheduled_delay_ms), event);
382
383 const bool completed = wait_for_status(
384 event, TimeoutQueue::Event::Executed, completion_timeout);
385 if (not completed)
386 {
387 const auto status = event->get_execution_status();
388 TimeoutQueue::Event* pending_event = event;
389 try
390 {
391 g_queue->cancel_delete_event(pending_event);
392 }
393 catch (const invalid_argument&)
394 {
395 if (event->get_execution_status() != TimeoutQueue::Event::Executed)
396 throw;
397 delete event;
398 }
399 ADD_FAILURE() << "rescheduled event did not complete before timeout; "
400 << "last status was " << status;
401 return;
402 }
403
404 EXPECT_TRUE(event->executed);
405 EXPECT_LT(event->elapsed_ms(), original_delay_ms);
406
407 delete event;
408}
409
410TEST(TimeoutQueueTest, RescheduleNotInQueue)
411{
412 auto* event = new TestEvent(time_from_now_ms(100));
413
414 // Now throws exception if event is not in registry
415 EXPECT_THROW(g_queue->reschedule_event(time_from_now_ms(50), event), std::invalid_argument);
416
417 delete event;
418}
419
420TEST(TimeoutQueueTest, SelfReschedulingEvent)
421{
422 // Pasos de 150 ms y espera total de 1000 ms para absorber jitter en
423 // runners de CI virtualizados (macOS arm64 Debug en particular).
424 // El test sigue verificando la lógica de auto-reprogramación: el evento
425 // debe ejecutarse exactamente max_reschedules+1 = 3 veces.
426 const int step_ms = 150;
427 const int max_reschedules = 2;
428 auto* event = new ReschedulingEvent(time_from_now_ms(step_ms), g_queue,
429 max_reschedules, step_ms);
430
431 g_queue->schedule_event(event);
432
433 this_thread::sleep_for(chrono::milliseconds(1000));
434 EXPECT_EQ(event->execution_count, max_reschedules + 1);
435
436 delete event;
437}
438
439// =============================================================================
440// Multiple Events Tests
441// =============================================================================
442
443TEST(TimeoutQueueTest, MultipleEventsExecuteInOrder)
444{
445 vector<int> execution_order;
446 mutex order_mutex;
447
448 auto make_event = [&](int id, int delay_ms) {
449 return new TestEvent(time_from_now_ms(delay_ms), [&, id]() {
450 lock_guard<mutex> lock(order_mutex);
451 execution_order.push_back(id);
452 });
453 };
454
455 auto* e1 = make_event(1, 150);
456 auto* e2 = make_event(2, 50);
457 auto* e3 = make_event(3, 100);
458
462
463 this_thread::sleep_for(chrono::milliseconds(400));
464
465 {
466 lock_guard<mutex> lock(order_mutex);
467 ASSERT_EQ(execution_order.size(), 3u);
468 EXPECT_EQ(execution_order[0], 2);
469 EXPECT_EQ(execution_order[1], 3);
470 EXPECT_EQ(execution_order[2], 1);
471 }
472
473 delete e1;
474 delete e2;
475 delete e3;
476}
477
478TEST(TimeoutQueueTest, ManyEventsStressTest)
479{
480 const int num_events = 30;
481 vector<TestEvent*> events;
482 atomic<int> total_executed{0};
483
484 for (int i = 0; i < num_events; ++i)
485 {
486 auto* e = new TestEvent(time_from_now_ms(50 + i * 10), [&]() {
487 ++total_executed;
488 });
489 events.push_back(e);
491 }
492
493 this_thread::sleep_for(chrono::milliseconds(600));
494
495 EXPECT_EQ(total_executed, num_events);
496
497 for (auto* e : events)
498 delete e;
499}
500
501// =============================================================================
502// Edge Cases and Error Handling
503// =============================================================================
504
505TEST(TimeoutQueueTest, EventWithImmediateTime)
506{
507 Time now = read_current_time();
508 auto* event = new TestEvent(now);
509
510 g_queue->schedule_event(event);
511
512 this_thread::sleep_for(chrono::milliseconds(100));
513 EXPECT_TRUE(event->executed);
514
515 delete event;
516}
517
518TEST(TimeoutQueueTest, EventThrowsException)
519{
520 auto* throwing_event = new TestEvent(time_from_now_ms(50), []() {
521 throw runtime_error("Test exception");
522 });
523
524 auto* normal_event = new TestEvent(time_from_now_ms(100));
525
526 g_queue->schedule_event(throwing_event);
527 g_queue->schedule_event(normal_event);
528
529 this_thread::sleep_for(chrono::milliseconds(300));
530
531 EXPECT_TRUE(throwing_event->executed);
532 EXPECT_TRUE(normal_event->executed);
533
534 delete throwing_event;
535 delete normal_event;
536}
537
538TEST(TimeoutQueueTest, SetForDeletion)
539{
540 auto* event = new TestEvent(time_from_now_ms(100));
541
542 event->set_for_deletion();
543 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::To_Delete);
544
545 delete event;
546}
547
548// =============================================================================
549// Timing Accuracy Tests
550// =============================================================================
551
552TEST(TimeoutQueueTest, TimingAccuracy)
553{
554 // Tolerancias asimétricas: la queue no debe disparar mucho antes de tiempo
555 // (límite inferior estricto), pero en VMs de CI el jitter del scheduler
556 // puede añadir varios cientos de ms al disparo (límite superior generoso).
557 const int expected_delay = 200;
558 const int lower_tolerance = 30;
559 const int upper_tolerance = 250;
560
561 auto* event = new TimingEvent(time_from_now_ms(expected_delay));
562
563 g_queue->schedule_event(event);
564
565 this_thread::sleep_for(
566 chrono::milliseconds(expected_delay + upper_tolerance + 100));
567 ASSERT_TRUE(event->executed);
568
569 int actual_delay = event->elapsed_ms();
570 EXPECT_GE(actual_delay, expected_delay - lower_tolerance);
571 EXPECT_LE(actual_delay, expected_delay + upper_tolerance);
572
573 delete event;
574}
575
576// =============================================================================
577// Thread Safety Tests
578// =============================================================================
579
580TEST(TimeoutQueueTest, ConcurrentScheduling)
581{
582 atomic<int> executed_count{0};
583 const int num_threads = 4;
584 const int events_per_thread = 5;
585 vector<thread> threads;
586 vector<TestEvent*> all_events;
587 mutex events_mutex;
588
589 for (int t = 0; t < num_threads; ++t)
590 {
591 threads.emplace_back([&, t]() {
592 for (int i = 0; i < events_per_thread; ++i)
593 {
594 auto* e = new TestEvent(time_from_now_ms(50 + i * 20), [&]() {
595 ++executed_count;
596 });
597 {
598 lock_guard<mutex> lock(events_mutex);
599 all_events.push_back(e);
600 }
602 }
603 });
604 }
605
606 for (auto& t : threads)
607 t.join();
608
609 this_thread::sleep_for(chrono::milliseconds(400));
610
611 EXPECT_EQ(executed_count, num_threads * events_per_thread);
612
613 for (auto* e : all_events)
614 delete e;
615}
616
617TEST(TimeoutQueueTest, ConcurrentCancellation)
618{
619 const int num_events = 10;
620 vector<TestEvent*> events;
621 atomic<int> canceled_count{0};
622
623 for (int i = 0; i < num_events; ++i)
624 {
625 auto* e = new TestEvent(time_from_now_ms(500));
626 events.push_back(e);
628 }
629
630 vector<thread> threads;
631 for (int t = 0; t < 2; ++t)
632 {
633 threads.emplace_back([&, t]() {
634 for (size_t i = t; i < events.size(); i += 2)
635 {
636 try {
637 if (g_queue->cancel_event(events[i]))
638 ++canceled_count;
639 } catch (const std::invalid_argument&) {
640 // Ignore if already canceled/deleted
641 }
642 }
643 });
644 }
645
646 for (auto& t : threads)
647 t.join();
648
649 EXPECT_EQ(canceled_count, num_events);
650
651 for (auto* e : events)
652 delete e;
653}
654
655// =============================================================================
656// Utility Methods Tests (new features)
657// =============================================================================
658
659TEST(TimeoutQueueTest, SizeAndIsEmpty)
660{
661 EXPECT_TRUE(g_queue->is_empty());
662 EXPECT_EQ(g_queue->size(), 0u);
663
664 auto* e1 = new TestEvent(time_from_now_ms(500));
665 auto* e2 = new TestEvent(time_from_now_ms(600));
666
668 EXPECT_FALSE(g_queue->is_empty());
669 EXPECT_EQ(g_queue->size(), 1u);
670
672 EXPECT_EQ(g_queue->size(), 2u);
673
675 EXPECT_EQ(g_queue->size(), 1u);
676
678 EXPECT_TRUE(g_queue->is_empty());
679
680 delete e1;
681 delete e2;
682}
683
684TEST(TimeoutQueueTest, IsRunning)
685{
686 EXPECT_TRUE(g_queue->is_running());
687}
688
689TEST(TimeoutQueueTest, ScheduleAfterMs)
690{
691 // Tolerancias asimétricas para acomodar el jitter del scheduler en
692 // runners de CI virtualizados (en particular macOS Debug). El test
693 // sigue verificando que el evento dispara cerca del delay pedido, no
694 // sólo que "eventualmente se ejecuta".
695 const int expected_delay = 100;
696 const int lower_tolerance = 20;
697 const int upper_tolerance = 250;
698
699 auto* event = new TimingEvent(time_from_now_ms(1000)); // Will be overridden
700
701 g_queue->schedule_after_ms(expected_delay, event);
702
703 this_thread::sleep_for(
704 chrono::milliseconds(expected_delay + upper_tolerance + 100));
705 ASSERT_TRUE(event->executed);
706
707 const int actual_delay = event->elapsed_ms();
708 EXPECT_GE(actual_delay, expected_delay - lower_tolerance);
709 EXPECT_LE(actual_delay, expected_delay + upper_tolerance);
710
711 delete event;
712}
713
714TEST(TimeoutQueueTest, NextEventTime)
715{
716 Time empty_time = g_queue->next_event_time();
717 EXPECT_EQ(empty_time.tv_sec, 0);
718 EXPECT_EQ(empty_time.tv_nsec, 0);
719
720 auto* e1 = new TestEvent(time_from_now_ms(500));
721 auto* e2 = new TestEvent(time_from_now_ms(200));
722
725 EXPECT_EQ(t1.tv_sec, e1->getAbsoluteTime().tv_sec);
726
729 EXPECT_EQ(t2.tv_sec, e2->getAbsoluteTime().tv_sec); // e2 is sooner
730
733
734 delete e1;
735 delete e2;
736}
737
738TEST(TimeoutQueueTest, ExecutedStatus)
739{
740 auto* event = new TestEvent(time_from_now_ms(50));
741
742 g_queue->schedule_event(event);
743 this_thread::sleep_for(chrono::milliseconds(200));
744
745 EXPECT_TRUE(event->executed);
746 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::Executed);
747
748 delete event;
749}
750
751TEST(TimeoutQueueTest, ClearAll)
752{
753 vector<TestEvent*> events;
754 for (int i = 0; i < 5; ++i)
755 {
756 auto* e = new TestEvent(time_from_now_ms(500 + i * 100));
757 events.push_back(e);
759 }
760
761 EXPECT_EQ(g_queue->size(), 5u);
762
763 size_t cleared = g_queue->clear_all();
764 EXPECT_EQ(cleared, 5u);
765 EXPECT_TRUE(g_queue->is_empty());
766
767 for (auto* e : events)
768 {
769 EXPECT_EQ(e->get_execution_status(), TimeoutQueue::Event::Canceled);
770 delete e;
771 }
772}
773
774TEST(TimeoutQueueTest, Statistics)
775{
777
778 size_t initial_executed = g_queue->executed_count();
779 size_t initial_canceled = g_queue->canceled_count();
780 EXPECT_EQ(initial_executed, 0u);
781 EXPECT_EQ(initial_canceled, 0u);
782
783 // Execute some events
784 mutex mtx;
785 condition_variable cv;
786 atomic<int> executed_callbacks{0};
787 auto* e1 = new TestEvent(time_from_now_ms(50));
788 auto* e2 = new TestEvent(time_from_now_ms(100));
789 // The worker counts and notifies with the lock taken: without it, the test
790 // could see the count, end and destroy cv while notify_all() runs
791 const auto on_executed =
793 {
794 lock_guard<mutex> lock(mtx);
795 if (status == TimeoutQueue::Event::Executed)
796 ++executed_callbacks;
797 cv.notify_all();
798 };
799 e1->set_completion_callback(on_executed);
800 e2->set_completion_callback(on_executed);
801
804
805 unique_lock<mutex> lock(mtx);
806 ASSERT_TRUE(cv.wait_for(lock, chrono::seconds(30),
807 [&] { return executed_callbacks.load() == 2; }));
808 lock.unlock();
809
810 EXPECT_EQ(g_queue->executed_count(), 2u);
811
812 // Cancel some events
813 auto* e3 = new TestEvent(time_from_now_ms(500));
814 auto* e4 = new TestEvent(time_from_now_ms(600));
817
818 EXPECT_TRUE(g_queue->cancel_event(e3));
819 EXPECT_TRUE(g_queue->cancel_event(e4));
820
821 EXPECT_EQ(g_queue->canceled_count(), 2u);
822
823 delete e1;
824 delete e2;
825 delete e3;
826 delete e4;
827}
828
829TEST(TimeoutQueueTest, ResetStats)
830{
831 // Ensure some stats exist
832 mutex mtx;
833 condition_variable cv;
834 atomic<bool> completed{false};
835
836 auto* e = new TestEvent(time_from_now_ms(50));
837 // The flag and the notification go with the lock taken, as in Statistics
838 e->set_completion_callback(
840 {
841 lock_guard<mutex> lock(mtx);
843 cv.notify_all();
844 });
845
847
848 unique_lock<mutex> lock(mtx);
849 ASSERT_TRUE(cv.wait_for(lock, chrono::seconds(30),
850 [&] { return completed.load(); }));
851 lock.unlock();
852
853 // Reset and verify
855 EXPECT_EQ(g_queue->executed_count(), 0u);
856 EXPECT_EQ(g_queue->canceled_count(), 0u);
857
858 delete e;
859}
860
861// =============================================================================
862// New Features Tests
863// =============================================================================
864
865TEST(TimeoutQueueTest, PauseAndResume)
866{
868 EXPECT_FALSE(g_queue->is_paused());
869
870 auto* e1 = new TestEvent(time_from_now_ms(100));
872
873 // Pause before event triggers
874 g_queue->pause();
875 EXPECT_TRUE(g_queue->is_paused());
876
877 // Wait past trigger time - event should NOT execute
878 this_thread::sleep_for(chrono::milliseconds(200));
879 EXPECT_FALSE(e1->executed);
880
881 // Resume - event should execute now
882 g_queue->resume();
883 EXPECT_FALSE(g_queue->is_paused());
884
885 this_thread::sleep_for(chrono::milliseconds(150));
886 EXPECT_TRUE(e1->executed);
887
888 delete e1;
889}
890
891TEST(TimeoutQueueTest, WaitUntilEmpty)
892{
893 auto* e1 = new TestEvent(time_from_now_ms(100));
894 auto* e2 = new TestEvent(time_from_now_ms(150));
895
898
899 EXPECT_FALSE(g_queue->is_empty());
900
901 // Wait for all events to complete
903 EXPECT_TRUE(completed);
904 EXPECT_TRUE(g_queue->is_empty());
905 EXPECT_TRUE(e1->executed);
906 EXPECT_TRUE(e2->executed);
907
908 delete e1;
909 delete e2;
910}
911
912TEST(TimeoutQueueTest, WaitUntilEmptyTimeout)
913{
914 auto* e = new TestEvent(time_from_now_ms(500));
916
917 // Wait with short timeout - should timeout
919 EXPECT_FALSE(completed);
920 EXPECT_FALSE(g_queue->is_empty());
921
922 // Cancel and cleanup
924 delete e;
925}
926
927TEST(TimeoutQueueTest, WaitUntilEmptyAfterCancel)
928{
929 auto* e = new TestEvent(time_from_now_ms(300));
931
932 EXPECT_TRUE(g_queue->cancel_event(e));
933
934 EXPECT_TRUE(g_queue->wait_until_empty(200));
935 EXPECT_TRUE(g_queue->is_empty());
936
937 delete e;
938}
939
940TEST(TimeoutQueueTest, WaitUntilEmptyAfterCancelDelete)
941{
944
946 EXPECT_EQ(e, nullptr);
947
948 EXPECT_TRUE(g_queue->wait_until_empty(200));
949 EXPECT_TRUE(g_queue->is_empty());
950}
951
952TEST(TimeoutQueueTest, EventName)
953{
954 // Create event with name
955 class NamedEvent : public TimeoutQueue::Event
956 {
957 public:
958 NamedEvent(const Time& t, const string& name) : Event(t, name) {}
959 void EventFct() override {}
960 };
961
962 auto* e = new NamedEvent(time_from_now_ms(100), "TestEventName");
963 EXPECT_EQ(e->get_name(), "TestEventName");
964
965 e->set_name("NewName");
966 EXPECT_EQ(e->get_name(), "NewName");
967
968 delete e;
969}
970
971TEST(TimeoutQueueTest, CompletionCallback)
972{
973 // The callback captures shared state, not this stack frame, so it stays
974 // valid if the test gives up on an event the worker still owns.
975 struct State
976 {
977 atomic<bool> callback_called{false};
978 atomic<int> final_status{-1};
979 };
980 const auto state = make_shared<State>();
981
982 auto* e = new TestEvent(time_from_now_ms(50));
983 e->set_completion_callback([state](TimeoutQueue::Event* ev, TimeoutQueue::Event::Execution_Status status) {
984 (void) ev;
985 // Publish the status before the flag the test waits on, so that once
986 // callback_called is observed, final_status is already valid.
987 state->final_status = static_cast<int>(status);
988 state->callback_called = true;
989 });
990
992
993 // Wait on the callback instead of a fixed sleep: on loaded CI runners the
994 // worker may not get CPU within a short window, which made this test flaky.
995 const auto callback_done = [&state] { return state->callback_called.load(); };
996 if (not wait_until(callback_done, chrono::seconds(5)))
997 {
998 // A successful cancel invokes the callback synchronously. A failed one
999 // means the worker is running the event: wait for its callback before
1000 // deleting it, and leak it if the callback never arrives.
1001 if (g_queue->cancel_event(e) or wait_until(callback_done, chrono::seconds(5)))
1002 delete e;
1003 FAIL() << "Completion callback was not invoked in time";
1004 }
1005
1006 EXPECT_EQ(state->final_status, static_cast<int>(TimeoutQueue::Event::Executed));
1007
1008 delete e;
1009}
1010
1011TEST(TimeoutQueueTest, CompletionCallbackOnCancel)
1012{
1013 atomic<bool> callback_called{false};
1014 atomic<int> final_status{-1};
1015
1016 auto* e = new TestEvent(time_from_now_ms(500));
1017 e->set_completion_callback([&](TimeoutQueue::Event*, TimeoutQueue::Event::Execution_Status status) {
1018 callback_called = true;
1019 final_status = static_cast<int>(status);
1020 });
1021
1023 g_queue->clear_all();
1024
1025 this_thread::sleep_for(chrono::milliseconds(50));
1026
1027 EXPECT_TRUE(callback_called);
1028 EXPECT_EQ(final_status, static_cast<int>(TimeoutQueue::Event::Canceled));
1029
1030 delete e;
1031}
1032
1033TEST(TimeoutQueueTest, EventId)
1034{
1035 auto* e1 = new TestEvent(time_from_now_ms(500));
1036 auto* e2 = new TestEvent(time_from_now_ms(600));
1037
1038 // Each event should have a unique ID
1039 EXPECT_NE(e1->get_id(), TimeoutQueue::Event::InvalidId);
1040 EXPECT_NE(e2->get_id(), TimeoutQueue::Event::InvalidId);
1041 EXPECT_NE(e1->get_id(), e2->get_id());
1042
1043 delete e1;
1044 delete e2;
1045}
1046
1047TEST(TimeoutQueueTest, FindById)
1048{
1049 auto* e1 = new TestEvent(time_from_now_ms(500));
1050 auto* e2 = new TestEvent(time_from_now_ms(600));
1051
1052 auto id1 = e1->get_id();
1053 auto id2 = e2->get_id();
1054
1057
1058 // Should find scheduled events
1059 EXPECT_EQ(g_queue->find_by_id(id1), e1);
1060 EXPECT_EQ(g_queue->find_by_id(id2), e2);
1061
1062 // Invalid ID should return nullptr
1064 EXPECT_EQ(g_queue->find_by_id(999999), nullptr);
1065
1066 g_queue->cancel_event(e1);
1067 g_queue->cancel_event(e2);
1068
1069 // After cancel, should not find
1070 EXPECT_EQ(g_queue->find_by_id(id1), nullptr);
1071
1072 delete e1;
1073 delete e2;
1074}
1075
1076TEST(TimeoutQueueTest, CancelById)
1077{
1078 auto* e1 = new TestEvent(time_from_now_ms(500));
1079 auto* e2 = new TestEvent(time_from_now_ms(600));
1080
1081 auto id1 = e1->get_id();
1082 auto id2 = e2->get_id();
1083
1086
1087 EXPECT_EQ(g_queue->size(), 2u);
1088
1089 // Cancel by ID
1090 EXPECT_TRUE(g_queue->cancel_by_id(id1));
1091 EXPECT_EQ(g_queue->size(), 1u);
1092 EXPECT_EQ(e1->get_execution_status(), TimeoutQueue::Event::Canceled);
1093
1094 // Cancel same ID again should fail
1095 EXPECT_FALSE(g_queue->cancel_by_id(id1));
1096
1097 // Cancel invalid ID should fail
1099 EXPECT_FALSE(g_queue->cancel_by_id(999999));
1100
1101 // Cancel second event
1102 EXPECT_TRUE(g_queue->cancel_by_id(id2));
1103 EXPECT_TRUE(g_queue->is_empty());
1104
1105 delete e1;
1106 delete e2;
1107}
1108
1109TEST(TimeoutQueueTest, CancelByIdWithCallback)
1110{
1111 atomic<bool> callback_called{false};
1112 auto* e = new TestEvent(time_from_now_ms(500));
1113 auto id = e->get_id();
1114
1115 e->set_completion_callback([&](TimeoutQueue::Event*, TimeoutQueue::Event::Execution_Status status) {
1116 callback_called = true;
1117 EXPECT_EQ(status, TimeoutQueue::Event::Canceled);
1118 });
1119
1121 EXPECT_TRUE(g_queue->cancel_by_id(id));
1122
1123 EXPECT_TRUE(callback_called);
1124
1125 delete e;
1126}
1127
1128// =============================================================================
1129// Regression Tests for Bug Fixes
1130// =============================================================================
1131
1132TEST(TimeoutQueueTest, DestructorWithoutShutdown)
1133{
1134 // Test that destructor auto-shutdowns if shutdown() wasn't called
1135 // In Debug builds, this should print a warning to stderr
1136 // In Release builds, it should silently auto-shutdown
1137 testing::internal::CaptureStderr();
1138
1139 TimeoutQueue* queue = new TimeoutQueue();
1140 auto* event = new TestEvent(time_from_now_ms(1000));
1141 queue->schedule_event(event);
1142
1143 // Delete without calling shutdown() - should auto-shutdown
1144 delete queue;
1145
1146 string output = testing::internal::GetCapturedStderr();
1147# ifndef NDEBUG
1148 // In debug builds, expect warning message
1149 EXPECT_NE(output.find("WARNING"), string::npos);
1150 EXPECT_NE(output.find("shutdown"), string::npos);
1151# else
1152 // In release builds, no warning should be printed
1153 EXPECT_EQ(output.find("WARNING"), string::npos);
1154# endif
1155
1156 delete event;
1157}
1158
1159TEST(TimeoutQueueTest, CancelBeforeDeleteIsSafe)
1160{
1161 // Test that canceling an event before deletion is safe (no error)
1162 testing::internal::CaptureStderr();
1163
1164 auto* event = new TestEvent(time_from_now_ms(1000));
1165 g_queue->schedule_event(event);
1166
1167 EXPECT_EQ(event->get_execution_status(), TimeoutQueue::Event::In_Queue);
1168
1169 // Cancel first to remove from the queue, then delete
1170 g_queue->cancel_event(event);
1171
1172 // Now it's safe to delete
1173 delete event;
1174
1175 string output = testing::internal::GetCapturedStderr();
1176 // Should not have warning/error since we canceled first
1177 EXPECT_EQ(output, "");
1178}
1179
1180// Death test: Verify that deleting an In_Queue event throws fatal error
1181// Disabled under ThreadSanitizer: TSAN does not support fork() after threads
1182// have been created, and ASSERT_DEATH uses fork().
1183#if defined(__SANITIZE_THREAD__)
1184 // GCC defines __SANITIZE_THREAD__ when compiled with -fsanitize=thread
1185# define TSAN_ENABLED 1
1186#endif
1187
1188#ifdef __clang__
1189 // Clang uses __has_feature(thread_sanitizer)
1190# if __has_feature(thread_sanitizer)
1191# define TSAN_ENABLED 1
1192# endif
1193#endif
1194
1195#ifdef TSAN_ENABLED
1196TEST(TimeoutQueueDeathTest, DISABLED_DeleteEventInQueueDirectlyThrows)
1197#else
1198TEST(TimeoutQueueDeathTest, DeleteEventInQueueDirectlyThrows)
1199#endif
1200{
1201 // This test verifies fail-fast behavior to prevent use-after-free.
1202 // When Event::~Event() aborts from destructor, std::terminate() is called.
1203 ASSERT_DEATH({
1204 TimeoutQueue queue;
1205 auto* event = new TestEvent(time_from_now_ms(1000));
1206 queue.schedule_event(event);
1207 // Deleting without cancel should abort, causing process termination
1208 delete event;
1209 queue.shutdown();
1210 }, "In_Queue.*use-after-free");
1211}
1212
1213TEST(TimeoutQueueTest, CancelDuringTimeout)
1214{
1215 // Regression test for getMin() bug: an event canceled while the worker
1216 // is inside wait_until must not cause the next event to be lost.
1217 //
1218 // Timing mirrors RescheduleDuringTimeout. GitHub-hosted macOS runners
1219 // (both macos-15 arm64 and Rosetta-emulated macos-15-intel) routinely
1220 // see sleep_for jitter exceeding 200 ms when ctest runs --parallel.
1221 // Two margins matter:
1222 //
1223 // 1. e1's trigger (500 ms) must NOT fire before we issue the cancel
1224 // (after a 200 ms sleep) — 300 ms of slack absorbs severe drift.
1225 // If e1 fires first, the worker moves it to Executing and the
1226 // subsequent cancel returns false, breaking every assertion below.
1227 // 2. e2's trigger (1500 ms) stays well past the cancel point so the
1228 // cancel demonstrably happens during the worker's wait_until on
1229 // e1's deadline, and the final 2000 ms wait clears e2 with margin.
1231
1232 auto* e1 = new TestEvent(time_from_now_ms(500));
1233 auto* e2 = new TestEvent(time_from_now_ms(1500));
1234
1237
1238 // Cancel e1 while the worker is inside wait_until on its deadline.
1239 this_thread::sleep_for(chrono::milliseconds(200));
1240 bool canceled = g_queue->cancel_event(e1);
1241 EXPECT_TRUE(canceled);
1242
1243 // e2 (≈1500 ms total, ≈1300 ms from here) must still fire; the extra
1244 // ~700 ms of slack absorbs scheduler drift on slow runners.
1245 this_thread::sleep_for(chrono::milliseconds(2000));
1246 EXPECT_FALSE(e1->executed);
1247 EXPECT_TRUE(e2->executed);
1248
1249 EXPECT_EQ(g_queue->executed_count(), 1u);
1250 EXPECT_EQ(g_queue->canceled_count(), 1u);
1251
1252 delete e1;
1253 delete e2;
1254}
1255
1256TEST(TimeoutQueueTest, RescheduleDuringTimeout)
1257{
1258 // Reschedule the top event while the worker is waiting for it.
1259 //
1260 // Timing is calibrated for slow virtualized CI runners (macos-15-intel
1261 // runs x86_64 emulated under Rosetta, where sleep_for jitter routinely
1262 // exceeds 200 ms). Two margins are critical:
1263 //
1264 // 1. e1's original trigger (500 ms) must NOT fire before we issue the
1265 // reschedule (after a 200 ms sleep) — 300 ms of slack absorbs even
1266 // severe scheduler drift.
1267 // 2. e1's rescheduled trigger (200 + 2000 = 2200 ms) must stay well
1268 // ahead of the mid-test assertion (~1500 ms) and well behind the
1269 // final assertion (~3000 ms), so the order of events is observable
1270 // regardless of jitter.
1271 auto* e1 = new TestEvent(time_from_now_ms(500));
1272 auto* e2 = new TestEvent(time_from_now_ms(1200));
1273
1276
1277 // Reschedule e1 to fire much later (absolute trigger ≈ t=2200 ms)
1278 this_thread::sleep_for(chrono::milliseconds(200));
1280
1281 // e2 should have executed at its original time (≈1200 ms),
1282 // e1 should still be waiting on its new trigger (≈2200 ms).
1283 this_thread::sleep_for(chrono::milliseconds(1300));
1284 EXPECT_TRUE(e2->executed);
1285 EXPECT_FALSE(e1->executed);
1286
1287 // e1 should now have fired
1288 this_thread::sleep_for(chrono::milliseconds(1500));
1289 EXPECT_TRUE(e1->executed);
1290
1291 delete e1;
1292 delete e2;
1293}
1294
1295TEST(TimeoutQueueTest, NullEventValidation)
1296{
1297 // Test that passing nullptr throws exception (not assertion failure in Release)
1298 Time t = time_from_now_ms(100);
1299
1300 EXPECT_THROW(g_queue->schedule_event(nullptr), std::invalid_argument);
1301 EXPECT_THROW(g_queue->schedule_event(t, nullptr), std::invalid_argument);
1302 EXPECT_THROW(g_queue->reschedule_event(t, nullptr), std::invalid_argument);
1303}
1304
1305TEST(TimeoutQueueTest, InvalidNsecValidation)
1306{
1307 // The implementation enforces tv_nsec bounds with assertions inside Event::set_trigger_time()
1308 // and with ah_domain_error_if inside schedule_event(Event*).
1309 // In Debug builds, the assert triggers first (process death).
1310 // In Release builds, assertions are disabled but ah_domain_error_if throws std::domain_error.
1311# ifndef NDEBUG
1312 ASSERT_DEATH(
1313 {
1314 TimeoutQueue q;
1315 auto* e = new TestEvent(time_from_now_ms(1000));
1316 Time bad = read_current_time();
1317 bad.tv_nsec = 2000000000; // Invalid: >= 1e9
1318 q.schedule_event(bad, e);
1319 },
1320 "");
1321# else
1322 TimeoutQueue q;
1323 auto* e = new TestEvent(time_from_now_ms(1000));
1324 Time bad = read_current_time();
1325 bad.tv_nsec = 2000000000; // Invalid: >= 1e9
1326 EXPECT_THROW(q.schedule_event(bad, e), std::domain_error);
1327 delete e; // Clean up since schedule_event threw before taking ownership
1328 q.shutdown();
1329# endif
1330}
1331
1332TEST(TimeoutQueueTest, ScheduleSameEventTwiceThrows)
1333{
1334 auto* e = new TestEvent(time_from_now_ms(500));
1336 EXPECT_THROW(g_queue->schedule_event(e), std::invalid_argument);
1338 delete e;
1339}
1340
1341TEST(TimeoutQueueTest, ShutdownCancelsPendingEventsAndInvokesCallback)
1342{
1343 TimeoutQueue q;
1344
1345 std::mutex m;
1346 std::condition_variable cv;
1347 int callbacks = 0;
1348
1349 auto* e = new TestEvent(time_from_now_ms(1000));
1350 e->set_completion_callback([&](TimeoutQueue::Event* ev, TimeoutQueue::Event::Execution_Status st) {
1351 std::lock_guard<std::mutex> lk(m);
1352 EXPECT_EQ(ev->get_execution_status(), st);
1353 EXPECT_EQ(st, TimeoutQueue::Event::Canceled);
1354 ++callbacks;
1355 cv.notify_all();
1356 });
1357
1358 q.schedule_event(e);
1359 q.shutdown();
1360
1361 std::unique_lock<std::mutex> lk(m);
1362 ASSERT_TRUE(cv.wait_for(lk, std::chrono::milliseconds(500), [&]{ return callbacks == 1; }));
1363
1364 EXPECT_FALSE(q.is_running());
1365
1366 delete e;
1367}
1368
1369TEST(TimeoutQueueTest, CancelDeleteEventCallback)
1370{
1371 // Test that cancel_delete_event invokes completion callback
1372 atomic<bool> callback_called{false};
1373 atomic<int> callback_status{-1};
1374
1376
1377 event->set_completion_callback([&](TimeoutQueue::Event* ev,
1379 EXPECT_EQ(ev, nullptr); // Event already destroyed when status is Deleted
1380 callback_called = true;
1381 callback_status = static_cast<int>(status);
1382 });
1383
1384 g_queue->schedule_event(event);
1386
1387 EXPECT_TRUE(callback_called);
1388 EXPECT_EQ(callback_status, static_cast<int>(TimeoutQueue::Event::Deleted));
1389 EXPECT_EQ(event, nullptr);
1390}
1391
1392TEST(TimeoutQueueTest, CancelDeleteExecutingEvent)
1393{
1394 // Test cancel_delete_event on an event that's currently Executing
1395 mutex mtx;
1396 condition_variable cv;
1397 atomic<bool> event_started{false};
1398 atomic<bool> can_finish{false};
1399
1400 class BlockingEvent : public TimeoutQueue::Event
1401 {
1402 public:
1403 atomic<bool>& started;
1404 atomic<bool>& finish_flag;
1405
1406 BlockingEvent(const Time& t, atomic<bool>& s, atomic<bool>& f)
1407 : Event(t), started(s), finish_flag(f) {}
1408
1409 void EventFct() override
1410 {
1411 started = true;
1412 while (!finish_flag)
1413 this_thread::sleep_for(chrono::milliseconds(10));
1414 }
1415 };
1416
1417 TimeoutQueue::Event* event = new BlockingEvent(
1418 time_from_now_ms(50), event_started, can_finish);
1419
1420 atomic<bool> callback_called{false};
1421 atomic<TimeoutQueue::Event*> callback_ev{reinterpret_cast<TimeoutQueue::Event*>(0x1)}; // sentinel
1422 event->set_completion_callback([&](auto* ev, auto status) {
1423 callback_ev = ev;
1424 callback_called = true;
1425 EXPECT_EQ(ev, nullptr); // Event already destroyed when status is Deleted
1426 EXPECT_EQ(status, TimeoutQueue::Event::Deleted);
1427 });
1428
1429 g_queue->schedule_event(event);
1430
1431 // Wait for event to start executing
1432 while (!event_started)
1433 this_thread::sleep_for(chrono::milliseconds(10));
1434
1435 // Try to cancel_delete while it's executing
1436 // Should mark as To_Delete and worker will delete it
1438 EXPECT_EQ(event, nullptr);
1439
1440 // Let event finish
1441 can_finish = true;
1442
1443 // Wait deterministically for the worker to leave EventFct(), delete the event,
1444 // and invoke the callback. A fixed sleep here is unreliable under CPU
1445 // starvation and can leak unfinished worker activity into the next test.
1446 EXPECT_TRUE(wait_until([&] { return callback_called.load(); },
1447 chrono::seconds(5)))
1448 << "Worker did not invoke the deletion callback in time";
1449
1450 // Callback should have been called by worker thread
1451 EXPECT_TRUE(callback_called);
1452 EXPECT_EQ(callback_ev.load(), nullptr);
1453}
1454
1455TEST(TimeoutQueueTest, CallbackReceivesNullptrOnlyForDeleted)
1456{
1457 // Verify that Deleted status yields nullptr, while Executed/Canceled yield
1458 // a valid pointer.
1459 atomic<TimeoutQueue::Event*> exec_ptr{nullptr};
1460 atomic<TimeoutQueue::Event*> cancel_ptr{nullptr};
1461 atomic<TimeoutQueue::Event*> delete_ptr{reinterpret_cast<TimeoutQueue::Event*>(0x1)};
1462 atomic<bool> exec_done{false};
1463
1464 // 1. Executed path: callback must receive non-null pointer.
1465 // Synchronize on the callback itself instead of a fixed sleep: under CPU
1466 // starvation the worker thread may take far longer than any fixed delay to
1467 // run the event, which previously caused this test to fail intermittently
1468 // (and to delete an event the worker still owned).
1470 e1->set_completion_callback([&](TimeoutQueue::Event* ev, auto status) {
1471 EXPECT_EQ(status, TimeoutQueue::Event::Executed);
1472 EXPECT_NE(ev, nullptr);
1473 exec_ptr = ev;
1474 exec_done = true; // set last: signals the worker is done touching the event
1475 });
1477
1478 const bool executed =
1479 wait_until([&] { return exec_done.load(); }, chrono::seconds(5));
1480 EXPECT_TRUE(executed) << "Executed completion callback was not invoked in time";
1481 EXPECT_NE(exec_ptr.load(), nullptr);
1482 if (executed)
1483 delete e1; // safe: status is Executed and the worker no longer references it
1484 else
1485 g_queue->cancel_delete_event(e1); // best-effort safe removal before return
1486
1487 // 2. Canceled path (cancel_event): the callback runs synchronously in this
1488 // thread, so no waiting is required.
1489 auto* e2 = new TestEvent(time_from_now_ms(500));
1490 e2->set_completion_callback([&](TimeoutQueue::Event* ev, auto status) {
1491 EXPECT_EQ(status, TimeoutQueue::Event::Canceled);
1492 EXPECT_NE(ev, nullptr);
1493 cancel_ptr = ev;
1494 });
1496 EXPECT_TRUE(g_queue->cancel_event(e2));
1497 EXPECT_NE(cancel_ptr.load(), nullptr);
1498 delete e2;
1499
1500 // 3. Deleted path (cancel_delete_event): callback must receive nullptr
1502 e3->set_completion_callback([&](TimeoutQueue::Event* ev, auto status) {
1503 EXPECT_EQ(status, TimeoutQueue::Event::Deleted);
1504 EXPECT_EQ(ev, nullptr);
1505 delete_ptr = ev;
1506 });
1509 EXPECT_EQ(delete_ptr.load(), nullptr);
1510 EXPECT_EQ(e3, nullptr);
1511}
1512
1513TEST(TimeoutQueueTest, CompletionCallbackOrderCorrect)
1514{
1515 // Test that completion callback is called AFTER status is set
1516 // (regression test for callback/status ordering inconsistency)
1517 atomic<bool> callback_called{false};
1518 atomic<TimeoutQueue::Event::Execution_Status> status_in_callback{
1520
1521 auto* event = new TestEvent(time_from_now_ms(50));
1522
1523 event->set_completion_callback([&](TimeoutQueue::Event* ev,
1525 // Status should already be set when callback is invoked
1526 status_in_callback = ev->get_execution_status();
1527 EXPECT_EQ(status, ev->get_execution_status());
1528 callback_called = true; // Must be last: main thread deletes after seeing this
1529 });
1530
1531 g_queue->schedule_event(event);
1532
1533 // Spin until callback completes to avoid racing with delete
1534 while (!callback_called)
1535 this_thread::sleep_for(chrono::milliseconds(10));
1536
1537 EXPECT_EQ(status_in_callback, TimeoutQueue::Event::Executed);
1538
1539 delete event;
1540}
1541
1542TEST(TimeoutQueueTest, CompletionCallbackCanClearAllWithoutDeadlock)
1543{
1544 atomic<bool> callback_called{false};
1545
1546 auto* e1 = new TestEvent(time_from_now_ms(50), [&]() { g_queue->clear_all(); });
1547 auto* e2 = new TestEvent(time_from_now_ms(200));
1548
1549 e1->set_completion_callback([&](auto*, auto) { callback_called = true; });
1550
1553
1554 this_thread::sleep_for(chrono::milliseconds(400));
1555
1556 EXPECT_TRUE(callback_called);
1557 EXPECT_TRUE(e1->executed);
1558 EXPECT_FALSE(e2->executed); // should have been canceled by clear_all()
1559 EXPECT_TRUE(g_queue->is_empty());
1560
1561 delete e1;
1562 delete e2;
1563}
1564
1565TEST(TimeoutQueueTest, MultipleEventsWithSameTime)
1566{
1567 // Test that multiple events scheduled for the same time all execute
1568 const int num_events = 5;
1569 vector<TestEvent*> events;
1570 atomic<int> executed_count{0};
1571
1572 Time same_time = time_from_now_ms(100);
1573
1574 for (int i = 0; i < num_events; ++i)
1575 {
1576 auto* e = new TestEvent(same_time, [&]() { ++executed_count; });
1577 events.push_back(e);
1579 }
1580
1581 this_thread::sleep_for(chrono::milliseconds(300));
1582
1583 EXPECT_EQ(executed_count, num_events);
1584
1585 for (auto* e : events)
1586 {
1587 EXPECT_TRUE(e->executed);
1588 delete e;
1589 }
1590}
1591
1592// =============================================================================
1593// Main
1594// =============================================================================
1595
1596int main(int argc, char **argv)
1597{
1598 ::testing::InitGoogleTest(&argc, argv);
1599 ::testing::AddGlobalTestEnvironment(new TimeoutQueueEnvironment());
1600 return RUN_ALL_TESTS();
1601}
Time time_plus_msec(const Time &current_time, const int &msec)
Definition ah-time.H:113
Time read_current_time()
Definition ah-time.H:104
struct timespec Time
Definition ah-time.H:51
int main()
Minimal std::expected-style result type for C++20.
ReschedulingEvent(const Time &t, TimeoutQueue *q, int max_resc, int step_ms=50)
atomic< int > execution_count
void EventFct() override
Event handler function to be overridden.
condition_variable & cv
void EventFct() override
Event handler function to be overridden.
SignalingEvent(const Time &t, mutex &m, condition_variable &c, bool &f)
function< void()> callback
TestEvent(const Time &t)
void EventFct() override
Event handler function to be overridden.
TestEvent(const Time &t, function< void()> cb)
atomic< bool > executed
atomic< int > execution_count
Base class for scheduled events.
Event(const Time &t, std::string name="")
Execution_Status
Possible states of an event in its lifecycle.
@ Deleted
Memory freed.
@ Out_Queue
Not currently in any queue.
@ Canceled
Removed from queue before execution.
@ Executed
Completed execution.
@ In_Queue
Scheduled and waiting for trigger time.
@ To_Delete
Marked for cleanup.
Execution_Status get_execution_status() const
void set_completion_callback(CompletionCallback cb)
Set the completion callback (called after EventFct completes or the event is canceled)
virtual void EventFct()=0
Event handler function to be overridden.
static constexpr EventId InvalidId
Invalid/null event ID.
Thread-safe priority queue for scheduling timed events.
size_t executed_count() const
Get count of events that have been executed.
void reschedule_event(const Time &trigger_time, Event *event)
Reschedule an event to a new time.
void reset_stats()
Reset statistics counters to zero.
size_t size() const
Get the number of pending events in the queue.
void schedule_event(const Time &trigger_time, Event *)
Schedule an event at a specific time.
bool is_running() const
Check if the queue is running (not shut down)
Time next_event_time() const
Get the trigger time of the next (soonest) event.
bool cancel_by_id(Event::EventId id)
Cancel a scheduled event by its ID.
void resume()
Resume event execution after pause.
size_t canceled_count() const
Get count of events that have been canceled.
void pause()
Pause event execution (events remain scheduled but won't execute)
void cancel_delete_event(Event *&event)
Cancel and delete an event.
void shutdown()
Shut down the queue and stop the background thread.
bool wait_until_empty(int timeout_ms=0)
Block until all pending events have been executed or canceled.
void schedule_after_ms(int ms_from_now, Event *event)
Schedule an event relative to the current time.
bool is_paused() const
Check if the queue is paused.
Event * find_by_id(const Event::EventId id) const
Find a scheduled event by its ID.
bool cancel_event(Event *event)
Cancel a scheduled event.
size_t clear_all()
Cancel all pending events in the queue.
bool is_empty() const
Check if the queue has no pending events.
atomic< bool > executed
chrono::steady_clock::time_point scheduled_at
chrono::steady_clock::time_point executed_at
TimingEvent(const Time &t)
void EventFct() override
Event handler function to be overridden.
int elapsed_ms() const
#define FAIL(msg)
#define TEST(name)
Freq_Node * pred
Predecessor node in level-order traversal.
bool completed() const noexcept
Return true if all underlying iterators are finished.
Definition ah-zip.H:183
STL namespace.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Priority queue for scheduling timed events.
static bool wait_for_status(const TimeoutQueue::Event *event, const TimeoutQueue::Event::Execution_Status expected, const chrono::milliseconds timeout)
Wait until an event reaches an expected lifecycle state.
static TimeoutQueue * g_queue
static bool wait_until(Pred pred, const chrono::milliseconds timeout)
Spin-wait until a predicate becomes true or a timeout elapses.
static Time time_from_now_ms(int ms)
ofstream output
Definition writeHeap.C:215