[0.6.1] - 2025-09-02
### 🚀 Изменено - Упрощение архитектуры - **Генерация миниатюр**: Полностью удалена из Quoter, теперь управляется Vercel Edge API - **Очистка legacy кода**: Удалены все функции генерации миниатюр и сложность - **Документация**: Сокращена с 17 файлов до 7, следуя принципам KISS/DRY - **Смена фокуса**: Quoter теперь сосредоточен на upload + storage, Vercel обрабатывает миниатюры - **Логирование запросов**: Добавлена аналитика источников для оптимизации CORS whitelist - **Реализация таймаутов**: Добавлены настраиваемые таймауты для S3, Redis и внешних операций - **Упрощенная безопасность**: Удален сложный rate limiting, оставлена только необходимая защита upload ### 📝 Обновлено - Консолидирована документация в практическую структуру: - Основной README.md с быстрым стартом - docs/SETUP.md для конфигурации и развертывания - Упрощенный features.md с фокусом на основную функциональность - Добавлен акцент на Vercel по всему коду и документации ### 🗑️ Удалено - Избыточные файлы документации (api-reference, deployment, development, и т.д.) - Дублирующийся контент в нескольких документах - Излишне детальная документация для простого файлового прокси 💋 **Упрощение**: KISS принцип применен - убрали избыточность, оставили суть.
This commit is contained in:
136
src/app_state.rs
136
src/app_state.rs
@@ -1,10 +1,11 @@
|
||||
use crate::s3_utils::get_s3_filelist;
|
||||
use crate::security::SecurityConfig;
|
||||
use actix_web::error::ErrorInternalServerError;
|
||||
use aws_config::BehaviorVersion;
|
||||
use aws_sdk_s3::{Client as S3Client, config::Credentials};
|
||||
use log::warn;
|
||||
use redis::{AsyncCommands, Client as RedisClient, aio::MultiplexedConnection};
|
||||
use std::env;
|
||||
use std::{env, time::Duration};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
@@ -12,6 +13,7 @@ pub struct AppState {
|
||||
pub storj_client: S3Client,
|
||||
pub aws_client: S3Client,
|
||||
pub bucket: String,
|
||||
pub request_timeout: Duration,
|
||||
}
|
||||
|
||||
const PATH_MAPPING_KEY: &str = "filepath_mapping"; // Ключ для хранения маппинга путей
|
||||
@@ -20,13 +22,25 @@ const PATH_MAPPING_KEY: &str = "filepath_mapping"; // Ключ для хране
|
||||
impl AppState {
|
||||
/// Инициализация нового состояния приложения.
|
||||
pub async fn new() -> Self {
|
||||
// Получаем конфигурацию для Redis
|
||||
let security_config = SecurityConfig::default();
|
||||
Self::new_with_config(security_config).await
|
||||
}
|
||||
|
||||
/// Инициализация с кастомной конфигурацией безопасности.
|
||||
pub async fn new_with_config(security_config: SecurityConfig) -> Self {
|
||||
// Получаем конфигурацию для Redis с таймаутом
|
||||
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set");
|
||||
let redis_client = RedisClient::open(redis_url).expect("Invalid Redis URL");
|
||||
let redis_connection = redis_client
|
||||
.get_multiplexed_async_connection()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Устанавливаем таймаут для Redis операций
|
||||
let redis_connection = tokio::time::timeout(
|
||||
Duration::from_secs(security_config.request_timeout_seconds),
|
||||
redis_client.get_multiplexed_async_connection(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "Redis connection timeout")
|
||||
.expect("Failed to connect to Redis within timeout")
|
||||
.expect("Redis connection failed");
|
||||
|
||||
// Получаем конфигурацию для S3 (Storj)
|
||||
let s3_access_key = env::var("STORJ_ACCESS_KEY").expect("STORJ_ACCESS_KEY must be set");
|
||||
@@ -41,7 +55,7 @@ impl AppState {
|
||||
let aws_endpoint =
|
||||
env::var("AWS_END_POINT").unwrap_or_else(|_| "https://s3.amazonaws.com".to_string());
|
||||
|
||||
// Конфигурируем клиент S3 для Storj
|
||||
// Конфигурируем клиент S3 для Storj с таймаутом
|
||||
let storj_config = aws_config::defaults(BehaviorVersion::latest())
|
||||
.region("eu-west-1")
|
||||
.endpoint_url(s3_endpoint)
|
||||
@@ -52,12 +66,20 @@ impl AppState {
|
||||
None,
|
||||
"rust-storj-client",
|
||||
))
|
||||
.timeout_config(
|
||||
aws_config::timeout::TimeoutConfig::builder()
|
||||
.operation_timeout(Duration::from_secs(security_config.request_timeout_seconds))
|
||||
.operation_attempt_timeout(Duration::from_secs(
|
||||
security_config.request_timeout_seconds / 2,
|
||||
))
|
||||
.build(),
|
||||
)
|
||||
.load()
|
||||
.await;
|
||||
|
||||
let storj_client = S3Client::new(&storj_config);
|
||||
|
||||
// Конфигурируем клиент S3 для AWS
|
||||
// Конфигурируем клиент S3 для AWS с таймаутом
|
||||
let aws_config = aws_config::defaults(BehaviorVersion::latest())
|
||||
.region("eu-west-1")
|
||||
.endpoint_url(aws_endpoint)
|
||||
@@ -68,6 +90,14 @@ impl AppState {
|
||||
None,
|
||||
"rust-aws-client",
|
||||
))
|
||||
.timeout_config(
|
||||
aws_config::timeout::TimeoutConfig::builder()
|
||||
.operation_timeout(Duration::from_secs(security_config.request_timeout_seconds))
|
||||
.operation_attempt_timeout(Duration::from_secs(
|
||||
security_config.request_timeout_seconds / 2,
|
||||
))
|
||||
.build(),
|
||||
)
|
||||
.load()
|
||||
.await;
|
||||
|
||||
@@ -78,6 +108,7 @@ impl AppState {
|
||||
storj_client,
|
||||
aws_client,
|
||||
bucket,
|
||||
request_timeout: Duration::from_secs(security_config.request_timeout_seconds),
|
||||
};
|
||||
|
||||
// Кэшируем список файлов из AWS при старте приложения
|
||||
@@ -105,40 +136,51 @@ impl AppState {
|
||||
warn!("cached {} files", filelist.len());
|
||||
}
|
||||
|
||||
/// Получает путь из ключа (имени файла) в Redis.
|
||||
/// Получает путь из ключа (имени файла) в Redis с таймаутом.
|
||||
pub async fn get_path(&self, filename: &str) -> Result<Option<String>, actix_web::Error> {
|
||||
let mut redis = self.redis.clone();
|
||||
let new_path: Option<String> = redis
|
||||
.hget(PATH_MAPPING_KEY, filename)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Failed to get path mapping from Redis"))?;
|
||||
|
||||
let new_path: Option<String> =
|
||||
tokio::time::timeout(self.request_timeout, redis.hget(PATH_MAPPING_KEY, filename))
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Redis operation timeout"))?
|
||||
.map_err(|_| ErrorInternalServerError("Failed to get path mapping from Redis"))?;
|
||||
|
||||
Ok(new_path)
|
||||
}
|
||||
|
||||
pub async fn set_path(&self, filename: &str, filepath: &str) {
|
||||
let mut redis = self.redis.clone();
|
||||
let _: () = redis
|
||||
.hset(PATH_MAPPING_KEY, filename, filepath)
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("Failed to cache file {} in Redis", filename));
|
||||
|
||||
let _: () = tokio::time::timeout(
|
||||
self.request_timeout,
|
||||
redis.hset(PATH_MAPPING_KEY, filename, filepath),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("Redis timeout when caching file {} in Redis", filename))
|
||||
.unwrap_or_else(|_| panic!("Failed to cache file {} in Redis", filename));
|
||||
}
|
||||
|
||||
/// создает или получает текущее значение квоты пользователя
|
||||
/// создает или получает текущее значение квоты пользователя с таймаутом
|
||||
pub async fn get_or_create_quota(&self, user_id: &str) -> Result<u64, actix_web::Error> {
|
||||
let mut redis = self.redis.clone();
|
||||
let quota_key = format!("quota:{}", user_id);
|
||||
|
||||
// Попытка получить квоту из Redis
|
||||
let quota: u64 = redis.get("a_key).await.unwrap_or(0);
|
||||
// Попытка получить квоту из Redis с таймаутом
|
||||
let quota: u64 = tokio::time::timeout(self.request_timeout, redis.get("a_key))
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Redis timeout getting user quota"))?
|
||||
.unwrap_or(0);
|
||||
|
||||
if quota == 0 {
|
||||
// Если квота не найдена, устанавливаем её в 0 байт без TTL (постоянная квота)
|
||||
redis
|
||||
.set::<&str, u64, ()>("a_key, 0)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ErrorInternalServerError("Failed to set initial user quota in Redis")
|
||||
})?;
|
||||
// Если квота не найдена, устанавливаем её в 0 байт без TTL с таймаутом
|
||||
tokio::time::timeout(
|
||||
self.request_timeout,
|
||||
redis.set::<&str, u64, ()>("a_key, 0),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Redis timeout setting user quota"))?
|
||||
.map_err(|_| ErrorInternalServerError("Failed to set initial user quota in Redis"))?;
|
||||
|
||||
Ok(0) // Возвращаем 0 как начальную квоту
|
||||
} else {
|
||||
@@ -146,7 +188,7 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// инкрементирует значение квоты пользователя в байтах
|
||||
/// инкрементирует значение квоты пользователя в байтах с таймаутом
|
||||
pub async fn increment_uploaded_bytes(
|
||||
&self,
|
||||
user_id: &str,
|
||||
@@ -155,27 +197,37 @@ impl AppState {
|
||||
let mut redis = self.redis.clone();
|
||||
let quota_key = format!("quota:{}", user_id);
|
||||
|
||||
// Проверяем, существует ли ключ в Redis
|
||||
let exists: bool = redis.exists::<_, bool>("a_key).await.map_err(|_| {
|
||||
ErrorInternalServerError("Failed to check if user quota exists in Redis")
|
||||
})?;
|
||||
// Проверяем, существует ли ключ в Redis с таймаутом
|
||||
let exists: bool =
|
||||
tokio::time::timeout(self.request_timeout, redis.exists::<_, bool>("a_key))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ErrorInternalServerError("Redis timeout checking user quota existence")
|
||||
})?
|
||||
.map_err(|_| {
|
||||
ErrorInternalServerError("Failed to check if user quota exists in Redis")
|
||||
})?;
|
||||
|
||||
// Если ключ не существует, создаем его с начальным значением без TTL
|
||||
if !exists {
|
||||
redis
|
||||
.set::<_, u64, ()>("a_key, bytes)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ErrorInternalServerError("Failed to set initial user quota in Redis")
|
||||
})?;
|
||||
tokio::time::timeout(
|
||||
self.request_timeout,
|
||||
redis.set::<_, u64, ()>("a_key, bytes),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Redis timeout setting initial user quota"))?
|
||||
.map_err(|_| ErrorInternalServerError("Failed to set initial user quota in Redis"))?;
|
||||
return Ok(bytes);
|
||||
}
|
||||
|
||||
// Если ключ существует, инкрементируем его значение на заданное количество байт
|
||||
let new_quota: u64 = redis
|
||||
.incr::<_, u64, u64>("a_key, bytes)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Failed to increment user quota in Redis"))?;
|
||||
let new_quota: u64 = tokio::time::timeout(
|
||||
self.request_timeout,
|
||||
redis.incr::<_, u64, u64>("a_key, bytes),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ErrorInternalServerError("Redis timeout incrementing user quota"))?
|
||||
.map_err(|_| ErrorInternalServerError("Failed to increment user quota in Redis"))?;
|
||||
|
||||
Ok(new_quota)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user