Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document cancellation safety of EventStream #936

Open
LeoniePhiline opened this issue Oct 23, 2024 · 0 comments
Open

Document cancellation safety of EventStream #936

LeoniePhiline opened this issue Oct 23, 2024 · 0 comments

Comments

@LeoniePhiline
Copy link

LeoniePhiline commented Oct 23, 2024

While documenting cancellation safety at uses of select! in my crates, I found it unclear if EventStream is cancellation safe.

I.e. in the following event loop:

pub async fn event_loop(&self, tick: u64) -> Result<()> {
    let mut terminal = self.take_terminal().await?;

    // Stream input events (Keyboard, Mouse, Resize)
    let mut reader = EventStream::new();

    // Prepare render tick interval
    let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(tick));
    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);

    self.render(&mut terminal).await?;

    loop {
        tokio::select! {
            biased;

            // Handle streamed input events as they occur
            maybe_event = reader.next() => match maybe_event {
                Some(Ok(ref event)) => if ! Self::handle_event(event) { break },
                // Event reader poll error, e.g. initialization failure, or interrupt
                Some(Err(e)) => return Err(eyre!(e)),
                // End of event stream
                None => break,
            },

            // Render every N milliseconds
            _ = interval.tick() => self.render(&mut terminal).await.map(|_| ())?
        }
    }
    Self::release_terminal(terminal)
}

If an event just becomes available as the interval tick select branch completes, the event stream reader poll is cancelled.

Is there a chance that events may get lost at cancellation?

Reading through the code, it appeared to me as if EventStream was indeed cancellation safe (with InternalEventReader keeping track of events (VecDeque) and skipped_events (Vec) which are only drained during an explicit read). However, I felt it was best to confirm with the original author.

I will be glad to contribute a cancellation safety documentation after your confirmation. (In case you have doubts regarding cancellation safety, then we should document this uncertainty as well.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant