Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 20 additions & 34 deletions crates/openplotva-app/src/asr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
Expand All @@ -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<TelegramFileError> 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,
Expand Down
9 changes: 2 additions & 7 deletions crates/openplotva-app/src/dialog_tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
})
}
}
Expand Down
35 changes: 12 additions & 23 deletions crates/openplotva-app/src/image_edit_references.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -45,32 +44,22 @@ impl TelegramImageEditReferenceLoader {
}

async fn file_path(&self, file_id: &str) -> Result<String, String> {
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<Vec<u8>, 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(),
})
}
}

Expand Down
35 changes: 32 additions & 3 deletions crates/openplotva-app/src/image_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
iamwavecut marked this conversation as resolved.
Resolved
pub const STICKER_DOWN_FILE_ID: &str =
"CAACAgIAAxkBAAEeROBkDjnz1i3WxxyNLBgWA_IKyjxbnQACuioAAqPicEh1C96_WINTHS8E";
pub const NSFW_BLOCKED_MESSAGE_TEXT: &str = "Ваш запрос заблокирован, так как содержит неприемлемый контент. Попробуйте переформулировать запрос.";
Expand Down Expand Up @@ -2445,13 +2449,27 @@ impl ImageJobTelegramSender for openplotva_telegram::TelegramClient {
method: TelegramOutboundMethod,
) -> ImageJobEffectFuture<'a, Result<TelegramOutboundResponse, String>> {
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<T>(
call: impl Future<Output = T>,
) -> Result<T, String> {
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>(
Expand Down Expand Up @@ -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");
}
}
}
Expand Down Expand Up @@ -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");
Expand Down
21 changes: 3 additions & 18 deletions crates/openplotva-app/src/music_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -901,26 +900,12 @@ impl MusicTelegramSender for openplotva_telegram::TelegramClient {
file_id: &'a str,
) -> MusicJobEffectFuture<'a, Result<Vec<u8>, 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())
})
}
}
Expand Down
43 changes: 14 additions & 29 deletions crates/openplotva-app/src/python_sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -689,9 +689,7 @@ impl TelegramSandboxIo {
}

async fn download(&self, file_id: &str) -> Result<(Vec<u8>, 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())
Expand All @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions crates/openplotva-app/src/video_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,9 @@ where
) -> VideoJobFuture<'a, Result<Option<i32>, 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}"))
})
Expand Down
Loading