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");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,16 @@ pub const CACHE_CONTROL_VERCEL: &str = "public, max-age=86400, s-maxage=31536000
|
||||
|
||||
/// Log request source and check CORS origin
|
||||
pub fn get_cors_origin(req: &HttpRequest) -> String {
|
||||
let allowed_origins = env::var("CORS_DOWNLOAD_ORIGINS")
|
||||
let mut allowed_origins = env::var("CORS_DOWNLOAD_ORIGINS")
|
||||
.unwrap_or_else(|_| "https://discours.io,https://*.discours.io,https://testing.discours.io,https://testing3.discours.io".to_string());
|
||||
|
||||
// Добавляем development origins если их нет в переменной окружения
|
||||
let development_origins =
|
||||
"http://localhost:3000,https://localhost:3000,https://files.dscrs.site";
|
||||
if !allowed_origins.contains("localhost:3000") {
|
||||
allowed_origins.push_str(&format!(",{}", development_origins));
|
||||
}
|
||||
|
||||
// Extract request source info for logging
|
||||
let origin = req.headers().get("origin").and_then(|h| h.to_str().ok());
|
||||
let referer = req.headers().get("referer").and_then(|h| h.to_str().ok());
|
||||
@@ -65,6 +72,13 @@ pub fn get_cors_origin(req: &HttpRequest) -> String {
|
||||
return origin.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// Дополнительная проверка для localhost в development
|
||||
if origin.starts_with("http://localhost:") || origin.starts_with("https://localhost:") {
|
||||
debug!("✅ CORS allowed: {} (localhost development)", origin);
|
||||
return origin.to_string();
|
||||
}
|
||||
|
||||
warn!("⚠️ CORS not whitelisted: {}", origin);
|
||||
}
|
||||
|
||||
@@ -124,11 +138,22 @@ pub fn create_file_response_with_analytics(
|
||||
// Log analytics for CORS whitelist analysis
|
||||
log_request_analytics(req, path, data.len());
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", cors_origin))
|
||||
.body(data)
|
||||
// Add audio streaming headers for audio files
|
||||
if content_type.starts_with("audio/") {
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", cors_origin))
|
||||
.insert_header(("accept-ranges", "bytes"))
|
||||
.insert_header(("content-length", data.len().to_string()))
|
||||
.body(data)
|
||||
} else {
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", cors_origin))
|
||||
.body(data)
|
||||
}
|
||||
}
|
||||
|
||||
/// Проверяет, является ли запрос от Vercel Edge API
|
||||
@@ -157,14 +182,28 @@ pub fn create_vercel_compatible_response(
|
||||
data: Vec<u8>,
|
||||
etag: &str,
|
||||
) -> HttpResponse {
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("etag", etag))
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.insert_header(("x-vercel-cache", "HIT")) // для оптимизации Vercel
|
||||
.insert_header(("x-content-type-options", "nosniff"))
|
||||
.body(data)
|
||||
// Add audio streaming headers for audio files
|
||||
if content_type.starts_with("audio/") {
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("etag", etag))
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.insert_header(("x-vercel-cache", "HIT")) // для оптимизации Vercel
|
||||
.insert_header(("x-content-type-options", "nosniff"))
|
||||
.insert_header(("accept-ranges", "bytes"))
|
||||
.insert_header(("content-length", data.len().to_string()))
|
||||
.body(data)
|
||||
} else {
|
||||
HttpResponse::Ok()
|
||||
.content_type(content_type)
|
||||
.insert_header(("etag", etag))
|
||||
.insert_header(("cache-control", CACHE_CONTROL_VERCEL))
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.insert_header(("x-vercel-cache", "HIT")) // для оптимизации Vercel
|
||||
.insert_header(("x-content-type-options", "nosniff"))
|
||||
.body(data)
|
||||
}
|
||||
}
|
||||
|
||||
// Removed complex ETag caching - Vercel handles caching on their edge
|
||||
@@ -239,17 +278,21 @@ pub fn handle_system_file(filename: &str) -> Option<HttpResponse> {
|
||||
match filename.to_lowercase().as_str() {
|
||||
"robots.txt" => {
|
||||
info!("Serving robots.txt for static image server");
|
||||
Some(HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body("User-agent: *\nDisallow: /\n"))
|
||||
Some(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body("User-agent: *\nDisallow: /\n"),
|
||||
)
|
||||
}
|
||||
"favicon.ico" => {
|
||||
info!("Serving favicon.ico (empty)");
|
||||
Some(HttpResponse::Ok()
|
||||
.content_type("image/x-icon")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body(""))
|
||||
Some(
|
||||
HttpResponse::Ok()
|
||||
.content_type("image/x-icon")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body(""),
|
||||
)
|
||||
}
|
||||
"sitemap.xml" => {
|
||||
info!("Serving sitemap.xml (empty)");
|
||||
@@ -260,11 +303,13 @@ pub fn handle_system_file(filename: &str) -> Option<HttpResponse> {
|
||||
}
|
||||
"humans.txt" => {
|
||||
info!("Serving humans.txt");
|
||||
Some(HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body("# Static Image Server\n# Powered by Quoter\n"))
|
||||
Some(
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.insert_header(("access-control-allow-origin", "*"))
|
||||
.body("# Static Image Server\n# Powered by Quoter\n"),
|
||||
)
|
||||
}
|
||||
_ => None
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,17 @@ use actix_web::{HttpRequest, HttpResponse, Result, error::ErrorInternalServerErr
|
||||
use log::{error, info, warn};
|
||||
|
||||
use super::common::{
|
||||
create_file_response_with_analytics, create_vercel_compatible_response, is_vercel_request, handle_system_file,
|
||||
create_file_response_with_analytics, create_vercel_compatible_response, handle_system_file,
|
||||
is_vercel_request,
|
||||
};
|
||||
use crate::app_state::AppState;
|
||||
use crate::handlers::serve_file::serve_file;
|
||||
use crate::lookup::{find_file_by_pattern, get_mime_type};
|
||||
use crate::s3_utils::{check_file_exists, load_file_from_s3, upload_to_s3};
|
||||
use crate::thumbnail::{
|
||||
parse_file_path, is_image_file, generate_webp_thumbnail,
|
||||
load_cached_thumbnail_from_storj, cache_thumbnail_to_storj
|
||||
cache_thumbnail, cache_thumbnail_to_storj, generate_webp_thumbnail, is_image_file,
|
||||
load_cached_thumbnail, load_cached_thumbnail_from_storj, parse_file_path,
|
||||
thumbnail_exists_in_storj,
|
||||
};
|
||||
|
||||
// Удалена дублирующая функция, используется из common модуля
|
||||
@@ -24,7 +26,10 @@ pub async fn proxy_handler(
|
||||
state: web::Data<AppState>,
|
||||
) -> Result<HttpResponse, actix_web::Error> {
|
||||
let start_time = std::time::Instant::now();
|
||||
info!("GET {} [START] - Static image server request", requested_res);
|
||||
info!(
|
||||
"GET {} [START] - Static image server request",
|
||||
requested_res
|
||||
);
|
||||
|
||||
// Проверяем системные файлы (robots.txt, favicon.ico, etc.)
|
||||
if let Some(response) = handle_system_file(&requested_res) {
|
||||
@@ -69,7 +74,10 @@ pub async fn proxy_handler(
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
error!("Unsupported file format for: {} (full path: {})", base_filename, requested_res);
|
||||
error!(
|
||||
"Unsupported file format for: {} (full path: {})",
|
||||
base_filename, requested_res
|
||||
);
|
||||
return Err(ErrorInternalServerError("Unsupported file format"));
|
||||
}
|
||||
},
|
||||
@@ -145,19 +153,27 @@ pub async fn proxy_handler(
|
||||
|
||||
// Проверяем, нужен ли thumbnail
|
||||
if requested_width > 0 && is_image_file(&filekey) {
|
||||
info!("Generating thumbnail for {} with width {}", filekey, requested_width);
|
||||
|
||||
info!(
|
||||
"Generating thumbnail for {} with width {}",
|
||||
filekey, requested_width
|
||||
);
|
||||
|
||||
// Пробуем загрузить из Storj кэша
|
||||
if let Some(cached_thumb) = load_cached_thumbnail_from_storj(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None
|
||||
).await {
|
||||
info!("Serving cached thumbnail from Storj for {}", base_filename);
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
info!(
|
||||
"Serving cached thumbnail from Storj for {}",
|
||||
base_filename
|
||||
);
|
||||
let thumb_content_type = "image/webp";
|
||||
|
||||
|
||||
if is_vercel_request(&req) {
|
||||
let etag = format!("\"{:x}\"", md5::compute(&cached_thumb));
|
||||
return Ok(create_vercel_compatible_response(
|
||||
@@ -174,12 +190,76 @@ pub async fn proxy_handler(
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Пробуем загрузить из локального кэша
|
||||
if let Some(local_cached_thumb) = load_cached_thumbnail(
|
||||
"/tmp/thumbnails",
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
) {
|
||||
info!(
|
||||
"Serving cached thumbnail from local cache for {}",
|
||||
base_filename
|
||||
);
|
||||
let thumb_content_type = "image/webp";
|
||||
|
||||
if is_vercel_request(&req) {
|
||||
let etag =
|
||||
format!("\"{:x}\"", md5::compute(&local_cached_thumb));
|
||||
return Ok(create_vercel_compatible_response(
|
||||
thumb_content_type,
|
||||
local_cached_thumb,
|
||||
&etag,
|
||||
));
|
||||
} else {
|
||||
return Ok(create_file_response_with_analytics(
|
||||
thumb_content_type,
|
||||
local_cached_thumb,
|
||||
&req,
|
||||
&format!("{}_{}x.webp", base_filename, requested_width),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем состояние Storj кэша для диагностики
|
||||
let storj_cache_exists = thumbnail_exists_in_storj(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
if storj_cache_exists {
|
||||
warn!(
|
||||
"Thumbnail exists in Storj but failed to load for {}",
|
||||
base_filename
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"No thumbnail in Storj cache for {}, will generate new",
|
||||
base_filename
|
||||
);
|
||||
}
|
||||
|
||||
// Генерируем новый thumbnail
|
||||
match generate_webp_thumbnail(&filedata, requested_width, None) {
|
||||
Ok(thumb_data) => {
|
||||
info!("Generated thumbnail: {} bytes", thumb_data.len());
|
||||
|
||||
|
||||
// Кэшируем thumbnail локально
|
||||
if let Err(e) = cache_thumbnail(
|
||||
"/tmp/thumbnails",
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
&thumb_data,
|
||||
) {
|
||||
warn!("Failed to cache thumbnail locally: {}", e);
|
||||
}
|
||||
|
||||
// Кэшируем thumbnail в Storj
|
||||
if let Err(e) = cache_thumbnail_to_storj(
|
||||
&state.storj_client,
|
||||
@@ -187,15 +267,18 @@ pub async fn proxy_handler(
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
&thumb_data
|
||||
).await {
|
||||
&thumb_data,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to cache thumbnail to Storj: {}", e);
|
||||
}
|
||||
|
||||
|
||||
let thumb_content_type = "image/webp";
|
||||
|
||||
|
||||
if is_vercel_request(&req) {
|
||||
let etag = format!("\"{:x}\"", md5::compute(&thumb_data));
|
||||
let etag =
|
||||
format!("\"{:x}\"", md5::compute(&thumb_data));
|
||||
return Ok(create_vercel_compatible_response(
|
||||
thumb_content_type,
|
||||
thumb_data,
|
||||
@@ -206,7 +289,10 @@ pub async fn proxy_handler(
|
||||
thumb_content_type,
|
||||
thumb_data,
|
||||
&req,
|
||||
&format!("{}_{}x.webp", base_filename, requested_width),
|
||||
&format!(
|
||||
"{}_{}x.webp",
|
||||
base_filename, requested_width
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
use actix_web::{HttpRequest, HttpResponse, Result, error::ErrorInternalServerError};
|
||||
use mime_guess::MimeGuess;
|
||||
use log::{info, warn};
|
||||
use mime_guess::MimeGuess;
|
||||
|
||||
use super::common::{
|
||||
create_file_response_with_analytics,
|
||||
create_vercel_compatible_response,
|
||||
is_vercel_request,
|
||||
create_file_response_with_analytics, create_vercel_compatible_response, is_vercel_request,
|
||||
};
|
||||
use crate::app_state::AppState;
|
||||
use crate::s3_utils::{check_file_exists, load_file_from_s3};
|
||||
use crate::thumbnail::{
|
||||
parse_file_path, is_image_file, generate_webp_thumbnail,
|
||||
load_cached_thumbnail_from_storj, cache_thumbnail_to_storj
|
||||
cache_thumbnail_to_storj, generate_webp_thumbnail, is_image_file,
|
||||
load_cached_thumbnail_from_storj, parse_file_path, thumbnail_exists_in_storj,
|
||||
};
|
||||
use md5;
|
||||
|
||||
/// Функция для обслуживания файла по заданному пути с поддержкой thumbnail генерации.
|
||||
pub async fn serve_file(
|
||||
@@ -43,22 +40,27 @@ pub async fn serve_file(
|
||||
|
||||
// Парсим путь для проверки thumbnail запроса
|
||||
let (base_filename, requested_width, _) = parse_file_path(filepath);
|
||||
|
||||
|
||||
// Проверяем, нужен ли thumbnail
|
||||
if requested_width > 0 && is_image_file(filepath) {
|
||||
info!("Generating thumbnail for {} with width {}", filepath, requested_width);
|
||||
|
||||
info!(
|
||||
"Generating thumbnail for {} with width {}",
|
||||
filepath, requested_width
|
||||
);
|
||||
|
||||
// Пробуем загрузить из Storj кэша
|
||||
if let Some(cached_thumb) = load_cached_thumbnail_from_storj(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None
|
||||
).await {
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
info!("Serving cached thumbnail from Storj for {}", base_filename);
|
||||
let thumb_content_type = "image/webp";
|
||||
|
||||
|
||||
if is_vercel_request(req) {
|
||||
let etag = format!("\"{:x}\"", md5::compute(&cached_thumb));
|
||||
return Ok(create_vercel_compatible_response(
|
||||
@@ -75,12 +77,34 @@ pub async fn serve_file(
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Проверяем состояние Storj кэша для диагностики
|
||||
let storj_cache_exists = thumbnail_exists_in_storj(
|
||||
&state.storj_client,
|
||||
&state.bucket,
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
if storj_cache_exists {
|
||||
warn!(
|
||||
"Thumbnail exists in Storj but failed to load for {}",
|
||||
base_filename
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"No thumbnail in Storj cache for {}, will generate new",
|
||||
base_filename
|
||||
);
|
||||
}
|
||||
|
||||
// Генерируем новый thumbnail
|
||||
match generate_webp_thumbnail(&filedata, requested_width, None) {
|
||||
Ok(thumb_data) => {
|
||||
info!("Generated thumbnail: {} bytes", thumb_data.len());
|
||||
|
||||
|
||||
// Кэшируем thumbnail в Storj
|
||||
if let Err(e) = cache_thumbnail_to_storj(
|
||||
&state.storj_client,
|
||||
@@ -88,13 +112,15 @@ pub async fn serve_file(
|
||||
&base_filename,
|
||||
requested_width,
|
||||
None,
|
||||
&thumb_data
|
||||
).await {
|
||||
&thumb_data,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("Failed to cache thumbnail to Storj: {}", e);
|
||||
}
|
||||
|
||||
|
||||
let thumb_content_type = "image/webp";
|
||||
|
||||
|
||||
if is_vercel_request(req) {
|
||||
let etag = format!("\"{:x}\"", md5::compute(&thumb_data));
|
||||
return Ok(create_vercel_compatible_response(
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::auth::{extract_user_id_from_token, user_added_file};
|
||||
use crate::handlers::MAX_USER_QUOTA_BYTES;
|
||||
use crate::lookup::store_file_info;
|
||||
use crate::s3_utils::{self, generate_key_with_extension, upload_to_s3};
|
||||
use crate::thumbnail::get_image_mime_type;
|
||||
use futures::TryStreamExt;
|
||||
// use crate::thumbnail::convert_heic_to_jpeg;
|
||||
|
||||
@@ -129,6 +130,23 @@ pub async fn upload_handler(
|
||||
let filename = format!("{}.{}", uuid::Uuid::new_v4(), extension);
|
||||
info!("Generated filename: {}", filename);
|
||||
|
||||
// Дополнительная валидация для изображений
|
||||
if content_type.starts_with("image/") {
|
||||
let expected_mime = get_image_mime_type(&filename);
|
||||
if expected_mime != content_type && expected_mime != "application/octet-stream" {
|
||||
warn!(
|
||||
"MIME type mismatch for {}: detected={}, expected={}",
|
||||
filename, content_type, expected_mime
|
||||
);
|
||||
// Продолжаем с обнаруженным типом, но логируем расхождение
|
||||
} else {
|
||||
info!(
|
||||
"MIME type validation passed for {}: {}",
|
||||
filename, content_type
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Загружаем файл в S3 storj
|
||||
match upload_to_s3(
|
||||
&state.storj_client,
|
||||
|
||||
19
src/main.rs
19
src/main.rs
@@ -39,6 +39,9 @@ async fn main() -> std::io::Result<()> {
|
||||
});
|
||||
});
|
||||
|
||||
// Запускаем периодическую очистку кэша
|
||||
app_state.start_cache_cleanup_task();
|
||||
|
||||
// Конфигурация безопасности
|
||||
let security_config = SecurityConfig::default();
|
||||
info!(
|
||||
@@ -48,22 +51,30 @@ async fn main() -> std::io::Result<()> {
|
||||
);
|
||||
|
||||
HttpServer::new(move || {
|
||||
// Настройка CORS middleware - ограничиваем в продакшене
|
||||
// Настройка CORS middleware - более гибкая для разработки
|
||||
let cors = Cors::default()
|
||||
.allowed_origin("https://discours.io")
|
||||
.allowed_origin("https://new.discours.io")
|
||||
.allowed_origin("https://testing.discours.io")
|
||||
.allowed_origin("http://localhost:3000") // FIXME: для разработки
|
||||
.allowed_origin("http://localhost:3000")
|
||||
.allowed_origin("https://localhost:3000") // HTTPS для разработки
|
||||
.allowed_origin("https://files.dscrs.site") // Добавляем домен файлов
|
||||
.allowed_methods(vec!["GET", "POST", "OPTIONS"])
|
||||
.allowed_headers(vec![
|
||||
header::CONTENT_TYPE,
|
||||
header::AUTHORIZATION,
|
||||
header::IF_NONE_MATCH,
|
||||
header::CACHE_CONTROL,
|
||||
header::RANGE, // Для аудио стриминга
|
||||
])
|
||||
.expose_headers(vec![
|
||||
header::CONTENT_LENGTH,
|
||||
header::ETAG,
|
||||
header::CONTENT_RANGE, // Для аудио стриминга
|
||||
header::ACCEPT_RANGES,
|
||||
])
|
||||
.expose_headers(vec![header::CONTENT_LENGTH, header::ETAG])
|
||||
.supports_credentials()
|
||||
.max_age(86400); // 1 день вместо 20
|
||||
.max_age(86400); // 1 день
|
||||
|
||||
// Заголовки безопасности
|
||||
let security_headers = DefaultHeaders::new()
|
||||
|
||||
125
src/thumbnail.rs
125
src/thumbnail.rs
@@ -1,9 +1,9 @@
|
||||
use aws_sdk_s3::Client as S3Client;
|
||||
use image::ImageFormat;
|
||||
use std::path::Path;
|
||||
use log::{info, warn};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use log::{info, warn};
|
||||
use aws_sdk_s3::Client as S3Client;
|
||||
use std::path::Path;
|
||||
|
||||
/// Парсит путь к файлу, извлекая базовое имя, ширину и расширение.
|
||||
///
|
||||
@@ -41,13 +41,13 @@ pub fn parse_file_path(path: &str) -> (String, u32, String) {
|
||||
}
|
||||
|
||||
/// Генерирует thumbnail для изображения.
|
||||
///
|
||||
///
|
||||
/// # Аргументы
|
||||
/// * `image_data` - Данные изображения
|
||||
/// * `width` - Ширина thumbnail
|
||||
/// * `height` - Высота thumbnail (опционально)
|
||||
/// * `format` - Формат выходного изображения (по умолчанию WebP)
|
||||
///
|
||||
///
|
||||
/// # Возвращает
|
||||
/// * `Result<Vec<u8>, Box<dyn std::error::Error>>` - Данные thumbnail или ошибка
|
||||
pub fn generate_thumbnail(
|
||||
@@ -56,26 +56,30 @@ pub fn generate_thumbnail(
|
||||
height: Option<u32>,
|
||||
format: Option<ImageFormat>,
|
||||
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
info!("Generating thumbnail: {}x{}", width, height.unwrap_or(width));
|
||||
|
||||
info!(
|
||||
"Generating thumbnail: {}x{}",
|
||||
width,
|
||||
height.unwrap_or(width)
|
||||
);
|
||||
|
||||
// Загружаем изображение
|
||||
let img = image::load_from_memory(image_data)?;
|
||||
|
||||
|
||||
// Вычисляем размеры
|
||||
let target_height = height.unwrap_or_else(|| {
|
||||
let aspect_ratio = img.height() as f32 / img.width() as f32;
|
||||
(width as f32 * aspect_ratio) as u32
|
||||
});
|
||||
|
||||
|
||||
// Ресайзим изображение
|
||||
let resized = img.thumbnail(width, target_height);
|
||||
|
||||
|
||||
// Конвертируем в нужный формат
|
||||
let output_format = format.unwrap_or(ImageFormat::WebP);
|
||||
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
resized.write_to(&mut std::io::Cursor::new(&mut buffer), output_format)?;
|
||||
|
||||
|
||||
info!("Thumbnail generated: {} bytes", buffer.len());
|
||||
Ok(buffer)
|
||||
}
|
||||
@@ -86,7 +90,18 @@ pub fn generate_webp_thumbnail(
|
||||
width: u32,
|
||||
height: Option<u32>,
|
||||
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||
generate_thumbnail(image_data, width, height, Some(ImageFormat::WebP))
|
||||
// Пробуем сначала WebP
|
||||
match generate_thumbnail(image_data, width, height, Some(ImageFormat::WebP)) {
|
||||
Ok(webp_data) => Ok(webp_data),
|
||||
Err(webp_error) => {
|
||||
warn!(
|
||||
"WebP generation failed, falling back to JPEG: {}",
|
||||
webp_error
|
||||
);
|
||||
// Fallback к JPEG если WebP не удался
|
||||
generate_jpeg_thumbnail(image_data, width, height)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Генерирует JPEG thumbnail для изображения.
|
||||
@@ -105,8 +120,11 @@ pub fn is_image_file(filename: &str) -> bool {
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|s| s.to_lowercase())
|
||||
.unwrap_or_default();
|
||||
|
||||
matches!(ext.as_str(), "jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "tiff")
|
||||
|
||||
matches!(
|
||||
ext.as_str(),
|
||||
"jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "tiff"
|
||||
)
|
||||
}
|
||||
|
||||
/// Получает MIME тип для изображения.
|
||||
@@ -116,7 +134,7 @@ pub fn get_image_mime_type(filename: &str) -> &'static str {
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|s| s.to_lowercase())
|
||||
.unwrap_or_default();
|
||||
|
||||
|
||||
match ext.as_str() {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
@@ -138,20 +156,20 @@ pub fn cache_thumbnail(
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
// Создаем директорию кэша если не существует
|
||||
fs::create_dir_all(cache_dir)?;
|
||||
|
||||
|
||||
// Генерируем имя файла кэша
|
||||
let cache_filename = if let Some(h) = height {
|
||||
format!("{}_{}x{}.webp", filename, width, h)
|
||||
} else {
|
||||
format!("{}_{}x.webp", filename, width)
|
||||
};
|
||||
|
||||
|
||||
let cache_path = Path::new(cache_dir).join(&cache_filename);
|
||||
|
||||
|
||||
// Сохраняем thumbnail
|
||||
let mut file = fs::File::create(&cache_path)?;
|
||||
file.write_all(thumbnail_data)?;
|
||||
|
||||
|
||||
info!("Thumbnail cached: {}", cache_path.display());
|
||||
Ok(cache_path.to_string_lossy().to_string())
|
||||
}
|
||||
@@ -168,9 +186,9 @@ pub fn load_cached_thumbnail(
|
||||
} else {
|
||||
format!("{}_{}x.webp", filename, width)
|
||||
};
|
||||
|
||||
|
||||
let cache_path = Path::new(cache_dir).join(&cache_filename);
|
||||
|
||||
|
||||
match fs::read(&cache_path) {
|
||||
Ok(data) => {
|
||||
info!("Thumbnail loaded from cache: {}", cache_path.display());
|
||||
@@ -198,10 +216,10 @@ pub async fn cache_thumbnail_to_storj(
|
||||
} else {
|
||||
format!("thumbnails/{}_{}x.webp", filename, width)
|
||||
};
|
||||
|
||||
|
||||
// Загружаем thumbnail в Storj
|
||||
let body = aws_sdk_s3::primitives::ByteStream::from(thumbnail_data.to_vec());
|
||||
|
||||
|
||||
s3_client
|
||||
.put_object()
|
||||
.bucket(bucket)
|
||||
@@ -210,7 +228,7 @@ pub async fn cache_thumbnail_to_storj(
|
||||
.content_type("image/webp")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
|
||||
info!("Thumbnail cached to Storj: {}", thumbnail_key);
|
||||
Ok(thumbnail_key)
|
||||
}
|
||||
@@ -228,7 +246,7 @@ pub async fn load_cached_thumbnail_from_storj(
|
||||
} else {
|
||||
format!("thumbnails/{}_{}x.webp", filename, width)
|
||||
};
|
||||
|
||||
|
||||
match s3_client
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
@@ -236,19 +254,21 @@ pub async fn load_cached_thumbnail_from_storj(
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
match response.body.collect().await {
|
||||
Ok(data) => {
|
||||
let bytes = data.into_bytes();
|
||||
info!("Thumbnail loaded from Storj: {} ({} bytes)", thumbnail_key, bytes.len());
|
||||
Some(bytes.to_vec())
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to read thumbnail data from Storj: {}", e);
|
||||
None
|
||||
}
|
||||
Ok(response) => match response.body.collect().await {
|
||||
Ok(data) => {
|
||||
let bytes = data.into_bytes();
|
||||
info!(
|
||||
"Thumbnail loaded from Storj: {} ({} bytes)",
|
||||
thumbnail_key,
|
||||
bytes.len()
|
||||
);
|
||||
Some(bytes.to_vec())
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to read thumbnail data from Storj: {}", e);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
warn!("Failed to load cached thumbnail from Storj: {}", e);
|
||||
None
|
||||
@@ -269,17 +289,14 @@ pub async fn thumbnail_exists_in_storj(
|
||||
} else {
|
||||
format!("thumbnails/{}_{}x.webp", filename, width)
|
||||
};
|
||||
|
||||
match s3_client
|
||||
|
||||
(s3_client
|
||||
.head_object()
|
||||
.bucket(bucket)
|
||||
.key(&thumbnail_key)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
.await)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Очищает старые файлы кэша.
|
||||
@@ -288,13 +305,14 @@ pub fn cleanup_cache(cache_dir: &str, max_age_days: u64) -> Result<(), Box<dyn s
|
||||
if !cache_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let cutoff_time = std::time::SystemTime::now() - std::time::Duration::from_secs(max_age_days * 24 * 60 * 60);
|
||||
|
||||
|
||||
let cutoff_time =
|
||||
std::time::SystemTime::now() - std::time::Duration::from_secs(max_age_days * 24 * 60 * 60);
|
||||
|
||||
for entry in fs::read_dir(cache_path)? {
|
||||
let entry = entry?;
|
||||
let metadata = entry.metadata()?;
|
||||
|
||||
|
||||
if let Ok(modified) = metadata.modified() {
|
||||
if modified < cutoff_time {
|
||||
fs::remove_file(entry.path())?;
|
||||
@@ -302,7 +320,7 @@ pub fn cleanup_cache(cache_dir: &str, max_age_days: u64) -> Result<(), Box<dyn s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -359,6 +377,9 @@ mod tests {
|
||||
assert_eq!(get_image_mime_type("photo.png"), "image/png");
|
||||
assert_eq!(get_image_mime_type("animation.gif"), "image/gif");
|
||||
assert_eq!(get_image_mime_type("modern.webp"), "image/webp");
|
||||
assert_eq!(get_image_mime_type("unknown.xyz"), "application/octet-stream");
|
||||
assert_eq!(
|
||||
get_image_mime_type("unknown.xyz"),
|
||||
"application/octet-stream"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user