iced icon indicating copy to clipboard operation
iced copied to clipboard

Clean way of using splitted/shared streams with subscriptions

Open fwcd opened this issue 6 years ago • 13 comments

When dealing with streams such as WebSockets, it is often useful to have both a sender and a receiver, where only the receiver serves as a subscription and the sender is stored externally (e.g. in the structure implementing the Application).

I have, however, not found a way to cleanly express this concept using the recipe/subscription mechanism, since, as far as I can tell:

  • A recipe should be "passive" (e.g. only a URL), hashable (to allow being identified by the runtime) and able to spawn an owned stream
  • A subscription should be created from a recipe (since this allows the recipe to internally track which recipes have changed, e.g. by its hash)

This, however, makes it hard to externally spawn a splitted/shared stream (such as a WebSocket) and pass it into a subscription. I have tried implementing Recipe as a wrapper around the actual stream, but this violates the assumption that recipes are "passive" and causes some other subtle issues, e.g. since Application.subscription takes an immutable receiver.

Does the framework have some way of expressing this?

fwcd avatar May 07 '20 22:05 fwcd

Why do you need to externally create the stream? I believe the receiver should be created close to its owner, instead of the senders.

In other words, I would create the channel in Recipe::stream, hold the Receiver, and then send a Sender in the first message of the stream.

hecrj avatar May 07 '20 23:05 hecrj

Neat idea, thank you!

fwcd avatar May 08 '20 00:05 fwcd

Why do you need to externally create the stream? I believe the receiver should be created close to its owner, instead of the senders.

In other words, I would create the channel in Recipe::stream, hold the Receiver, and then send a Sender in the first message of the stream.

I'm trying to figure out how to implement a socket connection. Maybe I am misunderstanding - but wouldn't the clone restriction on Message make it impossible to pass a websocket sender back to the Application?

jbtobar avatar Aug 31 '21 23:08 jbtobar

Instead of sending the websocket sender, you can setup a channel (like this) in Recipe::stream and send the mpsc::Sender across in the first message. That channel can have it's own Message enum that you can use to send commands back to Recipe::stream. You can use futures::stream::select to get messages from the websocket recevier or the mpsc::Receiver.

tarkah avatar Sep 01 '21 00:09 tarkah

Thank you for that tip! I'll explore this avenue. (if you have any examples of this implementation that would be awesome as well!)

jbtobar avatar Sep 01 '21 14:09 jbtobar

I think I am moving in some direction - not sure it the proper one.

The below approach creates a channel with iced_futures::futures::channel::mpsc and I am able to maintain an open socket connection, receive messages, but sending messages is not really working.

There is an issue with how the sender is being passed back to the application or maybe with the processing of the messages. The below code is adapted from the 'download_progress' example.

I cannot exactly decipher what you meant @tarkah , but I'll keep trying. Apologies of the messy code just placing in case anyone spots whats wrong with this approach. Hopefully will be able to report back with more promising results.

Cheers!

download.rs

fn stream(
      self: Box<Self>,
      _input: futures::stream::BoxStream<'static, I>,
  ) -> futures::stream::BoxStream<'static, Self::Output> {
      let id = self.id;

      Box::pin(futures::stream::unfold(
          State::Ready(self.url),
          move |state| async move {


              match state {
                  State::Ready(url) => {

                      let mut response = connect_async("wss://url.com".to_string())
                                                  .await;

                      let (sender, mut receiver) = mpsc::channel::<String>(0);
                      match response {
                          Ok(mut response) => {
                              response.0.send(tungstenite::Message::text("melo")).await.expect("Could not Send");
                              Some((
                                  (id, Progress::Started, "Start".to_string(), sender.clone()),
                                  State::Downloading {
                                      response: response.0,
                                      total: 54,
                                      downloaded: 0,
                                      msg: "Start".to_string(),
                                      sender,
                                      receiver
                                  },
                              ))
                          }
                          Err(_) => {
                              Some(((id, Progress::Errored, "ERROR".to_string(), sender), State::Finished))
                          }
                      }
                  }
                  State::Downloading {
                      mut response,
                      total,
                      downloaded,
                      sender,
                      mut receiver,
                      ..
                  } => {

                      match receiver.try_next() {
                          Ok(Some(string)) => {
                              println!("{}", string);
                              response.send(tungstenite::Message::text(&string)).await.ok()?;
                          },
                          Ok(None) => {
                              println!("none")
                          },
                          Err(_) => println!("Worker threads disconnected before the solution was found!"),
                      };


                      if let Some(msg) = response.next().await {
                          let msg = msg.ok()?;
                          let msg_string =  msg.to_string();
                          let msg_string_clone = msg_string.clone();
                          if msg.is_text() || msg.is_binary() {
                              // response.send(&msg).await.ok()?;
                              response.send(tungstenite::Message::text("melo55")).await.ok()?;

                          }
                          Some((
                              (id, Progress::Advanced(54.8), msg_string_clone, sender),
                              State::Downloading {
                                  response,
                                  total,
                                  msg:msg_string,
                                  downloaded,
                                  sender:sender,
                                  receiver:receiver
                              },
                          ))
                      } else {
                          Some(((id, Progress::Errored, "Error".to_string(), sender), State::Finished))
                      }
                  },
                  State::Finished => {
                      // We do not let the stream die, as it would start a
                      // new download repeatedly if the user is not careful
                      // in case of errors.
                      let _: () = iced::futures::future::pending().await;

                      None
                  }
              }
          },
      ))
  }

and over on main.rs

Message::DownloadProgressed((id, progress, msg, mut sender)) => {
                if let Some(download) =
                    self.downloads.iter_mut().find(|download| download.id == id)
                {
                    download.progress(progress, msg);
                }



                match &mut self.sender {
                    Some(p) => {
                        p.try_send("Johny".to_string());
                        Command::none()
                    },
                    None => {
                        self.sender = Some(sender);
                        Command::none()
                    },
                }

                // sender.try_send("Johny".to_string());

                // Command::none()
            }

jbtobar avatar Sep 01 '21 21:09 jbtobar

Thanks for the example, that's really helpful.

First, Self::Output should be some sort of enum that you can then map into your applications Message to handle in update. The variants will be the different types of output you need to send back to your application. For example:

pub enum Output {
    Connected(Sender),
    DownloadProgress(Id, Progress, String),
    ...
}

Then, add a State::Disconnected where you setup the websocket connection AND the channel. The Output from that state will be Output::Conected(channel_sender). You will receive that in your application, where you can store that Sender and use it in the future to send messages back to this recipe.

After State::Disconnected, you can pass the websocket connection and channel receiver into State::Ready(WsConnection, ChannelReceiver). Always pass those 2 object forward in the stream so you can always use both.

Hopefully that makes more sense! Don't hesitate to reach back out if you need more clarification. The whole stream::unfold concept is a bit difficult to get at first. Just think of it as a giant loop where you need to continually pass your state forward to the next iteration.

tarkah avatar Sep 01 '21 21:09 tarkah

Thank you for this! This is very helpful! I think I understand what you mean. I will give the implementation a shot throughout the day and I'll see where I go.

Thank you!

jbtobar avatar Sep 02 '21 12:09 jbtobar

Your pointers were amazing - thank you so much!

I spent the first hour following the steps in the previous message with quite a bit of success I would say!

I've spent the next 7 hours stuck on one line which refers to a previous comment regarding the use of futures::stream::select.

I am currently at a loss as to how to proceed here - will continue looking for answers but if you have faced this issue before a hint would be greatly appeciated!

The essence of the issue is here (copying only relevant lines):

use iced_futures::futures::stream::select;
use iced_futures::futures::channel::mpsc;
use async_tungstenite::async_std::connect_async;

let mut response = connect_async("wss://url.com/".to_string())
                                                    .await;

let (sender, mut receiver) = mpsc::channel::<String>(0);

let mut out = select(response.0,receiver);

The error is the following:

type mismatch resolving `<iced::futures::futures_channel::mpsc::Receiver<String> as iced::futures::Stream>::Item == Result<async_tungstenite::tungstenite::Message, async_tungstenite::tungstenite::Error>`

and the source code line where this error resides is:

pub fn select<St1, St2>(stream1: St1, stream2: St2) -> Select<St1, St2>
where
    St1: Stream,
    St2: Stream<Item = St1::Item>,
{
    fn round_robin(last: &mut PollNext) -> PollNext {
        last.toggle()
    }

    assert_stream::<St1::Item, _>(Select {
        inner: select_with_strategy(stream1, stream2, round_robin),
    })
}

So it seems to me that the type of response and receiver which I am sending into select should be the same. I haven't been able to solve this.

So I tried out the following:

Instead of using:

use iced_futures::futures::channel::mpsc;
let (sender, mut receiver) = mpsc::channel::<String>(0);

I replaced with:

use async_std::{
	channel::{self, Sender},
};
let (sender, mut receiver) = channel::unbounded();

And also instead of this:

use iced_futures::futures::stream::select;
let mut out = select(response.0,receiver);

I replaced with this:

use futures::{
	future::{self, Either},
	// pin_mut, SinkExt, StreamExt,
};

let mut read_future = response.next();
let recv_future = receiver.recv();
let mut out = future::select(read_future,recv_future);

And it finally compiled!

However - I am afraid I might be getting into some messy waters. This is because what made it compile is using futures::future::select instead of futures::stream::select which was suggested above. Also using async_std::channel::unbounded instead of iced_futures::futures::channel::mpsc - I'm specially afraid of this last one because I feel it might have unintended consequences further down the road since its from async_std and not from iced_futures.

For now I will continue exploring this path to see where it leads me.

If you have any comments on this please let me know - or if you have a snipped of code where you succesfully used the select to combine a WebSocketStream and mspc::channel that would also be super helpful.

Anyway - that is that. Back to work.

Cheers and thank you so much for helping me make it this far!

jbtobar avatar Sep 02 '21 21:09 jbtobar

@jbtobar Great progress! Yeah, the requirement of futures::stream::select is that both Stream's have the same Item. You can easily work around this by importing futures::future::FutureExt which will give you access to Map.

You can then define an enum, like:

enum Response {
    Websocket("output type of websocket"),
    Channel("output type of your channel receiver"),
}

And then you can map each future into Reponse, convert that future to a stream, then pass both into select:

let mut response = connect_async("wss://url.com/".to_string())
                                                    .await;

let (sender, mut receiver) = mpsc::channel::<String>(0);

let mut out = select(
                     response.0.map(Response::Websocket).into_stream(),
                     receiver.map(Response::Channel).into_stream());

As far as using future::select, I don't see any issue with that. It's just a bit more unwieldy to work with since it returns that Either type. Easier to pattern match on the newly defined Response in my opinion.

As for using async_std channels. I doubt there is an issue with that. Just make sure you have iced compiled to use async_std as the underlying futures executor so that it's fully compatible. You can do that by enabling the async-std cargo feature link, cargo run --features async-std.

Let me know how that goes, best of luck!

tarkah avatar Sep 02 '21 23:09 tarkah

Hi all! I am very new to Iced and i want to create WS connection after CONNECT button press. What is the best practice to keep WS Stream in Application structure and how to subscribe it to channel events? How could i use default Executor for it?

serzhiio avatar Sep 03 '21 12:09 serzhiio

@tarkah you are the best!!!

The method I implemented was working but I wanted to do it following the hints you gave - and it worked! It compiles - it receives messages and sends messages. Thank you so much! I couldn't have done it without your help so I am extremely grateful you took the time to drop some insights on this thread. It can often be daunting or frustrating to embark in something like this but having the help you offered made the entire difference. I really like this project and will spend much time in the foreseeable future in these threads - I hope to be able to contribute in any way and help just like you've helped me.

Here is the code I used for this. I've seen many questions around this topic and maybe this can help others. It compiles, it receives messages, and it sends messages. Apologies about sloppy code was just trying to get it to work. The starting point was the download_progress example and I nudged it from there to accomodate the websocket.

However - please be cautious because I wrote my first Rust line 5 days ago when I embarked in this project so I don't really know what I am doing. And it you spot something bad do let me know please.

This is the download.rs file:

use iced_futures::futures;
use std::hash::{Hash, Hasher};

use async_tungstenite::async_std::connect_async;
use async_tungstenite::{tungstenite};
use futures::prelude::*;
use iced_futures::futures::channel::mpsc;
use iced_futures::futures::stream::{ StreamExt, select };
use async_std::stream::IntoStream;

use async_tungstenite::{
    WebSocketStream,
};
use async_tungstenite::async_std::ConnectStream;
use iced_futures::futures::future;


// Just a little utility function
pub fn file<I: 'static + Hash + Copy + Send>(
    id: I,
) -> iced::Subscription<(I, String, Option<mpsc::Sender<String>>)> {
    iced::Subscription::from_recipe(DownloadSub {
        id,
    })
}

pub struct DownloadSub<I> {
    id: I,
}

// Make sure iced can use our download stream
impl<H, I, T> iced_native::subscription::Recipe<H, I> for DownloadSub<T>
where
    T: 'static + Hash + Copy + Send,
    H: Hasher,
{
    type Output = (T, String, Option<mpsc::Sender<String>>);

    fn hash(&self, state: &mut H) {
        struct Marker;
        std::any::TypeId::of::<Marker>().hash(state);

        self.id.hash(state);
    }

    fn stream(
        self: Box<Self>,
        _input: futures::stream::BoxStream<'static, I>,
    ) -> futures::stream::BoxStream<'static, Self::Output> {
        let id = self.id;

        println!("stream");

        Box::pin(futures::stream::unfold(
            State::Ready,
            move |state| async move {
                println!("Box::pin");

                match state {
                    State::Ready => {
                        let (sender, receiver) = mpsc::channel::<String>(0);
                        // let (sender, receiver) = channel::unbounded();

                        let response = connect_async("wss://websocketurl.com/".to_string())
                                                    .await;


                        match response {
                            Ok(mut response) => {
                                response.0.send(tungstenite::Message::text("melo")).await.expect("Could not Send");
                                Some((
                                    (id, "Start".to_string(), Some(sender)),
                                    State::Downloading {
                                        response: response.0,
                                        receiver
                                    },
                                ))
                            }
                            Err(_) => {
                                Some(((id, "ERROR".to_string(), None), State::Finished))
                            }
                        }
                    }
                    State::Downloading {
                        mut response,
                        mut receiver,
                        ..
                    } => {
                        let mut out = select(
                             (&mut response).map(Response::Websocket).into_stream(),
                             (&mut receiver).map(Response::Channel).into_stream()
                         );

                         match out.next().await {
                             Some(msg) => {
                                 match msg {
                                     Response::Websocket(wmsg) => {
                                         match wmsg {
                                             Ok(m) => {
                                                 let msg_string =  m.to_string();
                                                 Some((
                                                     (id, msg_string, None),
                                                     State::Downloading {
                                                         response,
                                                         receiver
                                                     },
                                                 ))
                                             }
                                             Err(_) => {
                                                 Some((
                                                     (id, "msg_string_clone".to_string(), None),
                                                     State::Downloading {
                                                         response,
                                                         receiver
                                                     },
                                                 ))
                                             }
                                         }
                                     }
                                     Response::Channel(mstr) => {
                                         println!("{}", mstr);
                                         response.send(tungstenite::Message::text(&mstr)).await.ok()?;
                                         Some((
                                             (id, mstr, None),
                                             State::Downloading {
                                                 response,
                                                 receiver
                                             },
                                         ))
                                     }

                                 }

                             }
                             _ => {
                                 Some((
                                     (id, "msg_string_clone".to_string(), None),
                                     State::Downloading {
                                         response,
                                         receiver
                                     },
                                 ))
                             }

                         }
                    },

                    State::Finished => {
                        // We do not let the stream die, as it would start a
                        // new download repeatedly if the user is not careful
                        // in case of errors.
                        let _: () = iced::futures::future::pending().await;

                        None
                    }
                }
            },
        ))
    }
}

enum Response {
    Websocket(Result<async_tungstenite::tungstenite::Message, async_tungstenite::tungstenite::Error>),
    Channel(String),
}


pub enum State {
    Ready,
    Downloading {
        response:WebSocketStream<ConnectStream>,
        receiver:mpsc::Receiver<String>
    },
    Finished,
}

This is the main.rs file:

use iced::{
    button, executor, Align, Application, Button, Clipboard, Column, Command,
    Container, Element, Length, ProgressBar, Settings, Subscription, Text,
    Color
};
use iced_futures::futures::channel::mpsc;
mod download;

pub fn main() -> iced::Result {
    Example::run(Settings::default())
}

#[derive(Debug)]
struct Example {
    socket_status_message:String,
    socket_message:String,
    sender:Option<mpsc::Sender<String>>,
    state: State,
}

#[derive(Debug)]
enum State {
    Idle { button: button::State },
    Connecting { button: button::State },
    Connected { button: button::State },
}

#[derive(Debug, Clone)]
pub enum Message {
    ConnectSocket,
    DownloadProgressed((usize, String, Option<mpsc::Sender<String>> )),
    SendMessage
}

impl Application for Example {
    type Executor = executor::Default;
    type Message = Message;
    type Flags = ();

    fn new(_flags: ()) -> (Example, Command<Message>) {
        (
            Example {
                socket_status_message:"disconnected".to_string(),
                socket_message:"none".to_string(),
                sender: None,
                state: State::Idle {
                    button: button::State::new(),
                },
            },
            Command::none(),
        )
    }

    fn title(&self) -> String {
        String::from("Download progress - Iced")
    }

    fn background_color(&self) -> Color {
        return Color::from_rgb(
            0x40 as f32 / 255.0,
            0x44 as f32 / 255.0,
            0x4B as f32 / 255.0,
        );
    }

    fn update(
        &mut self,
        message: Message,
        _clipboard: &mut Clipboard,
    ) -> Command<Message> {
        match message {
            Message::ConnectSocket => {
                self.state = State::Connecting {
                    button: button::State::new(),
                };
                Command::none()
            }
            Message::SendMessage => {
                match &mut self.sender {
                    Some(sender) => {
                        sender.try_send("pengu".to_string());
                        Command::none()
                    }
                    None => {
                        self.socket_status_message = "no sender".to_string();
                        Command::none()
                    }
                }
                // Command::none()
            }
            Message::DownloadProgressed((id, msg, sender)) => {
                match sender {
                    Some(sender) => {
                        self.socket_message = msg;
                        self.sender = Some(sender);
                    }
                    None => {
                        self.socket_message = msg;
                    }
                };
                Command::none()
            }
        }
        // Command::none()
    }

    fn subscription(&self) -> Subscription<Message> {
        match self.state {
            State::Connecting { .. } => {
                download::file(0)
                    .map(Message::DownloadProgressed)

            }
            _ => Subscription::none(),
        }
    }

    fn view(&mut self) -> Element<Message> {

        let control: Element<_> = match &mut self.state {
            State::Idle { button } => {
                Button::new(button, Text::new("Connect"))
                    .on_press(Message::ConnectSocket)
                    .into()
            }
            State::Connecting { button } => Column::new()
                .spacing(10)
                .align_items(Align::Center)
                // .push(Text::new("Download finished!"))
                .push(
                    Button::new(button, Text::new("Connecting"))
                        .on_press(Message::SendMessage),
                )
                .into(),
            State::Connected { button } => Column::new()
                .spacing(10)
                .align_items(Align::Center)
                // .push(Text::new("Something went wrong :("))
                .push(
                    Button::new(button, Text::new("Connected"))
                        // .on_press(Message::Download(self.id)),
                )
                .into(),
        };

        Container::new(
                Column::new()
                    .push(Text::new(&self.socket_status_message))
                    .push(Text::new(&self.socket_message))
                    .push(control)
            )
            .width(Length::Fill)
            .height(Length::Fill)
            .center_x()
            .center_y()
            .padding(20)
            .into()
    }
}

Again, @tarkah - thank you!!! 🙏🏻

jbtobar avatar Sep 03 '21 16:09 jbtobar

@jbtobar It was my pleasure! Pretty amazing work considering you've just touched Rust for the first time.

One last recommendation. Change the type Output to an enum, where you can encode the different output types instead of trying to return all the different outputs each time.

enum Output {
    Sender(mpsc::Sender<String>),
    Websocket(usize, String),
}

tarkah avatar Sep 03 '21 16:09 tarkah