teloxide/
update_stream.rs1use 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
51pub trait UpdateStreamExt {
53 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#[must_use = "the builder does nothing until build is called"]
68pub struct UpdateStreamBuilder(PollingBuilder<Bot>);
69
70impl UpdateStreamBuilder {
71 pub fn timeout(self, timeout: Duration) -> Self {
73 Self(self.0.timeout(timeout))
74 }
75
76 #[track_caller]
78 pub fn limit(self, limit: u8) -> Self {
79 Self(self.0.limit(limit))
80 }
81
82 pub fn allowed_updates(self, allowed: Vec<AllowedUpdate>) -> Self {
84 Self(self.0.allowed_updates(allowed))
85 }
86
87 pub fn drop_pending_updates(self) -> Self {
89 Self(self.0.drop_pending_updates())
90 }
91
92 pub async fn build(self) -> UpdateStream {
94 UpdateStream::from_listener(self.0.delete_webhook().await.build())
95 }
96}
97
98#[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 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 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 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 drop(router);
245 }
246}