diff --git a/Cargo.lock b/Cargo.lock index 769df637..ec29bc99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2316,6 +2316,7 @@ dependencies = [ "base64", "carapax", "crc", + "futures-util", "html-escape", "html5ever", "openplotva-updates", diff --git a/crates/openplotva-app/src/asr.rs b/crates/openplotva-app/src/asr.rs index ebf9e7cd..0e521981 100644 --- a/crates/openplotva-app/src/asr.rs +++ b/crates/openplotva-app/src/asr.rs @@ -11,7 +11,6 @@ use std::{ }; use base64::{Engine as _, engine::general_purpose}; -use futures_util::StreamExt; use openplotva_core::{ChatAttachment, ChatMessageMeta}; use openplotva_dialog::DialogInput; use openplotva_llm::{ @@ -30,7 +29,7 @@ use openplotva_taskman::{ ASR_GPU1_QUEUE_NAME, AsrJobParams, InMemoryTaskQueue, JobType, asr_job_params_from_stateless_job, new_asr_job_at, }; -use openplotva_telegram::TelegramClient; +use openplotva_telegram::{TelegramClient, TelegramFileError}; use serde::{Deserialize, Serialize}; use thiserror::Error; use time::OffsetDateTime; @@ -171,30 +170,14 @@ impl TelegramVoiceDownloader for TelegramClientVoiceDownloader { latest_file_id: &'a str, ) -> TelegramVoiceDownloadFuture<'a, Self::Error> { Box::pin(async move { - let file: carapax::types::File = self - .client - .execute(carapax::types::GetFile::new(latest_file_id)) - .await - .map_err(TelegramVoiceDownloadError::GetFile)?; - let file_path = file - .file_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or(TelegramVoiceDownloadError::MissingFilePath)?; - let mut stream = self - .client - .download_file(file_path) - .await - .map_err(TelegramVoiceDownloadError::Download)?; - let mut data = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(TelegramVoiceDownloadError::DownloadChunk)?; - if data.len().saturating_add(chunk.len()) > ASR_MAX_MEDIA_BYTES { - return Err(TelegramVoiceDownloadError::FileTooLarge); - } - data.extend_from_slice(&chunk); - } + let file_path = + openplotva_telegram::get_telegram_file_path(&self.client, latest_file_id).await?; + let data = openplotva_telegram::download_telegram_file( + &self.client, + &file_path, + ASR_MAX_MEDIA_BYTES, + ) + .await?; if data.is_empty() { return Err(TelegramVoiceDownloadError::EmptyFile); } @@ -205,20 +188,23 @@ impl TelegramVoiceDownloader for TelegramClientVoiceDownloader { #[derive(Debug, Error)] pub enum TelegramVoiceDownloadError { - #[error("get telegram file: {0}")] - GetFile(#[source] carapax::api::ExecuteError), - #[error("telegram file has no downloadable path")] - MissingFilePath, - #[error("download telegram file: {0}")] - Download(#[source] carapax::api::DownloadFileError), - #[error("download telegram file chunk: {0}")] - DownloadChunk(#[source] reqwest::Error), + #[error(transparent)] + File(TelegramFileError), #[error("empty telegram voice file")] EmptyFile, #[error("telegram media exceeds 20 MiB")] FileTooLarge, } +impl From for TelegramVoiceDownloadError { + fn from(error: TelegramFileError) -> Self { + match error { + TelegramFileError::TooLarge { .. } => Self::FileTooLarge, + error => Self::File(error), + } + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub struct AsrRequest { pub chat_id: i64, diff --git a/crates/openplotva-app/src/dialog_tools.rs b/crates/openplotva-app/src/dialog_tools.rs index 2c32ad1e..40ddff29 100644 --- a/crates/openplotva-app/src/dialog_tools.rs +++ b/crates/openplotva-app/src/dialog_tools.rs @@ -280,15 +280,10 @@ impl ImageEditFileProbe for TelegramBotFileProbe { if file_id.is_empty() { return Ok(false); } - let file: carapax::types::File = self - .client - .execute(carapax::types::GetFile::new(file_id)) + let file = openplotva_telegram::get_telegram_file(&self.client, file_id) .await .map_err(|error| Box::new(error) as ToolboxError)?; - Ok(file - .file_path - .as_deref() - .is_some_and(|path| !path.trim().is_empty())) + Ok(openplotva_telegram::telegram_file_path(&file).is_some()) }) } } diff --git a/crates/openplotva-app/src/image_edit_references.rs b/crates/openplotva-app/src/image_edit_references.rs index 60044d2c..eb4542af 100644 --- a/crates/openplotva-app/src/image_edit_references.rs +++ b/crates/openplotva-app/src/image_edit_references.rs @@ -4,12 +4,11 @@ use std::{fmt, future::Future, io::Cursor, pin::Pin, sync::Arc}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; -use futures_util::StreamExt; use image::{ DynamicImage, ImageDecoder, ImageReader, Limits, Rgb, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType, metadata::Orientation, }; -use openplotva_telegram::TelegramClient; +use openplotva_telegram::{TelegramClient, TelegramFileError}; use crate::image_jobs::{ImageEditError, ImageEditFuture, ImageEditRequest, ImageEditor}; @@ -45,32 +44,22 @@ impl TelegramImageEditReferenceLoader { } async fn file_path(&self, file_id: &str) -> Result { - let file: carapax::types::File = self - .client - .execute(carapax::types::GetFile::new(file_id)) + openplotva_telegram::get_telegram_file_path(&self.client, file_id) .await - .map_err(|error| format!("get telegram file: {error}"))?; - file.file_path - .map(|path| path.trim().to_owned()) - .filter(|path| !path.is_empty()) - .ok_or_else(|| "telegram file_path is empty".to_owned()) + .map_err(|error| error.to_string()) } async fn download(&self, file_path: &str) -> Result, String> { - let mut stream = self - .client - .download_file(file_path) + openplotva_telegram::download_telegram_file(&self.client, file_path, MAX_REFERENCE_BYTES) .await - .map_err(|_| "download telegram file failed".to_owned())?; - let mut data = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(|_| "download telegram file chunk failed".to_owned())?; - if data.len().saturating_add(chunk.len()) > MAX_REFERENCE_BYTES { - return Err("telegram image exceeds 20 MiB".to_owned()); - } - data.extend_from_slice(&chunk); - } - Ok(data) + .map_err(|error| match error { + TelegramFileError::TooLarge { .. } => "telegram image exceeds 20 MiB".to_owned(), + TelegramFileError::DownloadTimedOut(_) => error.to_string(), + TelegramFileError::DownloadChunk(_) => { + "download telegram file chunk failed".to_owned() + } + _ => "download telegram file failed".to_owned(), + }) } } diff --git a/crates/openplotva-app/src/image_jobs.rs b/crates/openplotva-app/src/image_jobs.rs index fe986640..9298a8c0 100644 --- a/crates/openplotva-app/src/image_jobs.rs +++ b/crates/openplotva-app/src/image_jobs.rs @@ -92,6 +92,10 @@ pub const AIFARM_DRAW_API_DEFAULT_CAPACITY_WAIT: StdDuration = StdDuration::from const AIFARM_DRAW_API_SUBMIT_MARGIN: StdDuration = StdDuration::from_secs(30); const AIFARM_DRAW_API_POLL_TIMEOUT: StdDuration = StdDuration::from_secs(30); const AIFARM_DRAW_API_MAX_POLL_RETRY_DELAY: StdDuration = StdDuration::from_secs(10); +/// Bound for one Telegram call made by a media generation worker. The worker +/// holds the accelerator slot while it waits, and the shared HTTP timeout is +/// sized for the `getUpdates` long poll. +pub const MEDIA_JOB_TELEGRAM_TIMEOUT: StdDuration = StdDuration::from_secs(30); pub const STICKER_DOWN_FILE_ID: &str = "CAACAgIAAxkBAAEeROBkDjnz1i3WxxyNLBgWA_IKyjxbnQACuioAAqPicEh1C96_WINTHS8E"; pub const NSFW_BLOCKED_MESSAGE_TEXT: &str = "Ваш запрос заблокирован, так как содержит неприемлемый контент. Попробуйте переформулировать запрос."; @@ -2445,13 +2449,27 @@ impl ImageJobTelegramSender for openplotva_telegram::TelegramClient { method: TelegramOutboundMethod, ) -> ImageJobEffectFuture<'a, Result> { Box::pin(async move { - execute_telegram_method(self, method) - .await + within_media_job_telegram_timeout(execute_telegram_method(self, method)) + .await? .map_err(|error| error.to_string()) }) } } +/// Run one Telegram call of a media generation worker within [`MEDIA_JOB_TELEGRAM_TIMEOUT`]. +pub(crate) async fn within_media_job_telegram_timeout( + call: impl Future, +) -> Result { + tokio::time::timeout(MEDIA_JOB_TELEGRAM_TIMEOUT, call) + .await + .map_err(|_| { + format!( + "telegram request timed out after {}s", + MEDIA_JOB_TELEGRAM_TIMEOUT.as_secs() + ) + }) +} + pub trait ImageJobEffects { #[allow(clippy::too_many_arguments)] fn offer_utility_ad<'a>( @@ -3465,7 +3483,7 @@ where { Ok(_) => filled += 1, Err(error) => { - tracing::debug!(%error, "progressive placeholder fill failed"); + tracing::warn!(chat_id, %error, "image placeholder fill failed"); } } } @@ -10171,6 +10189,17 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn media_job_telegram_call_gives_up_after_the_bound() { + let started = tokio::time::Instant::now(); + + let hung = within_media_job_telegram_timeout(std::future::pending::<()>()).await; + + assert_eq!(hung, Err("telegram request timed out after 30s".to_owned())); + assert_eq!(started.elapsed(), MEDIA_JOB_TELEGRAM_TIMEOUT); + assert_eq!(within_media_job_telegram_timeout(async { 7 }).await, Ok(7)); + } + #[tokio::test] async fn fallback_image_generator_uses_primary_success_without_fallback() { let primary = GeneratorStub::success("https://primary-image.test/1.png"); diff --git a/crates/openplotva-app/src/music_jobs.rs b/crates/openplotva-app/src/music_jobs.rs index 8c8efe76..be548549 100644 --- a/crates/openplotva-app/src/music_jobs.rs +++ b/crates/openplotva-app/src/music_jobs.rs @@ -5,7 +5,6 @@ use std::{ collections::BTreeMap, fmt, future::Future, pin::Pin, sync::Arc, time::Duration as StdDuration, }; -use futures_util::StreamExt; use openplotva_config::AppConfig; use openplotva_llm::{ aifarm::{AifarmHttpTransport, AifarmStructuredJsonGenerator, StatusUpdate}, @@ -901,26 +900,12 @@ impl MusicTelegramSender for openplotva_telegram::TelegramClient { file_id: &'a str, ) -> MusicJobEffectFuture<'a, Result, String>> { Box::pin(async move { - let file: carapax::types::File = self - .execute(carapax::types::GetFile::new(file_id)) + let file_path = openplotva_telegram::get_telegram_file_path(self, file_id) .await .map_err(|error| error.to_string())?; - let file_path = file - .file_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or_else(|| "telegram file_path is empty".to_owned())?; - let mut stream = self - .download_file(file_path) + openplotva_telegram::download_telegram_file(self, &file_path, usize::MAX) .await - .map_err(|error| error.to_string())?; - let mut data = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(|error| error.to_string())?; - data.extend_from_slice(&chunk); - } - Ok(data) + .map_err(|error| error.to_string()) }) } } diff --git a/crates/openplotva-app/src/python_sandbox.rs b/crates/openplotva-app/src/python_sandbox.rs index c1c3a0d3..c1ea5bbe 100644 --- a/crates/openplotva-app/src/python_sandbox.rs +++ b/crates/openplotva-app/src/python_sandbox.rs @@ -8,14 +8,14 @@ use std::{collections::BTreeSet, future::Future, path::Path, pin::Pin, sync::Arc}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; -use futures_util::StreamExt; use openplotva_dialog::{PythonRunRequest, TOOL_RESULT_STATUS_OK, ToolContext, ToolResult}; use openplotva_sandbox::api::{InputFile, RunRequest, RunResponse, Termination}; use openplotva_sandbox::client::{SandboxClient, SandboxClientError}; use openplotva_storage::{PostgresTelegramFileStore, TelegramFileRecord}; use openplotva_telegram::{ AudioMessageRequest, AudioSource, ChatRef, MediaGroupMessageRequest, MediaGroupPhotoItem, - PhotoMessageRequest, PhotoSource, ReplyParametersPlan, TelegramClient, UploadMessageRequest, + PhotoMessageRequest, PhotoSource, ReplyParametersPlan, TelegramClient, TelegramFileError, + UploadMessageRequest, }; use serde::Serialize; use serde_json::{Map, Value, json}; @@ -689,9 +689,7 @@ impl TelegramSandboxIo { } async fn download(&self, file_id: &str) -> Result<(Vec, String), ChatFileError> { - let file: carapax::types::File = self - .telegram - .execute(carapax::types::GetFile::new(file_id)) + let file = openplotva_telegram::get_telegram_file(&self.telegram, file_id) .await .map_err(|error| ChatFileError::Failed(format!("getFile failed: {error}")))?; if let Some(size) = file.file_size.and_then(|size| u64::try_from(size).ok()) @@ -702,32 +700,19 @@ impl TelegramSandboxIo { limit: MAX_INPUT_FILE_BYTES, }); } - let path = file - .file_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or_else(|| ChatFileError::Failed("Telegram returned no file path".to_owned()))? - .to_owned(); - let mut stream = self - .telegram - .download_file(&path) + let path = openplotva_telegram::telegram_file_path(&file) + .ok_or_else(|| ChatFileError::Failed("Telegram returned no file path".to_owned()))?; + let limit = usize::try_from(MAX_INPUT_FILE_BYTES).unwrap_or(usize::MAX); + let bytes = openplotva_telegram::download_telegram_file(&self.telegram, path, limit) .await - .map_err(|error| ChatFileError::Failed(format!("download failed: {error}")))?; - let mut bytes = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk - .map_err(|error| ChatFileError::Failed(format!("download failed: {error}")))?; - let size = (bytes.len() + chunk.len()) as u64; - if size > MAX_INPUT_FILE_BYTES { - return Err(ChatFileError::TooLarge { - size, + .map_err(|error| match error { + TelegramFileError::TooLarge { received, .. } => ChatFileError::TooLarge { + size: received as u64, limit: MAX_INPUT_FILE_BYTES, - }); - } - bytes.extend_from_slice(&chunk); - } - Ok((bytes, file_extension(&path))) + }, + error => ChatFileError::Failed(format!("download failed: {error}")), + })?; + Ok((bytes, file_extension(path))) } async fn send( diff --git a/crates/openplotva-app/src/video_jobs.rs b/crates/openplotva-app/src/video_jobs.rs index aef21897..92744359 100644 --- a/crates/openplotva-app/src/video_jobs.rs +++ b/crates/openplotva-app/src/video_jobs.rs @@ -206,9 +206,9 @@ where ) -> VideoJobFuture<'a, Result, String>> { Box::pin(async move { let method = animation_method(&delivery)?; - self.telegram - .execute(method) + crate::image_jobs::within_media_job_telegram_timeout(self.telegram.execute(method)) .await + .map_err(|error| format!("send video: {error}"))? .map(|message| i32::try_from(message.id).ok()) .map_err(|error| format!("send video: {error}")) }) diff --git a/crates/openplotva-app/src/vision.rs b/crates/openplotva-app/src/vision.rs index 797ddc10..8b48dc65 100644 --- a/crates/openplotva-app/src/vision.rs +++ b/crates/openplotva-app/src/vision.rs @@ -3,7 +3,6 @@ use std::{fmt, future::Future, io::Cursor, pin::Pin, sync::Arc, time::Duration}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; -use futures_util::StreamExt; use image::{GenericImageView, ImageFormat, ImageReader, Limits, imageops::FilterType}; use openplotva_config::AppConfig; use openplotva_core::ChatAttachment; @@ -21,7 +20,7 @@ use openplotva_storage::{ TelegramFileMetadataUpsert, TelegramFileRecord, TelegramFileVisionUpdate, VisionDescriptionUpdate, }; -use openplotva_telegram::TelegramClient; +use openplotva_telegram::{TelegramClient, TelegramFileError}; use thiserror::Error; use time::OffsetDateTime; @@ -683,33 +682,27 @@ impl TelegramVisionDataUrlProvider for TelegramClientVisionDataUrlProvider { ) -> TelegramVisionDataUrlFuture<'a, Self::Error> { Box::pin(async move { let video = vision_media_is_video(media_kind, mime_type); - let file: carapax::types::File = self - .client - .execute(carapax::types::GetFile::new(latest_file_id)) - .await - .map_err(TelegramVisionDataUrlError::GetFile)?; - let file_path = file - .file_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()) - .ok_or(TelegramVisionDataUrlError::MissingFilePath)?; - let mut stream = self - .client - .download_file(file_path) - .await - .map_err(TelegramVisionDataUrlError::Download)?; - let mut data = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(TelegramVisionDataUrlError::DownloadChunk)?; - if video && data.len().saturating_add(chunk.len()) > VISION_MAX_VIDEO_BYTES { - return Err(TelegramVisionDataUrlError::VideoTooLarge); - } - if !video && data.len().saturating_add(chunk.len()) > VISION_MAX_IMAGE_BYTES { - return Err(TelegramVisionDataUrlError::ImageTooLarge); - } - data.extend_from_slice(&chunk); - } + let file_path = + openplotva_telegram::get_telegram_file_path(&self.client, latest_file_id) + .await + .map_err(TelegramVisionDataUrlError::File)?; + let max_bytes = if video { + VISION_MAX_VIDEO_BYTES + } else { + VISION_MAX_IMAGE_BYTES + }; + let data = + openplotva_telegram::download_telegram_file(&self.client, &file_path, max_bytes) + .await + .map_err(|error| match error { + TelegramFileError::TooLarge { .. } if video => { + TelegramVisionDataUrlError::VideoTooLarge + } + TelegramFileError::TooLarge { .. } => { + TelegramVisionDataUrlError::ImageTooLarge + } + error => TelegramVisionDataUrlError::File(error), + })?; if video { telegram_vision_video_data_url_from_bytes(&data, mime_type) .map_err(TelegramVisionDataUrlError::Build) @@ -727,18 +720,9 @@ impl TelegramVisionDataUrlProvider for TelegramClientVisionDataUrlProvider { /// Error returned by concrete direct image payload preparation. #[derive(Debug, Error)] pub enum TelegramVisionDataUrlError { - /// `getFile` failed. - #[error("get telegram file: {0}")] - GetFile(#[source] carapax::api::ExecuteError), - /// Telegram returned no downloadable path. - #[error("telegram file_path is empty")] - MissingFilePath, - /// Download setup failed. - #[error("download telegram file: {0}")] - Download(#[source] carapax::api::DownloadFileError), - /// Download stream failed. - #[error("download telegram file chunk: {0}")] - DownloadChunk(#[source] reqwest::Error), + /// `getFile` or the download failed or ran out of time. + #[error(transparent)] + File(TelegramFileError), /// Video exceeded the Bot API download contract and local memory bound. #[error("telegram video exceeds 20 MiB")] VideoTooLarge, diff --git a/crates/openplotva-telegram/Cargo.toml b/crates/openplotva-telegram/Cargo.toml index 02b291cd..492947d4 100644 --- a/crates/openplotva-telegram/Cargo.toml +++ b/crates/openplotva-telegram/Cargo.toml @@ -11,6 +11,7 @@ publish = false base64.workspace = true carapax.workspace = true crc.workspace = true +futures-util.workspace = true html-escape.workspace = true html5ever.workspace = true openplotva-updates = { path = "../openplotva-updates" } diff --git a/crates/openplotva-telegram/src/files.rs b/crates/openplotva-telegram/src/files.rs new file mode 100644 index 00000000..ffe097c8 --- /dev/null +++ b/crates/openplotva-telegram/src/files.rs @@ -0,0 +1,245 @@ +//! Bounded Bot API file lookups and downloads. +//! +//! The shared HTTP client keeps a long request timeout for the `getUpdates` +//! long poll. File work runs inside queue workers that hold a slot while they +//! wait, so it gets its own short bounds here. + +use std::time::Duration; + +use carapax::{ + api::{DownloadFileError, ExecuteError}, + types::{File, GetFile}, +}; +use futures_util::StreamExt; +use thiserror::Error; + +use crate::TelegramClient; + +/// Bound for one `getFile` call, including the client's own retries. +pub const TELEGRAM_GET_FILE_TIMEOUT: Duration = Duration::from_secs(10); + +/// Bound for one file download, from the request to the last body chunk. +pub const TELEGRAM_FILE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(30); + +/// Failure of a bounded Bot API file lookup or download. +#[derive(Debug, Error)] +pub enum TelegramFileError { + #[error("get telegram file: timed out after {}s", .0.as_secs())] + GetFileTimedOut(Duration), + #[error("get telegram file: {0}")] + GetFile(#[source] ExecuteError), + #[error("telegram file_path is empty")] + MissingFilePath, + #[error("download telegram file: timed out after {}s", .0.as_secs())] + DownloadTimedOut(Duration), + #[error("download telegram file: {0}")] + Download(#[source] DownloadFileError), + #[error("download telegram file chunk: {0}")] + DownloadChunk(#[source] reqwest::Error), + #[error("telegram file exceeds {limit} bytes")] + TooLarge { received: usize, limit: usize }, +} + +/// Run `getFile` within [`TELEGRAM_GET_FILE_TIMEOUT`]. +pub async fn get_telegram_file( + client: &TelegramClient, + file_id: &str, +) -> Result { + get_telegram_file_within(client, file_id, TELEGRAM_GET_FILE_TIMEOUT).await +} + +/// Run `getFile` within [`TELEGRAM_GET_FILE_TIMEOUT`] and return the download path. +pub async fn get_telegram_file_path( + client: &TelegramClient, + file_id: &str, +) -> Result { + let file = get_telegram_file(client, file_id).await?; + telegram_file_path(&file) + .map(str::to_owned) + .ok_or(TelegramFileError::MissingFilePath) +} + +/// Download path of a `getFile` result, when Telegram returned a usable one. +#[must_use] +pub fn telegram_file_path(file: &File) -> Option<&str> { + file.file_path + .as_deref() + .map(str::trim) + .filter(|path| !path.is_empty()) +} + +/// Download a file within [`TELEGRAM_FILE_DOWNLOAD_TIMEOUT`], refusing bodies above `max_bytes`. +pub async fn download_telegram_file( + client: &TelegramClient, + file_path: &str, + max_bytes: usize, +) -> Result, TelegramFileError> { + download_telegram_file_within(client, file_path, max_bytes, TELEGRAM_FILE_DOWNLOAD_TIMEOUT) + .await +} + +async fn get_telegram_file_within( + client: &TelegramClient, + file_id: &str, + timeout: Duration, +) -> Result { + tokio::time::timeout(timeout, client.execute(GetFile::new(file_id))) + .await + .map_err(|_| TelegramFileError::GetFileTimedOut(timeout))? + .map_err(TelegramFileError::GetFile) +} + +async fn download_telegram_file_within( + client: &TelegramClient, + file_path: &str, + max_bytes: usize, + timeout: Duration, +) -> Result, TelegramFileError> { + let download = async { + let mut stream = client + .download_file(file_path) + .await + .map_err(TelegramFileError::Download)?; + let mut data = Vec::new(); + while let Some(chunk) = stream.next().await { + // The download URL carries the bot token. + let chunk = + chunk.map_err(|error| TelegramFileError::DownloadChunk(error.without_url()))?; + let received = data.len().saturating_add(chunk.len()); + if received > max_bytes { + return Err(TelegramFileError::TooLarge { + received, + limit: max_bytes, + }); + } + data.extend_from_slice(&chunk); + } + Ok(data) + }; + tokio::time::timeout(timeout, download) + .await + .map_err(|_| TelegramFileError::DownloadTimedOut(timeout))? +} + +#[cfg(test)] +mod tests { + use std::{ + io::{Read, Write}, + net::{SocketAddr, TcpListener}, + sync::mpsc, + time::{Duration, Instant}, + }; + + use super::{ + TELEGRAM_FILE_DOWNLOAD_TIMEOUT, TELEGRAM_GET_FILE_TIMEOUT, TelegramFileError, + download_telegram_file_within, get_telegram_file_within, + }; + use crate::TelegramClient; + + const TEST_TIMEOUT: Duration = Duration::from_millis(300); + + fn client(address: SocketAddr) -> TelegramClient { + TelegramClient::new("fixture") + .expect("fixture client") + .with_host(format!("http://{address}")) + .with_max_retries(0) + } + + /// Answer one request with `head` + `body`, then keep the socket open until released. + fn serve_once(head: String, body: Vec) -> (SocketAddr, mpsc::Sender<()>) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture server"); + let address = listener.local_addr().expect("fixture server address"); + let (release, released) = mpsc::channel::<()>(); + std::thread::spawn(move || { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let mut request = Vec::new(); + let mut buffer = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + match stream.read(&mut buffer) { + Ok(0) | Err(_) => return, + Ok(read) => request.extend_from_slice(&buffer[..read]), + } + } + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&body); + let _ = stream.flush(); + let _ = released.recv_timeout(Duration::from_secs(5)); + }); + (address, release) + } + + #[test] + fn get_file_bound_stays_within_ten_seconds() { + assert!(TELEGRAM_GET_FILE_TIMEOUT <= Duration::from_secs(10)); + assert!(TELEGRAM_FILE_DOWNLOAD_TIMEOUT <= Duration::from_secs(30)); + } + + #[tokio::test] + async fn get_file_stops_waiting_for_a_silent_server() { + // Never accepted: the kernel backlog completes the handshake and nothing answers. + let listener = TcpListener::bind("127.0.0.1:0").expect("bind silent server"); + let address = listener.local_addr().expect("silent server address"); + let started = Instant::now(); + + let error = get_telegram_file_within(&client(address), "file-id", TEST_TIMEOUT) + .await + .expect_err("a silent server must time out"); + + assert!( + matches!(error, TelegramFileError::GetFileTimedOut(timeout) if timeout == TEST_TIMEOUT) + ); + assert!(started.elapsed() < Duration::from_secs(5)); + assert_eq!( + TelegramFileError::GetFileTimedOut(Duration::from_secs(10)).to_string(), + "get telegram file: timed out after 10s" + ); + } + + #[tokio::test] + async fn download_stops_waiting_for_a_stalled_body() { + let head = "HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n".to_owned(); + let (address, _release) = serve_once(head, b"partial".to_vec()); + + let error = + download_telegram_file_within(&client(address), "voice/file.oga", 4096, TEST_TIMEOUT) + .await + .expect_err("a stalled body must time out"); + + assert!( + matches!(error, TelegramFileError::DownloadTimedOut(timeout) if timeout == TEST_TIMEOUT) + ); + } + + #[tokio::test] + async fn download_returns_the_body_and_enforces_the_size_limit() { + let body = b"0123456789".to_vec(); + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + + let (address, release) = serve_once(head.clone(), body.clone()); + let data = + download_telegram_file_within(&client(address), "photos/file.jpg", 10, TEST_TIMEOUT) + .await + .expect("a body at the limit downloads"); + let _ = release.send(()); + assert_eq!(data, body); + + let (address, release) = serve_once(head, body); + let error = + download_telegram_file_within(&client(address), "photos/file.jpg", 9, TEST_TIMEOUT) + .await + .expect_err("a body above the limit is refused"); + let _ = release.send(()); + assert!(matches!( + error, + TelegramFileError::TooLarge { + received: 10, + limit: 9 + } + )); + } +} diff --git a/crates/openplotva-telegram/src/lib.rs b/crates/openplotva-telegram/src/lib.rs index a36bd4b0..d4f0162a 100644 --- a/crates/openplotva-telegram/src/lib.rs +++ b/crates/openplotva-telegram/src/lib.rs @@ -3,6 +3,7 @@ mod callback; mod dedup; mod dispatcher; +mod files; mod html; mod markdown; mod outbound; @@ -38,6 +39,10 @@ pub use dispatcher::{ DispatcherWorkItem, DispatcherWorkerLoopOutcome, DispatcherWorkerOutcome, EnqueueOutcome, QueueSnapshot, RegularDequeueOutcome, run_limiter_cleanup_until, }; +pub use files::{ + TELEGRAM_FILE_DOWNLOAD_TIMEOUT, TELEGRAM_GET_FILE_TIMEOUT, TelegramFileError, + download_telegram_file, get_telegram_file, get_telegram_file_path, telegram_file_path, +}; pub use html::{ TELEGRAM_PARSE_MODE_HTML, clean_unicode_non_printables, decode_html_entities, ensure_telegram_safe_text, escape_telegram_html_text, extract_visible_text,