use std::{
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use futures::{Stream, StreamExt};
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use crate::{
stop::StopToken,
types::{AllowedUpdate, Update},
update_listeners::{Polling, PollingBuilder, UpdateListener},
Bot, RequestError,
};
pub trait UpdateStreamExt {
fn update_stream(&self) -> UpdateStreamBuilder;
}
impl UpdateStreamExt for Bot {
fn update_stream(&self) -> UpdateStreamBuilder {
UpdateStreamBuilder(Polling::builder(self.clone()).timeout(Duration::from_secs(10)))
}
}
#[must_use = "the builder does nothing until build is called"]
pub struct UpdateStreamBuilder(PollingBuilder<Bot>);
impl UpdateStreamBuilder {
pub fn timeout(self, timeout: Duration) -> Self {
Self(self.0.timeout(timeout))
}
#[track_caller]
pub fn limit(self, limit: u8) -> Self {
Self(self.0.limit(limit))
}
pub fn allowed_updates(self, allowed: Vec<AllowedUpdate>) -> Self {
Self(self.0.allowed_updates(allowed))
}
pub fn drop_pending_updates(self) -> Self {
Self(self.0.drop_pending_updates())
}
pub async fn build(self) -> UpdateStream {
UpdateStream::from_listener(self.0.delete_webhook().await.build())
}
}
#[must_use = "streams do nothing unless consumed"]
pub struct UpdateStream<E = RequestError> {
receiver: ReceiverStream<Result<Update, E>>,
stop: StopToken,
}
impl<E> UpdateStream<E> {
pub fn from_listener<L>(mut listener: L) -> Self
where
L: UpdateListener<Err = E> + Send + 'static,
E: Send + 'static,
{
let stop = listener.stop_token();
let (send, receive) = mpsc::channel(1);
tokio::spawn(async move {
let mut stream = std::pin::pin!(listener.as_stream());
while let Ok(permit) = send.reserve().await {
let item = tokio::select! {
item = stream.next() => item,
_ = send.closed() => break,
};
let Some(item) = item else { break };
permit.send(item);
}
});
Self { receiver: ReceiverStream::new(receive), stop }
}
pub fn shutdown(&self) {
self.stop.stop();
}
}
impl<E> Stream for UpdateStream<E> {
type Item = Result<Update, E>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.receiver.poll_next_unpin(cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.receiver.size_hint()
}
}
impl<E> Drop for UpdateStream<E> {
fn drop(&mut self) {
self.shutdown();
}
}
#[cfg(test)]
mod tests {
use futures::stream;
use super::*;
use crate::{stop::mk_stop_token, update_listeners::StatefulListener};
#[tokio::test]
async fn shutdown_drains_items_and_signals_listener() {
let (token, flag) = mk_stop_token();
let listener = StatefulListener::new(
token,
|_: &mut StopToken| stream::iter([Err::<Update, _>(1), Err(2)]),
|token: &mut StopToken| token.clone(),
);
let mut updates = UpdateStream::from_listener(listener);
updates.shutdown();
assert!(flag.is_stopped());
assert_eq!(updates.next().await.unwrap().unwrap_err(), 1);
assert_eq!(updates.next().await.unwrap().unwrap_err(), 2);
assert!(updates.next().await.is_none());
}
#[tokio::test]
async fn dropping_stream_signals_listener() {
let (token, flag) = mk_stop_token();
let listener = StatefulListener::new(
token,
|_: &mut StopToken| stream::pending::<Result<Update, ()>>(),
|token: &mut StopToken| token.clone(),
);
drop(UpdateStream::from_listener(listener));
assert!(flag.is_stopped());
}
}