Skip to main content

teloxide/
update_stream.rs

1//! Receive Telegram updates as a [`futures::Stream`] without a dispatcher.
2//!
3//! ```no_run
4//! use futures::StreamExt;
5//! use teloxide::{prelude::*, types::UpdateKind};
6//!
7//! #[tokio::main]
8//! async fn main() {
9//!     let bot = Bot::from_env();
10//!     let mut updates = bot.update_stream().build().await;
11//!
12//!     while let Some(item) = updates.next().await {
13//!         match item {
14//!             Ok(update) => {
15//!                 if let UpdateKind::Message(message) = update.kind {
16//!                     if let Some(text) = message.text() {
17//!                         bot.send_message(text)
18//!                             .chat_id(message.chat.id)
19//!                             .await
20//!                             .log_on_error()
21//!                             .await;
22//!                     }
23//!                 }
24//!             }
25//!             Err(error) => log::error!("Could not receive update: {error}"),
26//!         }
27//!     }
28//! }
29//! ```
30//!
31//! For a manually configured polling listener or a webhook listener, use
32//! [`UpdateStream::from_listener`] instead.
33
34use std::{
35    pin::Pin,
36    task::{Context, Poll},
37    time::Duration,
38};
39
40use futures::{Stream, StreamExt};
41use tokio::sync::mpsc;
42use tokio_stream::wrappers::ReceiverStream;
43
44use crate::{
45    stop::StopToken,
46    types::{AllowedUpdate, Update},
47    update_listeners::{Polling, PollingBuilder, UpdateListener},
48    Bot, RequestError,
49};
50
51/// Adds [`update_stream`](Self::update_stream) to [`Bot`].
52pub trait UpdateStreamExt {
53    /// Configures a stream backed by long polling, with a 10-second polling
54    /// timeout by default.
55    ///
56    /// Do not run another polling consumer for the same bot concurrently.
57    fn update_stream(&self) -> UpdateStreamBuilder;
58}
59
60impl UpdateStreamExt for Bot {
61    fn update_stream(&self) -> UpdateStreamBuilder {
62        UpdateStreamBuilder(Polling::builder(self.clone()).timeout(Duration::from_secs(10)))
63    }
64}
65
66/// Configures a long-polling [`UpdateStream`].
67#[must_use = "the builder does nothing until build is called"]
68pub struct UpdateStreamBuilder(PollingBuilder<Bot>);
69
70impl UpdateStreamBuilder {
71    /// Sets the long polling timeout. Defaults to 10 seconds.
72    pub fn timeout(self, timeout: Duration) -> Self {
73        Self(self.0.timeout(timeout))
74    }
75
76    /// Sets how many updates to retrieve per request. Panics outside `1..=100`.
77    #[track_caller]
78    pub fn limit(self, limit: u8) -> Self {
79        Self(self.0.limit(limit))
80    }
81
82    /// Selects the update types to receive.
83    pub fn allowed_updates(self, allowed: Vec<AllowedUpdate>) -> Self {
84        Self(self.0.allowed_updates(allowed))
85    }
86
87    /// Drops pending updates on startup.
88    pub fn drop_pending_updates(self) -> Self {
89        Self(self.0.drop_pending_updates())
90    }
91
92    /// Removes any configured webhook (logging errors) and starts polling.
93    pub async fn build(self) -> UpdateStream {
94        UpdateStream::from_listener(self.0.delete_webhook().await.build())
95    }
96}
97
98/// A stream yielding updates and errors from an update listener.
99///
100/// The listener runs in a Tokio task, forwarding items through a bounded
101/// channel. Polling errors are yielded as items, not treated as stream end.
102#[must_use = "streams do nothing unless consumed"]
103pub struct UpdateStream<E = RequestError> {
104    receiver: ReceiverStream<Result<Update, E>>,
105    stop: StopToken,
106}
107
108impl<E> UpdateStream<E> {
109    /// Runs an existing [`UpdateListener`] as an owned stream.
110    ///
111    /// This must be called from within a Tokio runtime. For example, with the
112    /// `webhooks-axum` feature, pass the listener returned by
113    /// `teloxide::update_listeners::webhooks::axum` to this method.
114    pub fn from_listener<L>(mut listener: L) -> Self
115    where
116        L: UpdateListener<Err = E> + Send + 'static,
117        E: Send + 'static,
118    {
119        let stop = listener.stop_token();
120        let (send, receive) = mpsc::channel(1);
121
122        tokio::spawn(async move {
123            let mut stream = std::pin::pin!(listener.as_stream());
124
125            // Wait for capacity before asking the listener for the next item.
126            while let Ok(permit) = send.reserve().await {
127                let item = tokio::select! {
128                    item = stream.next() => item,
129                    _ = send.closed() => break,
130                };
131                let Some(item) = item else { break };
132                permit.send(item);
133            }
134        });
135
136        Self { receiver: ReceiverStream::new(receive), stop }
137    }
138
139    /// Signals the listener to stop. Keep reading until the stream returns
140    /// `None` so the listener can finish shutting down and buffered items can
141    /// be delivered. Dropping the stream also signals the listener to stop,
142    /// but does not wait for graceful shutdown.
143    pub fn shutdown(&self) {
144        self.stop.stop();
145    }
146}
147
148impl<E> Stream for UpdateStream<E> {
149    type Item = Result<Update, E>;
150
151    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
152        self.receiver.poll_next_unpin(cx)
153    }
154
155    fn size_hint(&self) -> (usize, Option<usize>) {
156        self.receiver.size_hint()
157    }
158}
159
160impl<E> Drop for UpdateStream<E> {
161    fn drop(&mut self) {
162        self.shutdown();
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use futures::stream;
169
170    use super::*;
171    use crate::{stop::mk_stop_token, update_listeners::StatefulListener};
172
173    #[tokio::test]
174    async fn shutdown_drains_items_and_signals_listener() {
175        let (token, flag) = mk_stop_token();
176        let listener = StatefulListener::new(
177            token,
178            |_: &mut StopToken| stream::iter([Err::<Update, _>(1), Err(2)]),
179            |token: &mut StopToken| token.clone(),
180        );
181        let mut updates = UpdateStream::from_listener(listener);
182
183        updates.shutdown();
184        assert!(flag.is_stopped());
185        assert_eq!(updates.next().await.unwrap().unwrap_err(), 1);
186        assert_eq!(updates.next().await.unwrap().unwrap_err(), 2);
187        assert!(updates.next().await.is_none());
188    }
189
190    #[tokio::test]
191    async fn dropping_stream_signals_listener() {
192        let (token, flag) = mk_stop_token();
193        let listener = StatefulListener::new(
194            token,
195            |_: &mut StopToken| stream::pending::<Result<Update, ()>>(),
196            |token: &mut StopToken| token.clone(),
197        );
198        drop(UpdateStream::from_listener(listener));
199        assert!(flag.is_stopped());
200    }
201
202    #[cfg(feature = "webhooks-axum")]
203    #[tokio::test]
204    async fn webhook_shutdown_drains_and_ends_while_router_is_alive() {
205        use axum::{body::Body, http::Request, response::Response};
206        use tokio::time::timeout;
207        use tower::Service;
208
209        use crate::update_listeners::webhooks::{axum_no_setup, Options};
210
211        let options = Options::new(
212            "127.0.0.1:0".parse().unwrap(),
213            "https://example.test/webhook".parse().unwrap(),
214        )
215        .without_secret_token_check();
216        let (listener, stop, mut router) = axum_no_setup(options);
217        let stop = tokio::spawn(stop);
218
219        for id in [1, 2] {
220            let response: Response = router
221                .call(
222                    Request::post("/webhook")
223                        .body(Body::from(format!(r#"{{"update_id":{id}}}"#)))
224                        .unwrap(),
225                )
226                .await
227                .unwrap();
228            assert!(response.status().is_success());
229        }
230
231        let mut updates = UpdateStream::from_listener(listener);
232        updates.shutdown();
233        timeout(Duration::from_secs(5), async {
234            for id in [1, 2] {
235                assert_eq!(updates.next().await.unwrap().unwrap().id.0, id);
236            }
237            assert!(updates.next().await.is_none());
238            stop.await.unwrap();
239        })
240        .await
241        .unwrap();
242
243        // The router is still alive; no HTTP request was needed to close the stream.
244        drop(router);
245    }
246}