Skip to main content

servo_base/generic_channel/
generic_channelset.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/. */
4use ipc_channel::ipc::{IpcReceiverSet, IpcSelectionResult};
5use serde::{Deserialize, Serialize};
6use smallvec::SmallVec;
7
8use crate::generic_channel::{GenericReceiver, GenericReceiverVariants, SendError, use_ipc};
9
10/// A GenericReceiverSet. Allows you to wait on multiple GenericReceivers.
11/// Automatically selects either Ipc or crossbeam depending on multiprocess mode.
12/// # Examples
13/// ```ignore
14/// let mut rx_set = GenericReceiverSet::new();
15/// let private_channel = generic_channel::channel().unwrap();
16/// let public_channel = generic_channel::channel().unwrap();
17/// let reporter_channel = generic_channel::channel().unwrap();
18/// let private_id = rx_set.add(private_receiver);
19/// let public_id = rx_set.add(public_receiver);
20/// let reporter_id = rx_set.add(memory_reporter);
21/// for received in rx_set.select().into_iter() {
22///     match received {
23///         GenericSelectionResult::ChannelClosed(_) => continue,
24///         GenericSelectionResult::Error => println!("Found selection error"),
25///         GenericSelectionResult::MessageReceived(id, msg) => { /*...*/ }
26///     }
27/// }
28/// ```
29pub struct GenericReceiverSet<T: Serialize + for<'de> Deserialize<'de>>(
30    GenericReceiverSetVariants<T>,
31);
32
33impl<T: Serialize + for<'de> Deserialize<'de>> Default for GenericReceiverSet<T> {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38enum GenericReceiverSetVariants<T: for<'de> Deserialize<'de>> {
39    Ipc(ipc_channel::ipc::IpcReceiverSet),
40    Crossbeam(Vec<crossbeam_channel::Receiver<Result<T, SendError>>>),
41}
42
43#[cfg(test)]
44pub fn create_ipc_receiver_set<T: Serialize + for<'de> serde::Deserialize<'de>>()
45-> GenericReceiverSet<T> {
46    GenericReceiverSet(GenericReceiverSetVariants::Ipc(
47        IpcReceiverSet::new().expect("Could not create ipc receiver"),
48    ))
49}
50
51#[cfg(test)]
52pub fn create_crossbeam_receiver_set<T: Serialize + for<'de> serde::Deserialize<'de>>()
53-> GenericReceiverSet<T> {
54    GenericReceiverSet(GenericReceiverSetVariants::Crossbeam(vec![]))
55}
56
57/// Result for readable events returned from [GenericReceiverSet::select].
58#[derive(Debug, PartialEq)]
59pub enum GenericSelectionResult<T> {
60    /// A message received from the [`GenericReceiver`],
61    /// identified by the `u64` value and Deserialized into a 'T'.
62    MessageReceived(u64, T),
63    /// The channel has been closed for the [GenericReceiver] identified by the `u64` value.
64    ChannelClosed(u64),
65    /// The last active channel in the selection has been closed.
66    AllChannelsClosed(u64),
67    /// An error occurred decoding the message.
68    Error(String),
69}
70
71impl<T: Serialize + for<'de> serde::Deserialize<'de>> From<IpcSelectionResult>
72    for GenericSelectionResult<T>
73{
74    fn from(value: IpcSelectionResult) -> Self {
75        match value {
76            IpcSelectionResult::MessageReceived(channel_id, ipc_message) => {
77                match ipc_message.to() {
78                    Ok(value) => GenericSelectionResult::MessageReceived(channel_id, value),
79                    Err(error) => GenericSelectionResult::Error(error.to_string()),
80                }
81            },
82            IpcSelectionResult::ChannelClosed(channel_id) => {
83                GenericSelectionResult::ChannelClosed(channel_id)
84            },
85        }
86    }
87}
88
89impl<T: Serialize + for<'de> Deserialize<'de>> GenericReceiverSet<T> {
90    /// Create a new ReceiverSet.
91    pub fn new() -> GenericReceiverSet<T> {
92        if use_ipc() {
93            GenericReceiverSet(GenericReceiverSetVariants::Ipc(
94                IpcReceiverSet::new().expect("Could not create ipc receiver"),
95            ))
96        } else {
97            GenericReceiverSet(GenericReceiverSetVariants::Crossbeam(vec![]))
98        }
99    }
100
101    /// Add a receiver to the set.
102    pub fn add(&mut self, receiver: GenericReceiver<T>) -> u64 {
103        match (&mut self.0, receiver.0) {
104            (
105                GenericReceiverSetVariants::Ipc(ipc_receiver_set),
106                GenericReceiverVariants::Ipc(ipc_receiver),
107            ) => ipc_receiver_set
108                .add(ipc_receiver)
109                .expect("Could not add channel"),
110            (GenericReceiverSetVariants::Ipc(_), GenericReceiverVariants::Crossbeam(_)) => {
111                unreachable!()
112            },
113            (GenericReceiverSetVariants::Crossbeam(_), GenericReceiverVariants::Ipc(_)) => {
114                unreachable!()
115            },
116            (
117                GenericReceiverSetVariants::Crossbeam(receivers),
118                GenericReceiverVariants::Crossbeam(receiver),
119            ) => {
120                let index = receivers.len() as u64;
121                receivers.push(receiver);
122                index
123            },
124        }
125    }
126
127    /// Create a [`Selector`] that owns the underlying select state.
128    ///
129    /// # Examples
130    ///
131    /// ```no_run
132    ///  use servo_base::generic_channel::{self, GenericReceiverSet};
133    ///
134    ///  let (_, receiver_one) = generic_channel::channel::<()>().unwrap();
135    ///  let (_, receiver_two) = generic_channel::channel::<()>().unwrap();
136    ///  let mut rx_set = GenericReceiverSet::<()>::new();
137    ///  let _select_idx_1 = rx_set.add(receiver_one);
138    ///  let _select_idx_2 = rx_set.add(receiver_two);
139    ///  // Build the Selector once, before the loop if all receivers are known in advance.
140    ///  let mut selector = rx_set.selector();
141    ///  loop {
142    ///    for received in selector.select().into_iter() {
143    ///      // do something
144    ///    }
145    ///  }
146    /// ```
147    pub fn selector(&mut self) -> Selector<'_, T> {
148        let inner = match &mut self.0 {
149            GenericReceiverSetVariants::Ipc(set) => SelectorInner::Ipc(set),
150            GenericReceiverSetVariants::Crossbeam(receivers) => {
151                let mut sel = crossbeam_channel::Select::new();
152                for receiver in receivers.iter() {
153                    sel.recv(receiver);
154                }
155                SelectorInner::Crossbeam {
156                    receivers: receivers.as_slice(),
157                    sel,
158                }
159            },
160        };
161        Selector { inner }
162    }
163}
164
165/// Borrows of a [`GenericReceiverSet`] used to drive repeated `select` calls
166/// without rebuilding the underlying `crossbeam_channel::Select` each time.
167/// See [`GenericReceiverSet::selector`].
168pub struct Selector<'a, T: Serialize + for<'de> Deserialize<'de>> {
169    inner: SelectorInner<'a, T>,
170}
171
172enum SelectorInner<'a, T: for<'de> Deserialize<'de>> {
173    Ipc(&'a mut IpcReceiverSet),
174    Crossbeam {
175        receivers: &'a [crossbeam_channel::Receiver<Result<T, SendError>>],
176        sel: crossbeam_channel::Select<'a>,
177    },
178}
179
180impl<'a, T: Serialize + for<'de> Deserialize<'de>> Selector<'a, T> {
181    /// Block until at least one of the Receivers receives a message.
182    ///
183    /// Note: The IPC variant can return multiple results in one call.
184    /// The crossbeam variant always returns exactly one.
185    pub fn select(&mut self) -> SmallVec<[GenericSelectionResult<T>; 2]> {
186        match &mut self.inner {
187            SelectorInner::Ipc(ipc_receiver_set) => ipc_receiver_set
188                .select()
189                .map(|result_value| {
190                    result_value
191                        .into_iter()
192                        .map(|selection_result| selection_result.into())
193                        .collect()
194                })
195                .unwrap_or_else(|e| {
196                    smallvec::smallvec![GenericSelectionResult::Error(e.to_string())]
197                }),
198            SelectorInner::Crossbeam { receivers, sel } => {
199                let selected = sel.select();
200                let index = selected.index();
201                let selection_result = match receivers.get(index) {
202                    None => GenericSelectionResult::ChannelClosed(index as u64),
203                    Some(receiver) => match selected.recv(receiver) {
204                        Ok(Ok(value)) => {
205                            GenericSelectionResult::MessageReceived(index as u64, value)
206                        },
207                        Ok(Err(error)) => GenericSelectionResult::Error(error.to_string()),
208                        Err(_) => {
209                            // select on closed channels immediately returns, so we need to
210                            // remove it from our set.
211                            sel.remove(index);
212                            if receivers.len() == 1 {
213                                GenericSelectionResult::AllChannelsClosed(index as u64)
214                            } else {
215                                GenericSelectionResult::ChannelClosed(index as u64)
216                            }
217                        },
218                    },
219                };
220                smallvec::smallvec![selection_result]
221            },
222        }
223    }
224}