1#![forbid(unsafe_code)]
2
3use crate::cancellation::{CancellationSource, CancellationToken};
18use std::cell::Cell;
19use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::sync::mpsc;
22use std::thread;
23use web_time::{Duration, Instant};
24
25pub type SubId = u64;
30
31const SUBSCRIPTION_QUEUE_CAPACITY: usize = 256;
32const SUBSCRIPTION_BATCH_LIMIT: usize = 64;
33const SUBSCRIPTION_SEND_POLL: Duration = Duration::from_millis(5);
34
35pub struct SubscriptionSender<M> {
44 sender: mpsc::SyncSender<M>,
45 stop: StopSignal,
46}
47
48impl<M> Clone for SubscriptionSender<M> {
49 fn clone(&self) -> Self {
50 Self {
51 sender: self.sender.clone(),
52 stop: self.stop.clone(),
53 }
54 }
55}
56
57impl<M> SubscriptionSender<M> {
58 pub(crate) fn new(sender: mpsc::SyncSender<M>, stop: StopSignal) -> Self {
59 Self { sender, stop }
60 }
61
62 pub(crate) fn with_stop_signal(&self, stop: StopSignal) -> Self {
65 Self::new(self.sender.clone(), stop)
66 }
67
68 pub(crate) fn try_send(&self, message: M) -> Result<(), mpsc::TrySendError<M>> {
70 self.sender.try_send(message)
71 }
72
73 pub fn send(&self, mut message: M) -> Result<(), mpsc::SendError<M>> {
81 loop {
82 match self.sender.try_send(message) {
83 Ok(()) => return Ok(()),
84 Err(mpsc::TrySendError::Disconnected(unsent)) => {
85 return Err(mpsc::SendError(unsent));
86 }
87 Err(mpsc::TrySendError::Full(unsent)) => message = unsent,
88 }
89 if self.stop.wait_timeout(SUBSCRIPTION_SEND_POLL) {
90 return Err(mpsc::SendError(message));
91 }
92 }
93 }
94}
95
96pub trait Subscription<M: Send + 'static>: Send {
101 fn id(&self) -> SubId;
106
107 fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal);
113}
114
115#[derive(Clone)]
122pub struct StopSignal {
123 token: CancellationToken,
124}
125
126impl StopSignal {
127 pub(crate) fn new() -> (Self, StopTrigger) {
129 let source = CancellationSource::new();
130 let signal = Self {
131 token: source.token(),
132 };
133 let trigger = StopTrigger { source };
134 (signal, trigger)
135 }
136
137 pub fn is_stopped(&self) -> bool {
139 self.token.is_cancelled()
140 }
141
142 pub fn wait_timeout(&self, duration: Duration) -> bool {
148 self.token.wait_timeout(duration)
149 }
150
151 pub fn cancellation_token(&self) -> &CancellationToken {
156 &self.token
157 }
158}
159
160pub(crate) struct StopTrigger {
164 source: CancellationSource,
165}
166
167impl StopTrigger {
168 pub(crate) fn stop(&self) {
170 self.source.cancel();
171 }
172}
173
174pub(crate) struct RunningSubscription {
176 pub(crate) id: SubId,
177 trigger: StopTrigger,
178 thread: Option<thread::JoinHandle<()>>,
179 panicked: std::sync::Arc<std::sync::atomic::AtomicBool>,
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
185pub(crate) struct SubscriptionFailure {
186 pub(crate) id: SubId,
187 pub(crate) error: String,
188}
189
190const SUBSCRIPTION_STOP_JOIN_TIMEOUT: Duration = Duration::from_millis(250);
191const SUBSCRIPTION_STOP_JOIN_POLL: Duration = Duration::from_millis(1);
197
198impl RunningSubscription {
199 pub(crate) fn has_panicked(&self) -> bool {
201 self.panicked.load(std::sync::atomic::Ordering::Acquire)
202 }
203
204 pub(crate) fn signal_stop(&self) {
209 self.trigger.stop();
210 }
211
212 pub(crate) fn join_bounded(mut self) -> Option<thread::JoinHandle<()>> {
217 let handle = self.thread.take()?;
218 let start = Instant::now();
219
220 if handle.is_finished() {
222 let _ = handle.join();
223 tracing::trace!(
224 target: crate::telemetry_schema::TARGET_RUNTIME,
225 sub_id = self.id,
226 panicked = self.has_panicked(),
227 elapsed_us = start.elapsed().as_micros() as u64,
228 "subscription join (fast path)"
229 );
230 return None;
231 }
232
233 while !handle.is_finished() {
235 if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
236 tracing::warn!(
237 target: crate::telemetry_schema::TARGET_RUNTIME,
238 sub_id = self.id,
239 panicked = self.has_panicked(),
240 timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
241 "subscription join timed out, detaching thread"
242 );
243 return Some(handle);
244 }
245 thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
246 }
247
248 let _ = handle.join();
249 tracing::trace!(
250 target: crate::telemetry_schema::TARGET_RUNTIME,
251 sub_id = self.id,
252 panicked = self.has_panicked(),
253 elapsed_us = start.elapsed().as_micros() as u64,
254 "subscription join (slow path)"
255 );
256 None
257 }
258
259 #[cfg_attr(not(test), allow(dead_code))]
264 pub(crate) fn stop(mut self) {
265 self.trigger.stop();
266 if let Some(handle) = self.thread.take() {
267 let start = Instant::now();
268 if handle.is_finished() {
270 let _ = handle.join();
271 tracing::trace!(
272 target: crate::telemetry_schema::TARGET_RUNTIME,
273 sub_id = self.id,
274 panicked = self.has_panicked(),
275 elapsed_us = start.elapsed().as_micros() as u64,
276 "subscription stop (fast path)"
277 );
278 return;
279 }
280 while !handle.is_finished() {
282 if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
283 tracing::warn!(
284 target: crate::telemetry_schema::TARGET_RUNTIME,
285 sub_id = self.id,
286 panicked = self.has_panicked(),
287 timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
288 "subscription did not stop within timeout; detaching thread"
289 );
290 return;
291 }
292 thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
293 }
294 let _ = handle.join();
295 tracing::trace!(
296 target: crate::telemetry_schema::TARGET_RUNTIME,
297 sub_id = self.id,
298 panicked = self.has_panicked(),
299 elapsed_us = start.elapsed().as_micros() as u64,
300 "subscription stop (slow path)"
301 );
302 }
303 }
304}
305
306impl Drop for RunningSubscription {
307 fn drop(&mut self) {
308 self.trigger.stop();
309 }
311}
312
313pub(crate) struct SubscriptionManager<M: Send + 'static> {
315 active: Vec<RunningSubscription>,
316 sender: mpsc::SyncSender<M>,
317 receiver: mpsc::Receiver<M>,
318 batch_limit_reached: Cell<bool>,
319 failure_sender: mpsc::Sender<SubscriptionFailure>,
320 failure_receiver: mpsc::Receiver<SubscriptionFailure>,
321}
322
323impl<M: Send + 'static> SubscriptionManager<M> {
324 pub(crate) fn new() -> Self {
325 let (sender, receiver) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
326 let (failure_sender, failure_receiver) = mpsc::channel();
327 Self {
328 active: Vec::new(),
329 sender,
330 receiver,
331 batch_limit_reached: Cell::new(false),
332 failure_sender,
333 failure_receiver,
334 }
335 }
336
337 pub(crate) fn reconcile(&mut self, subscriptions: Vec<Box<dyn Subscription<M>>>) {
344 let reconcile_start = Instant::now();
345 let new_ids: HashSet<SubId> = subscriptions.iter().map(|s| s.id()).collect();
346 let active_count_before = self.active.len();
347
348 crate::debug_trace!(
349 "reconcile: new_ids={:?}, active_before={}",
350 new_ids,
351 active_count_before
352 );
353 tracing::trace!(
354 target: crate::telemetry_schema::TARGET_RUNTIME,
355 new_id_count = new_ids.len(),
356 active_before = active_count_before,
357 new_ids = ?new_ids,
358 "subscription reconcile starting"
359 );
360
361 let mut remaining = Vec::new();
363 let mut to_stop = Vec::new();
364 for running in self.active.drain(..) {
365 if new_ids.contains(&running.id) {
366 remaining.push(running);
367 } else {
368 crate::debug_trace!("stopping subscription: id={}", running.id);
369 tracing::debug!(
370 target: crate::telemetry_schema::TARGET_RUNTIME,
371 sub_id = running.id,
372 "Stopping subscription"
373 );
374 crate::effect_system::record_subscription_stop("subscription", running.id, 0);
375 crate::effect_system::record_dynamics_sub_stop();
376 to_stop.push(running);
377 }
378 }
379 for running in &to_stop {
381 running.signal_stop();
382 }
383 let stopped_count = to_stop.len();
384 for running in to_stop {
386 let _ = running.join_bounded();
387 }
388 self.active = remaining;
389
390 let mut started_count = 0usize;
392 let mut active_ids: HashSet<SubId> = self.active.iter().map(|r| r.id).collect();
393 for sub in subscriptions {
394 let id = sub.id();
395 if !active_ids.insert(id) {
396 continue;
397 }
398 started_count += 1;
399
400 crate::debug_trace!("starting subscription: id={}", id);
401 tracing::debug!(
402 target: crate::telemetry_schema::TARGET_RUNTIME,
403 sub_id = id,
404 "Starting subscription"
405 );
406 crate::effect_system::record_subscription_start("subscription", id);
407 crate::effect_system::record_dynamics_sub_start();
408 let (signal, trigger) = StopSignal::new();
409 let sender = SubscriptionSender::new(self.sender.clone(), signal.clone());
410 let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
411 let panicked_flag = panicked.clone();
412 let sub_id_for_thread = id;
413 let failure_sender = self.failure_sender.clone();
414
415 let thread = thread::spawn(move || {
416 let result = ftui_core::with_panic_cleanup_suppressed(|| {
420 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
421 sub.run(sender, signal);
422 }))
423 });
424 if let Err(payload) = result {
425 panicked_flag.store(true, std::sync::atomic::Ordering::Release);
426 crate::effect_system::record_dynamics_sub_panic();
427 let panic_msg = match payload.downcast_ref::<&str>() {
428 Some(s) => (*s).to_string(),
429 None => match payload.downcast_ref::<String>() {
430 Some(s) => s.clone(),
431 None => "unknown panic payload".to_string(),
432 },
433 };
434 crate::effect_system::error_effect_panic(
435 "subscription",
436 &format!("sub_id={sub_id_for_thread}: {panic_msg}"),
437 );
438 let _ = failure_sender.send(SubscriptionFailure {
439 id: sub_id_for_thread,
440 error: panic_msg,
441 });
442 }
443 });
444
445 self.active.push(RunningSubscription {
446 id,
447 trigger,
448 thread: Some(thread),
449 panicked,
450 });
451 }
452
453 let active_count_after = self.active.len();
454 let reconcile_elapsed_us = reconcile_start.elapsed().as_micros() as u64;
455 crate::effect_system::record_dynamics_reconcile(reconcile_elapsed_us);
456 crate::debug_trace!("reconcile complete: active_after={}", active_count_after);
457 tracing::trace!(
458 target: crate::telemetry_schema::TARGET_RUNTIME,
459 active_before = active_count_before,
460 active_after = active_count_after,
461 started = started_count,
462 stopped = stopped_count,
463 reconcile_us = reconcile_elapsed_us,
464 "subscription reconcile complete"
465 );
466 }
467
468 pub(crate) fn drain_messages(&self) -> Vec<M> {
471 let messages: Vec<M> = self
472 .receiver
473 .try_iter()
474 .take(SUBSCRIPTION_BATCH_LIMIT)
475 .collect();
476 self.batch_limit_reached
477 .set(messages.len() == SUBSCRIPTION_BATCH_LIMIT);
478 messages
479 }
480
481 pub(crate) fn may_have_pending_messages(&self) -> bool {
484 self.batch_limit_reached.get()
485 }
486
487 pub(crate) fn drain_failures(&self) -> Vec<SubscriptionFailure> {
489 let mut failures = Vec::new();
490 while let Ok(failure) = self.failure_receiver.try_recv() {
491 failures.push(failure);
492 }
493 failures
494 }
495
496 #[inline]
498 pub(crate) fn active_count(&self) -> usize {
499 self.active.len()
500 }
501
502 pub(crate) fn stop_all(&mut self) {
511 let count = self.active.len();
512 if count == 0 {
513 return;
514 }
515 let start = Instant::now();
516
517 for running in &self.active {
519 running.signal_stop();
520 }
521
522 let signal_elapsed_us = start.elapsed().as_micros() as u64;
523 tracing::trace!(
524 target: crate::telemetry_schema::TARGET_RUNTIME,
525 count,
526 signal_elapsed_us,
527 "subscription stop_all phase 1 (signal) complete"
528 );
529
530 let mut panicked_count = 0_usize;
532 let mut timed_out_count = 0_usize;
533 for running in self.active.drain(..) {
534 if running.has_panicked() {
535 panicked_count += 1;
536 }
537 if running.join_bounded().is_some() {
538 timed_out_count += 1;
539 }
540 }
541
542 let shutdown_elapsed_us = start.elapsed().as_micros() as u64;
543 crate::effect_system::record_dynamics_shutdown(shutdown_elapsed_us, timed_out_count as u64);
544 tracing::debug!(
545 target: crate::telemetry_schema::TARGET_RUNTIME,
546 count,
547 panicked_count,
548 timed_out_count,
549 elapsed_us = shutdown_elapsed_us,
550 "subscription stop_all complete"
551 );
552 }
553}
554
555impl<M: Send + 'static> Drop for SubscriptionManager<M> {
556 fn drop(&mut self) {
557 self.stop_all();
558 }
559}
560
561pub struct Every<M: Send + 'static> {
573 id: SubId,
574 interval: Duration,
575 make_msg: Box<dyn Fn() -> M + Send + Sync>,
576 clock: Option<ftui_core::cx::LabClock>,
577}
578
579impl<M: Send + 'static> Every<M> {
580 pub fn new(interval: Duration, make_msg: impl Fn() -> M + Send + Sync + 'static) -> Self {
582 let id = interval.as_nanos() as u64 ^ 0x5449_434B; Self {
585 id,
586 interval,
587 make_msg: Box::new(make_msg),
588 clock: None,
589 }
590 }
591
592 pub fn with_id(
594 id: SubId,
595 interval: Duration,
596 make_msg: impl Fn() -> M + Send + Sync + 'static,
597 ) -> Self {
598 Self {
599 id,
600 interval,
601 make_msg: Box::new(make_msg),
602 clock: None,
603 }
604 }
605
606 #[must_use]
608 pub fn with_clock(
609 id: SubId,
610 interval: Duration,
611 clock: ftui_core::cx::LabClock,
612 make_msg: impl Fn() -> M + Send + Sync + 'static,
613 ) -> Self {
614 Self {
615 id,
616 interval,
617 make_msg: Box::new(make_msg),
618 clock: Some(clock),
619 }
620 }
621
622 #[must_use]
626 pub fn poll_virtual(
627 &self,
628 clock: &ftui_core::cx::LabClock,
629 last_tick: &mut Instant,
630 sender: &SubscriptionSender<M>,
631 ) -> Option<usize> {
632 let now = clock.now();
633 let mut emitted = 0;
634 while now.saturating_duration_since(*last_tick) >= self.interval {
635 *last_tick += self.interval;
636 if sender.send((self.make_msg)()).is_err() {
637 return None;
638 }
639 emitted += 1;
640 }
641 Some(emitted)
642 }
643}
644
645pub fn tick_every<M: Send + 'static>(
657 interval: Duration,
658 make_msg: impl Fn() -> M + Send + Sync + 'static,
659) -> Box<dyn Subscription<M>> {
660 Box::new(Every::new(interval, make_msg))
661}
662
663#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
665pub enum FileEvent {
666 Created,
668 Modified,
670 Removed,
672}
673
674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676struct FileFingerprint {
677 modified: Option<std::time::SystemTime>,
678 len: u64,
679}
680
681fn file_fingerprint(path: &Path) -> Option<FileFingerprint> {
682 std::fs::metadata(path).ok().map(|meta| FileFingerprint {
683 modified: meta.modified().ok(),
684 len: meta.len(),
685 })
686}
687
688fn file_watcher_id(path: &Path) -> SubId {
692 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
694 for byte in path.as_os_str().as_encoded_bytes() {
695 hash ^= u64::from(*byte);
696 hash = hash.wrapping_mul(0x0100_0000_01b3);
697 }
698 hash ^ 0x4653_5754 }
700
701pub struct FileWatcher<M: Send + 'static> {
722 id: SubId,
723 path: PathBuf,
724 interval: Duration,
725 make_msg: Box<dyn Fn(FileEvent) -> M + Send + Sync>,
726}
727
728impl<M: Send + 'static> FileWatcher<M> {
729 pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
731
732 pub fn new(
734 path: impl Into<PathBuf>,
735 make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
736 ) -> Self {
737 let path = path.into();
738 Self {
739 id: file_watcher_id(&path),
740 path,
741 interval: Self::DEFAULT_INTERVAL,
742 make_msg: Box::new(make_msg),
743 }
744 }
745
746 #[must_use]
748 pub fn with_interval(mut self, interval: Duration) -> Self {
749 self.interval = interval.max(Duration::from_millis(1));
750 self
751 }
752
753 #[must_use]
755 pub fn path(&self) -> &Path {
756 &self.path
757 }
758
759 #[must_use]
761 pub fn interval(&self) -> Duration {
762 self.interval
763 }
764}
765
766pub fn file_watcher<M: Send + 'static>(
771 path: impl Into<PathBuf>,
772 make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
773) -> Box<dyn Subscription<M>> {
774 Box::new(FileWatcher::new(path, make_msg))
775}
776
777impl<M: Send + 'static> Subscription<M> for FileWatcher<M> {
778 fn id(&self) -> SubId {
779 self.id
780 }
781
782 fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal) {
783 let mut last = file_fingerprint(&self.path);
784 let mut sent: u64 = 0;
785 crate::debug_trace!(
786 "FileWatcher started: id={}, path={}, interval={:?}",
787 self.id,
788 self.path.display(),
789 self.interval
790 );
791 loop {
792 if stop.wait_timeout(self.interval) {
793 crate::debug_trace!("FileWatcher stopped: id={}, sent {} events", self.id, sent);
794 break;
795 }
796 let now = file_fingerprint(&self.path);
797 let event = match (last, now) {
798 (None, Some(_)) => Some(FileEvent::Created),
799 (Some(_), None) => Some(FileEvent::Removed),
800 (Some(prev), Some(cur)) if prev != cur => Some(FileEvent::Modified),
801 _ => None,
802 };
803 last = now;
804 if let Some(event) = event {
805 sent += 1;
806 if sender.send((self.make_msg)(event)).is_err() {
807 crate::debug_trace!(
808 "FileWatcher channel closed: id={}, sent {} events",
809 self.id,
810 sent
811 );
812 break;
813 }
814 }
815 }
816 }
817}
818
819impl<M: Send + 'static> Subscription<M> for Every<M> {
820 fn id(&self) -> SubId {
821 self.id
822 }
823
824 fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal) {
825 let mut tick_count: u64 = 0;
826 crate::debug_trace!(
827 "Every subscription started: id={}, interval={:?}",
828 self.id,
829 self.interval
830 );
831 if let Some(ref clock) = self.clock {
832 let mut last_tick = clock.now();
833 loop {
834 if stop.wait_timeout(Duration::from_millis(1)) {
835 break;
836 }
837 match self.poll_virtual(clock, &mut last_tick, &sender) {
838 Some(emitted) => tick_count += emitted as u64,
839 None => break,
840 }
841 }
842 crate::debug_trace!(
843 "Every virtual-clock subscription stopped: id={}, sent {} ticks",
844 self.id,
845 tick_count
846 );
847 return;
848 }
849 loop {
850 if stop.wait_timeout(self.interval) {
851 crate::debug_trace!(
852 "Every subscription stopped: id={}, sent {} ticks",
853 self.id,
854 tick_count
855 );
856 break;
857 }
858 tick_count += 1;
859 let msg = (self.make_msg)();
860 if sender.send(msg).is_err() {
861 crate::debug_trace!(
862 "Every subscription channel closed: id={}, sent {} ticks",
863 self.id,
864 tick_count
865 );
866 break;
867 }
868 }
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
875
876 #[test]
877 fn bounded_sender_waits_for_capacity_and_preserves_fifo() {
878 let (tx, rx) = mpsc::sync_channel(2);
879 let (signal, _trigger) = StopSignal::new();
880 let sender = SubscriptionSender::new(tx, signal);
881 sender.send(1).unwrap();
882 sender.clone().send(2).unwrap();
883 let (started_tx, started_rx) = mpsc::channel();
884 let (finished_tx, finished_rx) = mpsc::channel();
885 let handle = thread::spawn(move || {
886 started_tx.send(()).unwrap();
887 sender.send(3).unwrap();
888 finished_tx.send(()).unwrap();
889 });
890 started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
891 assert_eq!(
892 finished_rx.recv_timeout(Duration::from_millis(30)),
893 Err(mpsc::RecvTimeoutError::Timeout),
894 "third message must wait while both slots remain occupied"
895 );
896 assert_eq!(rx.recv().unwrap(), 1);
897 finished_rx.recv_timeout(Duration::from_secs(2)).unwrap();
898 handle.join().unwrap();
899 assert_eq!(rx.try_iter().collect::<Vec<_>>(), [2, 3]);
900 }
901
902 #[test]
903 fn bounded_sender_returns_unsent_message_on_stop_or_disconnect() {
904 for disconnect in [false, true] {
905 let (tx, rx) = mpsc::sync_channel(1);
906 let (signal, trigger) = StopSignal::new();
907 let sender = SubscriptionSender::new(tx, signal);
908 sender.send("admitted").unwrap();
909 let (started_tx, started_rx) = mpsc::channel();
910 let (finished_tx, finished_rx) = mpsc::channel();
911 let handle = thread::spawn(move || {
912 started_tx.send(()).unwrap();
913 let result = sender.send("pending");
914 finished_tx.send(result).unwrap();
915 });
916 started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
917 assert_eq!(
918 finished_rx.recv_timeout(Duration::from_millis(30)),
919 Err(mpsc::RecvTimeoutError::Timeout)
920 );
921 if disconnect {
922 drop(rx);
923 } else {
924 trigger.stop();
925 let result = finished_rx.recv_timeout(Duration::from_secs(2)).unwrap();
926 assert_eq!(result, Err(mpsc::SendError("pending")));
927 assert_eq!(rx.try_iter().collect::<Vec<_>>(), ["admitted"]);
928 handle.join().unwrap();
929 continue;
930 }
931 assert_eq!(
932 finished_rx.recv_timeout(Duration::from_secs(2)).unwrap(),
933 Err(mpsc::SendError("pending"))
934 );
935 handle.join().unwrap();
936 }
937 }
938
939 #[test]
940 fn bounded_sender_allows_final_status_only_when_capacity_is_available() {
941 let (tx, rx) = mpsc::sync_channel(1);
942 let (signal, trigger) = StopSignal::new();
943 let sender = SubscriptionSender::new(tx, signal);
944 trigger.stop();
945 assert_eq!(sender.send("final"), Ok(()));
946 assert_eq!(sender.send("unsent"), Err(mpsc::SendError("unsent")));
947 assert_eq!(rx.try_iter().collect::<Vec<_>>(), ["final"]);
948 }
949
950 #[test]
951 fn manager_bounds_queue_and_each_drain_preserving_its_suffix() {
952 let manager = SubscriptionManager::new();
953 assert!(!manager.may_have_pending_messages());
954 for value in 0..SUBSCRIPTION_QUEUE_CAPACITY {
955 manager.sender.try_send(value).unwrap();
956 }
957 assert_eq!(
958 manager.sender.try_send(SUBSCRIPTION_QUEUE_CAPACITY),
959 Err(mpsc::TrySendError::Full(SUBSCRIPTION_QUEUE_CAPACITY))
960 );
961 let mut received = Vec::new();
962 for _ in 0..SUBSCRIPTION_QUEUE_CAPACITY / SUBSCRIPTION_BATCH_LIMIT {
963 let batch = manager.drain_messages();
964 assert_eq!(batch.len(), SUBSCRIPTION_BATCH_LIMIT);
965 assert!(manager.may_have_pending_messages());
966 received.extend(batch);
967 }
968 assert_eq!(
969 received,
970 (0..SUBSCRIPTION_QUEUE_CAPACITY).collect::<Vec<_>>()
971 );
972 assert!(manager.drain_messages().is_empty());
973 assert!(!manager.may_have_pending_messages());
974 }
975
976 #[derive(Debug, Clone, PartialEq)]
977 enum TestMsg {
978 Tick,
979 Value(i32),
980 File(FileEvent),
981 }
982
983 struct ChannelSubscription<M: Send + 'static> {
984 id: SubId,
985 receiver: mpsc::Receiver<M>,
986 poll: Duration,
987 }
988
989 impl<M: Send + 'static> ChannelSubscription<M> {
990 fn new(id: SubId, receiver: mpsc::Receiver<M>) -> Self {
991 Self {
992 id,
993 receiver,
994 poll: Duration::from_millis(5),
995 }
996 }
997 }
998
999 impl<M: Send + 'static> Subscription<M> for ChannelSubscription<M> {
1000 fn id(&self) -> SubId {
1001 self.id
1002 }
1003
1004 fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal) {
1005 loop {
1006 if stop.is_stopped() {
1007 break;
1008 }
1009 match self.receiver.recv_timeout(self.poll) {
1010 Ok(msg) => {
1011 if sender.send(msg).is_err() {
1012 break;
1013 }
1014 }
1015 Err(mpsc::RecvTimeoutError::Timeout) => {}
1016 Err(mpsc::RecvTimeoutError::Disconnected) => break,
1017 }
1018 }
1019 }
1020 }
1021
1022 fn channel_subscription(id: SubId) -> (ChannelSubscription<TestMsg>, mpsc::Sender<TestMsg>) {
1023 let (tx, rx) = mpsc::channel();
1024 (ChannelSubscription::new(id, rx), tx)
1025 }
1026
1027 #[test]
1028 fn stop_signal_starts_false() {
1029 let (signal, _trigger) = StopSignal::new();
1030 assert!(!signal.is_stopped());
1031 }
1032
1033 #[test]
1034 fn stop_signal_becomes_true_after_trigger() {
1035 let (signal, trigger) = StopSignal::new();
1036 trigger.stop();
1037 assert!(signal.is_stopped());
1038 }
1039
1040 #[test]
1041 fn stop_signal_wait_returns_true_when_stopped() {
1042 let (signal, trigger) = StopSignal::new();
1043 trigger.stop();
1044 assert!(signal.wait_timeout(Duration::from_millis(100)));
1045 }
1046
1047 #[test]
1048 fn stop_signal_wait_returns_false_on_timeout() {
1049 let (signal, _trigger) = StopSignal::new();
1050 assert!(!signal.wait_timeout(Duration::from_millis(10)));
1051 }
1052
1053 #[test]
1054 fn channel_subscription_forwards_messages() {
1055 let (sub, event_tx) = channel_subscription(1);
1056 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1057 let (signal, trigger) = StopSignal::new();
1058
1059 let handle = thread::spawn(move || {
1060 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1061 });
1062
1063 event_tx.send(TestMsg::Value(1)).unwrap();
1064 event_tx.send(TestMsg::Value(2)).unwrap();
1065 thread::sleep(Duration::from_millis(10));
1066 trigger.stop();
1067 handle.join().unwrap();
1068
1069 let msgs: Vec<_> = rx.try_iter().collect();
1070 assert_eq!(msgs, vec![TestMsg::Value(1), TestMsg::Value(2)]);
1071 }
1072
1073 #[test]
1074 fn every_subscription_fires() {
1075 let sub = Every::new(Duration::from_millis(10), || TestMsg::Tick);
1076 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1077 let (signal, trigger) = StopSignal::new();
1078
1079 let handle = thread::spawn(move || {
1080 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1081 });
1082
1083 thread::sleep(Duration::from_millis(50));
1085 trigger.stop();
1086 handle.join().unwrap();
1087
1088 let msgs: Vec<_> = rx.try_iter().collect();
1089 assert!(!msgs.is_empty(), "Should have received at least one tick");
1090 assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
1091 }
1092
1093 #[test]
1094 fn tick_every_is_a_boxed_every_with_the_same_id() {
1095 let boxed: Box<dyn Subscription<TestMsg>> =
1096 tick_every(Duration::from_millis(10), || TestMsg::Tick);
1097 let plain = Every::new(Duration::from_millis(10), || TestMsg::Tick);
1098 assert_eq!(
1099 boxed.id(),
1100 plain.id(),
1101 "the helper must not change subscription identity (diffing relies on it)"
1102 );
1103
1104 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1105 let (signal, trigger) = StopSignal::new();
1106 let handle = thread::spawn(move || {
1107 boxed.run(SubscriptionSender::new(tx, signal.clone()), signal);
1108 });
1109 thread::sleep(Duration::from_millis(50));
1110 trigger.stop();
1111 handle.join().unwrap();
1112
1113 let msgs: Vec<_> = rx.try_iter().collect();
1114 assert!(!msgs.is_empty(), "boxed tick subscription must fire");
1115 assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
1116 }
1117
1118 #[test]
1119 fn file_watcher_id_is_stable_per_path_and_distinct_from_ticks() {
1120 let a1 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
1121 let a2 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
1122 let b = FileWatcher::new("/tmp/b.toml", TestMsg::File);
1123 assert_eq!(a1.id(), a2.id(), "same path must dedupe across frames");
1124 assert_ne!(
1125 a1.id(),
1126 b.id(),
1127 "different paths are different subscriptions"
1128 );
1129 let tick = Every::new(Duration::from_millis(250), || TestMsg::Tick);
1130 assert_ne!(a1.id(), tick.id());
1131 assert_eq!(a1.interval(), FileWatcher::<TestMsg>::DEFAULT_INTERVAL);
1132 assert_eq!(
1133 a1.with_interval(Duration::ZERO).interval(),
1134 Duration::from_millis(1),
1135 "interval is clamped so the poll loop can never spin"
1136 );
1137 }
1138
1139 #[test]
1142 fn file_watcher_reports_create_modify_remove() {
1143 let dir = tempfile::Builder::new()
1144 .prefix("ftui-file-watcher-")
1145 .disable_cleanup(true)
1146 .tempdir()
1147 .expect("temp dir");
1148 let path = dir.path().join("watched.toml");
1149 let sub = FileWatcher::new(&path, TestMsg::File).with_interval(Duration::from_millis(5));
1150 assert_eq!(sub.path(), path.as_path());
1151 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1152 let (signal, trigger) = StopSignal::new();
1153 let handle = thread::spawn(move || {
1154 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1155 });
1156 let wait = Duration::from_secs(10);
1157 thread::sleep(Duration::from_millis(40));
1159 assert!(rx.try_recv().is_err(), "no event before anything happens");
1160
1161 std::fs::write(&path, b"a = 1\n").expect("create file");
1162 assert_eq!(
1163 rx.recv_timeout(wait).expect("created"),
1164 TestMsg::File(FileEvent::Created)
1165 );
1166 thread::sleep(Duration::from_millis(40));
1169 let _ = rx.try_iter().count();
1170
1171 std::fs::write(&path, b"a = 1\nb = 22\n").expect("modify file");
1174 assert_eq!(
1175 rx.recv_timeout(wait).expect("modified"),
1176 TestMsg::File(FileEvent::Modified)
1177 );
1178 thread::sleep(Duration::from_millis(40));
1179 let _ = rx.try_iter().count();
1180
1181 std::fs::remove_file(&path).expect("remove file");
1182 assert_eq!(
1183 rx.recv_timeout(wait).expect("removed"),
1184 TestMsg::File(FileEvent::Removed)
1185 );
1186 thread::sleep(Duration::from_millis(40));
1187 assert!(rx.try_recv().is_err(), "nothing after removal");
1188
1189 trigger.stop();
1190 handle.join().unwrap();
1191 }
1192
1193 #[test]
1195 fn file_watcher_helper_boxes_the_same_subscription() {
1196 let boxed: Box<dyn Subscription<TestMsg>> = file_watcher("/tmp/x.toml", TestMsg::File);
1197 assert_eq!(
1198 boxed.id(),
1199 FileWatcher::new("/tmp/x.toml", TestMsg::File).id()
1200 );
1201 }
1202
1203 #[test]
1204 fn every_subscription_uses_stable_id() {
1205 let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
1206 let sub2 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
1207 assert_eq!(sub1.id(), sub2.id());
1208 }
1209
1210 #[test]
1211 fn every_subscription_different_intervals_different_ids() {
1212 let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
1213 let sub2 = Every::<TestMsg>::new(Duration::from_secs(2), || TestMsg::Tick);
1214 assert_ne!(sub1.id(), sub2.id());
1215 }
1216
1217 fn wait_for_messages<M: Send + 'static>(
1218 mgr: &mut SubscriptionManager<M>,
1219 min_count: usize,
1220 timeout: Duration,
1221 ) -> Vec<M> {
1222 let deadline = Instant::now() + timeout;
1223 let mut collected = Vec::new();
1224 while collected.len() < min_count && Instant::now() < deadline {
1225 collected.extend(mgr.drain_messages());
1226 if collected.len() >= min_count {
1227 break;
1228 }
1229 thread::sleep(Duration::from_millis(2));
1230 }
1231 collected
1232 }
1233
1234 #[test]
1235 fn subscription_manager_starts_subscriptions() {
1236 let mut mgr = SubscriptionManager::<TestMsg>::new();
1237 let (sub, event_tx) = channel_subscription(1);
1238 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
1239
1240 mgr.reconcile(subs);
1241 event_tx.send(TestMsg::Value(42)).unwrap();
1242
1243 let msgs = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1244 assert_eq!(msgs, vec![TestMsg::Value(42)]);
1245 }
1246
1247 #[test]
1248 fn subscription_manager_dedupes_duplicate_ids() {
1249 let mut mgr = SubscriptionManager::<TestMsg>::new();
1250 let (sub_a, tx_a) = channel_subscription(7);
1251 let (sub_b, tx_b) = channel_subscription(7);
1252 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub_a), Box::new(sub_b)];
1253
1254 mgr.reconcile(subs);
1255
1256 tx_a.send(TestMsg::Value(1)).unwrap();
1257 assert!(
1258 tx_b.send(TestMsg::Value(2)).is_err(),
1259 "Duplicate subscription should be dropped"
1260 );
1261
1262 let msgs = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1263 assert_eq!(msgs, vec![TestMsg::Value(1)]);
1264 }
1265
1266 #[test]
1267 fn subscription_manager_stops_removed() {
1268 let mut mgr = SubscriptionManager::<TestMsg>::new();
1269
1270 mgr.reconcile(vec![Box::new(Every::with_id(
1272 99,
1273 Duration::from_millis(5),
1274 || TestMsg::Tick,
1275 ))]);
1276
1277 let msgs_before = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1278 assert!(!msgs_before.is_empty());
1279
1280 mgr.reconcile(vec![]);
1282
1283 thread::sleep(Duration::from_millis(20));
1285 let _ = mgr.drain_messages();
1286
1287 thread::sleep(Duration::from_millis(30));
1289 let msgs_after = mgr.drain_messages();
1290 assert!(
1291 msgs_after.is_empty(),
1292 "Should stop receiving after reconcile with empty set"
1293 );
1294 }
1295
1296 #[test]
1297 fn subscription_manager_keeps_unchanged() {
1298 let mut mgr = SubscriptionManager::<TestMsg>::new();
1299
1300 mgr.reconcile(vec![Box::new(Every::with_id(
1302 50,
1303 Duration::from_millis(10),
1304 || TestMsg::Tick,
1305 ))]);
1306
1307 let _ = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1308
1309 mgr.reconcile(vec![Box::new(Every::with_id(
1311 50,
1312 Duration::from_millis(10),
1313 || TestMsg::Tick,
1314 ))]);
1315
1316 let msgs = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1317 assert!(!msgs.is_empty(), "Subscription should still be running");
1318 }
1319
1320 #[test]
1321 fn subscription_manager_stop_all() {
1322 let mut mgr = SubscriptionManager::<TestMsg>::new();
1323
1324 mgr.reconcile(vec![
1325 Box::new(Every::with_id(1, Duration::from_millis(5), || {
1326 TestMsg::Value(1)
1327 })),
1328 Box::new(Every::with_id(2, Duration::from_millis(5), || {
1329 TestMsg::Value(2)
1330 })),
1331 ]);
1332
1333 thread::sleep(Duration::from_millis(20));
1334 mgr.stop_all();
1335
1336 thread::sleep(Duration::from_millis(20));
1337 let _ = mgr.drain_messages();
1338 thread::sleep(Duration::from_millis(30));
1339 let msgs = mgr.drain_messages();
1340 assert!(msgs.is_empty());
1341 }
1342
1343 #[test]
1348 fn stop_signal_is_cloneable() {
1349 let (signal, trigger) = StopSignal::new();
1350 let signal_clone = signal.clone();
1351
1352 assert!(!signal.is_stopped());
1353 assert!(!signal_clone.is_stopped());
1354
1355 trigger.stop();
1356
1357 assert!(signal.is_stopped());
1358 assert!(signal_clone.is_stopped());
1359 }
1360
1361 #[test]
1362 fn stop_signal_wait_wakes_immediately_when_already_stopped() {
1363 stop_signal_wait_wakes_immediately_when_already_stopped_property();
1364 }
1365
1366 #[test]
1367 fn stop_signal_wait_wakes_immediately_when_already_stopped_property() {
1368 let (signal, trigger) = StopSignal::new();
1369 trigger.stop();
1370
1371 let start = Instant::now();
1374 let stopped = signal.wait_timeout(Duration::from_secs(10));
1375 let elapsed = start.elapsed();
1376
1377 assert!(stopped);
1378 assert!(
1379 elapsed < Duration::from_secs(5) * ftui_core::cx::test_time_scale(),
1380 "wait_timeout on a stopped signal must not wait for the timeout; took {elapsed:?}"
1381 );
1382 }
1383
1384 #[test]
1385 fn stop_signal_wait_is_interrupted_by_trigger() {
1386 let (signal, trigger) = StopSignal::new();
1387
1388 let signal_clone = signal.clone();
1389 let handle = thread::spawn(move || signal_clone.wait_timeout(Duration::from_secs(10)));
1390
1391 thread::sleep(Duration::from_millis(20));
1393 trigger.stop();
1394
1395 let stopped = handle.join().unwrap();
1396 assert!(stopped);
1397 }
1398
1399 #[test]
1400 fn channel_subscription_no_messages_without_events() {
1401 let (sub, _event_tx) = channel_subscription(1);
1402 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1403 let (signal, trigger) = StopSignal::new();
1404
1405 let handle = thread::spawn(move || {
1406 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1407 });
1408
1409 thread::sleep(Duration::from_millis(10));
1410 trigger.stop();
1411 handle.join().unwrap();
1412
1413 let msgs: Vec<_> = rx.try_iter().collect();
1414 assert!(msgs.is_empty());
1415 }
1416
1417 #[test]
1418 fn channel_subscription_id_is_preserved() {
1419 let (sub, _tx) = channel_subscription(42);
1420 assert_eq!(sub.id(), 42);
1421 }
1422
1423 #[test]
1424 fn channel_subscription_stops_on_disconnected_receiver() {
1425 let (sub, event_tx) = channel_subscription(1);
1426 let (tx, _rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1427 let (signal, _trigger) = StopSignal::new();
1428
1429 drop(event_tx);
1430
1431 let handle = thread::spawn(move || {
1432 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1433 });
1434
1435 let result = handle.join();
1436 assert!(result.is_ok());
1437 }
1438
1439 #[test]
1440 fn every_with_id_preserves_custom_id() {
1441 let sub = Every::<TestMsg>::with_id(12345, Duration::from_secs(1), || TestMsg::Tick);
1442 assert_eq!(sub.id(), 12345);
1443 }
1444
1445 #[test]
1446 fn every_stops_on_disconnected_receiver() {
1447 let sub = Every::new(Duration::from_millis(5), || TestMsg::Tick);
1448 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1449 let (signal, _trigger) = StopSignal::new();
1450
1451 drop(rx);
1453
1454 let handle = thread::spawn(move || {
1456 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1457 });
1458
1459 let result = handle.join();
1461 assert!(result.is_ok());
1462 }
1463
1464 #[test]
1465 fn every_respects_interval() {
1466 let interval = Duration::from_millis(50);
1467 let sub = Every::with_id(1, interval, Instant::now);
1468 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1469 let (signal, trigger) = StopSignal::new();
1470
1471 let start = Instant::now();
1472 let handle = thread::spawn(move || {
1473 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1474 });
1475
1476 let mut arrivals = Vec::new();
1481 let deadline = Instant::now() + Duration::from_secs(10);
1482 while arrivals.len() < 3 && Instant::now() < deadline {
1483 match rx.recv_timeout(Duration::from_millis(100)) {
1484 Ok(produced_at) => arrivals.push(produced_at),
1485 Err(mpsc::RecvTimeoutError::Timeout) => {}
1486 Err(mpsc::RecvTimeoutError::Disconnected) => break,
1487 }
1488 }
1489 trigger.stop();
1490 handle.join().unwrap();
1491
1492 assert!(
1493 arrivals.len() >= 2,
1494 "expected at least 2 ticks within 10 s, got {}",
1495 arrivals.len()
1496 );
1497 for pair in arrivals.windows(2) {
1498 let gap = pair[1].duration_since(pair[0]);
1499 assert!(
1500 gap >= interval,
1501 "ticks were generated {gap:?} apart, closer than the {interval:?} interval"
1502 );
1503 }
1504 assert!(
1505 start.elapsed() >= interval * 2,
1506 "two ticks cannot arrive before two intervals have passed"
1507 );
1508 }
1509
1510 #[test]
1511 fn every_respects_interval_virtual_clock() {
1512 let clock = ftui_core::cx::LabClock::new();
1513 let epoch = clock.now();
1514 let interval = Duration::from_millis(50);
1515 let sub = Every::with_clock(1, interval, clock.clone(), || TestMsg::Tick);
1516 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1517 let (signal, _trigger) = StopSignal::new();
1518 let sender = SubscriptionSender::new(tx, signal);
1519 let mut last_tick = epoch;
1520 let mut arrivals = Vec::new();
1521
1522 for _ in 0..16 {
1523 clock.advance(Duration::from_millis(10));
1524 sub.poll_virtual(&clock, &mut last_tick, &sender).unwrap();
1525 let virtual_elapsed = clock.now().duration_since(epoch);
1526 for msg in rx.try_iter() {
1527 arrivals.push((msg, virtual_elapsed));
1528 }
1529 }
1530
1531 assert_eq!(
1532 arrivals.len(),
1533 3,
1534 "expected 3 ticks in 160ms at 50ms interval"
1535 );
1536 for (idx, (msg, elapsed)) in arrivals.iter().enumerate() {
1537 assert_eq!(*msg, TestMsg::Tick);
1538 let expected = Duration::from_millis(50 * (idx as u64 + 1));
1539 assert_eq!(
1540 *elapsed,
1541 expected,
1542 "tick {} arrived at {:?}",
1543 idx + 1,
1544 elapsed
1545 );
1546 }
1547 }
1548
1549 #[test]
1550 fn every_ticks_at_least_once_wall() {
1551 let scale = ftui_core::cx::test_time_scale();
1552 let interval = Duration::from_millis(20);
1553 let sub = Every::with_id(2, interval, || TestMsg::Tick);
1554 let (tx, rx) = mpsc::sync_channel(SUBSCRIPTION_QUEUE_CAPACITY);
1555 let (signal, trigger) = StopSignal::new();
1556
1557 let start = Instant::now();
1558 let handle = thread::spawn(move || {
1559 sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
1560 });
1561
1562 thread::sleep(Duration::from_millis(60) * scale);
1563 let mut msgs: Vec<TestMsg> = rx.try_iter().collect();
1566 if msgs.is_empty()
1567 && let Ok(first) = rx.recv_timeout(Duration::from_secs(5) * scale)
1568 {
1569 msgs.push(first);
1570 }
1571 let elapsed_ms = start.elapsed().as_millis();
1572 trigger.stop();
1573 handle.join().unwrap();
1574
1575 eprintln!(
1576 "{{\"event\":\"every_ticks_wall\",\"elapsed_ms\":{},\"ticks\":{},\"scale\":{}}}",
1577 elapsed_ms,
1578 msgs.len(),
1579 scale
1580 );
1581 assert!(
1582 !msgs.is_empty(),
1583 "expected at least 1 tick after 60ms * scale={scale}, got 0"
1584 );
1585 }
1586
1587 #[test]
1588 fn subscription_manager_empty_reconcile() {
1589 let mut mgr = SubscriptionManager::<TestMsg>::new();
1590
1591 mgr.reconcile(vec![]);
1593 let msgs = mgr.drain_messages();
1594 assert!(msgs.is_empty());
1595 }
1596
1597 #[test]
1598 fn subscription_manager_drain_messages_returns_all() {
1599 let mut mgr = SubscriptionManager::<TestMsg>::new();
1600 let (sub, event_tx) = channel_subscription(1);
1601 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
1602
1603 mgr.reconcile(subs);
1604 event_tx.send(TestMsg::Value(1)).unwrap();
1605 event_tx.send(TestMsg::Value(2)).unwrap();
1606
1607 let msgs = wait_for_messages(&mut mgr, 2, Duration::from_secs(2));
1608 assert_eq!(msgs.len(), 2);
1609 assert_eq!(msgs[0], TestMsg::Value(1));
1610 assert_eq!(msgs[1], TestMsg::Value(2));
1611
1612 let msgs2 = mgr.drain_messages();
1614 assert!(msgs2.is_empty());
1615 }
1616
1617 #[test]
1618 fn subscription_manager_replaces_subscription_with_different_id() {
1619 let mut mgr = SubscriptionManager::<TestMsg>::new();
1620 let (sub1, tx1) = channel_subscription(1);
1621
1622 mgr.reconcile(vec![Box::new(sub1)]);
1624 tx1.send(TestMsg::Value(1)).unwrap();
1625 let msgs1 = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1626 assert_eq!(msgs1, vec![TestMsg::Value(1)]);
1627
1628 let (sub2, tx2) = channel_subscription(2);
1630 mgr.reconcile(vec![Box::new(sub2)]);
1631 tx2.send(TestMsg::Value(2)).unwrap();
1632 let msgs2 = wait_for_messages(&mut mgr, 1, Duration::from_secs(2));
1633 assert_eq!(msgs2, vec![TestMsg::Value(2)]);
1634 }
1635
1636 #[test]
1637 fn subscription_manager_multiple_subscriptions() {
1638 let mut mgr = SubscriptionManager::<TestMsg>::new();
1639 let (sub1, tx1) = channel_subscription(1);
1640 let (sub2, tx2) = channel_subscription(2);
1641 let (sub3, tx3) = channel_subscription(3);
1642 let subs: Vec<Box<dyn Subscription<TestMsg>>> =
1643 vec![Box::new(sub1), Box::new(sub2), Box::new(sub3)];
1644
1645 mgr.reconcile(subs);
1646 tx1.send(TestMsg::Value(10)).unwrap();
1647 tx2.send(TestMsg::Value(20)).unwrap();
1648 tx3.send(TestMsg::Value(30)).unwrap();
1649
1650 let mut msgs = wait_for_messages(&mut mgr, 3, Duration::from_secs(2));
1651 msgs.sort_by_key(|m| match m {
1652 TestMsg::Value(v) => *v,
1653 _ => 0,
1654 });
1655
1656 assert_eq!(msgs.len(), 3);
1657 assert_eq!(msgs[0], TestMsg::Value(10));
1658 assert_eq!(msgs[1], TestMsg::Value(20));
1659 assert_eq!(msgs[2], TestMsg::Value(30));
1660 }
1661
1662 #[test]
1663 fn subscription_manager_partial_update() {
1664 let mut mgr = SubscriptionManager::<TestMsg>::new();
1665
1666 mgr.reconcile(vec![
1668 Box::new(Every::with_id(1, Duration::from_millis(10), || {
1669 TestMsg::Value(1)
1670 })),
1671 Box::new(Every::with_id(2, Duration::from_millis(10), || {
1672 TestMsg::Value(2)
1673 })),
1674 Box::new(Every::with_id(3, Duration::from_millis(10), || {
1675 TestMsg::Value(3)
1676 })),
1677 ]);
1678
1679 let _ = wait_for_messages(&mut mgr, 3, Duration::from_secs(2));
1680
1681 mgr.reconcile(vec![
1683 Box::new(Every::with_id(1, Duration::from_millis(10), || {
1684 TestMsg::Value(1)
1685 })),
1686 Box::new(Every::with_id(3, Duration::from_millis(10), || {
1687 TestMsg::Value(3)
1688 })),
1689 ]);
1690
1691 thread::sleep(Duration::from_millis(15));
1694 let _ = mgr.drain_messages();
1695
1696 let deadline = Instant::now() + Duration::from_secs(2);
1698 let mut msgs = Vec::new();
1699 while Instant::now() < deadline {
1700 msgs.extend(mgr.drain_messages());
1701 let has_1 = msgs.contains(&TestMsg::Value(1));
1702 let has_3 = msgs.contains(&TestMsg::Value(3));
1703 if has_1 && has_3 {
1704 break;
1705 }
1706 thread::sleep(Duration::from_millis(2));
1707 }
1708
1709 let values: Vec<i32> = msgs
1711 .iter()
1712 .filter_map(|m| match m {
1713 TestMsg::Value(v) => Some(*v),
1714 _ => None,
1715 })
1716 .collect();
1717
1718 assert!(
1719 values.contains(&1),
1720 "Should still receive from subscription 1"
1721 );
1722 assert!(
1723 values.contains(&3),
1724 "Should still receive from subscription 3"
1725 );
1726 assert!(
1727 !values.contains(&2),
1728 "Should not receive from stopped subscription 2"
1729 );
1730 }
1731
1732 #[test]
1733 fn subscription_manager_drop_stops_all() {
1734 let (_signal, _) = StopSignal::new();
1735 let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1736 let flag_clone = flag.clone();
1737
1738 struct FlagSubscription {
1739 id: SubId,
1740 flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
1741 }
1742
1743 impl Subscription<TestMsg> for FlagSubscription {
1744 fn id(&self) -> SubId {
1745 self.id
1746 }
1747
1748 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
1749 while !stop.is_stopped() {
1750 thread::sleep(Duration::from_millis(5));
1751 }
1752 self.flag.store(true, std::sync::atomic::Ordering::SeqCst);
1753 }
1754 }
1755
1756 {
1757 let mut mgr = SubscriptionManager::<TestMsg>::new();
1758 mgr.reconcile(vec![Box::new(FlagSubscription {
1759 id: 1,
1760 flag: flag_clone,
1761 })]);
1762
1763 thread::sleep(Duration::from_millis(20));
1764 }
1766
1767 thread::sleep(Duration::from_millis(50));
1768 assert!(
1769 flag.load(std::sync::atomic::Ordering::SeqCst),
1770 "Subscription should have stopped on drop"
1771 );
1772 }
1773
1774 #[test]
1775 fn running_subscription_stop_joins_thread() {
1776 use std::sync::atomic::{AtomicBool, Ordering};
1777
1778 let completed = std::sync::Arc::new(AtomicBool::new(false));
1779 let completed_clone = completed.clone();
1780
1781 let (signal, trigger) = StopSignal::new();
1782 let (_tx, _rx) = mpsc::channel::<TestMsg>();
1783
1784 let thread = thread::spawn(move || {
1785 while !signal.is_stopped() {
1786 thread::sleep(Duration::from_millis(5));
1787 }
1788 completed_clone.store(true, Ordering::SeqCst);
1789 });
1790
1791 let running = RunningSubscription {
1792 id: 1,
1793 trigger,
1794 thread: Some(thread),
1795 panicked: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1796 };
1797
1798 running.stop();
1799 assert!(completed.load(Ordering::SeqCst));
1800 }
1801
1802 #[test]
1803 fn running_subscription_stop_times_out_for_uncooperative_thread() {
1804 running_subscription_stop_times_out_for_uncooperative_thread_property();
1805 }
1806
1807 #[test]
1808 fn running_subscription_stop_times_out_for_uncooperative_thread_property() {
1809 use std::sync::atomic::{AtomicBool, Ordering};
1810
1811 let completed = std::sync::Arc::new(AtomicBool::new(false));
1812 let completed_clone = completed.clone();
1813 let scale = ftui_core::cx::test_time_scale();
1814 let (release_tx, release_rx) = mpsc::channel::<()>();
1815
1816 let (_signal, trigger) = StopSignal::new();
1819 let thread = thread::spawn(move || {
1820 let _ = release_rx.recv_timeout(Duration::from_secs(10) * scale);
1821 completed_clone.store(true, Ordering::SeqCst);
1822 });
1823
1824 let running = RunningSubscription {
1825 id: 7,
1826 trigger,
1827 thread: Some(thread),
1828 panicked: std::sync::Arc::new(AtomicBool::new(false)),
1829 };
1830
1831 let start = Instant::now();
1832 running.stop();
1833 let elapsed = start.elapsed();
1834 assert!(
1835 elapsed < Duration::from_millis(1500) * ftui_core::cx::test_time_scale(),
1836 "stop() should not block behind an uncooperative subscription thread; took {elapsed:?}"
1837 );
1838
1839 let _ = release_tx.send(());
1841 let deadline = Instant::now() + Duration::from_secs(10) * scale;
1842 while !completed.load(Ordering::SeqCst) && Instant::now() < deadline {
1843 thread::sleep(Duration::from_millis(1));
1844 }
1845 assert!(completed.load(Ordering::SeqCst));
1846 }
1847
1848 #[test]
1849 fn every_id_stable_across_instances() {
1850 let sub1 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1852 let sub2 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1853 let sub3 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(1));
1854
1855 assert_eq!(sub1.id(), sub2.id());
1856 assert_eq!(sub2.id(), sub3.id()); }
1858
1859 #[test]
1860 fn drain_messages_preserves_order() {
1861 let mut mgr = SubscriptionManager::<TestMsg>::new();
1862
1863 struct OrderedSubscription {
1865 values: Vec<i32>,
1866 }
1867
1868 impl Subscription<TestMsg> for OrderedSubscription {
1869 fn id(&self) -> SubId {
1870 999
1871 }
1872
1873 fn run(&self, sender: SubscriptionSender<TestMsg>, _stop: StopSignal) {
1874 for v in &self.values {
1875 let _ = sender.send(TestMsg::Value(*v));
1876 thread::sleep(Duration::from_millis(1));
1877 }
1878 }
1879 }
1880
1881 mgr.reconcile(vec![Box::new(OrderedSubscription {
1882 values: vec![1, 2, 3, 4, 5],
1883 })]);
1884
1885 thread::sleep(Duration::from_millis(30));
1886 let msgs = mgr.drain_messages();
1887
1888 let values: Vec<i32> = msgs
1889 .iter()
1890 .filter_map(|m| match m {
1891 TestMsg::Value(v) => Some(*v),
1892 _ => None,
1893 })
1894 .collect();
1895
1896 assert_eq!(values, vec![1, 2, 3, 4, 5]);
1897 }
1898
1899 #[test]
1900 fn subscription_manager_new_is_empty() {
1901 let mgr = SubscriptionManager::<TestMsg>::new();
1902 let msgs = mgr.drain_messages();
1903 assert!(msgs.is_empty());
1904 }
1905
1906 #[test]
1918 fn contract_stop_signal_resilient_to_thread_panics() {
1919 let (signal, trigger) = StopSignal::new();
1920 let signal_clone = signal.clone();
1921
1922 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1924 assert!(!signal_clone.is_stopped());
1925 panic!("intentional panic while holding signal clone");
1926 }));
1927 assert!(result.is_err());
1928
1929 assert!(
1931 !signal.is_stopped(),
1932 "signal should still report not-stopped"
1933 );
1934 trigger.stop();
1935 assert!(
1936 signal.is_stopped(),
1937 "signal should report stopped after trigger"
1938 );
1939 assert!(
1940 signal.wait_timeout(Duration::from_millis(10)),
1941 "wait_timeout should return true when stopped"
1942 );
1943 }
1944
1945 #[test]
1948 fn contract_stop_signal_exposes_cancellation_token() {
1949 let (signal, trigger) = StopSignal::new();
1950 let token = signal.cancellation_token();
1951 assert!(!token.is_cancelled(), "token should start uncancelled");
1952 trigger.stop();
1953 assert!(token.is_cancelled(), "token should be cancelled after stop");
1954 }
1955
1956 #[test]
1960 fn contract_stop_all_bounded_time_with_uncooperative_subscriptions() {
1961 contract_stop_all_bounded_time_with_uncooperative_subscriptions_property();
1962 }
1963
1964 #[test]
1965 fn contract_stop_all_bounded_time_with_uncooperative_subscriptions_property() {
1966 let mut mgr = SubscriptionManager::<TestMsg>::new();
1967 let scale = ftui_core::cx::test_time_scale();
1968 let release = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1969
1970 struct UncooperativeSub {
1972 id: SubId,
1973 scale: u32,
1974 release: std::sync::Arc<std::sync::atomic::AtomicBool>,
1975 }
1976
1977 impl Subscription<TestMsg> for UncooperativeSub {
1978 fn id(&self) -> SubId {
1979 self.id
1980 }
1981
1982 fn run(&self, _sender: SubscriptionSender<TestMsg>, _stop: StopSignal) {
1983 let deadline = Instant::now() + Duration::from_secs(10) * self.scale;
1984 while !self.release.load(std::sync::atomic::Ordering::Relaxed)
1985 && Instant::now() < deadline
1986 {
1987 thread::sleep(Duration::from_millis(5));
1988 }
1989 }
1990 }
1991
1992 mgr.reconcile(vec![
1993 Box::new(UncooperativeSub {
1994 id: 100,
1995 scale,
1996 release: release.clone(),
1997 }),
1998 Box::new(UncooperativeSub {
1999 id: 200,
2000 scale,
2001 release: release.clone(),
2002 }),
2003 ]);
2004
2005 thread::sleep(Duration::from_millis(20)); let start = Instant::now();
2008 mgr.stop_all();
2009 let elapsed = start.elapsed();
2010 release.store(true, std::sync::atomic::Ordering::Relaxed);
2011
2012 assert!(
2017 elapsed < Duration::from_millis(2500) * ftui_core::cx::test_time_scale(),
2018 "stop_all took {elapsed:?}: it blocked on an uncooperative subscription"
2019 );
2020 }
2021
2022 #[test]
2025 fn contract_reconcile_deduplicates_by_id_not_identity() {
2026 let mut mgr = SubscriptionManager::<TestMsg>::new();
2027 let counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
2028
2029 struct CountingSub {
2030 id: SubId,
2031 counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
2032 }
2033
2034 impl Subscription<TestMsg> for CountingSub {
2035 fn id(&self) -> SubId {
2036 self.id
2037 }
2038
2039 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2040 self.counter
2041 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2042 while !stop.is_stopped() {
2043 thread::sleep(Duration::from_millis(5));
2044 }
2045 }
2046 }
2047
2048 mgr.reconcile(vec![Box::new(CountingSub {
2050 id: 42,
2051 counter: counter.clone(),
2052 })]);
2053 thread::sleep(Duration::from_millis(20));
2054 assert_eq!(
2055 counter.load(std::sync::atomic::Ordering::SeqCst),
2056 1,
2057 "first reconcile should start exactly 1 thread"
2058 );
2059
2060 mgr.reconcile(vec![Box::new(CountingSub {
2062 id: 42,
2063 counter: counter.clone(),
2064 })]);
2065 thread::sleep(Duration::from_millis(20));
2066 assert_eq!(
2067 counter.load(std::sync::atomic::Ordering::SeqCst),
2068 1,
2069 "second reconcile with same ID must not start another thread"
2070 );
2071
2072 mgr.stop_all();
2073 }
2074
2075 #[test]
2079 fn contract_buffered_messages_available_after_subscription_stopped() {
2080 let mut mgr = SubscriptionManager::<TestMsg>::new();
2081
2082 struct BurstSub;
2083
2084 impl Subscription<TestMsg> for BurstSub {
2085 fn id(&self) -> SubId {
2086 77
2087 }
2088
2089 fn run(&self, sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2090 for i in 0..10 {
2092 let _ = sender.send(TestMsg::Value(i));
2093 }
2094 while !stop.is_stopped() {
2096 thread::sleep(Duration::from_millis(5));
2097 }
2098 }
2099 }
2100
2101 mgr.reconcile(vec![Box::new(BurstSub)]);
2102 thread::sleep(Duration::from_millis(30));
2103
2104 mgr.reconcile(vec![]);
2106
2107 let msgs = mgr.drain_messages();
2109 let values: Vec<i32> = msgs
2110 .iter()
2111 .filter_map(|m| match m {
2112 TestMsg::Value(v) => Some(*v),
2113 _ => None,
2114 })
2115 .collect();
2116
2117 assert!(
2118 values.len() >= 5,
2119 "Expected at least 5 buffered messages after stop, got {}",
2120 values.len()
2121 );
2122 }
2123
2124 #[test]
2127 fn contract_active_count_tracks_running_subscriptions() {
2128 let mut mgr = SubscriptionManager::<TestMsg>::new();
2129
2130 assert_eq!(mgr.active_count(), 0, "empty manager");
2131
2132 mgr.reconcile(vec![
2133 Box::new(Every::with_id(1, Duration::from_millis(50), || {
2134 TestMsg::Tick
2135 })),
2136 Box::new(Every::with_id(2, Duration::from_millis(50), || {
2137 TestMsg::Tick
2138 })),
2139 ]);
2140 assert_eq!(mgr.active_count(), 2, "after starting 2");
2141
2142 mgr.reconcile(vec![Box::new(Every::with_id(
2143 1,
2144 Duration::from_millis(50),
2145 || TestMsg::Tick,
2146 ))]);
2147 assert_eq!(mgr.active_count(), 1, "after removing 1");
2148
2149 mgr.stop_all();
2150 assert_eq!(mgr.active_count(), 0, "after stop_all");
2151 }
2152
2153 #[test]
2157 fn contract_every_id_derived_from_interval_only() {
2158 let sub_a = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
2159 let sub_b = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(999));
2160 assert_eq!(
2161 sub_a.id(),
2162 sub_b.id(),
2163 "Every ID must depend only on interval, not message factory"
2164 );
2165
2166 let sub_c = Every::<TestMsg>::new(Duration::from_millis(200), || TestMsg::Tick);
2167 assert_ne!(
2168 sub_a.id(),
2169 sub_c.id(),
2170 "Different intervals must produce different IDs"
2171 );
2172 }
2173
2174 #[test]
2177 fn contract_every_id_formula_is_stable() {
2178 let interval = Duration::from_millis(100);
2179 let expected_id = interval.as_nanos() as u64 ^ 0x5449_434B;
2180 let sub = Every::<TestMsg>::new(interval, || TestMsg::Tick);
2181 assert_eq!(
2182 sub.id(),
2183 expected_id,
2184 "Every ID formula must be: interval.as_nanos() as u64 ^ 0x5449_434B"
2185 );
2186 }
2187
2188 #[test]
2191 fn contract_drop_triggers_stop_all() {
2192 use std::sync::atomic::{AtomicUsize, Ordering};
2193
2194 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
2195
2196 struct StopCountingSub {
2197 id: SubId,
2198 counter: std::sync::Arc<AtomicUsize>,
2199 }
2200
2201 impl Subscription<TestMsg> for StopCountingSub {
2202 fn id(&self) -> SubId {
2203 self.id
2204 }
2205
2206 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2207 while !stop.is_stopped() {
2208 thread::sleep(Duration::from_millis(5));
2209 }
2210 self.counter.fetch_add(1, Ordering::SeqCst);
2211 }
2212 }
2213
2214 {
2215 let mut mgr = SubscriptionManager::<TestMsg>::new();
2216 mgr.reconcile(vec![
2217 Box::new(StopCountingSub {
2218 id: 1,
2219 counter: stop_count.clone(),
2220 }),
2221 Box::new(StopCountingSub {
2222 id: 2,
2223 counter: stop_count.clone(),
2224 }),
2225 Box::new(StopCountingSub {
2226 id: 3,
2227 counter: stop_count.clone(),
2228 }),
2229 ]);
2230 thread::sleep(Duration::from_millis(20));
2231 }
2233
2234 thread::sleep(Duration::from_millis(400));
2236 assert_eq!(
2237 stop_count.load(std::sync::atomic::Ordering::SeqCst),
2238 3,
2239 "all 3 subscription threads must have observed stop signal on drop"
2240 );
2241 }
2242
2243 #[test]
2246 fn contract_stop_join_timeout_is_250ms() {
2247 assert_eq!(
2248 SUBSCRIPTION_STOP_JOIN_TIMEOUT,
2249 Duration::from_millis(250),
2250 "join timeout must be 250ms"
2251 );
2252 assert_eq!(
2253 SUBSCRIPTION_STOP_JOIN_POLL,
2254 Duration::from_millis(1),
2255 "join poll interval must be 1ms (bd-1f2aw)"
2256 );
2257 }
2258
2259 #[test]
2269 fn lifecycle_panic_in_subscription_is_caught() {
2270 use std::sync::atomic::Ordering;
2271
2272 let mut mgr = SubscriptionManager::<TestMsg>::new();
2273
2274 struct PanickingSub;
2275
2276 impl Subscription<TestMsg> for PanickingSub {
2277 fn id(&self) -> SubId {
2278 0xDEAD
2279 }
2280
2281 fn run(&self, _sender: SubscriptionSender<TestMsg>, _stop: StopSignal) {
2282 panic!("intentional test panic in subscription");
2283 }
2284 }
2285
2286 mgr.reconcile(vec![Box::new(PanickingSub)]);
2287
2288 let failure = mgr
2292 .failure_receiver
2293 .recv_timeout(Duration::from_secs(5))
2294 .expect("subscription panic must be caught and reported");
2295 assert_eq!(failure.id, 0xDEAD);
2296 assert_eq!(failure.error, "intentional test panic in subscription");
2297
2298 assert_eq!(
2300 mgr.active_count(),
2301 1,
2302 "panicked sub still tracked as active"
2303 );
2304
2305 assert!(
2307 mgr.active[0].panicked.load(Ordering::Acquire),
2308 "panicked flag should be set after subscription panic"
2309 );
2310
2311 mgr.stop_all();
2313 assert_eq!(mgr.active_count(), 0);
2314 }
2315
2316 #[test]
2319 fn lifecycle_panic_does_not_affect_sibling_subscriptions() {
2320 let mut mgr = SubscriptionManager::<TestMsg>::new();
2321
2322 struct PanickingSub;
2323 impl Subscription<TestMsg> for PanickingSub {
2324 fn id(&self) -> SubId {
2325 0xBAD
2326 }
2327 fn run(&self, _sender: SubscriptionSender<TestMsg>, _stop: StopSignal) {
2328 panic!("boom");
2329 }
2330 }
2331
2332 mgr.reconcile(vec![
2333 Box::new(PanickingSub),
2334 Box::new(Every::with_id(42, Duration::from_millis(10), || {
2335 TestMsg::Tick
2336 })),
2337 ]);
2338
2339 thread::sleep(Duration::from_millis(100));
2342
2343 let msgs = mgr.drain_messages();
2344 assert!(
2345 !msgs.is_empty(),
2346 "sibling subscription should still deliver messages after a panic in another sub"
2347 );
2348
2349 mgr.stop_all();
2350 }
2351
2352 #[test]
2355 fn lifecycle_stop_all_parallel_shutdown() {
2356 lifecycle_stop_all_parallel_shutdown_property();
2357 }
2358
2359 #[test]
2360 fn lifecycle_stop_all_parallel_shutdown_property() {
2361 use std::sync::atomic::{AtomicUsize, Ordering};
2362
2363 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
2364 let sub_count = 4;
2365 let scale = ftui_core::cx::test_time_scale();
2366
2367 let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
2373 let stranded = std::sync::Arc::new(AtomicUsize::new(0));
2374
2375 struct SlowStopSub {
2376 id: SubId,
2377 expected: usize,
2378 scale: u32,
2379 winding_down: std::sync::Arc<AtomicUsize>,
2380 stranded: std::sync::Arc<AtomicUsize>,
2381 counter: std::sync::Arc<AtomicUsize>,
2382 }
2383
2384 impl Subscription<TestMsg> for SlowStopSub {
2385 fn id(&self) -> SubId {
2386 self.id
2387 }
2388
2389 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2390 while !stop.is_stopped() {
2391 thread::sleep(Duration::from_millis(5));
2392 }
2393 self.winding_down.fetch_add(1, Ordering::SeqCst);
2394 let guard = Instant::now();
2395 while self.winding_down.load(Ordering::SeqCst) < self.expected {
2396 if guard.elapsed() > Duration::from_secs(5) * self.scale {
2397 self.stranded.fetch_add(1, Ordering::SeqCst);
2398 return;
2399 }
2400 thread::sleep(Duration::from_millis(1));
2401 }
2402 self.counter.fetch_add(1, Ordering::SeqCst);
2403 }
2404 }
2405
2406 let mut mgr = SubscriptionManager::<TestMsg>::new();
2407 let subs: Vec<Box<dyn Subscription<TestMsg>>> = (0..sub_count)
2408 .map(|i| -> Box<dyn Subscription<TestMsg>> {
2409 Box::new(SlowStopSub {
2410 id: 1000 + i,
2411 expected: sub_count as usize,
2412 scale,
2413 winding_down: winding_down.clone(),
2414 stranded: stranded.clone(),
2415 counter: stop_count.clone(),
2416 })
2417 })
2418 .collect();
2419
2420 mgr.reconcile(subs);
2421 thread::sleep(Duration::from_millis(20));
2422
2423 mgr.stop_all();
2424
2425 let deadline = Instant::now() + Duration::from_secs(10) * scale;
2428 while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst)
2429 < sub_count as usize
2430 && Instant::now() < deadline
2431 {
2432 thread::sleep(Duration::from_millis(1));
2433 }
2434 assert_eq!(
2435 stranded.load(Ordering::SeqCst),
2436 0,
2437 "stop phases did not overlap: stop_all signalled subscriptions sequentially"
2438 );
2439 assert_eq!(
2440 stop_count.load(Ordering::SeqCst),
2441 sub_count as usize,
2442 "all subscriptions should have completed their cleanup"
2443 );
2444 }
2445
2446 #[test]
2449 fn lifecycle_reconcile_removal_uses_parallel_stop() {
2450 reconcile_removal_stops_subscriptions_in_parallel();
2451 }
2452
2453 #[test]
2454 fn reconcile_removal_stops_subscriptions_in_parallel() {
2455 use std::sync::{
2456 Mutex,
2457 atomic::{AtomicUsize, Ordering},
2458 };
2459
2460 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
2461 let scale = ftui_core::cx::test_time_scale();
2462 let epoch = Instant::now();
2463 let records: std::sync::Arc<Mutex<Vec<(SubId, u64, u64)>>> =
2464 std::sync::Arc::new(Mutex::new(Vec::new()));
2465
2466 let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
2470 let stranded = std::sync::Arc::new(AtomicUsize::new(0));
2471
2472 struct SlowStopSub {
2473 id: SubId,
2474 epoch: Instant,
2475 scale: u32,
2476 winding_down: std::sync::Arc<AtomicUsize>,
2477 stranded: std::sync::Arc<AtomicUsize>,
2478 counter: std::sync::Arc<AtomicUsize>,
2479 records: std::sync::Arc<Mutex<Vec<(SubId, u64, u64)>>>,
2480 }
2481
2482 impl Subscription<TestMsg> for SlowStopSub {
2483 fn id(&self) -> SubId {
2484 self.id
2485 }
2486
2487 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2488 while !stop.is_stopped() {
2489 thread::sleep(Duration::from_millis(5));
2490 }
2491 let start_ns = self.epoch.elapsed().as_nanos() as u64;
2492 self.winding_down.fetch_add(1, Ordering::SeqCst);
2493 let guard = Instant::now();
2494 while self.winding_down.load(Ordering::SeqCst) < 3 {
2495 if guard.elapsed() > Duration::from_secs(5) * self.scale {
2496 self.stranded.fetch_add(1, Ordering::SeqCst);
2497 return;
2498 }
2499 thread::sleep(Duration::from_millis(1));
2500 }
2501 thread::sleep(Duration::from_millis(1));
2502 let end_ns = self.epoch.elapsed().as_nanos() as u64;
2503 self.records
2504 .lock()
2505 .unwrap()
2506 .push((self.id, start_ns, end_ns));
2507 self.counter.fetch_add(1, Ordering::SeqCst);
2508 }
2509 }
2510
2511 let mut mgr = SubscriptionManager::<TestMsg>::new();
2512 mgr.reconcile(
2513 [2000, 2001, 2002]
2514 .into_iter()
2515 .map(|id| -> Box<dyn Subscription<TestMsg>> {
2516 Box::new(SlowStopSub {
2517 id,
2518 epoch,
2519 scale,
2520 winding_down: winding_down.clone(),
2521 stranded: stranded.clone(),
2522 counter: stop_count.clone(),
2523 records: records.clone(),
2524 })
2525 })
2526 .collect(),
2527 );
2528 thread::sleep(Duration::from_millis(20));
2529
2530 let remove_start = Instant::now();
2532 mgr.reconcile(vec![]);
2533 let elapsed_ms = remove_start.elapsed().as_millis();
2534 eprintln!(
2535 "{{\"event\":\"reconcile_removal\",\"elapsed_ms\":{},\"scale\":{}}}",
2536 elapsed_ms, scale
2537 );
2538
2539 let deadline = Instant::now() + Duration::from_secs(10) * scale;
2540 while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst) < 3
2541 && Instant::now() < deadline
2542 {
2543 thread::sleep(Duration::from_millis(1));
2544 }
2545 assert_eq!(
2546 stranded.load(Ordering::SeqCst),
2547 0,
2548 "reconcile removal stopped subscriptions sequentially"
2549 );
2550 assert_eq!(stop_count.load(Ordering::SeqCst), 3);
2551
2552 let recorded = records.lock().unwrap();
2553 assert_eq!(recorded.len(), 3, "all 3 subscriptions must record spans");
2554 let min_end_ns = recorded.iter().map(|&(_, _, end)| end).min().unwrap();
2555 for &(id, start_ns, end_ns) in recorded.iter() {
2556 assert!(
2557 start_ns < min_end_ns,
2558 "subscription {id} start_ns={start_ns} did not overlap min_end_ns={min_end_ns} (end_ns={end_ns})"
2559 );
2560 }
2561 }
2562
2563 #[test]
2565 fn lifecycle_has_panicked_tracks_state() {
2566 let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2567 let panicked_flag = panicked.clone();
2568
2569 let (signal, trigger) = StopSignal::new();
2570 let thread = thread::spawn(move || {
2571 signal.wait_timeout(Duration::from_secs(10));
2572 });
2573
2574 let running = RunningSubscription {
2575 id: 999,
2576 trigger,
2577 thread: Some(thread),
2578 panicked,
2579 };
2580
2581 assert!(!running.has_panicked(), "should not be panicked initially");
2582
2583 panicked_flag.store(true, std::sync::atomic::Ordering::Release);
2585 assert!(running.has_panicked(), "should reflect panicked state");
2586
2587 running.stop();
2588 }
2589
2590 #[test]
2593 fn lifecycle_signal_then_join_works() {
2594 use std::sync::atomic::{AtomicBool, Ordering};
2595
2596 let completed = std::sync::Arc::new(AtomicBool::new(false));
2597 let completed_clone = completed.clone();
2598
2599 let (signal, trigger) = StopSignal::new();
2600 let thread = thread::spawn(move || {
2601 while !signal.is_stopped() {
2602 thread::sleep(Duration::from_millis(5));
2603 }
2604 completed_clone.store(true, Ordering::SeqCst);
2605 });
2606
2607 let running = RunningSubscription {
2608 id: 888,
2609 trigger,
2610 thread: Some(thread),
2611 panicked: std::sync::Arc::new(AtomicBool::new(false)),
2612 };
2613
2614 running.signal_stop();
2615 let leftover = running.join_bounded();
2616 assert!(
2617 leftover.is_none(),
2618 "cooperative thread should join within timeout"
2619 );
2620 assert!(
2621 completed.load(Ordering::SeqCst),
2622 "thread should have completed"
2623 );
2624 }
2625
2626 #[test]
2628 fn lifecycle_join_bounded_returns_handle_for_uncooperative() {
2629 lifecycle_join_bounded_returns_handle_for_uncooperative_property();
2630 }
2631
2632 #[test]
2633 fn lifecycle_join_bounded_returns_handle_for_uncooperative_property() {
2634 use std::sync::atomic::AtomicBool;
2635
2636 let scale = ftui_core::cx::test_time_scale();
2637 let (release_tx, release_rx) = mpsc::channel::<()>();
2638
2639 let (_signal, trigger) = StopSignal::new();
2643 let thread = thread::spawn(move || {
2644 let _ = release_rx.recv_timeout(Duration::from_secs(10) * scale);
2645 });
2646
2647 let running = RunningSubscription {
2648 id: 777,
2649 trigger,
2650 thread: Some(thread),
2651 panicked: std::sync::Arc::new(AtomicBool::new(false)),
2652 };
2653
2654 running.signal_stop();
2655 let start = Instant::now();
2656 let leftover = running.join_bounded();
2657 let elapsed = start.elapsed();
2658 let _ = release_tx.send(());
2659
2660 assert!(
2661 leftover.is_some(),
2662 "uncooperative thread should not join within timeout"
2663 );
2664 if let Some(handle) = leftover {
2665 let _ = handle.join();
2666 }
2667 assert!(
2668 elapsed < Duration::from_millis(1500) * ftui_core::cx::test_time_scale(),
2669 "join_bounded should respect the 250ms timeout, took {elapsed:?}"
2670 );
2671 }
2672
2673 #[test]
2676 fn lifecycle_restart_after_stop() {
2677 let mut mgr = SubscriptionManager::<TestMsg>::new();
2678
2679 mgr.reconcile(vec![Box::new(Every::with_id(
2681 300,
2682 Duration::from_millis(10),
2683 || TestMsg::Tick,
2684 ))]);
2685 thread::sleep(Duration::from_millis(30));
2686 let msgs = mgr.drain_messages();
2687 assert!(!msgs.is_empty(), "should receive ticks");
2688
2689 mgr.reconcile(vec![]);
2691 thread::sleep(Duration::from_millis(20));
2692 let _ = mgr.drain_messages();
2693 thread::sleep(Duration::from_millis(30));
2694 let msgs = mgr.drain_messages();
2695 assert!(msgs.is_empty(), "should stop receiving after removal");
2696
2697 mgr.reconcile(vec![Box::new(Every::with_id(
2699 300,
2700 Duration::from_millis(10),
2701 || TestMsg::Value(99),
2702 ))]);
2703 thread::sleep(Duration::from_millis(30));
2704 let msgs = mgr.drain_messages();
2705 assert!(
2706 !msgs.is_empty(),
2707 "should receive messages again after restart"
2708 );
2709 assert!(
2710 msgs.iter().any(|m| matches!(m, TestMsg::Value(99))),
2711 "restarted sub should use the new message factory"
2712 );
2713
2714 mgr.stop_all();
2715 }
2716
2717 #[test]
2725 fn lifecycle_non_interference_with_manager_state() {
2726 use std::sync::atomic::{AtomicUsize, Ordering};
2727
2728 let msg_count = std::sync::Arc::new(AtomicUsize::new(0));
2729
2730 struct CountingSub {
2731 id: SubId,
2732 counter: std::sync::Arc<AtomicUsize>,
2733 }
2734
2735 impl Subscription<TestMsg> for CountingSub {
2736 fn id(&self) -> SubId {
2737 self.id
2738 }
2739
2740 fn run(&self, sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2741 while !stop.is_stopped() {
2742 if sender.send(TestMsg::Tick).is_err() {
2743 break;
2744 }
2745 self.counter.fetch_add(1, Ordering::SeqCst);
2746 thread::sleep(Duration::from_millis(5));
2747 }
2748 }
2749 }
2750
2751 let mut mgr = SubscriptionManager::<TestMsg>::new();
2752
2753 mgr.reconcile(vec![
2755 Box::new(CountingSub {
2756 id: 400,
2757 counter: msg_count.clone(),
2758 }),
2759 Box::new(CountingSub {
2760 id: 401,
2761 counter: msg_count.clone(),
2762 }),
2763 ]);
2764
2765 thread::sleep(Duration::from_millis(50));
2766
2767 assert_eq!(mgr.active_count(), 2);
2769 let drained = mgr.drain_messages();
2770 let sent_count = msg_count.load(Ordering::SeqCst);
2771 assert!(sent_count > 0, "subscriptions should have sent messages");
2772 assert!(
2773 drained.len() <= sent_count,
2774 "drained {} but only {} sent",
2775 drained.len(),
2776 sent_count
2777 );
2778
2779 mgr.stop_all();
2781 assert_eq!(mgr.active_count(), 0);
2782
2783 let remaining = mgr.drain_messages();
2785 let total_drained = drained.len() + remaining.len();
2786 let final_sent = msg_count.load(Ordering::SeqCst);
2787 assert!(
2788 total_drained <= final_sent,
2789 "total drained ({total_drained}) must not exceed total sent ({final_sent})"
2790 );
2791 }
2792
2793 #[test]
2797 fn lifecycle_shutdown_signal_ordering() {
2798 use std::sync::atomic::{AtomicU64, Ordering};
2799
2800 let signal_times =
2801 std::sync::Arc::new([AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]);
2802 let epoch = Instant::now();
2803
2804 struct TimingStopSub {
2805 id: SubId,
2806 index: usize,
2807 signal_times: std::sync::Arc<[AtomicU64; 3]>,
2808 epoch: Instant,
2809 }
2810
2811 impl Subscription<TestMsg> for TimingStopSub {
2812 fn id(&self) -> SubId {
2813 self.id
2814 }
2815
2816 fn run(&self, _sender: SubscriptionSender<TestMsg>, stop: StopSignal) {
2817 while !stop.is_stopped() {
2818 thread::sleep(Duration::from_millis(1));
2819 }
2820 let elapsed_us = self.epoch.elapsed().as_micros() as u64;
2821 self.signal_times[self.index].store(elapsed_us, Ordering::SeqCst);
2822 }
2823 }
2824
2825 let mut mgr = SubscriptionManager::<TestMsg>::new();
2826 mgr.reconcile(vec![
2827 Box::new(TimingStopSub {
2828 id: 500,
2829 index: 0,
2830 signal_times: signal_times.clone(),
2831 epoch,
2832 }),
2833 Box::new(TimingStopSub {
2834 id: 501,
2835 index: 1,
2836 signal_times: signal_times.clone(),
2837 epoch,
2838 }),
2839 Box::new(TimingStopSub {
2840 id: 502,
2841 index: 2,
2842 signal_times: signal_times.clone(),
2843 epoch,
2844 }),
2845 ]);
2846 thread::sleep(Duration::from_millis(20));
2847
2848 mgr.stop_all();
2849
2850 let t0 = signal_times[0].load(Ordering::SeqCst);
2854 let t1 = signal_times[1].load(Ordering::SeqCst);
2855 let t2 = signal_times[2].load(Ordering::SeqCst);
2856
2857 assert!(
2858 t0 > 0 && t1 > 0 && t2 > 0,
2859 "all subs should have recorded stop time"
2860 );
2861
2862 let max_t = t0.max(t1).max(t2);
2863 let min_t = t0.min(t1).min(t2);
2864 let spread_us = max_t - min_t;
2865
2866 assert!(
2867 spread_us < 10_000, "stop signal spread should be < 10ms for parallel signaling, got {spread_us}us \
2869 (t0={t0}, t1={t1}, t2={t2})"
2870 );
2871 }
2872}