1use std::thread;
2
3use tokio::runtime;
4
5use crate::connected::Connected;
6use crate::failure::Failure;
7use crate::print::print_stderr;
8
9pub trait Restore: Send + Sized + 'static {
11 const WHAT: &'static str;
13
14 type Client: Sync;
16
17 fn connect() -> Result<Connected<Self::Client>, ql_qmi::Error>;
23
24 fn restore(&self, client: &Self::Client) -> impl Future<Output = Result<(), Failure>> + Send;
26
27 fn restore_new(
29 &self,
30 client: &Self::Client,
31 ) -> impl Future<Output = Result<(), Failure>> + Send {
32 self.restore(client)
33 }
34}
35
36#[derive(Debug)]
43pub struct Guard<T: Restore> {
44 state: Option<T>,
45}
46
47impl<T: Restore> Guard<T> {
48 pub const fn new(state: T) -> Self {
50 Self { state: Some(state) }
51 }
52
53 pub fn dismiss(mut self) {
56 self.state = None;
57 }
58
59 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}