Skip to main content

servo_base/generic_channel/
lazy_callback.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! # Lazy Callbacks
6//!
7//! When constructing callbacks we sometimes have a large distance between where the channel for the callback
8//! is created and where the initial callback will be created. Refactoring of this code is sometimes not possible.
9//! Here we provide [LazyCallback]. We use 'lazy_callback()' to generate a [LazyCallback] and a [CallbackSetter].
10//! The [LazyCallback] works like a [GenericCallback] and can be used to execute callbacks in the receiver process.
11//! The [CallbackSetter] has a single consuming method of 'set_callback' which will set the callback that the [LazyCallback]
12//! will then execute on messages send to it.
13//!
14//! This is achieved with having the LazyCallback having a back channel in single process mode that sets the [GenericCallback].
15//! Hence, this is slightly less efficient than a [GenericCallback]
16
17use std::cell::{OnceCell, RefCell};
18use std::fmt;
19use std::marker::PhantomData;
20
21use ipc_channel::ipc::{IpcReceiver, IpcSender};
22use ipc_channel::router::ROUTER;
23use malloc_size_of::{MallocSizeOf as MallocSizeOfTrait, MallocSizeOfOps};
24use malloc_size_of_derive::MallocSizeOf;
25use serde::de::VariantAccess;
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27
28use crate::generic_channel::{GenericCallback, SendError, SendResult, use_ipc};
29
30/// Basic struct for [LazyCallback]
31#[derive(MallocSizeOf)]
32pub struct LazyCallback<T: Serialize + for<'de> Deserialize<'de> + Send + 'static>(
33    LazyCallbackVariants<T>,
34);
35
36enum LazyCallbackVariants<T>
37where
38    T: Serialize + Send + 'static,
39{
40    InProcess {
41        callback_receiver: RefCell<Option<crossbeam_channel::Receiver<GenericCallback<T>>>>,
42        callback: OnceCell<GenericCallback<T>>,
43    },
44    Ipc(IpcSender<T>),
45}
46
47impl<T> MallocSizeOfTrait for LazyCallbackVariants<T>
48where
49    T: Serialize + Send + 'static,
50{
51    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
52        match self {
53            LazyCallbackVariants::InProcess {
54                callback_receiver,
55                callback,
56            } => callback_receiver.size_of(ops) + callback.size_of(ops),
57            LazyCallbackVariants::Ipc(_) => 0,
58        }
59    }
60}
61
62impl<T> LazyCallback<T>
63where
64    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
65{
66    /// Send messages to the callback. This might block until the callback is set via the 'CallbackSetter'
67    pub fn send(&self, value: T) -> SendResult {
68        match &self.0 {
69            LazyCallbackVariants::InProcess {
70                callback_receiver,
71                callback,
72            } => {
73                if let Some(cb) = callback.get() {
74                    cb.send(value)
75                } else {
76                    // Init callback
77                    let Some(receiver) = callback_receiver.borrow_mut().take() else {
78                        log::error!("Could not get callback. Callback_receiver already taken");
79                        return Err(SendError::Disconnected);
80                    };
81                    if let Ok(cb) = receiver.recv() {
82                        let _ = callback.set(cb);
83                        callback.get().unwrap().send(value)
84                    } else {
85                        log::error!("Could not get callback. Callback_receiver already dropped");
86                        SendResult::Err(SendError::Disconnected)
87                    }
88                }
89            },
90            LazyCallbackVariants::Ipc(ipc_sender) => {
91                ipc_sender.send(value).map_err(|error| match error {
92                    ipc_channel::IpcError::SerializationError(ser_de_error) => {
93                        SendError::SerializationError(ser_de_error.to_string())
94                    },
95                    ipc_channel::IpcError::Io(_) | ipc_channel::IpcError::Disconnected => {
96                        SendError::Disconnected
97                    },
98                })
99            },
100        }
101    }
102}
103
104pub struct CallbackSetter<T: Serialize + Send + 'static>(CallbackSetterVariants<T>);
105
106impl<T: Serialize + Send> fmt::Debug for CallbackSetter<T> {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.debug_tuple("CallbackSetter").finish()
109    }
110}
111
112impl<T> Serialize for CallbackSetter<T>
113where
114    T: Serialize + Send + 'static,
115{
116    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
117        match &self.0 {
118            CallbackSetterVariants::Ipc(sender) => {
119                s.serialize_newtype_variant("CallbackSetter", 0, "Ipc", sender)
120            },
121            // The only reason we need / want serialization in single-process mode is to support
122            // sending GenericCallbacks over existing IPC channels. This allows us to
123            // incrementally port IPC channels to the GenericChannel, without needing to follow a
124            // top-to-bottom approach.
125            // Long-term we can remove this branch in the code again and replace it with
126            // unreachable, since likely all IPC channels would be GenericChannels.
127            CallbackSetterVariants::InProcess(wrapped_callback) => {
128                if use_ipc() {
129                    return Err(serde::ser::Error::custom(
130                        "InProcess callback setter can't be serialized in multiprocess mode",
131                    ));
132                }
133                // Due to the signature of `serialize` we need to clone the Arc to get an owned
134                // pointer we can leak.
135                // We additionally need to Box to get a thin pointer.
136                let cloned_callback = Box::new(wrapped_callback.clone());
137                let sender_clone_addr = Box::into_raw(cloned_callback) as *mut _ as usize;
138                s.serialize_newtype_variant("CallbackSetter", 1, "InProcess", &sender_clone_addr)
139            },
140        }
141    }
142}
143
144struct LazyCallbackSetterVisitor<T> {
145    marker: PhantomData<T>,
146}
147
148impl<'de, T> serde::de::Visitor<'de> for LazyCallbackSetterVisitor<T>
149where
150    T: Serialize + Deserialize<'de> + Send + 'static,
151{
152    type Value = CallbackSetter<T>;
153
154    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
155        formatter.write_str("a GenericCallback variant")
156    }
157
158    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
159    where
160        A: serde::de::EnumAccess<'de>,
161    {
162        #[derive(Deserialize)]
163        enum LazyCallbackSetterVariantNames {
164            Ipc,
165            InProcess,
166        }
167
168        let (variant_name, variant_data): (LazyCallbackSetterVariantNames, _) = data.variant()?;
169
170        match variant_name {
171            LazyCallbackSetterVariantNames::Ipc => variant_data
172                .newtype_variant::<IpcReceiver<T>>()
173                .map(|receiver| CallbackSetter(CallbackSetterVariants::Ipc(receiver))),
174            LazyCallbackSetterVariantNames::InProcess => {
175                if use_ipc() {
176                    return Err(serde::de::Error::custom(
177                        "InProcess callback found in multiprocess mode",
178                    ));
179                }
180                let addr = variant_data.newtype_variant::<usize>()?;
181                let ptr = addr as *mut _;
182                // SAFETY: We know we are in the same address space as the sender, so we can safely
183                // reconstruct the Box, that we previously leaked with `into_raw` during
184                // serialization.
185                // Attention: Code reviewers should carefully compare the deserialization here
186                // with the serialization above.
187                #[expect(unsafe_code)]
188                let callback = unsafe { Box::from_raw(ptr) };
189                Ok(CallbackSetter(CallbackSetterVariants::InProcess(*callback)))
190            },
191        }
192    }
193}
194
195impl<'a, T> Deserialize<'a> for CallbackSetter<T>
196where
197    T: Serialize + Deserialize<'a> + Send + 'static,
198{
199    fn deserialize<D>(d: D) -> Result<CallbackSetter<T>, D::Error>
200    where
201        D: Deserializer<'a>,
202    {
203        d.deserialize_enum(
204            "GenericCallback",
205            &["CrossProcess", "InProcess"],
206            LazyCallbackSetterVisitor {
207                marker: PhantomData,
208            },
209        )
210    }
211}
212
213enum CallbackSetterVariants<T>
214where
215    T: Serialize + Send + 'static,
216{
217    InProcess(crossbeam_channel::Sender<GenericCallback<T>>),
218    Ipc(IpcReceiver<T>),
219}
220
221impl<T> CallbackSetter<T>
222where
223    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
224{
225    /// This sets the callback.
226    pub fn set_callback<F: FnMut(Result<T, SendError>) + Send + 'static>(self, mut callback: F) {
227        match self.0 {
228            CallbackSetterVariants::InProcess(sender) => {
229                let callback = GenericCallback::new(callback).expect("Could not create callback");
230                if sender.send(callback).is_err() {
231                    log::error!("Could not send callback, sender was already dropped");
232                }
233            },
234            CallbackSetterVariants::Ipc(ipc_receiver) => {
235                let new_callback = move |msg: Result<T, ipc_channel::SerDeError>| {
236                    callback(msg.map_err(|error| error.into()))
237                };
238                ROUTER.add_typed_route(ipc_receiver, Box::new(new_callback));
239            },
240        }
241    }
242}
243
244/// This function should never be exported.
245fn lazy_callback_inprocess<T>() -> (LazyCallback<T>, CallbackSetter<T>)
246where
247    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
248{
249    let (callback_sender, callback_receiver) = crossbeam_channel::bounded(1);
250    let lazycallback = LazyCallback(LazyCallbackVariants::InProcess {
251        callback_receiver: RefCell::new(Some(callback_receiver)),
252        callback: OnceCell::new(),
253    });
254
255    let callback_setter = CallbackSetter(CallbackSetterVariants::InProcess(callback_sender));
256
257    (lazycallback, callback_setter)
258}
259
260/// This function should never be exported.
261fn lazy_callback_ipc<T>() -> (LazyCallback<T>, CallbackSetter<T>)
262where
263    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
264{
265    let (sender, receiver) = ipc_channel::ipc::channel().expect("Could not create channel");
266    let callback = LazyCallback(LazyCallbackVariants::Ipc(sender));
267    let callback_setter = CallbackSetter(CallbackSetterVariants::Ipc(receiver));
268    (callback, callback_setter)
269}
270
271/// A LazyCallback is a Callback that will be initialized at a later date.
272/// We return the 'LazyCallback' which is a GenericCallback.
273/// We also return a 'CallbackSetter' where the callback can be set at a later date.
274pub fn lazy_callback<T>() -> (LazyCallback<T>, CallbackSetter<T>)
275where
276    T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
277{
278    if use_ipc() {
279        lazy_callback_ipc()
280    } else {
281        lazy_callback_inprocess()
282    }
283}
284
285#[cfg(test)]
286mod single_process_callback_test {
287    use crate::generic_channel::lazy_callback::{lazy_callback_inprocess, lazy_callback_ipc};
288    use crate::generic_channel::{CallbackSetter, LazyCallback, SendError};
289    fn test_lazy_callback(callback: LazyCallback<bool>, callback_setter: CallbackSetter<bool>) {
290        let t1 = std::thread::spawn(move || {
291            callback.send(true).expect("Could not send");
292        });
293
294        let (sender, receiver) = crossbeam_channel::bounded(1);
295        let t2 = std::thread::spawn(move || {
296            std::thread::sleep(std::time::Duration::from_secs(1));
297            callback_setter.set_callback(move |value| {
298                sender.send(value).expect("Could not send");
299            });
300        });
301
302        t1.join().expect("error joining thread");
303        t2.join().expect("error joining thread");
304        assert_eq!(receiver.recv().unwrap().unwrap(), true);
305    }
306
307    #[test]
308    fn lazy_callback_already_taken_receiver_returns_disconnected() {
309        let (callback, callback_setter) = lazy_callback_inprocess::<bool>();
310        drop(callback_setter);
311
312        assert!(matches!(callback.send(true), Err(SendError::Disconnected)));
313        assert!(matches!(callback.send(true), Err(SendError::Disconnected)));
314    }
315
316    #[test]
317    fn lazy_callback_simple_inprocess() {
318        let (callback, callback_setter) = lazy_callback_inprocess();
319        test_lazy_callback(callback, callback_setter);
320    }
321
322    #[test]
323    fn lazy_callback_simple_ipc() {
324        let (callback, callback_setter) = lazy_callback_ipc();
325        test_lazy_callback(callback, callback_setter);
326    }
327}