servo/
proxies.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
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use constellation_traits::EmbedderToConstellationMessage;
9use crossbeam_channel::{SendError, Sender};
10use log::warn;
11
12#[derive(Clone)]
13pub(crate) struct ConstellationProxy {
14    sender: Sender<EmbedderToConstellationMessage>,
15    disconnected: Arc<AtomicBool>,
16}
17
18impl ConstellationProxy {
19    pub fn new(sender: Sender<EmbedderToConstellationMessage>) -> Self {
20        Self {
21            sender,
22            disconnected: Arc::default(),
23        }
24    }
25
26    pub fn disconnected(&self) -> bool {
27        self.disconnected.load(Ordering::SeqCst)
28    }
29
30    pub fn send(&self, msg: EmbedderToConstellationMessage) {
31        if self.try_send(msg).is_err() {
32            warn!("Lost connection to Constellation. Will report to embedder.")
33        }
34    }
35
36    #[allow(clippy::result_large_err)]
37    fn try_send(
38        &self,
39        msg: EmbedderToConstellationMessage,
40    ) -> Result<(), SendError<EmbedderToConstellationMessage>> {
41        if self.disconnected() {
42            return Err(SendError(msg));
43        }
44        if let Err(error) = self.sender.send(msg) {
45            self.disconnected.store(true, Ordering::SeqCst);
46            return Err(error);
47        }
48
49        Ok(())
50    }
51
52    pub fn sender(&self) -> Sender<EmbedderToConstellationMessage> {
53        self.sender.clone()
54    }
55}