fdomain_client/
handle.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::responder::Responder;
6use crate::{ordinals, Client, Error};
7use fidl_fuchsia_fdomain as proto;
8use futures::FutureExt;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::{Arc, Weak};
12use std::task::{Context, Poll};
13
14/// A handle of unspecified type within a remote FDomain.
15#[derive(Debug)]
16pub struct Handle {
17    pub(crate) id: u32,
18    pub(crate) client: Weak<Client>,
19}
20
21impl Handle {
22    /// Get the FDomain client this handle belongs to.
23    pub(crate) fn client(&self) -> Arc<Client> {
24        self.client.upgrade().unwrap_or_else(|| Arc::clone(&*crate::DEAD_CLIENT))
25    }
26
27    /// Get an invalid handle.
28    pub(crate) fn invalid() -> Self {
29        Handle { id: 0, client: Weak::new() }
30    }
31}
32
33impl std::cmp::PartialEq for Handle {
34    fn eq(&self, other: &Self) -> bool {
35        self.id == other.id && Weak::ptr_eq(&self.client, &other.client)
36    }
37}
38
39impl std::cmp::Eq for Handle {}
40
41impl std::cmp::PartialOrd for Handle {
42    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
43        Some(self.cmp(other))
44    }
45}
46
47impl std::cmp::Ord for Handle {
48    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
49        self.id.cmp(&other.id)
50    }
51}
52
53impl std::hash::Hash for Handle {
54    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
55        self.id.hash(state);
56    }
57}
58
59/// A reference to a [`Handle`]. Can be derived from a [`Handle`] or any other
60/// type implementing [`AsHandleRef`].
61#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
62pub struct HandleRef<'a>(&'a Handle);
63
64impl std::ops::Deref for HandleRef<'_> {
65    type Target = Handle;
66
67    fn deref(&self) -> &Self::Target {
68        self.0
69    }
70}
71
72impl HandleRef<'_> {
73    /// Replace this handle with a new handle to the same object, with different
74    /// rights.
75    pub fn duplicate(
76        &self,
77        rights: fidl::Rights,
78    ) -> impl Future<Output = Result<Handle, Error>> + 'static {
79        let client = self.0.client();
80        let handle = self.0.proto();
81        let new_handle = client.new_hid();
82        let id = new_handle.id;
83        client
84            .transaction(
85                ordinals::DUPLICATE,
86                proto::FDomainDuplicateRequest { handle, new_handle, rights },
87                Responder::Duplicate,
88            )
89            .map(move |res| res.map(|_| Handle { id, client: Arc::downgrade(&client) }))
90    }
91
92    /// Assert and deassert signals on this handle.
93    pub fn signal(
94        &self,
95        set: fidl::Signals,
96        clear: fidl::Signals,
97    ) -> impl Future<Output = Result<(), Error>> {
98        let handle = self.proto();
99        let client = self.client();
100
101        client.transaction(
102            ordinals::SIGNAL,
103            proto::FDomainSignalRequest { handle, set: set.bits(), clear: clear.bits() },
104            Responder::Signal,
105        )
106    }
107}
108
109/// Trait for turning handle-based types into [`HandleRef`], and for handle
110/// operations that can be performed on [`HandleRef`].
111pub trait AsHandleRef {
112    fn as_handle_ref(&self) -> HandleRef<'_>;
113    fn object_type() -> fidl::ObjectType;
114
115    fn signal_handle(
116        &self,
117        set: fidl::Signals,
118        clear: fidl::Signals,
119    ) -> impl Future<Output = Result<(), Error>> {
120        self.as_handle_ref().signal(set, clear)
121    }
122
123    /// Get the client supporting this handle. See `fidl::Proxy::domain`.
124    fn domain(&self) -> Arc<Client> {
125        self.as_handle_ref().0.client()
126    }
127}
128
129impl AsHandleRef for Handle {
130    /// Get a [`HandleRef`] referring to the handle contained in `Self`
131    fn as_handle_ref(&self) -> HandleRef<'_> {
132        HandleRef(self)
133    }
134
135    /// Get the object type of this handle.
136    fn object_type() -> fidl::ObjectType {
137        fidl::ObjectType::NONE
138    }
139}
140
141/// Trait for handle-based types that have a peer.
142pub trait Peered: HandleBased {
143    /// Assert and deassert signals on this handle's peer.
144    fn signal_peer(
145        &self,
146        set: fidl::Signals,
147        clear: fidl::Signals,
148    ) -> impl Future<Output = Result<(), Error>> {
149        let handle = self.as_handle_ref().proto();
150        let client = self.as_handle_ref().client();
151
152        client.transaction(
153            ordinals::SIGNAL_PEER,
154            proto::FDomainSignalPeerRequest { handle, set: set.bits(), clear: clear.bits() },
155            Responder::SignalPeer,
156        )
157    }
158}
159
160pub trait HandleBased: AsHandleRef + From<Handle> + Into<Handle> {
161    /// Closes this handle. Surfaces errors that dropping the handle will not.
162    fn close(self) -> impl Future<Output = Result<(), Error>> {
163        let h = <Self as Into<Handle>>::into(self);
164        Handle::close(h)
165    }
166
167    /// Duplicate this handle.
168    fn duplicate_handle(&self, rights: fidl::Rights) -> impl Future<Output = Result<Self, Error>> {
169        let fut = self.as_handle_ref().duplicate(rights);
170        async move { fut.await.map(|handle| Self::from(handle)) }
171    }
172
173    /// Replace this handle with an equivalent one with different rights.
174    fn replace_handle(self, rights: fidl::Rights) -> impl Future<Output = Result<Self, Error>> {
175        let h = <Self as Into<Handle>>::into(self);
176        async move { h.replace(rights).await.map(|handle| Self::from(handle)) }
177    }
178
179    /// Convert this handle-based value into a pure [`Handle`].
180    fn into_handle(self) -> Handle {
181        self.into()
182    }
183
184    /// Construct a new handle-based value from a [`Handle`].
185    fn from_handle(handle: Handle) -> Self {
186        Self::from(handle)
187    }
188
189    /// Turn this handle-based value into one of a different type.
190    fn into_handle_based<H: HandleBased>(self) -> H {
191        H::from_handle(self.into_handle())
192    }
193
194    /// Turn another handle-based type into this one.
195    fn from_handle_based<H: HandleBased>(h: H) -> Self {
196        Self::from_handle(h.into_handle())
197    }
198}
199
200impl HandleBased for Handle {}
201
202/// Future which waits for a particular set of signals to be asserted for a
203/// given handle.
204pub struct OnFDomainSignals {
205    fut: futures::future::BoxFuture<'static, Result<fidl::Signals, Error>>,
206}
207
208impl OnFDomainSignals {
209    /// Construct a new [`OnFDomainSignals`]. The next time one of the given
210    /// signals is asserted the future will return. The return value is all
211    /// asserted signals intersected with the input signals.
212    pub fn new(handle: &Handle, signals: fidl::Signals) -> Self {
213        let client = handle.client();
214        let handle = handle.proto();
215        let fut = client
216            .transaction(
217                ordinals::WAIT_FOR_SIGNALS,
218                proto::FDomainWaitForSignalsRequest { handle, signals: signals.bits() },
219                Responder::WaitForSignals,
220            )
221            .map(|f| f.map(|x| fidl::Signals::from_bits_retain(x.signals)));
222        OnFDomainSignals { fut: fut.boxed() }
223    }
224}
225
226impl Future for OnFDomainSignals {
227    type Output = Result<fidl::Signals, Error>;
228
229    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
230        self.fut.as_mut().poll(cx)
231    }
232}
233
234impl Handle {
235    /// Get a proto::HandleId with the ID of this handle.
236    pub(crate) fn proto(&self) -> proto::HandleId {
237        proto::HandleId { id: self.id }
238    }
239
240    /// Get a proto::HandleId with the ID of this handle, then destroy this object
241    /// without sending a request to close the handlel.
242    pub(crate) fn take_proto(mut self) -> proto::HandleId {
243        let ret = self.proto();
244        // Detach from the client so we don't close the handle when we drop self.
245        self.client = Weak::new();
246        ret
247    }
248
249    /// Close this handle. Surfaces errors that dropping the handle will not.
250    pub fn close(self) -> impl Future<Output = Result<(), Error>> {
251        let client = self.client();
252        client.transaction(
253            ordinals::CLOSE,
254            proto::FDomainCloseRequest { handles: vec![self.take_proto()] },
255            Responder::Close,
256        )
257    }
258
259    /// Replace this handle with a new handle to the same object, with different
260    /// rights.
261    pub fn replace(self, rights: fidl::Rights) -> impl Future<Output = Result<Handle, Error>> {
262        let client = self.client();
263        let handle = self.take_proto();
264        {
265            let mut client = client.0.lock().unwrap();
266            let _ = client.channel_read_states.remove(&handle);
267            let _ = client.socket_read_states.remove(&handle);
268        }
269        let new_handle = client.new_hid();
270
271        let id = new_handle.id;
272        let ret = Handle { id, client: Arc::downgrade(&client) };
273        let fut = client.transaction(
274            ordinals::REPLACE,
275            proto::FDomainReplaceRequest { handle, new_handle, rights },
276            Responder::Replace,
277        );
278
279        async move {
280            fut.await?;
281            Ok(ret)
282        }
283    }
284}
285
286impl Drop for Handle {
287    fn drop(&mut self) {
288        if let Some(client) = self.client.upgrade() {
289            let mut client = client.0.lock().unwrap();
290            if client.waiting_to_close.is_empty() {
291                client.waiting_to_close_waker.wake_by_ref();
292            }
293            client.waiting_to_close.push(self.proto());
294        }
295    }
296}
297
298macro_rules! handle_type {
299    ($name:ident $objtype:ident) => {
300        impl From<$name> for Handle {
301            fn from(other: $name) -> Handle {
302                other.0
303            }
304        }
305
306        impl From<Handle> for $name {
307            fn from(other: Handle) -> $name {
308                $name(other)
309            }
310        }
311
312        impl $crate::AsHandleRef for $name {
313            fn as_handle_ref(&self) -> $crate::HandleRef<'_> {
314                self.0.as_handle_ref()
315            }
316
317            fn object_type(
318            ) -> fidl::ObjectType {
319                ::fidl::ObjectType::$objtype
320            }
321        }
322
323        impl $crate::HandleBased for $name {}
324    };
325    ($name:ident $objtype:ident peered) => {
326        handle_type!($name $objtype);
327
328        impl $crate::Peered for $name {}
329    };
330}
331
332pub(crate) use handle_type;