Skip to content

Commit

Permalink
Implement detached signal sender
Browse files Browse the repository at this point in the history
Allow signals to be sent detached from the channel struct.

This is done using a higher-order function and by cloning the sender so
it can be used independently of the `Channel`.

This is useful to be able to spawn a cancelation handler separately from
the main `Channel` recieve loop.

Signed-off-by: Joe Grund <[email protected]>
  • Loading branch information
jgrund committed Dec 26, 2022
1 parent f08f749 commit 7b12f66
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions russh/src/channels.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::pin::Pin;

use futures::{Future, FutureExt};
use russh_cryptovec::CryptoVec;
use tokio::sync::mpsc::{Sender, UnboundedReceiver};

Expand Down Expand Up @@ -119,7 +122,7 @@ impl<T: From<(ChannelId, ChannelMsg)>> std::fmt::Debug for Channel<T> {
}
}

impl<S: From<(ChannelId, ChannelMsg)> + Send + 'static> Channel<S> {
impl<Send: From<(ChannelId, ChannelMsg)> + std::marker::Send + 'static> Channel<Send> {
pub fn id(&self) -> ChannelId {
self.id
}
Expand Down Expand Up @@ -179,11 +182,33 @@ impl<S: From<(ChannelId, ChannelMsg)> + Send + 'static> Channel<S> {
}

/// Signal a remote process.
pub async fn signal(&mut self, signal: Sig) -> Result<(), Error> {
pub async fn signal(self, signal: Sig) -> Result<(), Error> {
self.send_msg(ChannelMsg::Signal { signal }).await?;

Ok(())
}

/// Get a `FnOnce` that can be used to send a signal through this channel
pub fn get_signal_sender(
&self,
) -> impl FnOnce(Sig) -> Pin<Box<dyn Future<Output = Result<(), Error>> + std::marker::Send>>
{
let sender = self.sender.clone();
let id = self.id;

move |signal| {
async move {
sender
.send((id, ChannelMsg::Signal { signal }).into())
.await
.map_err(|_| Error::SendError)?;

Ok(())
}
.boxed()
}
}

/// Request the start of a subsystem with the given name.
pub async fn request_subsystem<A: Into<String>>(
&mut self,
Expand Down

0 comments on commit 7b12f66

Please sign in to comment.