1#![forbid(unsafe_code)]
2
3use crate::cancellation::{CancellationSource, CancellationToken};
18use std::collections::HashSet;
19use std::path::{Path, PathBuf};
20use std::sync::mpsc;
21use std::thread;
22use web_time::{Duration, Instant};
23
24pub type SubId = u64;
29
30pub trait Subscription<M: Send + 'static>: Send {
35 fn id(&self) -> SubId;
40
41 fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal);
47}
48
49#[derive(Clone)]
56pub struct StopSignal {
57 token: CancellationToken,
58}
59
60impl StopSignal {
61 pub(crate) fn new() -> (Self, StopTrigger) {
63 let source = CancellationSource::new();
64 let signal = Self {
65 token: source.token(),
66 };
67 let trigger = StopTrigger { source };
68 (signal, trigger)
69 }
70
71 pub fn is_stopped(&self) -> bool {
73 self.token.is_cancelled()
74 }
75
76 pub fn wait_timeout(&self, duration: Duration) -> bool {
82 self.token.wait_timeout(duration)
83 }
84
85 pub fn cancellation_token(&self) -> &CancellationToken {
90 &self.token
91 }
92}
93
94pub(crate) struct StopTrigger {
98 source: CancellationSource,
99}
100
101impl StopTrigger {
102 pub(crate) fn stop(&self) {
104 self.source.cancel();
105 }
106}
107
108pub(crate) struct RunningSubscription {
110 pub(crate) id: SubId,
111 trigger: StopTrigger,
112 thread: Option<thread::JoinHandle<()>>,
113 panicked: std::sync::Arc<std::sync::atomic::AtomicBool>,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
119pub(crate) struct SubscriptionFailure {
120 pub(crate) id: SubId,
121 pub(crate) error: String,
122}
123
124const SUBSCRIPTION_STOP_JOIN_TIMEOUT: Duration = Duration::from_millis(250);
125const SUBSCRIPTION_STOP_JOIN_POLL: Duration = Duration::from_millis(1);
131
132impl RunningSubscription {
133 pub(crate) fn has_panicked(&self) -> bool {
135 self.panicked.load(std::sync::atomic::Ordering::Acquire)
136 }
137
138 pub(crate) fn signal_stop(&self) {
143 self.trigger.stop();
144 }
145
146 pub(crate) fn join_bounded(mut self) -> Option<thread::JoinHandle<()>> {
151 let handle = self.thread.take()?;
152 let start = Instant::now();
153
154 if handle.is_finished() {
156 let _ = handle.join();
157 tracing::trace!(
158 sub_id = self.id,
159 panicked = self.has_panicked(),
160 elapsed_us = start.elapsed().as_micros() as u64,
161 "subscription join (fast path)"
162 );
163 return None;
164 }
165
166 while !handle.is_finished() {
168 if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
169 tracing::warn!(
170 sub_id = self.id,
171 panicked = self.has_panicked(),
172 timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
173 "subscription join timed out, detaching thread"
174 );
175 return Some(handle);
176 }
177 thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
178 }
179
180 let _ = handle.join();
181 tracing::trace!(
182 sub_id = self.id,
183 panicked = self.has_panicked(),
184 elapsed_us = start.elapsed().as_micros() as u64,
185 "subscription join (slow path)"
186 );
187 None
188 }
189
190 #[cfg_attr(not(test), allow(dead_code))]
195 pub(crate) fn stop(mut self) {
196 self.trigger.stop();
197 if let Some(handle) = self.thread.take() {
198 let start = Instant::now();
199 if handle.is_finished() {
201 let _ = handle.join();
202 tracing::trace!(
203 sub_id = self.id,
204 panicked = self.has_panicked(),
205 elapsed_us = start.elapsed().as_micros() as u64,
206 "subscription stop (fast path)"
207 );
208 return;
209 }
210 while !handle.is_finished() {
212 if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
213 tracing::warn!(
214 sub_id = self.id,
215 panicked = self.has_panicked(),
216 timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
217 "subscription did not stop within timeout; detaching thread"
218 );
219 return;
220 }
221 thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
222 }
223 let _ = handle.join();
224 tracing::trace!(
225 sub_id = self.id,
226 panicked = self.has_panicked(),
227 elapsed_us = start.elapsed().as_micros() as u64,
228 "subscription stop (slow path)"
229 );
230 }
231 }
232}
233
234impl Drop for RunningSubscription {
235 fn drop(&mut self) {
236 self.trigger.stop();
237 }
239}
240
241pub(crate) struct SubscriptionManager<M: Send + 'static> {
243 active: Vec<RunningSubscription>,
244 sender: mpsc::Sender<M>,
245 receiver: mpsc::Receiver<M>,
246 failure_sender: mpsc::Sender<SubscriptionFailure>,
247 failure_receiver: mpsc::Receiver<SubscriptionFailure>,
248}
249
250impl<M: Send + 'static> SubscriptionManager<M> {
251 pub(crate) fn new() -> Self {
252 let (sender, receiver) = mpsc::channel();
253 let (failure_sender, failure_receiver) = mpsc::channel();
254 Self {
255 active: Vec::new(),
256 sender,
257 receiver,
258 failure_sender,
259 failure_receiver,
260 }
261 }
262
263 pub(crate) fn reconcile(&mut self, subscriptions: Vec<Box<dyn Subscription<M>>>) {
270 let reconcile_start = Instant::now();
271 let new_ids: HashSet<SubId> = subscriptions.iter().map(|s| s.id()).collect();
272 let active_count_before = self.active.len();
273
274 crate::debug_trace!(
275 "reconcile: new_ids={:?}, active_before={}",
276 new_ids,
277 active_count_before
278 );
279 tracing::trace!(
280 new_id_count = new_ids.len(),
281 active_before = active_count_before,
282 new_ids = ?new_ids,
283 "subscription reconcile starting"
284 );
285
286 let mut remaining = Vec::new();
288 let mut to_stop = Vec::new();
289 for running in self.active.drain(..) {
290 if new_ids.contains(&running.id) {
291 remaining.push(running);
292 } else {
293 crate::debug_trace!("stopping subscription: id={}", running.id);
294 tracing::debug!(sub_id = running.id, "Stopping subscription");
295 crate::effect_system::record_subscription_stop("subscription", running.id, 0);
296 crate::effect_system::record_dynamics_sub_stop();
297 to_stop.push(running);
298 }
299 }
300 for running in &to_stop {
302 running.signal_stop();
303 }
304 let stopped_count = to_stop.len();
305 for running in to_stop {
307 let _ = running.join_bounded();
308 }
309 self.active = remaining;
310
311 let mut started_count = 0usize;
313 let mut active_ids: HashSet<SubId> = self.active.iter().map(|r| r.id).collect();
314 for sub in subscriptions {
315 let id = sub.id();
316 if !active_ids.insert(id) {
317 continue;
318 }
319 started_count += 1;
320
321 crate::debug_trace!("starting subscription: id={}", id);
322 tracing::debug!(sub_id = id, "Starting subscription");
323 crate::effect_system::record_subscription_start("subscription", id);
324 crate::effect_system::record_dynamics_sub_start();
325 let (signal, trigger) = StopSignal::new();
326 let sender = self.sender.clone();
327 let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
328 let panicked_flag = panicked.clone();
329 let sub_id_for_thread = id;
330 let failure_sender = self.failure_sender.clone();
331
332 let thread = thread::spawn(move || {
333 let result = ftui_core::with_panic_cleanup_suppressed(|| {
337 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
338 sub.run(sender, signal);
339 }))
340 });
341 if let Err(payload) = result {
342 panicked_flag.store(true, std::sync::atomic::Ordering::Release);
343 crate::effect_system::record_dynamics_sub_panic();
344 let panic_msg = match payload.downcast_ref::<&str>() {
345 Some(s) => (*s).to_string(),
346 None => match payload.downcast_ref::<String>() {
347 Some(s) => s.clone(),
348 None => "unknown panic payload".to_string(),
349 },
350 };
351 crate::effect_system::error_effect_panic(
352 "subscription",
353 &format!("sub_id={sub_id_for_thread}: {panic_msg}"),
354 );
355 let _ = failure_sender.send(SubscriptionFailure {
356 id: sub_id_for_thread,
357 error: panic_msg,
358 });
359 }
360 });
361
362 self.active.push(RunningSubscription {
363 id,
364 trigger,
365 thread: Some(thread),
366 panicked,
367 });
368 }
369
370 let active_count_after = self.active.len();
371 let reconcile_elapsed_us = reconcile_start.elapsed().as_micros() as u64;
372 crate::effect_system::record_dynamics_reconcile(reconcile_elapsed_us);
373 crate::debug_trace!("reconcile complete: active_after={}", active_count_after);
374 tracing::trace!(
375 active_before = active_count_before,
376 active_after = active_count_after,
377 started = started_count,
378 stopped = stopped_count,
379 reconcile_us = reconcile_elapsed_us,
380 "subscription reconcile complete"
381 );
382 }
383
384 pub(crate) fn drain_messages(&self) -> Vec<M> {
386 let mut messages = Vec::new();
387 while let Ok(msg) = self.receiver.try_recv() {
388 messages.push(msg);
389 }
390 messages
391 }
392
393 pub(crate) fn drain_failures(&self) -> Vec<SubscriptionFailure> {
395 let mut failures = Vec::new();
396 while let Ok(failure) = self.failure_receiver.try_recv() {
397 failures.push(failure);
398 }
399 failures
400 }
401
402 #[inline]
404 pub(crate) fn active_count(&self) -> usize {
405 self.active.len()
406 }
407
408 pub(crate) fn stop_all(&mut self) {
417 let count = self.active.len();
418 if count == 0 {
419 return;
420 }
421 let start = Instant::now();
422
423 for running in &self.active {
425 running.signal_stop();
426 }
427
428 let signal_elapsed_us = start.elapsed().as_micros() as u64;
429 tracing::trace!(
430 target: crate::telemetry_schema::TARGET_RUNTIME,
431 count,
432 signal_elapsed_us,
433 "subscription stop_all phase 1 (signal) complete"
434 );
435
436 let mut panicked_count = 0_usize;
438 let mut timed_out_count = 0_usize;
439 for running in self.active.drain(..) {
440 if running.has_panicked() {
441 panicked_count += 1;
442 }
443 if running.join_bounded().is_some() {
444 timed_out_count += 1;
445 }
446 }
447
448 let shutdown_elapsed_us = start.elapsed().as_micros() as u64;
449 crate::effect_system::record_dynamics_shutdown(shutdown_elapsed_us, timed_out_count as u64);
450 tracing::debug!(
451 target: crate::telemetry_schema::TARGET_RUNTIME,
452 count,
453 panicked_count,
454 timed_out_count,
455 elapsed_us = shutdown_elapsed_us,
456 "subscription stop_all complete"
457 );
458 }
459}
460
461impl<M: Send + 'static> Drop for SubscriptionManager<M> {
462 fn drop(&mut self) {
463 self.stop_all();
464 }
465}
466
467pub struct Every<M: Send + 'static> {
479 id: SubId,
480 interval: Duration,
481 make_msg: Box<dyn Fn() -> M + Send + Sync>,
482}
483
484impl<M: Send + 'static> Every<M> {
485 pub fn new(interval: Duration, make_msg: impl Fn() -> M + Send + Sync + 'static) -> Self {
487 let id = interval.as_nanos() as u64 ^ 0x5449_434B; Self {
490 id,
491 interval,
492 make_msg: Box::new(make_msg),
493 }
494 }
495
496 pub fn with_id(
498 id: SubId,
499 interval: Duration,
500 make_msg: impl Fn() -> M + Send + Sync + 'static,
501 ) -> Self {
502 Self {
503 id,
504 interval,
505 make_msg: Box::new(make_msg),
506 }
507 }
508}
509
510pub fn tick_every<M: Send + 'static>(
522 interval: Duration,
523 make_msg: impl Fn() -> M + Send + Sync + 'static,
524) -> Box<dyn Subscription<M>> {
525 Box::new(Every::new(interval, make_msg))
526}
527
528#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
530pub enum FileEvent {
531 Created,
533 Modified,
535 Removed,
537}
538
539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541struct FileFingerprint {
542 modified: Option<std::time::SystemTime>,
543 len: u64,
544}
545
546fn file_fingerprint(path: &Path) -> Option<FileFingerprint> {
547 std::fs::metadata(path).ok().map(|meta| FileFingerprint {
548 modified: meta.modified().ok(),
549 len: meta.len(),
550 })
551}
552
553fn file_watcher_id(path: &Path) -> SubId {
557 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
559 for byte in path.as_os_str().as_encoded_bytes() {
560 hash ^= u64::from(*byte);
561 hash = hash.wrapping_mul(0x0100_0000_01b3);
562 }
563 hash ^ 0x4653_5754 }
565
566pub struct FileWatcher<M: Send + 'static> {
587 id: SubId,
588 path: PathBuf,
589 interval: Duration,
590 make_msg: Box<dyn Fn(FileEvent) -> M + Send + Sync>,
591}
592
593impl<M: Send + 'static> FileWatcher<M> {
594 pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
596
597 pub fn new(
599 path: impl Into<PathBuf>,
600 make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
601 ) -> Self {
602 let path = path.into();
603 Self {
604 id: file_watcher_id(&path),
605 path,
606 interval: Self::DEFAULT_INTERVAL,
607 make_msg: Box::new(make_msg),
608 }
609 }
610
611 #[must_use]
613 pub fn with_interval(mut self, interval: Duration) -> Self {
614 self.interval = interval.max(Duration::from_millis(1));
615 self
616 }
617
618 #[must_use]
620 pub fn path(&self) -> &Path {
621 &self.path
622 }
623
624 #[must_use]
626 pub fn interval(&self) -> Duration {
627 self.interval
628 }
629}
630
631pub fn file_watcher<M: Send + 'static>(
636 path: impl Into<PathBuf>,
637 make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
638) -> Box<dyn Subscription<M>> {
639 Box::new(FileWatcher::new(path, make_msg))
640}
641
642impl<M: Send + 'static> Subscription<M> for FileWatcher<M> {
643 fn id(&self) -> SubId {
644 self.id
645 }
646
647 fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
648 let mut last = file_fingerprint(&self.path);
649 let mut sent: u64 = 0;
650 crate::debug_trace!(
651 "FileWatcher started: id={}, path={}, interval={:?}",
652 self.id,
653 self.path.display(),
654 self.interval
655 );
656 loop {
657 if stop.wait_timeout(self.interval) {
658 crate::debug_trace!("FileWatcher stopped: id={}, sent {} events", self.id, sent);
659 break;
660 }
661 let now = file_fingerprint(&self.path);
662 let event = match (last, now) {
663 (None, Some(_)) => Some(FileEvent::Created),
664 (Some(_), None) => Some(FileEvent::Removed),
665 (Some(prev), Some(cur)) if prev != cur => Some(FileEvent::Modified),
666 _ => None,
667 };
668 last = now;
669 if let Some(event) = event {
670 sent += 1;
671 if sender.send((self.make_msg)(event)).is_err() {
672 crate::debug_trace!(
673 "FileWatcher channel closed: id={}, sent {} events",
674 self.id,
675 sent
676 );
677 break;
678 }
679 }
680 }
681 }
682}
683
684impl<M: Send + 'static> Subscription<M> for Every<M> {
685 fn id(&self) -> SubId {
686 self.id
687 }
688
689 fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
690 let mut tick_count: u64 = 0;
691 crate::debug_trace!(
692 "Every subscription started: id={}, interval={:?}",
693 self.id,
694 self.interval
695 );
696 loop {
697 if stop.wait_timeout(self.interval) {
698 crate::debug_trace!(
699 "Every subscription stopped: id={}, sent {} ticks",
700 self.id,
701 tick_count
702 );
703 break;
704 }
705 tick_count += 1;
706 let msg = (self.make_msg)();
707 if sender.send(msg).is_err() {
708 crate::debug_trace!(
709 "Every subscription channel closed: id={}, sent {} ticks",
710 self.id,
711 tick_count
712 );
713 break;
714 }
715 }
716 }
717}
718
719#[cfg(test)]
720mod tests {
721 use super::*;
722
723 #[derive(Debug, Clone, PartialEq)]
724 enum TestMsg {
725 Tick,
726 Value(i32),
727 File(FileEvent),
728 }
729
730 struct ChannelSubscription<M: Send + 'static> {
731 id: SubId,
732 receiver: mpsc::Receiver<M>,
733 poll: Duration,
734 }
735
736 impl<M: Send + 'static> ChannelSubscription<M> {
737 fn new(id: SubId, receiver: mpsc::Receiver<M>) -> Self {
738 Self {
739 id,
740 receiver,
741 poll: Duration::from_millis(5),
742 }
743 }
744 }
745
746 impl<M: Send + 'static> Subscription<M> for ChannelSubscription<M> {
747 fn id(&self) -> SubId {
748 self.id
749 }
750
751 fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
752 loop {
753 if stop.is_stopped() {
754 break;
755 }
756 match self.receiver.recv_timeout(self.poll) {
757 Ok(msg) => {
758 if sender.send(msg).is_err() {
759 break;
760 }
761 }
762 Err(mpsc::RecvTimeoutError::Timeout) => {}
763 Err(mpsc::RecvTimeoutError::Disconnected) => break,
764 }
765 }
766 }
767 }
768
769 fn channel_subscription(id: SubId) -> (ChannelSubscription<TestMsg>, mpsc::Sender<TestMsg>) {
770 let (tx, rx) = mpsc::channel();
771 (ChannelSubscription::new(id, rx), tx)
772 }
773
774 #[test]
775 fn stop_signal_starts_false() {
776 let (signal, _trigger) = StopSignal::new();
777 assert!(!signal.is_stopped());
778 }
779
780 #[test]
781 fn stop_signal_becomes_true_after_trigger() {
782 let (signal, trigger) = StopSignal::new();
783 trigger.stop();
784 assert!(signal.is_stopped());
785 }
786
787 #[test]
788 fn stop_signal_wait_returns_true_when_stopped() {
789 let (signal, trigger) = StopSignal::new();
790 trigger.stop();
791 assert!(signal.wait_timeout(Duration::from_millis(100)));
792 }
793
794 #[test]
795 fn stop_signal_wait_returns_false_on_timeout() {
796 let (signal, _trigger) = StopSignal::new();
797 assert!(!signal.wait_timeout(Duration::from_millis(10)));
798 }
799
800 #[test]
801 fn channel_subscription_forwards_messages() {
802 let (sub, event_tx) = channel_subscription(1);
803 let (tx, rx) = mpsc::channel();
804 let (signal, trigger) = StopSignal::new();
805
806 let handle = thread::spawn(move || {
807 sub.run(tx, signal);
808 });
809
810 event_tx.send(TestMsg::Value(1)).unwrap();
811 event_tx.send(TestMsg::Value(2)).unwrap();
812 thread::sleep(Duration::from_millis(10));
813 trigger.stop();
814 handle.join().unwrap();
815
816 let msgs: Vec<_> = rx.try_iter().collect();
817 assert_eq!(msgs, vec![TestMsg::Value(1), TestMsg::Value(2)]);
818 }
819
820 #[test]
821 fn every_subscription_fires() {
822 let sub = Every::new(Duration::from_millis(10), || TestMsg::Tick);
823 let (tx, rx) = mpsc::channel();
824 let (signal, trigger) = StopSignal::new();
825
826 let handle = thread::spawn(move || {
827 sub.run(tx, signal);
828 });
829
830 thread::sleep(Duration::from_millis(50));
832 trigger.stop();
833 handle.join().unwrap();
834
835 let msgs: Vec<_> = rx.try_iter().collect();
836 assert!(!msgs.is_empty(), "Should have received at least one tick");
837 assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
838 }
839
840 #[test]
841 fn tick_every_is_a_boxed_every_with_the_same_id() {
842 let boxed: Box<dyn Subscription<TestMsg>> =
843 tick_every(Duration::from_millis(10), || TestMsg::Tick);
844 let plain = Every::new(Duration::from_millis(10), || TestMsg::Tick);
845 assert_eq!(
846 boxed.id(),
847 plain.id(),
848 "the helper must not change subscription identity (diffing relies on it)"
849 );
850
851 let (tx, rx) = mpsc::channel();
852 let (signal, trigger) = StopSignal::new();
853 let handle = thread::spawn(move || boxed.run(tx, signal));
854 thread::sleep(Duration::from_millis(50));
855 trigger.stop();
856 handle.join().unwrap();
857
858 let msgs: Vec<_> = rx.try_iter().collect();
859 assert!(!msgs.is_empty(), "boxed tick subscription must fire");
860 assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
861 }
862
863 #[test]
864 fn file_watcher_id_is_stable_per_path_and_distinct_from_ticks() {
865 let a1 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
866 let a2 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
867 let b = FileWatcher::new("/tmp/b.toml", TestMsg::File);
868 assert_eq!(a1.id(), a2.id(), "same path must dedupe across frames");
869 assert_ne!(
870 a1.id(),
871 b.id(),
872 "different paths are different subscriptions"
873 );
874 let tick = Every::new(Duration::from_millis(250), || TestMsg::Tick);
875 assert_ne!(a1.id(), tick.id());
876 assert_eq!(a1.interval(), FileWatcher::<TestMsg>::DEFAULT_INTERVAL);
877 assert_eq!(
878 a1.with_interval(Duration::ZERO).interval(),
879 Duration::from_millis(1),
880 "interval is clamped so the poll loop can never spin"
881 );
882 }
883
884 #[test]
887 fn file_watcher_reports_create_modify_remove() {
888 let dir = tempfile::tempdir().expect("temp dir");
889 let path = dir.path().join("watched.toml");
890 let sub = FileWatcher::new(&path, TestMsg::File).with_interval(Duration::from_millis(5));
891 assert_eq!(sub.path(), path.as_path());
892 let (tx, rx) = mpsc::channel();
893 let (signal, trigger) = StopSignal::new();
894 let handle = thread::spawn(move || sub.run(tx, signal));
895 let wait = Duration::from_secs(10);
896 thread::sleep(Duration::from_millis(40));
898 assert!(rx.try_recv().is_err(), "no event before anything happens");
899
900 std::fs::write(&path, b"a = 1\n").expect("create file");
901 assert_eq!(
902 rx.recv_timeout(wait).expect("created"),
903 TestMsg::File(FileEvent::Created)
904 );
905 thread::sleep(Duration::from_millis(40));
908 let _ = rx.try_iter().count();
909
910 std::fs::write(&path, b"a = 1\nb = 22\n").expect("modify file");
913 assert_eq!(
914 rx.recv_timeout(wait).expect("modified"),
915 TestMsg::File(FileEvent::Modified)
916 );
917 thread::sleep(Duration::from_millis(40));
918 let _ = rx.try_iter().count();
919
920 std::fs::remove_file(&path).expect("remove file");
921 assert_eq!(
922 rx.recv_timeout(wait).expect("removed"),
923 TestMsg::File(FileEvent::Removed)
924 );
925 thread::sleep(Duration::from_millis(40));
926 assert!(rx.try_recv().is_err(), "nothing after removal");
927
928 trigger.stop();
929 handle.join().unwrap();
930 }
931
932 #[test]
934 fn file_watcher_helper_boxes_the_same_subscription() {
935 let boxed: Box<dyn Subscription<TestMsg>> = file_watcher("/tmp/x.toml", TestMsg::File);
936 assert_eq!(
937 boxed.id(),
938 FileWatcher::new("/tmp/x.toml", TestMsg::File).id()
939 );
940 }
941
942 #[test]
943 fn every_subscription_uses_stable_id() {
944 let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
945 let sub2 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
946 assert_eq!(sub1.id(), sub2.id());
947 }
948
949 #[test]
950 fn every_subscription_different_intervals_different_ids() {
951 let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
952 let sub2 = Every::<TestMsg>::new(Duration::from_secs(2), || TestMsg::Tick);
953 assert_ne!(sub1.id(), sub2.id());
954 }
955
956 #[test]
957 fn subscription_manager_starts_subscriptions() {
958 let mut mgr = SubscriptionManager::<TestMsg>::new();
959 let (sub, event_tx) = channel_subscription(1);
960 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
961
962 mgr.reconcile(subs);
963 event_tx.send(TestMsg::Value(42)).unwrap();
964
965 thread::sleep(Duration::from_millis(20));
967
968 let msgs = mgr.drain_messages();
969 assert_eq!(msgs, vec![TestMsg::Value(42)]);
970 }
971
972 #[test]
973 fn subscription_manager_dedupes_duplicate_ids() {
974 let mut mgr = SubscriptionManager::<TestMsg>::new();
975 let (sub_a, tx_a) = channel_subscription(7);
976 let (sub_b, tx_b) = channel_subscription(7);
977 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub_a), Box::new(sub_b)];
978
979 mgr.reconcile(subs);
980
981 tx_a.send(TestMsg::Value(1)).unwrap();
982 assert!(
983 tx_b.send(TestMsg::Value(2)).is_err(),
984 "Duplicate subscription should be dropped"
985 );
986
987 thread::sleep(Duration::from_millis(20));
988 let msgs = mgr.drain_messages();
989 assert_eq!(msgs, vec![TestMsg::Value(1)]);
990 }
991
992 #[test]
993 fn subscription_manager_stops_removed() {
994 let mut mgr = SubscriptionManager::<TestMsg>::new();
995
996 mgr.reconcile(vec![Box::new(Every::with_id(
998 99,
999 Duration::from_millis(5),
1000 || TestMsg::Tick,
1001 ))]);
1002
1003 thread::sleep(Duration::from_millis(20));
1004 let msgs_before = mgr.drain_messages();
1005 assert!(!msgs_before.is_empty());
1006
1007 mgr.reconcile(vec![]);
1009
1010 thread::sleep(Duration::from_millis(20));
1012 let _ = mgr.drain_messages();
1013
1014 thread::sleep(Duration::from_millis(30));
1016 let msgs_after = mgr.drain_messages();
1017 assert!(
1018 msgs_after.is_empty(),
1019 "Should stop receiving after reconcile with empty set"
1020 );
1021 }
1022
1023 #[test]
1024 fn subscription_manager_keeps_unchanged() {
1025 let mut mgr = SubscriptionManager::<TestMsg>::new();
1026
1027 mgr.reconcile(vec![Box::new(Every::with_id(
1029 50,
1030 Duration::from_millis(10),
1031 || TestMsg::Tick,
1032 ))]);
1033
1034 thread::sleep(Duration::from_millis(30));
1035 let _ = mgr.drain_messages();
1036
1037 mgr.reconcile(vec![Box::new(Every::with_id(
1039 50,
1040 Duration::from_millis(10),
1041 || TestMsg::Tick,
1042 ))]);
1043
1044 thread::sleep(Duration::from_millis(30));
1045 let msgs = mgr.drain_messages();
1046 assert!(!msgs.is_empty(), "Subscription should still be running");
1047 }
1048
1049 #[test]
1050 fn subscription_manager_stop_all() {
1051 let mut mgr = SubscriptionManager::<TestMsg>::new();
1052
1053 mgr.reconcile(vec![
1054 Box::new(Every::with_id(1, Duration::from_millis(5), || {
1055 TestMsg::Value(1)
1056 })),
1057 Box::new(Every::with_id(2, Duration::from_millis(5), || {
1058 TestMsg::Value(2)
1059 })),
1060 ]);
1061
1062 thread::sleep(Duration::from_millis(20));
1063 mgr.stop_all();
1064
1065 thread::sleep(Duration::from_millis(20));
1066 let _ = mgr.drain_messages();
1067 thread::sleep(Duration::from_millis(30));
1068 let msgs = mgr.drain_messages();
1069 assert!(msgs.is_empty());
1070 }
1071
1072 #[test]
1077 fn stop_signal_is_cloneable() {
1078 let (signal, trigger) = StopSignal::new();
1079 let signal_clone = signal.clone();
1080
1081 assert!(!signal.is_stopped());
1082 assert!(!signal_clone.is_stopped());
1083
1084 trigger.stop();
1085
1086 assert!(signal.is_stopped());
1087 assert!(signal_clone.is_stopped());
1088 }
1089
1090 #[test]
1091 fn stop_signal_wait_wakes_immediately_when_already_stopped() {
1092 let (signal, trigger) = StopSignal::new();
1093 trigger.stop();
1094
1095 let start = Instant::now();
1099 let stopped = signal.wait_timeout(Duration::from_secs(10));
1100 let elapsed = start.elapsed();
1101
1102 assert!(stopped);
1103 assert!(
1104 elapsed < Duration::from_secs(5),
1105 "wait_timeout on a stopped signal must not wait for the timeout; took {elapsed:?}"
1106 );
1107 }
1108
1109 #[test]
1110 fn stop_signal_wait_is_interrupted_by_trigger() {
1111 let (signal, trigger) = StopSignal::new();
1112
1113 let signal_clone = signal.clone();
1114 let handle = thread::spawn(move || signal_clone.wait_timeout(Duration::from_secs(10)));
1115
1116 thread::sleep(Duration::from_millis(20));
1118 trigger.stop();
1119
1120 let stopped = handle.join().unwrap();
1121 assert!(stopped);
1122 }
1123
1124 #[test]
1125 fn channel_subscription_no_messages_without_events() {
1126 let (sub, _event_tx) = channel_subscription(1);
1127 let (tx, rx) = mpsc::channel();
1128 let (signal, trigger) = StopSignal::new();
1129
1130 let handle = thread::spawn(move || {
1131 sub.run(tx, signal);
1132 });
1133
1134 thread::sleep(Duration::from_millis(10));
1135 trigger.stop();
1136 handle.join().unwrap();
1137
1138 let msgs: Vec<_> = rx.try_iter().collect();
1139 assert!(msgs.is_empty());
1140 }
1141
1142 #[test]
1143 fn channel_subscription_id_is_preserved() {
1144 let (sub, _tx) = channel_subscription(42);
1145 assert_eq!(sub.id(), 42);
1146 }
1147
1148 #[test]
1149 fn channel_subscription_stops_on_disconnected_receiver() {
1150 let (sub, event_tx) = channel_subscription(1);
1151 let (tx, _rx) = mpsc::channel();
1152 let (signal, _trigger) = StopSignal::new();
1153
1154 drop(event_tx);
1155
1156 let handle = thread::spawn(move || {
1157 sub.run(tx, signal);
1158 });
1159
1160 let result = handle.join();
1161 assert!(result.is_ok());
1162 }
1163
1164 #[test]
1165 fn every_with_id_preserves_custom_id() {
1166 let sub = Every::<TestMsg>::with_id(12345, Duration::from_secs(1), || TestMsg::Tick);
1167 assert_eq!(sub.id(), 12345);
1168 }
1169
1170 #[test]
1171 fn every_stops_on_disconnected_receiver() {
1172 let sub = Every::new(Duration::from_millis(5), || TestMsg::Tick);
1173 let (tx, rx) = mpsc::channel();
1174 let (signal, _trigger) = StopSignal::new();
1175
1176 drop(rx);
1178
1179 let handle = thread::spawn(move || {
1181 sub.run(tx, signal);
1182 });
1183
1184 let result = handle.join();
1186 assert!(result.is_ok());
1187 }
1188
1189 #[test]
1190 fn every_respects_interval() {
1191 let interval = Duration::from_millis(50);
1192 let sub = Every::with_id(1, interval, Instant::now);
1193 let (tx, rx) = mpsc::channel();
1194 let (signal, trigger) = StopSignal::new();
1195
1196 let start = Instant::now();
1197 let handle = thread::spawn(move || {
1198 sub.run(tx, signal);
1199 });
1200
1201 let mut arrivals = Vec::new();
1206 let deadline = Instant::now() + Duration::from_secs(10);
1207 while arrivals.len() < 3 && Instant::now() < deadline {
1208 match rx.recv_timeout(Duration::from_millis(100)) {
1209 Ok(produced_at) => arrivals.push(produced_at),
1210 Err(mpsc::RecvTimeoutError::Timeout) => {}
1211 Err(mpsc::RecvTimeoutError::Disconnected) => break,
1212 }
1213 }
1214 trigger.stop();
1215 handle.join().unwrap();
1216
1217 assert!(
1218 arrivals.len() >= 2,
1219 "expected at least 2 ticks within 10 s, got {}",
1220 arrivals.len()
1221 );
1222 for pair in arrivals.windows(2) {
1223 let gap = pair[1].duration_since(pair[0]);
1224 assert!(
1225 gap >= interval,
1226 "ticks were generated {gap:?} apart, closer than the {interval:?} interval"
1227 );
1228 }
1229 assert!(
1230 start.elapsed() >= interval * 2,
1231 "two ticks cannot arrive before two intervals have passed"
1232 );
1233 }
1234
1235 #[test]
1236 fn subscription_manager_empty_reconcile() {
1237 let mut mgr = SubscriptionManager::<TestMsg>::new();
1238
1239 mgr.reconcile(vec![]);
1241 let msgs = mgr.drain_messages();
1242 assert!(msgs.is_empty());
1243 }
1244
1245 #[test]
1246 fn subscription_manager_drain_messages_returns_all() {
1247 let mut mgr = SubscriptionManager::<TestMsg>::new();
1248 let (sub, event_tx) = channel_subscription(1);
1249 let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
1250
1251 mgr.reconcile(subs);
1252 event_tx.send(TestMsg::Value(1)).unwrap();
1253 event_tx.send(TestMsg::Value(2)).unwrap();
1254 thread::sleep(Duration::from_millis(20));
1255
1256 let msgs = mgr.drain_messages();
1257 assert_eq!(msgs.len(), 2);
1258 assert_eq!(msgs[0], TestMsg::Value(1));
1259 assert_eq!(msgs[1], TestMsg::Value(2));
1260
1261 let msgs2 = mgr.drain_messages();
1263 assert!(msgs2.is_empty());
1264 }
1265
1266 #[test]
1267 fn subscription_manager_replaces_subscription_with_different_id() {
1268 let mut mgr = SubscriptionManager::<TestMsg>::new();
1269 let (sub1, tx1) = channel_subscription(1);
1270
1271 mgr.reconcile(vec![Box::new(sub1)]);
1273 tx1.send(TestMsg::Value(1)).unwrap();
1274 thread::sleep(Duration::from_millis(20));
1275 let msgs1 = mgr.drain_messages();
1276 assert_eq!(msgs1, vec![TestMsg::Value(1)]);
1277
1278 let (sub2, tx2) = channel_subscription(2);
1280 mgr.reconcile(vec![Box::new(sub2)]);
1281 tx2.send(TestMsg::Value(2)).unwrap();
1282 thread::sleep(Duration::from_millis(20));
1283 let msgs2 = mgr.drain_messages();
1284 assert_eq!(msgs2, vec![TestMsg::Value(2)]);
1285 }
1286
1287 #[test]
1288 fn subscription_manager_multiple_subscriptions() {
1289 let mut mgr = SubscriptionManager::<TestMsg>::new();
1290 let (sub1, tx1) = channel_subscription(1);
1291 let (sub2, tx2) = channel_subscription(2);
1292 let (sub3, tx3) = channel_subscription(3);
1293 let subs: Vec<Box<dyn Subscription<TestMsg>>> =
1294 vec![Box::new(sub1), Box::new(sub2), Box::new(sub3)];
1295
1296 mgr.reconcile(subs);
1297 tx1.send(TestMsg::Value(10)).unwrap();
1298 tx2.send(TestMsg::Value(20)).unwrap();
1299 tx3.send(TestMsg::Value(30)).unwrap();
1300 thread::sleep(Duration::from_millis(30));
1301
1302 let mut msgs = mgr.drain_messages();
1303 msgs.sort_by_key(|m| match m {
1304 TestMsg::Value(v) => *v,
1305 _ => 0,
1306 });
1307
1308 assert_eq!(msgs.len(), 3);
1309 assert_eq!(msgs[0], TestMsg::Value(10));
1310 assert_eq!(msgs[1], TestMsg::Value(20));
1311 assert_eq!(msgs[2], TestMsg::Value(30));
1312 }
1313
1314 #[test]
1315 fn subscription_manager_partial_update() {
1316 let mut mgr = SubscriptionManager::<TestMsg>::new();
1317
1318 mgr.reconcile(vec![
1320 Box::new(Every::with_id(1, Duration::from_millis(10), || {
1321 TestMsg::Value(1)
1322 })),
1323 Box::new(Every::with_id(2, Duration::from_millis(10), || {
1324 TestMsg::Value(2)
1325 })),
1326 Box::new(Every::with_id(3, Duration::from_millis(10), || {
1327 TestMsg::Value(3)
1328 })),
1329 ]);
1330
1331 thread::sleep(Duration::from_millis(30));
1332 let _ = mgr.drain_messages();
1333
1334 mgr.reconcile(vec![
1336 Box::new(Every::with_id(1, Duration::from_millis(10), || {
1337 TestMsg::Value(1)
1338 })),
1339 Box::new(Every::with_id(3, Duration::from_millis(10), || {
1340 TestMsg::Value(3)
1341 })),
1342 ]);
1343
1344 let _ = mgr.drain_messages();
1347
1348 thread::sleep(Duration::from_millis(30));
1350 let msgs = mgr.drain_messages();
1351
1352 let values: Vec<i32> = msgs
1354 .iter()
1355 .filter_map(|m| match m {
1356 TestMsg::Value(v) => Some(*v),
1357 _ => None,
1358 })
1359 .collect();
1360
1361 assert!(
1362 values.contains(&1),
1363 "Should still receive from subscription 1"
1364 );
1365 assert!(
1366 values.contains(&3),
1367 "Should still receive from subscription 3"
1368 );
1369 assert!(
1370 !values.contains(&2),
1371 "Should not receive from stopped subscription 2"
1372 );
1373 }
1374
1375 #[test]
1376 fn subscription_manager_drop_stops_all() {
1377 let (_signal, _) = StopSignal::new();
1378 let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1379 let flag_clone = flag.clone();
1380
1381 struct FlagSubscription {
1382 id: SubId,
1383 flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
1384 }
1385
1386 impl Subscription<TestMsg> for FlagSubscription {
1387 fn id(&self) -> SubId {
1388 self.id
1389 }
1390
1391 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1392 while !stop.is_stopped() {
1393 thread::sleep(Duration::from_millis(5));
1394 }
1395 self.flag.store(true, std::sync::atomic::Ordering::SeqCst);
1396 }
1397 }
1398
1399 {
1400 let mut mgr = SubscriptionManager::<TestMsg>::new();
1401 mgr.reconcile(vec![Box::new(FlagSubscription {
1402 id: 1,
1403 flag: flag_clone,
1404 })]);
1405
1406 thread::sleep(Duration::from_millis(20));
1407 }
1409
1410 thread::sleep(Duration::from_millis(50));
1411 assert!(
1412 flag.load(std::sync::atomic::Ordering::SeqCst),
1413 "Subscription should have stopped on drop"
1414 );
1415 }
1416
1417 #[test]
1418 fn running_subscription_stop_joins_thread() {
1419 use std::sync::atomic::{AtomicBool, Ordering};
1420
1421 let completed = std::sync::Arc::new(AtomicBool::new(false));
1422 let completed_clone = completed.clone();
1423
1424 let (signal, trigger) = StopSignal::new();
1425 let (_tx, _rx) = mpsc::channel::<TestMsg>();
1426
1427 let thread = thread::spawn(move || {
1428 while !signal.is_stopped() {
1429 thread::sleep(Duration::from_millis(5));
1430 }
1431 completed_clone.store(true, Ordering::SeqCst);
1432 });
1433
1434 let running = RunningSubscription {
1435 id: 1,
1436 trigger,
1437 thread: Some(thread),
1438 panicked: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1439 };
1440
1441 running.stop();
1442 assert!(completed.load(Ordering::SeqCst));
1443 }
1444
1445 #[test]
1446 fn running_subscription_stop_times_out_for_uncooperative_thread() {
1447 use std::sync::atomic::{AtomicBool, Ordering};
1448
1449 let completed = std::sync::Arc::new(AtomicBool::new(false));
1450 let completed_clone = completed.clone();
1451
1452 let (_signal, trigger) = StopSignal::new();
1457 let thread = thread::spawn(move || {
1458 thread::sleep(Duration::from_secs(3));
1459 completed_clone.store(true, Ordering::SeqCst);
1460 });
1461
1462 let running = RunningSubscription {
1463 id: 7,
1464 trigger,
1465 thread: Some(thread),
1466 panicked: std::sync::Arc::new(AtomicBool::new(false)),
1467 };
1468
1469 let start = Instant::now();
1470 running.stop();
1471 let elapsed = start.elapsed();
1472 assert!(
1473 elapsed < Duration::from_millis(1500),
1474 "stop() should not block behind an uncooperative subscription thread; took {elapsed:?}"
1475 );
1476
1477 let deadline = Instant::now() + Duration::from_secs(10);
1479 while !completed.load(Ordering::SeqCst) && Instant::now() < deadline {
1480 thread::sleep(Duration::from_millis(10));
1481 }
1482 assert!(completed.load(Ordering::SeqCst));
1483 }
1484
1485 #[test]
1486 fn every_id_stable_across_instances() {
1487 let sub1 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1489 let sub2 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1490 let sub3 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(1));
1491
1492 assert_eq!(sub1.id(), sub2.id());
1493 assert_eq!(sub2.id(), sub3.id()); }
1495
1496 #[test]
1497 fn drain_messages_preserves_order() {
1498 let mut mgr = SubscriptionManager::<TestMsg>::new();
1499
1500 struct OrderedSubscription {
1502 values: Vec<i32>,
1503 }
1504
1505 impl Subscription<TestMsg> for OrderedSubscription {
1506 fn id(&self) -> SubId {
1507 999
1508 }
1509
1510 fn run(&self, sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1511 for v in &self.values {
1512 let _ = sender.send(TestMsg::Value(*v));
1513 thread::sleep(Duration::from_millis(1));
1514 }
1515 }
1516 }
1517
1518 mgr.reconcile(vec![Box::new(OrderedSubscription {
1519 values: vec![1, 2, 3, 4, 5],
1520 })]);
1521
1522 thread::sleep(Duration::from_millis(30));
1523 let msgs = mgr.drain_messages();
1524
1525 let values: Vec<i32> = msgs
1526 .iter()
1527 .filter_map(|m| match m {
1528 TestMsg::Value(v) => Some(*v),
1529 _ => None,
1530 })
1531 .collect();
1532
1533 assert_eq!(values, vec![1, 2, 3, 4, 5]);
1534 }
1535
1536 #[test]
1537 fn subscription_manager_new_is_empty() {
1538 let mgr = SubscriptionManager::<TestMsg>::new();
1539 let msgs = mgr.drain_messages();
1540 assert!(msgs.is_empty());
1541 }
1542
1543 #[test]
1555 fn contract_stop_signal_resilient_to_thread_panics() {
1556 let (signal, trigger) = StopSignal::new();
1557 let signal_clone = signal.clone();
1558
1559 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1561 assert!(!signal_clone.is_stopped());
1562 panic!("intentional panic while holding signal clone");
1563 }));
1564 assert!(result.is_err());
1565
1566 assert!(
1568 !signal.is_stopped(),
1569 "signal should still report not-stopped"
1570 );
1571 trigger.stop();
1572 assert!(
1573 signal.is_stopped(),
1574 "signal should report stopped after trigger"
1575 );
1576 assert!(
1577 signal.wait_timeout(Duration::from_millis(10)),
1578 "wait_timeout should return true when stopped"
1579 );
1580 }
1581
1582 #[test]
1585 fn contract_stop_signal_exposes_cancellation_token() {
1586 let (signal, trigger) = StopSignal::new();
1587 let token = signal.cancellation_token();
1588 assert!(!token.is_cancelled(), "token should start uncancelled");
1589 trigger.stop();
1590 assert!(token.is_cancelled(), "token should be cancelled after stop");
1591 }
1592
1593 #[test]
1597 fn contract_stop_all_bounded_time_with_uncooperative_subscriptions() {
1598 let mut mgr = SubscriptionManager::<TestMsg>::new();
1599
1600 struct UncooperativeSub {
1602 id: SubId,
1603 }
1604
1605 impl Subscription<TestMsg> for UncooperativeSub {
1606 fn id(&self) -> SubId {
1607 self.id
1608 }
1609
1610 fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1611 thread::sleep(Duration::from_secs(5));
1613 }
1614 }
1615
1616 mgr.reconcile(vec![
1617 Box::new(UncooperativeSub { id: 100 }),
1618 Box::new(UncooperativeSub { id: 200 }),
1619 ]);
1620
1621 thread::sleep(Duration::from_millis(20)); let start = Instant::now();
1624 mgr.stop_all();
1625 let elapsed = start.elapsed();
1626
1627 assert!(
1633 elapsed < Duration::from_millis(2500),
1634 "stop_all took {elapsed:?}: it blocked on an uncooperative subscription"
1635 );
1636 }
1637
1638 #[test]
1641 fn contract_reconcile_deduplicates_by_id_not_identity() {
1642 let mut mgr = SubscriptionManager::<TestMsg>::new();
1643 let counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1644
1645 struct CountingSub {
1646 id: SubId,
1647 counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1648 }
1649
1650 impl Subscription<TestMsg> for CountingSub {
1651 fn id(&self) -> SubId {
1652 self.id
1653 }
1654
1655 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1656 self.counter
1657 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1658 while !stop.is_stopped() {
1659 thread::sleep(Duration::from_millis(5));
1660 }
1661 }
1662 }
1663
1664 mgr.reconcile(vec![Box::new(CountingSub {
1666 id: 42,
1667 counter: counter.clone(),
1668 })]);
1669 thread::sleep(Duration::from_millis(20));
1670 assert_eq!(
1671 counter.load(std::sync::atomic::Ordering::SeqCst),
1672 1,
1673 "first reconcile should start exactly 1 thread"
1674 );
1675
1676 mgr.reconcile(vec![Box::new(CountingSub {
1678 id: 42,
1679 counter: counter.clone(),
1680 })]);
1681 thread::sleep(Duration::from_millis(20));
1682 assert_eq!(
1683 counter.load(std::sync::atomic::Ordering::SeqCst),
1684 1,
1685 "second reconcile with same ID must not start another thread"
1686 );
1687
1688 mgr.stop_all();
1689 }
1690
1691 #[test]
1695 fn contract_buffered_messages_available_after_subscription_stopped() {
1696 let mut mgr = SubscriptionManager::<TestMsg>::new();
1697
1698 struct BurstSub;
1699
1700 impl Subscription<TestMsg> for BurstSub {
1701 fn id(&self) -> SubId {
1702 77
1703 }
1704
1705 fn run(&self, sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1706 for i in 0..10 {
1708 let _ = sender.send(TestMsg::Value(i));
1709 }
1710 while !stop.is_stopped() {
1712 thread::sleep(Duration::from_millis(5));
1713 }
1714 }
1715 }
1716
1717 mgr.reconcile(vec![Box::new(BurstSub)]);
1718 thread::sleep(Duration::from_millis(30));
1719
1720 mgr.reconcile(vec![]);
1722
1723 let msgs = mgr.drain_messages();
1725 let values: Vec<i32> = msgs
1726 .iter()
1727 .filter_map(|m| match m {
1728 TestMsg::Value(v) => Some(*v),
1729 _ => None,
1730 })
1731 .collect();
1732
1733 assert!(
1734 values.len() >= 5,
1735 "Expected at least 5 buffered messages after stop, got {}",
1736 values.len()
1737 );
1738 }
1739
1740 #[test]
1743 fn contract_active_count_tracks_running_subscriptions() {
1744 let mut mgr = SubscriptionManager::<TestMsg>::new();
1745
1746 assert_eq!(mgr.active_count(), 0, "empty manager");
1747
1748 mgr.reconcile(vec![
1749 Box::new(Every::with_id(1, Duration::from_millis(50), || {
1750 TestMsg::Tick
1751 })),
1752 Box::new(Every::with_id(2, Duration::from_millis(50), || {
1753 TestMsg::Tick
1754 })),
1755 ]);
1756 assert_eq!(mgr.active_count(), 2, "after starting 2");
1757
1758 mgr.reconcile(vec![Box::new(Every::with_id(
1759 1,
1760 Duration::from_millis(50),
1761 || TestMsg::Tick,
1762 ))]);
1763 assert_eq!(mgr.active_count(), 1, "after removing 1");
1764
1765 mgr.stop_all();
1766 assert_eq!(mgr.active_count(), 0, "after stop_all");
1767 }
1768
1769 #[test]
1773 fn contract_every_id_derived_from_interval_only() {
1774 let sub_a = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1775 let sub_b = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(999));
1776 assert_eq!(
1777 sub_a.id(),
1778 sub_b.id(),
1779 "Every ID must depend only on interval, not message factory"
1780 );
1781
1782 let sub_c = Every::<TestMsg>::new(Duration::from_millis(200), || TestMsg::Tick);
1783 assert_ne!(
1784 sub_a.id(),
1785 sub_c.id(),
1786 "Different intervals must produce different IDs"
1787 );
1788 }
1789
1790 #[test]
1793 fn contract_every_id_formula_is_stable() {
1794 let interval = Duration::from_millis(100);
1795 let expected_id = interval.as_nanos() as u64 ^ 0x5449_434B;
1796 let sub = Every::<TestMsg>::new(interval, || TestMsg::Tick);
1797 assert_eq!(
1798 sub.id(),
1799 expected_id,
1800 "Every ID formula must be: interval.as_nanos() as u64 ^ 0x5449_434B"
1801 );
1802 }
1803
1804 #[test]
1807 fn contract_drop_triggers_stop_all() {
1808 use std::sync::atomic::{AtomicUsize, Ordering};
1809
1810 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
1811
1812 struct StopCountingSub {
1813 id: SubId,
1814 counter: std::sync::Arc<AtomicUsize>,
1815 }
1816
1817 impl Subscription<TestMsg> for StopCountingSub {
1818 fn id(&self) -> SubId {
1819 self.id
1820 }
1821
1822 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1823 while !stop.is_stopped() {
1824 thread::sleep(Duration::from_millis(5));
1825 }
1826 self.counter.fetch_add(1, Ordering::SeqCst);
1827 }
1828 }
1829
1830 {
1831 let mut mgr = SubscriptionManager::<TestMsg>::new();
1832 mgr.reconcile(vec![
1833 Box::new(StopCountingSub {
1834 id: 1,
1835 counter: stop_count.clone(),
1836 }),
1837 Box::new(StopCountingSub {
1838 id: 2,
1839 counter: stop_count.clone(),
1840 }),
1841 Box::new(StopCountingSub {
1842 id: 3,
1843 counter: stop_count.clone(),
1844 }),
1845 ]);
1846 thread::sleep(Duration::from_millis(20));
1847 }
1849
1850 thread::sleep(Duration::from_millis(400));
1852 assert_eq!(
1853 stop_count.load(std::sync::atomic::Ordering::SeqCst),
1854 3,
1855 "all 3 subscription threads must have observed stop signal on drop"
1856 );
1857 }
1858
1859 #[test]
1862 fn contract_stop_join_timeout_is_250ms() {
1863 assert_eq!(
1864 SUBSCRIPTION_STOP_JOIN_TIMEOUT,
1865 Duration::from_millis(250),
1866 "join timeout must be 250ms"
1867 );
1868 assert_eq!(
1869 SUBSCRIPTION_STOP_JOIN_POLL,
1870 Duration::from_millis(1),
1871 "join poll interval must be 1ms (bd-1f2aw)"
1872 );
1873 }
1874
1875 #[test]
1885 fn lifecycle_panic_in_subscription_is_caught() {
1886 use std::sync::atomic::Ordering;
1887
1888 let mut mgr = SubscriptionManager::<TestMsg>::new();
1889
1890 struct PanickingSub;
1891
1892 impl Subscription<TestMsg> for PanickingSub {
1893 fn id(&self) -> SubId {
1894 0xDEAD
1895 }
1896
1897 fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1898 panic!("intentional test panic in subscription");
1899 }
1900 }
1901
1902 mgr.reconcile(vec![Box::new(PanickingSub)]);
1903
1904 let failure = mgr
1908 .failure_receiver
1909 .recv_timeout(Duration::from_secs(5))
1910 .expect("subscription panic must be caught and reported");
1911 assert_eq!(failure.id, 0xDEAD);
1912 assert_eq!(failure.error, "intentional test panic in subscription");
1913
1914 assert_eq!(
1916 mgr.active_count(),
1917 1,
1918 "panicked sub still tracked as active"
1919 );
1920
1921 assert!(
1923 mgr.active[0].panicked.load(Ordering::Acquire),
1924 "panicked flag should be set after subscription panic"
1925 );
1926
1927 mgr.stop_all();
1929 assert_eq!(mgr.active_count(), 0);
1930 }
1931
1932 #[test]
1935 fn lifecycle_panic_does_not_affect_sibling_subscriptions() {
1936 let mut mgr = SubscriptionManager::<TestMsg>::new();
1937
1938 struct PanickingSub;
1939 impl Subscription<TestMsg> for PanickingSub {
1940 fn id(&self) -> SubId {
1941 0xBAD
1942 }
1943 fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1944 panic!("boom");
1945 }
1946 }
1947
1948 mgr.reconcile(vec![
1949 Box::new(PanickingSub),
1950 Box::new(Every::with_id(42, Duration::from_millis(10), || {
1951 TestMsg::Tick
1952 })),
1953 ]);
1954
1955 thread::sleep(Duration::from_millis(100));
1958
1959 let msgs = mgr.drain_messages();
1960 assert!(
1961 !msgs.is_empty(),
1962 "sibling subscription should still deliver messages after a panic in another sub"
1963 );
1964
1965 mgr.stop_all();
1966 }
1967
1968 #[test]
1971 fn lifecycle_stop_all_parallel_shutdown() {
1972 use std::sync::atomic::{AtomicUsize, Ordering};
1973
1974 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
1975 let sub_count = 4;
1976
1977 let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
1983 let stranded = std::sync::Arc::new(AtomicUsize::new(0));
1984
1985 struct SlowStopSub {
1986 id: SubId,
1987 expected: usize,
1988 winding_down: std::sync::Arc<AtomicUsize>,
1989 stranded: std::sync::Arc<AtomicUsize>,
1990 counter: std::sync::Arc<AtomicUsize>,
1991 }
1992
1993 impl Subscription<TestMsg> for SlowStopSub {
1994 fn id(&self) -> SubId {
1995 self.id
1996 }
1997
1998 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1999 while !stop.is_stopped() {
2000 thread::sleep(Duration::from_millis(5));
2001 }
2002 self.winding_down.fetch_add(1, Ordering::SeqCst);
2003 let guard = Instant::now();
2004 while self.winding_down.load(Ordering::SeqCst) < self.expected {
2005 if guard.elapsed() > Duration::from_secs(5) {
2006 self.stranded.fetch_add(1, Ordering::SeqCst);
2007 return;
2008 }
2009 thread::sleep(Duration::from_millis(1));
2010 }
2011 self.counter.fetch_add(1, Ordering::SeqCst);
2012 }
2013 }
2014
2015 let mut mgr = SubscriptionManager::<TestMsg>::new();
2016 let subs: Vec<Box<dyn Subscription<TestMsg>>> = (0..sub_count)
2017 .map(|i| -> Box<dyn Subscription<TestMsg>> {
2018 Box::new(SlowStopSub {
2019 id: 1000 + i,
2020 expected: sub_count as usize,
2021 winding_down: winding_down.clone(),
2022 stranded: stranded.clone(),
2023 counter: stop_count.clone(),
2024 })
2025 })
2026 .collect();
2027
2028 mgr.reconcile(subs);
2029 thread::sleep(Duration::from_millis(20));
2030
2031 mgr.stop_all();
2032
2033 let deadline = Instant::now() + Duration::from_secs(10);
2036 while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst)
2037 < sub_count as usize
2038 && Instant::now() < deadline
2039 {
2040 thread::sleep(Duration::from_millis(1));
2041 }
2042 assert_eq!(
2043 stranded.load(Ordering::SeqCst),
2044 0,
2045 "stop phases did not overlap: stop_all signalled subscriptions sequentially"
2046 );
2047 assert_eq!(
2048 stop_count.load(Ordering::SeqCst),
2049 sub_count as usize,
2050 "all subscriptions should have completed their cleanup"
2051 );
2052 }
2053
2054 #[test]
2057 fn lifecycle_reconcile_removal_uses_parallel_stop() {
2058 use std::sync::atomic::{AtomicUsize, Ordering};
2059
2060 let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
2061
2062 let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
2066 let stranded = std::sync::Arc::new(AtomicUsize::new(0));
2067
2068 struct SlowStopSub {
2069 id: SubId,
2070 winding_down: std::sync::Arc<AtomicUsize>,
2071 stranded: std::sync::Arc<AtomicUsize>,
2072 counter: std::sync::Arc<AtomicUsize>,
2073 }
2074
2075 impl Subscription<TestMsg> for SlowStopSub {
2076 fn id(&self) -> SubId {
2077 self.id
2078 }
2079
2080 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2081 while !stop.is_stopped() {
2082 thread::sleep(Duration::from_millis(5));
2083 }
2084 self.winding_down.fetch_add(1, Ordering::SeqCst);
2085 let guard = Instant::now();
2086 while self.winding_down.load(Ordering::SeqCst) < 3 {
2087 if guard.elapsed() > Duration::from_secs(5) {
2088 self.stranded.fetch_add(1, Ordering::SeqCst);
2089 return;
2090 }
2091 thread::sleep(Duration::from_millis(1));
2092 }
2093 self.counter.fetch_add(1, Ordering::SeqCst);
2094 }
2095 }
2096
2097 let mut mgr = SubscriptionManager::<TestMsg>::new();
2098 mgr.reconcile(
2099 [2000, 2001, 2002]
2100 .into_iter()
2101 .map(|id| -> Box<dyn Subscription<TestMsg>> {
2102 Box::new(SlowStopSub {
2103 id,
2104 winding_down: winding_down.clone(),
2105 stranded: stranded.clone(),
2106 counter: stop_count.clone(),
2107 })
2108 })
2109 .collect(),
2110 );
2111 thread::sleep(Duration::from_millis(20));
2112
2113 mgr.reconcile(vec![]);
2115
2116 let deadline = Instant::now() + Duration::from_secs(10);
2117 while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst) < 3
2118 && Instant::now() < deadline
2119 {
2120 thread::sleep(Duration::from_millis(1));
2121 }
2122 assert_eq!(
2123 stranded.load(Ordering::SeqCst),
2124 0,
2125 "reconcile removal stopped subscriptions sequentially"
2126 );
2127 assert_eq!(stop_count.load(Ordering::SeqCst), 3);
2128 }
2129
2130 #[test]
2132 fn lifecycle_has_panicked_tracks_state() {
2133 let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2134 let panicked_flag = panicked.clone();
2135
2136 let (signal, trigger) = StopSignal::new();
2137 let thread = thread::spawn(move || {
2138 signal.wait_timeout(Duration::from_secs(10));
2139 });
2140
2141 let running = RunningSubscription {
2142 id: 999,
2143 trigger,
2144 thread: Some(thread),
2145 panicked,
2146 };
2147
2148 assert!(!running.has_panicked(), "should not be panicked initially");
2149
2150 panicked_flag.store(true, std::sync::atomic::Ordering::Release);
2152 assert!(running.has_panicked(), "should reflect panicked state");
2153
2154 running.stop();
2155 }
2156
2157 #[test]
2160 fn lifecycle_signal_then_join_works() {
2161 use std::sync::atomic::{AtomicBool, Ordering};
2162
2163 let completed = std::sync::Arc::new(AtomicBool::new(false));
2164 let completed_clone = completed.clone();
2165
2166 let (signal, trigger) = StopSignal::new();
2167 let thread = thread::spawn(move || {
2168 while !signal.is_stopped() {
2169 thread::sleep(Duration::from_millis(5));
2170 }
2171 completed_clone.store(true, Ordering::SeqCst);
2172 });
2173
2174 let running = RunningSubscription {
2175 id: 888,
2176 trigger,
2177 thread: Some(thread),
2178 panicked: std::sync::Arc::new(AtomicBool::new(false)),
2179 };
2180
2181 running.signal_stop();
2182 let leftover = running.join_bounded();
2183 assert!(
2184 leftover.is_none(),
2185 "cooperative thread should join within timeout"
2186 );
2187 assert!(
2188 completed.load(Ordering::SeqCst),
2189 "thread should have completed"
2190 );
2191 }
2192
2193 #[test]
2195 fn lifecycle_join_bounded_returns_handle_for_uncooperative() {
2196 use std::sync::atomic::AtomicBool;
2197
2198 let (_signal, trigger) = StopSignal::new();
2202 let thread = thread::spawn(move || {
2203 thread::sleep(Duration::from_secs(3));
2204 });
2205
2206 let running = RunningSubscription {
2207 id: 777,
2208 trigger,
2209 thread: Some(thread),
2210 panicked: std::sync::Arc::new(AtomicBool::new(false)),
2211 };
2212
2213 running.signal_stop();
2214 let start = Instant::now();
2215 let leftover = running.join_bounded();
2216 let elapsed = start.elapsed();
2217
2218 assert!(
2219 leftover.is_some(),
2220 "uncooperative thread should not join within timeout"
2221 );
2222 assert!(
2223 elapsed < Duration::from_millis(1500),
2224 "join_bounded should respect the 250ms timeout, took {elapsed:?}"
2225 );
2226 }
2227
2228 #[test]
2231 fn lifecycle_restart_after_stop() {
2232 let mut mgr = SubscriptionManager::<TestMsg>::new();
2233
2234 mgr.reconcile(vec![Box::new(Every::with_id(
2236 300,
2237 Duration::from_millis(10),
2238 || TestMsg::Tick,
2239 ))]);
2240 thread::sleep(Duration::from_millis(30));
2241 let msgs = mgr.drain_messages();
2242 assert!(!msgs.is_empty(), "should receive ticks");
2243
2244 mgr.reconcile(vec![]);
2246 thread::sleep(Duration::from_millis(20));
2247 let _ = mgr.drain_messages();
2248 thread::sleep(Duration::from_millis(30));
2249 let msgs = mgr.drain_messages();
2250 assert!(msgs.is_empty(), "should stop receiving after removal");
2251
2252 mgr.reconcile(vec![Box::new(Every::with_id(
2254 300,
2255 Duration::from_millis(10),
2256 || TestMsg::Value(99),
2257 ))]);
2258 thread::sleep(Duration::from_millis(30));
2259 let msgs = mgr.drain_messages();
2260 assert!(
2261 !msgs.is_empty(),
2262 "should receive messages again after restart"
2263 );
2264 assert!(
2265 msgs.iter().any(|m| matches!(m, TestMsg::Value(99))),
2266 "restarted sub should use the new message factory"
2267 );
2268
2269 mgr.stop_all();
2270 }
2271
2272 #[test]
2280 fn lifecycle_non_interference_with_manager_state() {
2281 use std::sync::atomic::{AtomicUsize, Ordering};
2282
2283 let msg_count = std::sync::Arc::new(AtomicUsize::new(0));
2284
2285 struct CountingSub {
2286 id: SubId,
2287 counter: std::sync::Arc<AtomicUsize>,
2288 }
2289
2290 impl Subscription<TestMsg> for CountingSub {
2291 fn id(&self) -> SubId {
2292 self.id
2293 }
2294
2295 fn run(&self, sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2296 while !stop.is_stopped() {
2297 if sender.send(TestMsg::Tick).is_err() {
2298 break;
2299 }
2300 self.counter.fetch_add(1, Ordering::SeqCst);
2301 thread::sleep(Duration::from_millis(5));
2302 }
2303 }
2304 }
2305
2306 let mut mgr = SubscriptionManager::<TestMsg>::new();
2307
2308 mgr.reconcile(vec![
2310 Box::new(CountingSub {
2311 id: 400,
2312 counter: msg_count.clone(),
2313 }),
2314 Box::new(CountingSub {
2315 id: 401,
2316 counter: msg_count.clone(),
2317 }),
2318 ]);
2319
2320 thread::sleep(Duration::from_millis(50));
2321
2322 assert_eq!(mgr.active_count(), 2);
2324 let drained = mgr.drain_messages();
2325 let sent_count = msg_count.load(Ordering::SeqCst);
2326 assert!(sent_count > 0, "subscriptions should have sent messages");
2327 assert!(
2328 drained.len() <= sent_count,
2329 "drained {} but only {} sent",
2330 drained.len(),
2331 sent_count
2332 );
2333
2334 mgr.stop_all();
2336 assert_eq!(mgr.active_count(), 0);
2337
2338 let remaining = mgr.drain_messages();
2340 let total_drained = drained.len() + remaining.len();
2341 let final_sent = msg_count.load(Ordering::SeqCst);
2342 assert!(
2343 total_drained <= final_sent,
2344 "total drained ({total_drained}) must not exceed total sent ({final_sent})"
2345 );
2346 }
2347
2348 #[test]
2352 fn lifecycle_shutdown_signal_ordering() {
2353 use std::sync::atomic::{AtomicU64, Ordering};
2354
2355 let signal_times =
2356 std::sync::Arc::new([AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]);
2357 let epoch = Instant::now();
2358
2359 struct TimingStopSub {
2360 id: SubId,
2361 index: usize,
2362 signal_times: std::sync::Arc<[AtomicU64; 3]>,
2363 epoch: Instant,
2364 }
2365
2366 impl Subscription<TestMsg> for TimingStopSub {
2367 fn id(&self) -> SubId {
2368 self.id
2369 }
2370
2371 fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2372 while !stop.is_stopped() {
2373 thread::sleep(Duration::from_millis(1));
2374 }
2375 let elapsed_us = self.epoch.elapsed().as_micros() as u64;
2376 self.signal_times[self.index].store(elapsed_us, Ordering::SeqCst);
2377 }
2378 }
2379
2380 let mut mgr = SubscriptionManager::<TestMsg>::new();
2381 mgr.reconcile(vec![
2382 Box::new(TimingStopSub {
2383 id: 500,
2384 index: 0,
2385 signal_times: signal_times.clone(),
2386 epoch,
2387 }),
2388 Box::new(TimingStopSub {
2389 id: 501,
2390 index: 1,
2391 signal_times: signal_times.clone(),
2392 epoch,
2393 }),
2394 Box::new(TimingStopSub {
2395 id: 502,
2396 index: 2,
2397 signal_times: signal_times.clone(),
2398 epoch,
2399 }),
2400 ]);
2401 thread::sleep(Duration::from_millis(20));
2402
2403 mgr.stop_all();
2404
2405 let t0 = signal_times[0].load(Ordering::SeqCst);
2409 let t1 = signal_times[1].load(Ordering::SeqCst);
2410 let t2 = signal_times[2].load(Ordering::SeqCst);
2411
2412 assert!(
2413 t0 > 0 && t1 > 0 && t2 > 0,
2414 "all subs should have recorded stop time"
2415 );
2416
2417 let max_t = t0.max(t1).max(t2);
2418 let min_t = t0.min(t1).min(t2);
2419 let spread_us = max_t - min_t;
2420
2421 assert!(
2422 spread_us < 10_000, "stop signal spread should be < 10ms for parallel signaling, got {spread_us}us \
2424 (t0={t0}, t1={t1}, t2={t2})"
2425 );
2426 }
2427}