Skip to main content

device_tests/
restore.rs

1use std::thread;
2
3use tokio::runtime;
4
5use crate::connected::Connected;
6use crate::failure::Failure;
7use crate::print::print_stderr;
8
9/// Modem state that a test changed and must set back.
10pub trait Restore: Send + Sized + 'static {
11    /// What the test changed, for messages.
12    const WHAT: &'static str;
13
14    /// The client that restores the state.
15    type Client: Sync;
16
17    /// Connects a client that can restore the state.
18    ///
19    /// # Errors
20    ///
21    /// Returns an error if the client can't connect.
22    fn connect() -> Result<Connected<Self::Client>, ql_qmi::Error>;
23
24    /// Sets the state back.
25    fn restore(&self, client: &Self::Client) -> impl Future<Output = Result<(), Failure>> + Send;
26
27    /// Sets the state back with a new client from [`Restore::connect`].
28    fn restore_new(
29        &self,
30        client: &Self::Client,
31    ) -> impl Future<Output = Result<(), Failure>> + Send {
32        self.restore(client)
33    }
34}
35
36/// Sets modem state back on every path.
37///
38/// [`Guard::restore`] restores the state with the client of the test and
39/// reports errors. If the guard is dropped without that, for example after a
40/// panic or an early return, it restores the state with a new client on its
41/// own thread and prints errors.
42#[derive(Debug)]
43pub struct Guard<T: Restore> {
44    state: Option<T>,
45}
46
47impl<T: Restore> Guard<T> {
48    /// Guards `state`, which the test is about to change.
49    pub const fn new(state: T) -> Self {
50        Self { state: Some(state) }
51    }
52
53    /// Drops the guard without restoring the state, for example because the
54    /// modem did it.
55    pub fn dismiss(mut self) {
56        self.state = None;
57    }
58
59    /// Restores the state with the client of the test.
60    ///
61    /// # Errors
62    ///
63    /// Returns the error of [`Restore::restore`].
64    pub async fn restore(mut self, client: &T::Client) -> Result<(), Failure> {
65        match self.state.take() {
66            Some(state) => state.restore(client).await,
67            None => Ok(()),
68        }
69    }
70}
71
72impl<T: Restore> Drop for Guard<T> {
73    fn drop(&mut self) {
74        let Some(state) = self.state.take() else {
75            return;
76        };
77        let restored = thread::Builder::new().spawn(move || {
78            let runtime = runtime::Builder::new_current_thread()
79                .enable_all()
80                .build()
81                .map_err(Failure::Runtime)?;
82            runtime.block_on(async {
83                let client = T::connect()?;
84                let restored = state.restore_new(&client).await;
85                client.close().await;
86                restored
87            })
88        });
89        let what = T::WHAT;
90        match restored.map(thread::JoinHandle::join) {
91            Ok(Ok(Ok(()))) => print_stderr(format_args!("restored the {what} with a new client")),
92            Ok(Ok(Err(err))) => print_stderr(format_args!("failed to restore the {what}: {err:?}")),
93            Ok(Err(_panic)) => print_stderr(format_args!("restoring the {what} panicked")),
94            Err(err) => print_stderr(format_args!(
95                "failed to start a thread to restore the {what}: {err}"
96            )),
97        }
98    }
99}