Debian Codegraph @

src/sources/ping.rs

raw symbols SCIP
1 //! Ping to the event loop
2 //!
3 //! This is an event source that just produces `()` events whevener the associated
4 //! [`Ping::ping`](Ping#method.ping) method is called. If the event source is pinged multiple times
5 //! between a single dispatching, it'll only generate one event.
6 //!
7 //! This event source is a simple way of waking up the event loop from an other part of your program
8 //! (and is what backs the [`LoopSignal`](crate::LoopSignal)). It can also be used as a building
9 //! block to construct event sources whose source of event is not file descriptor, but rather an
10 //! userspace source (like an other thread).
11
12 use nix::unistd::close;
13 use std::os::unix::io::RawFd;
14
15 // The ping source has platform-dependent implementations provided by modules
16 // under this one. These modules should expose:
17 // - a make_ping() function
18 // - a Ping type
19 // - a PingSource type
20 //
21 // See eg. the pipe implementation for these items' specific requirements.
22
23 #[cfg(target_os = "linux")]
24 mod eventfd;
25 #[cfg(target_os = "linux")]
26 use eventfd as platform;
27
28 #[cfg(not(target_os = "linux"))]
29 mod pipe;
30 #[cfg(not(target_os = "linux"))]
31 use pipe as platform;
32
33 /// Create a new ping event source
34 ///
35 /// you are given a [`Ping`] instance, which can be cloned and used to ping the
36 /// event loop, and a [`PingSource`], which you can insert in your event loop to
37 /// receive the pings.
38 pub fn make_ping() -> std::io::Result<(Ping, PingSource)> {
39 platform::make_ping()
40 }
41
42 /// The ping event source
43 ///
44 /// You can insert it in your event loop to receive pings.
45 ///
46 /// If you use it directly, it will automatically remove itself from the event loop
47 /// once all [`Ping`] instances are dropped.
48 pub type Ping = platform::Ping;
49
50 /// The Ping handle
51 ///
52 /// This handle can be cloned and sent accross threads. It can be used to
53 /// send pings to the `PingSource`.
54 pub type PingSource = platform::PingSource;
55
56 /// An error arising from processing events for a ping.
57 #[derive(thiserror::Error, Debug)]
58 #[error(transparent)]
59 pub struct PingError(Box<dyn std::error::Error + Sync + Send>);
60
61 #[derive(Debug)]
62 struct CloseOnDrop(RawFd);
63
64 impl Drop for CloseOnDrop {
65 fn drop(&mut self) {
66 if let Err(e) = close(self.0) {
67 log::warn!("[calloop] Failed to close ping fd: {:?}", e);
68 }
69 }
70 }
71
72 #[cfg(test)]
73 mod tests {
74 use crate::transient::TransientSource;
75 use std::time::Duration;
76
77 use super::*;
78
79 #[test]
80 fn ping() {
81 let mut event_loop = crate::EventLoop::<bool>::try_new().unwrap();
82
83 let (ping, source) = make_ping().unwrap();
84
85 event_loop
86 .handle()
87 .insert_source(source, |(), &mut (), dispatched| *dispatched = true)
88 .unwrap();
89
90 ping.ping();
91
92 let mut dispatched = false;
93 event_loop
94 .dispatch(std::time::Duration::ZERO, &mut dispatched)
95 .unwrap();
96 assert!(dispatched);
97
98 // Ping has been drained an no longer generates events
99 let mut dispatched = false;
100 event_loop
101 .dispatch(std::time::Duration::ZERO, &mut dispatched)
102 .unwrap();
103 assert!(!dispatched);
104 }
105
106 #[test]
107 fn ping_closed() {
108 let mut event_loop = crate::EventLoop::<bool>::try_new().unwrap();
109
110 let (_, source) = make_ping().unwrap();
111 event_loop
112 .handle()
113 .insert_source(source, |(), &mut (), dispatched| *dispatched = true)
114 .unwrap();
115
116 let mut dispatched = false;
117
118 // If the sender is closed from the start, the ping should first trigger
119 // once, disabling itself but not invoking the callback
120 event_loop
121 .dispatch(std::time::Duration::ZERO, &mut dispatched)
122 .unwrap();
123 assert!(!dispatched);
124
125 // Then it should not trigger any more, so this dispatch should wait the whole 100ms
126 let now = std::time::Instant::now();
127 event_loop
128 .dispatch(std::time::Duration::from_millis(100), &mut dispatched)
129 .unwrap();
130 assert!(now.elapsed() >= std::time::Duration::from_millis(100));
131 }
132
133 #[test]
134 fn ping_removed() {
135 // This keeps track of whether the event fired.
136 let mut dispatched = false;
137
138 let mut event_loop = crate::EventLoop::<bool>::try_new().unwrap();
139
140 let (sender, source) = make_ping().unwrap();
141 let wrapper = TransientSource::from(source);
142
143 // Check that the source starts off in the wrapper.
144 assert!(!matches!(wrapper, TransientSource::None));
145
146 // Put the source in the loop.
147
148 let dispatcher =
149 crate::Dispatcher::new(wrapper, |(), &mut (), dispatched| *dispatched = true);
150
151 let token = event_loop
152 .handle()
153 .register_dispatcher(dispatcher.clone())
154 .unwrap();
155
156 // Drop the sender and check that it's actually removed.
157 drop(sender);
158
159 // There should be no event, but the loop still needs to wake up to
160 // process the close event (just like in the ping_closed() test).
161 event_loop
162 .dispatch(Duration::ZERO, &mut dispatched)
163 .unwrap();
164 assert!(!dispatched);
165
166 // Pull the source wrapper out.
167
168 event_loop.handle().remove(token);
169 let wrapper = dispatcher.into_source_inner();
170
171 // Check that the inner source is now gone.
172 assert!(matches!(wrapper, TransientSource::None));
173 }
174
175 #[test]
176 fn ping_fired_and_removed() {
177 // This is like ping_removed() with the single difference that we fire a
178 // ping and drop it between two successive dispatches of the loop.
179
180 // This keeps track of whether the event fired.
181 let mut dispatched = false;
182
183 let mut event_loop = crate::EventLoop::<bool>::try_new().unwrap();
184
185 let (sender, source) = make_ping().unwrap();
186 let wrapper = TransientSource::from(source);
187
188 // Check that the source starts off in the wrapper.
189 assert!(!matches!(wrapper, TransientSource::None));
190
191 // Put the source in the loop.
192
193 let dispatcher =
194 crate::Dispatcher::new(wrapper, |(), &mut (), dispatched| *dispatched = true);
195
196 let token = event_loop
197 .handle()
198 .register_dispatcher(dispatcher.clone())
199 .unwrap();
200
201 // Send a ping AND drop the sender and check that it's actually removed.
202 sender.ping();
203 drop(sender);
204
205 // There should be an event, but the source should be removed from the
206 // loop immediately after.
207 event_loop
208 .dispatch(Duration::ZERO, &mut dispatched)
209 .unwrap();
210 assert!(dispatched);
211
212 // Pull the source wrapper out.
213
214 event_loop.handle().remove(token);
215 let wrapper = dispatcher.into_source_inner();
216
217 // Check that the inner source is now gone.
218 assert!(matches!(wrapper, TransientSource::None));
219 }
220
221 #[test]
222 fn ping_multiple_senders() {
223 // This is like ping_removed() but for testing the behaviour of multiple
224 // senders.
225
226 // This keeps track of whether the event fired.
227 let mut dispatched = false;
228
229 let mut event_loop = crate::EventLoop::<bool>::try_new().unwrap();
230
231 let (sender0, source) = make_ping().unwrap();
232 let wrapper = TransientSource::from(source);
233 let sender1 = sender0.clone();
234 let sender2 = sender1.clone();
235
236 // Check that the source starts off in the wrapper.
237 assert!(!matches!(wrapper, TransientSource::None));
238
239 // Put the source in the loop.
240
241 let dispatcher =
242 crate::Dispatcher::new(wrapper, |(), &mut (), dispatched| *dispatched = true);
243
244 let token = event_loop
245 .handle()
246 .register_dispatcher(dispatcher.clone())
247 .unwrap();
248
249 // Send a ping AND drop the sender and check that it's actually removed.
250 sender0.ping();
251 drop(sender0);
252
253 // There should be an event, and the source should remain in the loop.
254 event_loop
255 .dispatch(Duration::ZERO, &mut dispatched)
256 .unwrap();
257 assert!(dispatched);
258
259 // Now test that the clones still work. Drop after the dispatch loop
260 // instead of before, this time.
261 dispatched = false;
262
263 sender1.ping();
264
265 event_loop
266 .dispatch(Duration::ZERO, &mut dispatched)
267 .unwrap();
268 assert!(dispatched);
269
270 // Finally, drop all of them without sending anything.
271
272 dispatched = false;
273
274 drop(sender1);
275 drop(sender2);
276
277 event_loop
278 .dispatch(Duration::ZERO, &mut dispatched)
279 .unwrap();
280 assert!(!dispatched);
281
282 // Pull the source wrapper out.
283
284 event_loop.handle().remove(token);
285 let wrapper = dispatcher.into_source_inner();
286
287 // Check that the inner source is now gone.
288 assert!(matches!(wrapper, TransientSource::None));
289 }
290 }