0.6.4-thumb-upgrade
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
use crate::s3_utils::get_s3_filelist;
|
||||
use crate::security::SecurityConfig;
|
||||
use crate::thumbnail::cleanup_cache;
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use aws_config::BehaviorVersion;
|
||||
use aws_sdk_s3::{Client as S3Client, config::Credentials};
|
||||
@@ -29,7 +30,7 @@ impl AppState {
|
||||
/// Инициализация с кастомной конфигурацией безопасности.
|
||||
pub async fn new_with_config(security_config: SecurityConfig) -> Self {
|
||||
log::warn!("🚀 Starting AppState initialization...");
|
||||
|
||||
|
||||
// Получаем конфигурацию для Redis с таймаутом
|
||||
log::warn!("📋 Getting REDIS_URL from environment...");
|
||||
let redis_url = match env::var("REDIS_URL") {
|
||||
@@ -42,10 +43,13 @@ impl AppState {
|
||||
panic!("REDIS_URL must be set: {}", e);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Детальное логирование для отладки
|
||||
log::warn!("🔗 Redis URL: {}", redis_url.replace(&redis_url.split('@').nth(0).unwrap_or(""), "***"));
|
||||
|
||||
log::warn!(
|
||||
"🔗 Redis URL: {}",
|
||||
redis_url.replace(redis_url.split('@').nth(0).unwrap_or(""), "***")
|
||||
);
|
||||
|
||||
// Парсим URL для детального анализа
|
||||
log::warn!("🔍 Parsing Redis URL...");
|
||||
let final_redis_url = match url::Url::parse(&redis_url) {
|
||||
@@ -53,32 +57,38 @@ impl AppState {
|
||||
log::warn!("✅ Redis URL parsed successfully");
|
||||
log::warn!(" Host: {}", parsed_url.host_str().unwrap_or("none"));
|
||||
log::warn!(" Port: {}", parsed_url.port().unwrap_or(0));
|
||||
|
||||
|
||||
let username = parsed_url.username();
|
||||
let password = parsed_url.password();
|
||||
|
||||
|
||||
log::warn!(" Username: '{}'", username);
|
||||
log::warn!(" Password: {}", if password.is_some() { "***" } else { "none" });
|
||||
|
||||
// Если username пустой и есть пароль, оставляем как есть
|
||||
// Redis может работать только с паролем без username
|
||||
if username.is_empty() && password.is_some() {
|
||||
log::warn!(" 🔧 Using password-only authentication (no username)");
|
||||
}
|
||||
redis_url
|
||||
log::warn!(
|
||||
" Password: {}",
|
||||
if password.is_some() { "***" } else { "none" }
|
||||
);
|
||||
|
||||
// Если username пустой и есть пароль, оставляем как есть
|
||||
// Redis может работать только с паролем без username
|
||||
if username.is_empty() && password.is_some() {
|
||||
log::warn!(" 🔧 Using password-only authentication (no username)");
|
||||
}
|
||||
redis_url
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("❌ Failed to parse Redis URL: {}", e);
|
||||
panic!("Invalid Redis URL: {}", e);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Используем исправленный URL
|
||||
Self::create_app_state_with_redis_url(security_config, final_redis_url).await
|
||||
}
|
||||
|
||||
/// Создает AppState с указанным Redis URL.
|
||||
async fn create_app_state_with_redis_url(security_config: SecurityConfig, redis_url: String) -> Self {
|
||||
async fn create_app_state_with_redis_url(
|
||||
security_config: SecurityConfig,
|
||||
redis_url: String,
|
||||
) -> Self {
|
||||
let redis_client = match RedisClient::open(redis_url) {
|
||||
Ok(client) => {
|
||||
log::warn!("✅ Redis client created successfully");
|
||||
@@ -91,8 +101,11 @@ impl AppState {
|
||||
};
|
||||
|
||||
// Устанавливаем таймаут для Redis операций с graceful fallback
|
||||
log::warn!("🔄 Attempting Redis connection with timeout: {}s", security_config.request_timeout_seconds);
|
||||
|
||||
log::warn!(
|
||||
"🔄 Attempting Redis connection with timeout: {}s",
|
||||
security_config.request_timeout_seconds
|
||||
);
|
||||
|
||||
let redis_connection = match tokio::time::timeout(
|
||||
Duration::from_secs(security_config.request_timeout_seconds),
|
||||
redis_client.get_multiplexed_async_connection(),
|
||||
@@ -101,12 +114,9 @@ impl AppState {
|
||||
{
|
||||
Ok(Ok(mut conn)) => {
|
||||
log::warn!("✅ Redis connection established");
|
||||
|
||||
|
||||
// Тестируем подключение простой командой
|
||||
match tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
conn.ping::<String>()
|
||||
).await {
|
||||
match tokio::time::timeout(Duration::from_secs(2), conn.ping::<String>()).await {
|
||||
Ok(Ok(result)) => {
|
||||
log::warn!("✅ Redis PING successful: {}", result);
|
||||
Some(conn)
|
||||
@@ -128,7 +138,10 @@ impl AppState {
|
||||
None
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!("⚠️ Redis connection timeout after {} seconds", security_config.request_timeout_seconds);
|
||||
log::warn!(
|
||||
"⚠️ Redis connection timeout after {} seconds",
|
||||
security_config.request_timeout_seconds
|
||||
);
|
||||
log::warn!("⚠️ Running in fallback mode without Redis (quotas disabled)");
|
||||
None
|
||||
}
|
||||
@@ -355,4 +368,27 @@ impl AppState {
|
||||
|
||||
Ok(new_quota)
|
||||
}
|
||||
|
||||
/// Очищает старые файлы из локального кэша.
|
||||
pub fn cleanup_local_cache(&self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Очищаем кэш старше 7 дней
|
||||
cleanup_cache("/tmp/thumbnails", 7)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Запускает периодическую очистку кэша.
|
||||
pub fn start_cache_cleanup_task(&self) {
|
||||
let state = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(24 * 60 * 60)); // раз в день
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if let Err(e) = state.cleanup_local_cache() {
|
||||
warn!("Failed to cleanup local cache: {}", e);
|
||||
} else {
|
||||
warn!("Local cache cleanup completed successfully");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user