1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
// Copyright 2022 System76 <info@system76.com>
// SPDX-License-Identifier: MIT or Apache-2.0
//! Contains various flavors of channels to send messages between components and workers.
use std::fmt::Debug;
use std::future::Future;
use std::sync::Arc;
use crate::component::AsyncComponent;
use crate::factory::{AsyncFactoryComponent, FactoryComponent};
use crate::{Component, Sender, ShutdownReceiver};
// Contains senders used by components and factories internally.
#[derive(Debug)]
struct ComponentSenderInner<Input, Output, CommandOutput>
where
Input: Debug,
CommandOutput: Send + 'static,
{
/// Emits component inputs.
input: Sender<Input>,
/// Emits component outputs.
output: Sender<Output>,
/// Emits command outputs.
command: Sender<CommandOutput>,
shutdown: ShutdownReceiver,
}
impl<Input, Output, CommandOutput> ComponentSenderInner<Input, Output, CommandOutput>
where
Input: Debug,
CommandOutput: Send + 'static,
{
/// Retrieve the sender for input messages.
///
/// Useful to forward inputs from another component. If you just need to send input messages,
/// [`input()`][Self::input] is more concise.
#[must_use]
fn input_sender(&self) -> &Sender<Input> {
&self.input
}
/// Retrieve the sender for output messages.
///
/// Useful to forward outputs from another component. If you just need to send output messages,
/// [`output()`][Self::output] is more concise.
#[must_use]
fn output_sender(&self) -> &Sender<Output> {
&self.output
}
/// Retrieve the sender for command output messages.
///
/// Useful to forward outputs from another component. If you just need to send output messages,
/// [`command()`][Self::command] is more concise.
#[must_use]
fn command_sender(&self) -> &Sender<CommandOutput> {
&self.command
}
/// Emit an input to the component.
fn input(&self, message: Input) {
// Input messages should always be safe to send
// because the runtime keeps the receiver alive.
self.input.send(message).expect("The runtime of the component was shutdown. Maybe you accidentally dropped a controller?");
}
/// This is not public because factories can unwrap the result
/// because they keep the output receiver alive internally.
fn output(&self, message: Output) -> Result<(), Output> {
self.output.send(message)
}
/// Spawns an asynchronous command.
/// You can bind the the command to the lifetime of the component
/// by using a [`ShutdownReceiver`].
fn command<Cmd, Fut>(&self, cmd: Cmd)
where
Cmd: FnOnce(Sender<CommandOutput>, ShutdownReceiver) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send,
{
let recipient = self.shutdown.clone();
let sender = self.command.clone();
crate::spawn(async move {
cmd(sender, recipient).await;
});
}
/// Spawns a synchronous command.
///
/// This is particularly useful for CPU-intensive background jobs that
/// need to run on a thread-pool in the background.
///
/// If you expect the component to be dropped while
/// the command is running take care while sending messages!
fn spawn_command<Cmd>(&self, cmd: Cmd)
where
Cmd: FnOnce(Sender<CommandOutput>) + Send + 'static,
{
let sender = self.command.clone();
crate::spawn_blocking(move || cmd(sender));
}
/// Spawns a future that will be dropped as soon as the factory component is shut down.
///
/// Essentially, this is a simpler version of [`Self::command()`].
fn oneshot_command<Fut>(&self, future: Fut)
where
Fut: Future<Output = CommandOutput> + Send + 'static,
{
// Async closures would be awesome here...
self.command(move |out, shutdown| {
shutdown
.register(async move { out.send(future.await) })
.drop_on_shutdown()
});
}
/// Spawns a synchronous command that will be dropped as soon as the factory component is shut down.
///
/// Essentially, this is a simpler version of [`Self::spawn_command()`].
fn spawn_oneshot_command<Cmd>(&self, cmd: Cmd)
where
Cmd: FnOnce() -> CommandOutput + Send + 'static,
{
let handle = crate::spawn_blocking(cmd);
self.oneshot_command(async move { handle.await.unwrap() })
}
}
macro_rules! sender_impl {
($name:ident, $trait:ident) => {
/// Contains senders to send and receive messages from a [`Component`].
#[derive(Debug)]
pub struct $name<C: $trait> {
shared: Arc<ComponentSenderInner<C::Input, C::Output, C::CommandOutput>>,
}
impl<C: $trait> $name<C> {
pub(crate) fn new(
input: Sender<C::Input>,
output: Sender<C::Output>,
command: Sender<C::CommandOutput>,
shutdown: ShutdownReceiver,
) -> Self {
Self {
shared: Arc::new(ComponentSenderInner {
input,
output,
command,
shutdown,
}),
}
}
/// Retrieve the sender for input messages.
///
/// Useful to forward inputs from another component. If you just need to send input messages,
/// [`input()`][Self::input] is more concise.
#[must_use]
pub fn input_sender(&self) -> &Sender<C::Input> {
self.shared.input_sender()
}
/// Retrieve the sender for output messages.
///
/// Useful to forward outputs from another component. If you just need to send output messages,
/// [`output()`][Self::output] is more concise.
#[must_use]
pub fn output_sender(&self) -> &Sender<C::Output> {
self.shared.output_sender()
}
/// Retrieve the sender for command output messages.
///
/// Useful to forward outputs from another component. If you just need to send output messages,
/// [`command()`][Self::command] is more concise.
#[must_use]
pub fn command_sender(&self) -> &Sender<C::CommandOutput> {
self.shared.command_sender()
}
/// Emit an input to the component.
pub fn input(&self, message: C::Input) {
self.shared.input(message);
}
/// Spawns an asynchronous command.
/// You can bind the the command to the lifetime of the component
/// by using a [`ShutdownReceiver`].
pub fn command<Cmd, Fut>(&self, cmd: Cmd)
where
Cmd: FnOnce(Sender<C::CommandOutput>, ShutdownReceiver) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send,
{
self.shared.command(cmd)
}
/// Spawns a synchronous command.
///
/// This is particularly useful for CPU-intensive background jobs that
/// need to run on a thread-pool in the background.
///
/// If you expect the component to be dropped while
/// the command is running take care while sending messages!
pub fn spawn_command<Cmd>(&self, cmd: Cmd)
where
Cmd: FnOnce(Sender<C::CommandOutput>) + Send + 'static,
{
self.shared.spawn_command(cmd)
}
/// Spawns a future that will be dropped as soon as the factory component is shut down.
///
/// Essentially, this is a simpler version of [`Self::command()`].
pub fn oneshot_command<Fut>(&self, future: Fut)
where
Fut: Future<Output = C::CommandOutput> + Send + 'static,
{
self.shared.oneshot_command(future)
}
/// Spawns a synchronous command that will be dropped as soon as the factory component is shut down.
///
/// Essentially, this is a simpler version of [`Self::spawn_command()`].
pub fn spawn_oneshot_command<Cmd>(&self, cmd: Cmd)
where
Cmd: FnOnce() -> C::CommandOutput + Send + 'static,
{
self.shared.spawn_oneshot_command(cmd)
}
}
impl<C: $trait> Clone for $name<C> {
fn clone(&self) -> Self {
Self {
shared: Arc::clone(&self.shared),
}
}
}
};
}
sender_impl!(ComponentSender, Component);
impl<C: Component> ComponentSender<C> {
/// Emit an output to the component.
///
/// Returns [`Err`] if all receivers were dropped,
/// for example by [`detach`].
///
/// [`detach`]: crate::component::Connector::detach
pub fn output(&self, message: C::Output) -> Result<(), C::Output> {
self.shared.output(message)
}
}
sender_impl!(AsyncComponentSender, AsyncComponent);
impl<C: AsyncComponent> AsyncComponentSender<C> {
/// Emit an output to the component.
///
/// Returns [`Err`] if all receivers were dropped,
/// for example by [`detach`].
///
/// [`detach`]: crate::component::AsyncConnector::detach
pub fn output(&self, message: C::Output) -> Result<(), C::Output> {
self.shared.output(message)
}
}
sender_impl!(FactorySender, FactoryComponent);
impl<C: FactoryComponent> FactorySender<C> {
/// Emit an output to the component.
pub fn output(&self, message: C::Output) {
self.shared.output(message).unwrap()
}
}
sender_impl!(AsyncFactorySender, AsyncFactoryComponent);
impl<C: AsyncFactoryComponent> AsyncFactorySender<C> {
/// Emit an output to the component.
pub fn output(&self, message: C::Output) {
self.shared.output(message).unwrap()
}
}