Debian Codegraph @

src/sources/transient.rs

raw symbols SCIP
1 //! Wrapper for a transient Calloop event source.
2 //!
3 //! If you have high level event source that you expect to remain in the event
4 //! loop indefinitely, and another event source nested inside that one that you
5 //! expect to require removal or disabling from time to time, this module can
6 //! handle it for you.
7
8 /// A [`TransientSource`] wraps a Calloop event source and manages its
9 /// registration. A user of this type only needs to perform the usual Calloop
10 /// calls (`process_events()` and `*register()`) and the return value of
11 /// [`process_events()`](crate::EventSource::process_events).
12 ///
13 /// Rather than needing to check for the full set of
14 /// [`PostAction`](crate::PostAction) values returned from `process_events()`,
15 /// you can just check for `Continue` or `Reregister` and pass that back out
16 /// through your own `process_events()` implementation. In your registration
17 /// functions, you then only need to call the same function on this type ie.
18 /// `register()` inside `register()` etc.
19 ///
20 /// For example, say you have a source that contains a channel along with some
21 /// other logic. If the channel's sending end has been dropped, it needs to be
22 /// removed from the loop. So to manage this, you use this in your struct:
23 ///
24 /// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
25 /// struct CompositeSource {
26 /// // Event source for channel.
27 /// mpsc_receiver: TransientSource<calloop::channel::Channel<T>>,
28 ///
29 /// // Any other fields go here...
30 /// }
31 /// ```
32 ///
33 /// To create the transient source, you can simply use the `Into`
34 /// implementation:
35 ///
36 /// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
37 /// let (sender, source) = channel();
38 /// let mpsc_receiver: TransientSource<Channel> = source.into();
39 /// ```
40 ///
41 /// `TransientSource` implements [`EventSource`](crate::EventSource) and passes
42 /// through `process_events()` calls, so in the parent's `process_events()`
43 /// implementation you can just do this:
44 ///
45 /// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
46 /// fn process_events<F>(
47 /// &mut self,
48 /// readiness: calloop::Readiness,
49 /// token: calloop::Token,
50 /// callback: F,
51 /// ) -> Result<calloop::PostAction, Self::Error>
52 /// where
53 /// F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
54 /// {
55 /// let channel_return = self.mpsc_receiver.process_events(readiness, token, callback)?;
56 ///
57 /// // Perform other logic here...
58 ///
59 /// Ok(channel_return)
60 /// }
61 /// ```
62 ///
63 /// Note that:
64 ///
65 /// - You can call `process_events()` on the `TransientSource<Channel>` even
66 /// if the channel has been unregistered and dropped. All that will happen
67 /// is that you won't get any events from it.
68 ///
69 /// - The [`PostAction`](crate::PostAction) returned from `process_events()`
70 /// will only ever be `PostAction::Continue` or `PostAction::Reregister`.
71 /// You will still need to combine this with the result of any other sources
72 /// (transient or not).
73 ///
74 /// Once you return `channel_return` from your `process_events()` method (and
75 /// assuming it propagates all the way up to the event loop itself through any
76 /// other event sources), the event loop might call `reregister()` on your
77 /// source. All your source has to do is:
78 ///
79 /// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
80 /// fn reregister(
81 /// &mut self,
82 /// poll: &mut calloop::Poll,
83 /// token_factory: &mut calloop::TokenFactory,
84 /// ) -> crate::Result<()> {
85 /// self.mpsc_receiver.reregister(poll, token_factory)?;
86 ///
87 /// // Other registration actions...
88 ///
89 /// Ok(())
90 /// }
91 /// ```
92 ///
93 /// The `TransientSource` will take care of updating the registration of the
94 /// inner source, even if it actually needs to be unregistered or initially
95 /// registered.
96 #[derive(Debug)]
97 pub enum TransientSource<T> {
98 /// The source should be kept in the loop.
99 Keep(T),
100 /// The source needs to be registered with the loop.
101 Register(T),
102 /// The source needs to be disabled but kept.
103 Disable(T),
104 /// The source needs to be removed from the loop.
105 Remove(T),
106 /// The source has been removed from the loop and dropped (this might also
107 /// be observed if there is a panic while changing states).
108 None,
109 }
110
111 impl<T> TransientSource<T> {
112 /// Apply a function to the enclosed source, if it exists. It will be
113 /// appplied even if the source is ready to be removed or is disabled.
114 pub fn map<F, U>(&mut self, f: F) -> Option<U>
115 where
116 F: FnOnce(&mut T) -> U,
117 {
118 match self {
119 TransientSource::Keep(source)
120 | TransientSource::Register(source)
121 | TransientSource::Disable(source)
122 | TransientSource::Remove(source) => Some(f(source)),
123 TransientSource::None => None,
124 }
125 }
126
127 /// If a caller needs to flag the contained source for removal or
128 /// registration, we need to replace the enum variant safely. This requires
129 /// having a `None` value in there temporarily while we do the swap.
130 ///
131 /// If the variant is `None` the value will not change and `replacer` will
132 /// not be called.
133 ///
134 /// The `replacer` function here is expected to be one of the enum variant
135 /// constructors eg. `replace(TransientSource::Remove)`.
136 fn replace<F>(&mut self, replacer: F)
137 where
138 F: FnOnce(T) -> Self,
139 {
140 *self = match std::mem::replace(self, TransientSource::None) {
141 TransientSource::Keep(source)
142 | TransientSource::Register(source)
143 | TransientSource::Remove(source)
144 | TransientSource::Disable(source) => replacer(source),
145 TransientSource::None => return,
146 };
147 }
148 }
149
150 impl<T: crate::EventSource> From<T> for TransientSource<T> {
151 fn from(source: T) -> Self {
152 Self::Register(source)
153 }
154 }
155
156 impl<T: crate::EventSource> crate::EventSource for TransientSource<T> {
157 type Event = T::Event;
158 type Metadata = T::Metadata;
159 type Ret = T::Ret;
160 type Error = T::Error;
161
162 fn process_events<F>(
163 &mut self,
164 readiness: crate::Readiness,
165 token: crate::Token,
166 callback: F,
167 ) -> Result<crate::PostAction, Self::Error>
168 where
169 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
170 {
171 let reregister = if let TransientSource::Keep(ref mut source) = self {
172 let child_post_action = source.process_events(readiness, token, callback)?;
173
174 match child_post_action {
175 // Nothing needs to change.
176 crate::PostAction::Continue => false,
177
178 // Our child source needs re-registration, therefore this
179 // wrapper needs re-registration.
180 crate::PostAction::Reregister => true,
181
182 // If our nested source needs to be removed or disabled, we need
183 // to swap it out for the "Remove" or "Disable" variant.
184 crate::PostAction::Disable => {
185 self.replace(TransientSource::Disable);
186 true
187 }
188
189 crate::PostAction::Remove => {
190 self.replace(TransientSource::Remove);
191 true
192 }
193 }
194 } else {
195 false
196 };
197
198 let post_action = if reregister {
199 crate::PostAction::Reregister
200 } else {
201 crate::PostAction::Continue
202 };
203
204 Ok(post_action)
205 }
206
207 fn register(
208 &mut self,
209 poll: &mut crate::Poll,
210 token_factory: &mut crate::TokenFactory,
211 ) -> crate::Result<()> {
212 match self {
213 TransientSource::Keep(source) => {
214 source.register(poll, token_factory)?;
215 }
216 TransientSource::Register(source) | TransientSource::Disable(source) => {
217 source.register(poll, token_factory)?;
218 self.replace(TransientSource::Keep);
219 }
220 TransientSource::Remove(_source) => {
221 *self = TransientSource::None;
222 }
223 TransientSource::None => (),
224 }
225 Ok(())
226 }
227
228 fn reregister(
229 &mut self,
230 poll: &mut crate::Poll,
231 token_factory: &mut crate::TokenFactory,
232 ) -> crate::Result<()> {
233 match self {
234 TransientSource::Keep(source) => source.reregister(poll, token_factory)?,
235 TransientSource::Register(source) => {
236 source.register(poll, token_factory)?;
237 self.replace(TransientSource::Keep);
238 }
239 TransientSource::Disable(source) => {
240 source.unregister(poll)?;
241 }
242 TransientSource::Remove(source) => {
243 source.unregister(poll)?;
244 *self = TransientSource::None;
245 }
246 TransientSource::None => (),
247 }
248 Ok(())
249 }
250
251 fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
252 match self {
253 TransientSource::Keep(source)
254 | TransientSource::Register(source)
255 | TransientSource::Disable(source) => source.unregister(poll)?,
256 TransientSource::Remove(source) => {
257 source.unregister(poll)?;
258 *self = TransientSource::None;
259 }
260 TransientSource::None => (),
261 }
262 Ok(())
263 }
264 }
265
266 #[cfg(test)]
267 mod tests {
268 use super::*;
269 use crate::{
270 channel::{channel, Event},
271 ping::{make_ping, PingSource},
272 Dispatcher, EventSource, PostAction,
273 };
274 use std::{
275 sync::atomic::{AtomicBool, Ordering},
276 time::Duration,
277 };
278
279 #[test]
280 fn test_transient_drop() {
281 // A test source that sets a flag when it's dropped.
282 struct TestSource<'a> {
283 dropped: &'a AtomicBool,
284 ping: PingSource,
285 }
286
287 impl<'a> Drop for TestSource<'a> {
288 fn drop(&mut self) {
289 self.dropped.store(true, Ordering::Relaxed)
290 }
291 }
292
293 impl<'a> crate::EventSource for TestSource<'a> {
294 type Event = ();
295 type Metadata = ();
296 type Ret = ();
297 type Error = Box<dyn std::error::Error + Sync + Send>;
298
299 fn process_events<F>(
300 &mut self,
301 readiness: crate::Readiness,
302 token: crate::Token,
303 callback: F,
304 ) -> Result<crate::PostAction, Self::Error>
305 where
306 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
307 {
308 self.ping.process_events(readiness, token, callback)?;
309 Ok(PostAction::Remove)
310 }
311
312 fn register(
313 &mut self,
314 poll: &mut crate::Poll,
315 token_factory: &mut crate::TokenFactory,
316 ) -> crate::Result<()> {
317 self.ping.register(poll, token_factory)
318 }
319
320 fn reregister(
321 &mut self,
322 poll: &mut crate::Poll,
323 token_factory: &mut crate::TokenFactory,
324 ) -> crate::Result<()> {
325 self.ping.reregister(poll, token_factory)
326 }
327
328 fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
329 self.ping.unregister(poll)
330 }
331 }
332
333 // Test that the inner source is actually dropped when it asks to be
334 // removed from the loop, while the TransientSource remains. We use two
335 // flags for this:
336 // - fired: should be set only when the inner event source has an event
337 // - dropped: set by the drop handler for the inner source (it's an
338 // AtomicBool becaues it requires a longer lifetime than the fired
339 // flag)
340 let mut fired = false;
341 let dropped = false.into();
342
343 // The inner source that should be dropped after the first loop run.
344 let (pinger, ping) = make_ping().unwrap();
345 let inner = TestSource {
346 dropped: &dropped,
347 ping,
348 };
349
350 // The TransientSource wrapper.
351 let outer: TransientSource<_> = inner.into();
352
353 let mut event_loop = crate::EventLoop::try_new().unwrap();
354 let handle = event_loop.handle();
355
356 let _token = handle
357 .insert_source(outer, |_, _, fired| {
358 *fired = true;
359 })
360 .unwrap();
361
362 // First loop run: the ping generates an event for the inner source.
363 pinger.ping();
364
365 event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
366
367 assert!(fired);
368 assert!(dropped.load(Ordering::Relaxed));
369
370 // Second loop run: the ping does nothing because the receiver has been
371 // dropped.
372 fired = false;
373
374 pinger.ping();
375
376 event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
377 assert!(!fired);
378 }
379
380 #[test]
381 fn test_transient_passthrough() {
382 // Test that event processing works when a source is nested inside a
383 // TransientSource. In particular, we want to ensure that the final
384 // event is received even if it corresponds to that same event source
385 // returning `PostAction::Remove`.
386 let (sender, receiver) = channel();
387 let outer: TransientSource<_> = receiver.into();
388
389 let mut event_loop = crate::EventLoop::try_new().unwrap();
390 let handle = event_loop.handle();
391
392 // Our callback puts the receied events in here for us to check later.
393 let mut msg_queue = vec![];
394
395 let _token = handle
396 .insert_source(outer, |msg, _, queue: &mut Vec<_>| {
397 queue.push(msg);
398 })
399 .unwrap();
400
401 // Send some data and drop the sender. We specifically want to test that
402 // we get the "closed" message.
403 sender.send(0u32).unwrap();
404 sender.send(1u32).unwrap();
405 sender.send(2u32).unwrap();
406 sender.send(3u32).unwrap();
407 drop(sender);
408
409 // Run loop once to process events.
410 event_loop.dispatch(Duration::ZERO, &mut msg_queue).unwrap();
411
412 assert!(matches!(
413 msg_queue.as_slice(),
414 &[
415 Event::Msg(0u32),
416 Event::Msg(1u32),
417 Event::Msg(2u32),
418 Event::Msg(3u32),
419 Event::Closed
420 ]
421 ));
422 }
423
424 #[test]
425 fn test_transient_map() {
426 struct IdSource {
427 id: u32,
428 ping: PingSource,
429 }
430
431 impl EventSource for IdSource {
432 type Event = u32;
433 type Metadata = ();
434 type Ret = ();
435 type Error = Box<dyn std::error::Error + Sync + Send>;
436
437 fn process_events<F>(
438 &mut self,
439 readiness: crate::Readiness,
440 token: crate::Token,
441 mut callback: F,
442 ) -> Result<PostAction, Self::Error>
443 where
444 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
445 {
446 let id = self.id;
447 self.ping
448 .process_events(readiness, token, |_, md| callback(id, md))?;
449
450 let action = if self.id > 2 {
451 PostAction::Remove
452 } else {
453 PostAction::Continue
454 };
455
456 Ok(action)
457 }
458
459 fn register(
460 &mut self,
461 poll: &mut crate::Poll,
462 token_factory: &mut crate::TokenFactory,
463 ) -> crate::Result<()> {
464 self.ping.register(poll, token_factory)
465 }
466
467 fn reregister(
468 &mut self,
469 poll: &mut crate::Poll,
470 token_factory: &mut crate::TokenFactory,
471 ) -> crate::Result<()> {
472 self.ping.reregister(poll, token_factory)
473 }
474
475 fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
476 self.ping.unregister(poll)
477 }
478 }
479
480 struct WrapperSource(TransientSource<IdSource>);
481
482 impl EventSource for WrapperSource {
483 type Event = <IdSource as EventSource>::Event;
484 type Metadata = <IdSource as EventSource>::Metadata;
485 type Ret = <IdSource as EventSource>::Ret;
486 type Error = <IdSource as EventSource>::Error;
487
488 fn process_events<F>(
489 &mut self,
490 readiness: crate::Readiness,
491 token: crate::Token,
492 callback: F,
493 ) -> Result<PostAction, Self::Error>
494 where
495 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
496 {
497 let action = self.0.process_events(readiness, token, callback);
498 self.0.map(|inner| inner.id += 1);
499 action
500 }
501
502 fn register(
503 &mut self,
504 poll: &mut crate::Poll,
505 token_factory: &mut crate::TokenFactory,
506 ) -> crate::Result<()> {
507 self.0.map(|inner| inner.id += 1);
508 self.0.register(poll, token_factory)
509 }
510
511 fn reregister(
512 &mut self,
513 poll: &mut crate::Poll,
514 token_factory: &mut crate::TokenFactory,
515 ) -> crate::Result<()> {
516 self.0.map(|inner| inner.id += 1);
517 self.0.reregister(poll, token_factory)
518 }
519
520 fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
521 self.0.map(|inner| inner.id += 1);
522 self.0.unregister(poll)
523 }
524 }
525
526 // To test the id later.
527 let mut id = 0;
528
529 // Create our source.
530 let (pinger, ping) = make_ping().unwrap();
531 let inner = IdSource { id, ping };
532
533 // The TransientSource wrapper.
534 let outer: TransientSource<_> = inner.into();
535
536 // The top level source.
537 let top = WrapperSource(outer);
538
539 // Create a dispatcher so we can check the source afterwards.
540 let dispatcher = Dispatcher::new(top, |got_id, _, test_id| {
541 *test_id = got_id;
542 });
543
544 let mut event_loop = crate::EventLoop::try_new().unwrap();
545 let handle = event_loop.handle();
546
547 let token = handle.register_dispatcher(dispatcher.clone()).unwrap();
548
549 // First loop run: the ping generates an event for the inner source.
550 // The ID should be 1 after the increment in register().
551 pinger.ping();
552 event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
553 assert_eq!(id, 1);
554
555 // Second loop run: the ID should be 2 after the previous
556 // process_events().
557 pinger.ping();
558 event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
559 assert_eq!(id, 2);
560
561 // Third loop run: the ID should be 3 after another process_events().
562 pinger.ping();
563 event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
564 assert_eq!(id, 3);
565
566 // Fourth loop run: the callback is no longer called by the inner
567 // source, so our local ID is not incremented.
568 pinger.ping();
569 event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
570 assert_eq!(id, 3);
571
572 // Remove the dispatcher so we can inspect the sources.
573 handle.remove(token);
574
575 let mut top_after = dispatcher.into_source_inner();
576
577 // I expect the inner source to be dropped, so the TransientSource
578 // variant is None (its version of None, not Option::None), so its map()
579 // won't call the passed-in function (hence the unreachable!()) and its
580 // return value should be Option::None.
581 assert!(top_after.0.map(|_| unreachable!()).is_none());
582 }
583
584 #[test]
585 fn test_transient_disable() {
586 // Test that disabling and enabling is handled properly.
587 struct DisablingSource(PingSource);
588
589 impl EventSource for DisablingSource {
590 type Event = ();
591 type Metadata = ();
592 type Ret = ();
593 type Error = Box<dyn std::error::Error + Sync + Send>;
594
595 fn process_events<F>(
596 &mut self,
597 readiness: crate::Readiness,
598 token: crate::Token,
599 callback: F,
600 ) -> Result<PostAction, Self::Error>
601 where
602 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
603 {
604 self.0.process_events(readiness, token, callback)?;
605 Ok(PostAction::Disable)
606 }
607
608 fn register(
609 &mut self,
610 poll: &mut crate::Poll,
611 token_factory: &mut crate::TokenFactory,
612 ) -> crate::Result<()> {
613 self.0.register(poll, token_factory)
614 }
615
616 fn reregister(
617 &mut self,
618 poll: &mut crate::Poll,
619 token_factory: &mut crate::TokenFactory,
620 ) -> crate::Result<()> {
621 self.0.reregister(poll, token_factory)
622 }
623
624 fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
625 self.0.unregister(poll)
626 }
627 }
628
629 // Flag for checking when the source fires.
630 let mut fired = false;
631
632 // Create our source.
633 let (pinger, ping) = make_ping().unwrap();
634
635 let inner = DisablingSource(ping);
636
637 // The TransientSource wrapper.
638 let outer: TransientSource<_> = inner.into();
639
640 let mut event_loop = crate::EventLoop::try_new().unwrap();
641 let handle = event_loop.handle();
642 let token = handle
643 .insert_source(outer, |_, _, fired| {
644 *fired = true;
645 })
646 .unwrap();
647
648 // Ping here and not later, to check that disabling after an event is
649 // triggered but not processed does not discard the event.
650 pinger.ping();
651 event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
652 assert!(fired);
653
654 // Source should now be disabled.
655 pinger.ping();
656 fired = false;
657 event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
658 assert!(!fired);
659
660 // Re-enable the source.
661 handle.enable(&token).unwrap();
662
663 // Trigger another event.
664 pinger.ping();
665 fired = false;
666 event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
667 assert!(fired);
668 }
669 }