task.rs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely
  2. use std::{sync::atomic::AtomicUsize, time::Duration};
  3. use dioxus::prelude::*;
  4. async fn run_vdom(app: fn() -> Element) {
  5. let mut dom = VirtualDom::new(app);
  6. dom.rebuild(&mut dioxus_core::NoOpMutations);
  7. tokio::select! {
  8. _ = dom.wait_for_work() => {}
  9. _ = tokio::time::sleep(Duration::from_millis(500)) => {}
  10. };
  11. }
  12. #[tokio::test]
  13. async fn running_async() {
  14. static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
  15. fn app() -> Element {
  16. use_hook(|| {
  17. spawn(async {
  18. for x in 0..10 {
  19. tokio::time::sleep(Duration::from_micros(50)).await;
  20. POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed);
  21. }
  22. });
  23. spawn(async {
  24. for x in 0..10 {
  25. tokio::time::sleep(Duration::from_micros(25)).await;
  26. POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed);
  27. }
  28. });
  29. });
  30. rsx!({})
  31. }
  32. run_vdom(app).await;
  33. // By the time the tasks are finished, we should've accumulated ticks from two tasks
  34. // Be warned that by setting the delay to too short, tokio might not schedule in the tasks
  35. assert_eq!(
  36. POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed),
  37. 135
  38. );
  39. }
  40. #[tokio::test]
  41. async fn spawn_forever_persists() {
  42. use std::sync::atomic::Ordering;
  43. static POLL_COUNT: AtomicUsize = AtomicUsize::new(0);
  44. fn app() -> Element {
  45. if generation() > 0 {
  46. rsx!(div {})
  47. } else {
  48. needs_update();
  49. rsx!(Child {})
  50. }
  51. }
  52. #[component]
  53. fn Child() -> Element {
  54. spawn_forever(async move {
  55. for _ in 0..10 {
  56. POLL_COUNT.fetch_add(1, Ordering::Relaxed);
  57. tokio::time::sleep(Duration::from_millis(50)).await;
  58. }
  59. });
  60. rsx!(div {})
  61. }
  62. let mut dom = VirtualDom::new(app);
  63. dom.rebuild(&mut dioxus_core::NoOpMutations);
  64. dom.render_immediate(&mut dioxus_core::NoOpMutations);
  65. tokio::select! {
  66. _ = dom.wait_for_work() => {}
  67. // We intentionally wait a bit longer than 50ms*10 to make sure the test has time to finish
  68. // Without the extra time, the test can fail on windows
  69. _ = tokio::time::sleep(Duration::from_millis(1000)) => {}
  70. };
  71. // By the time the tasks are finished, we should've accumulated ticks from two tasks
  72. // Be warned that by setting the delay to too short, tokio might not schedule in the tasks
  73. assert_eq!(POLL_COUNT.load(Ordering::Relaxed), 10);
  74. }
  75. /// Prove that yield_now doesn't cause a deadlock
  76. #[tokio::test]
  77. async fn yield_now_works() {
  78. thread_local! {
  79. static SEQUENCE: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  80. }
  81. fn app() -> Element {
  82. // these two tasks should yield to eachother
  83. use_hook(|| {
  84. spawn(async move {
  85. for _ in 0..10 {
  86. tokio::task::yield_now().await;
  87. SEQUENCE.with(|s| s.borrow_mut().push(1));
  88. }
  89. })
  90. });
  91. use_hook(|| {
  92. spawn(async move {
  93. for _ in 0..10 {
  94. tokio::task::yield_now().await;
  95. SEQUENCE.with(|s| s.borrow_mut().push(2));
  96. }
  97. })
  98. });
  99. rsx!({})
  100. }
  101. run_vdom(app).await;
  102. SEQUENCE.with(|s| assert_eq!(s.borrow().len(), 20));
  103. }
  104. /// Ensure that calling wait_for_flush waits for dioxus to finish its synchronous work
  105. #[tokio::test]
  106. async fn flushing() {
  107. thread_local! {
  108. static SEQUENCE: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
  109. static BROADCAST: (tokio::sync::broadcast::Sender<()>, tokio::sync::broadcast::Receiver<()>) = tokio::sync::broadcast::channel(1);
  110. }
  111. fn app() -> Element {
  112. if generation() > 0 {
  113. println!("App");
  114. SEQUENCE.with(|s| s.borrow_mut().push(0));
  115. }
  116. // The next two tasks mimic effects. They should only be run after the app has been rendered
  117. use_hook(|| {
  118. spawn(async move {
  119. let mut channel = BROADCAST.with(|b| b.1.resubscribe());
  120. for _ in 0..10 {
  121. wait_for_next_render().await;
  122. println!("Task 1 recved");
  123. channel.recv().await.unwrap();
  124. println!("Task 1");
  125. SEQUENCE.with(|s| s.borrow_mut().push(1));
  126. }
  127. })
  128. });
  129. use_hook(|| {
  130. spawn(async move {
  131. let mut channel = BROADCAST.with(|b| b.1.resubscribe());
  132. for _ in 0..10 {
  133. wait_for_next_render().await;
  134. println!("Task 2 recved");
  135. channel.recv().await.unwrap();
  136. println!("Task 2");
  137. SEQUENCE.with(|s| s.borrow_mut().push(2));
  138. }
  139. })
  140. });
  141. rsx! {}
  142. }
  143. let mut dom = VirtualDom::new(app);
  144. dom.rebuild(&mut dioxus_core::NoOpMutations);
  145. let fut = async {
  146. // Trigger the flush by waiting for work
  147. for i in 0..10 {
  148. BROADCAST.with(|b| b.0.send(()).unwrap());
  149. dom.mark_dirty(ScopeId(0));
  150. dom.wait_for_work().await;
  151. dom.render_immediate(&mut dioxus_core::NoOpMutations);
  152. println!("Flushed {}", i);
  153. }
  154. BROADCAST.with(|b| b.0.send(()).unwrap());
  155. dom.wait_for_work().await;
  156. };
  157. tokio::select! {
  158. _ = fut => {}
  159. _ = tokio::time::sleep(Duration::from_millis(500)) => {
  160. println!("Aborting due to timeout");
  161. }
  162. };
  163. SEQUENCE.with(|s| {
  164. let s = s.borrow();
  165. println!("{:?}", s);
  166. assert_eq!(s.len(), 30);
  167. // We need to check if every three elements look like [0, 1, 2] or [0, 2, 1]
  168. let mut has_seen_1 = false;
  169. for (i, &x) in s.iter().enumerate() {
  170. let stage = i % 3;
  171. if stage == 0 {
  172. assert_eq!(x, 0);
  173. } else if stage == 1 {
  174. assert!(x == 1 || x == 2);
  175. has_seen_1 = x == 1;
  176. } else if stage == 2 {
  177. if has_seen_1 {
  178. assert_eq!(x, 2);
  179. } else {
  180. assert_eq!(x, 1);
  181. }
  182. }
  183. }
  184. });
  185. }