Debian Codegraph @

src/backend/request.rs

raw
1 use std::{boxed::Box, future::Future, sync::Arc};
2
3 use async_trait::async_trait;
4 use futures_util::{
5 future::{AbortHandle, abortable},
6 lock::Mutex,
7 task::SpawnExt,
8 };
9 use zbus::zvariant::{ObjectPath, OwnedObjectPath};
10
11 use crate::{
12 PortalError,
13 desktop::{HandleToken, Response},
14 };
15
16 #[async_trait]
17 pub trait RequestImpl: Send + Sync {
18 #[doc(alias = "Close")]
19 async fn close(&self, token: HandleToken);
20 }
21
22 pub struct Request {
23 close_cb: Mutex<Option<Box<dyn FnOnce() + Send + Sync>>>,
24 path: OwnedObjectPath,
25 abort_handle: AbortHandle,
26 #[allow(dead_code)]
27 cnx: zbus::Connection,
28 }
29
30 impl Request {
31 pub fn path(&self) -> ObjectPath<'_> {
32 self.path.as_ref()
33 }
34
35 pub(crate) async fn spawn<T, R>(
36 _method: &'static str,
37 cnx: &zbus::Connection,
38 path: OwnedObjectPath,
39 imp: Arc<R>,
40 spawn: Arc<dyn futures_util::task::Spawn + Send + Sync>,
41 callback: impl Future<Output = crate::backend::Result<T>>,
42 ) -> crate::backend::Result<Response<T>>
43 where
44 R: RequestImpl + 'static + ?Sized,
45 T: std::fmt::Debug,
46 {
47 #[cfg(feature = "tracing")]
48 tracing::debug!("{_method}");
49 let (fut, abort_handle) = abortable(callback);
50 let token = HandleToken::try_from(&path).unwrap();
51 let close_cb = move || {
52 if let Err(err) = spawn.spawn(async move {
53 RequestImpl::close(&*imp, token).await;
54 }) {
55 #[cfg(feature = "tracing")]
56 tracing::error!("Failed to spawn request closer: {}", err);
57 let _ = err;
58 }
59 };
60 let request = Request::new(close_cb, path.clone(), abort_handle, cnx.clone());
61 let server = cnx.object_server();
62 #[cfg(feature = "tracing")]
63 tracing::debug!(
64 "Serving `org.freedesktop.impl.portal.Request` at {:?}",
65 path.as_str()
66 );
67 server.at(&path, request).await?;
68
69 let result = fut.await;
70
71 #[cfg(feature = "tracing")]
72 tracing::debug!("{_method} returned {:#?}", result);
73 #[cfg(feature = "tracing")]
74 tracing::debug!("Releasing request {:?}", path.as_str());
75 server.remove::<Self, _>(&path).await?;
76
77 let response = match result {
78 Err(_) => Response::cancelled(),
79 Ok(result) => match result {
80 Ok(results) => Response::ok(results),
81 Err(error) => match error {
82 PortalError::Cancelled(_) => Response::cancelled(),
83 other => {
84 return Err(other);
85 }
86 },
87 },
88 };
89 Ok(response)
90 }
91
92 pub(crate) fn new(
93 close_cb: impl FnOnce() + Send + Sync + 'static,
94 path: OwnedObjectPath,
95 abort_handle: AbortHandle,
96 cnx: zbus::Connection,
97 ) -> Self {
98 Self {
99 close_cb: Mutex::new(Some(Box::new(close_cb))),
100 path,
101 abort_handle,
102 cnx,
103 }
104 }
105 }
106
107 impl PartialEq for Request {
108 fn eq(&self, other: &Self) -> bool {
109 self.path == other.path
110 }
111 }
112 impl Eq for Request {}
113
114 #[zbus::interface(name = "org.freedesktop.impl.portal.Request")]
115 impl Request {
116 async fn close(
117 &self,
118 #[zbus(object_server)] server: &zbus::ObjectServer,
119 ) -> zbus::fdo::Result<()> {
120 self.abort_handle.abort();
121 if let Some(close_cb) = self.close_cb.lock().await.take() {
122 close_cb();
123 }
124
125 // Drop the request as it served it purpose once closed
126 #[cfg(feature = "tracing")]
127 tracing::debug!("Releasing request {:?}", self.path.as_str());
128 server.remove::<Self, _>(&self.path).await?;
129 Ok(())
130 }
131 }