fmt
Some checks failed
Deploy / deploy (push) Has been skipped
CI / lint (push) Failing after 7m37s
CI / test (push) Has been cancelled

This commit is contained in:
2025-09-01 22:58:03 +03:00
parent d6b286f478
commit 112f102bb5
14 changed files with 444 additions and 316 deletions

View File

@@ -1,5 +1,5 @@
use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse, Result};
use actix_web::{HttpRequest, HttpResponse, Result, web};
use log::{error, info, warn};
use crate::app_state::AppState;
@@ -24,26 +24,29 @@ pub async fn upload_handler(
.headers()
.get("Authorization")
.and_then(|header_value| header_value.to_str().ok());
if token.is_none() {
warn!("Upload attempt without authorization token");
return Err(actix_web::error::ErrorUnauthorized("Authorization token required"));
return Err(actix_web::error::ErrorUnauthorized(
"Authorization token required",
));
}
let token = token.unwrap();
// Сначала валидируем токен
if !validate_token(token).unwrap_or(false) {
warn!("Token validation failed");
return Err(actix_web::error::ErrorUnauthorized("Invalid or expired token"));
return Err(actix_web::error::ErrorUnauthorized(
"Invalid or expired token",
));
}
// Затем извлекаем user_id
let user_id = extract_user_id_from_token(token)
.map_err(|e| {
warn!("Failed to extract user_id from token: {}", e);
actix_web::error::ErrorUnauthorized("Invalid authorization token")
})?;
let user_id = extract_user_id_from_token(token).map_err(|e| {
warn!("Failed to extract user_id from token: {}", e);
actix_web::error::ErrorUnauthorized("Invalid authorization token")
})?;
// Получаем текущую квоту пользователя
let current_quota: u64 = state.get_or_create_quota(&user_id).await.unwrap_or(0);
@@ -51,12 +54,17 @@ pub async fn upload_handler(
// Предварительная проверка: есть ли вообще место для файлов
if current_quota >= MAX_USER_QUOTA_BYTES {
warn!("Author {} quota already at maximum: {}", user_id, current_quota);
return Err(actix_web::error::ErrorPayloadTooLarge("Author quota limit exceeded"));
warn!(
"Author {} quota already at maximum: {}",
user_id, current_quota
);
return Err(actix_web::error::ErrorPayloadTooLarge(
"Author quota limit exceeded",
));
}
let mut uploaded_files = Vec::new();
while let Ok(Some(field)) = payload.try_next().await {
let mut field = field;
let mut file_bytes = Vec::new();
@@ -65,21 +73,32 @@ pub async fn upload_handler(
// Читаем данные файла с проверкой размера
while let Ok(Some(chunk)) = field.try_next().await {
let chunk_size = chunk.len() as u64;
// Проверка лимита одного файла
if file_size + chunk_size > MAX_SINGLE_FILE_BYTES {
warn!("File size exceeds single file limit: {} > {}",
file_size + chunk_size, MAX_SINGLE_FILE_BYTES);
return Err(actix_web::error::ErrorPayloadTooLarge("Single file size limit exceeded"));
warn!(
"File size exceeds single file limit: {} > {}",
file_size + chunk_size,
MAX_SINGLE_FILE_BYTES
);
return Err(actix_web::error::ErrorPayloadTooLarge(
"Single file size limit exceeded",
));
}
// Проверка общей квоты пользователя
if current_quota + file_size + chunk_size > MAX_USER_QUOTA_BYTES {
warn!("Upload would exceed user quota: current={}, adding={}, limit={}",
current_quota, file_size + chunk_size, MAX_USER_QUOTA_BYTES);
return Err(actix_web::error::ErrorPayloadTooLarge("Author quota limit would be exceeded"));
warn!(
"Upload would exceed user quota: current={}, adding={}, limit={}",
current_quota,
file_size + chunk_size,
MAX_USER_QUOTA_BYTES
);
return Err(actix_web::error::ErrorPayloadTooLarge(
"Author quota limit would be exceeded",
));
}
file_size += chunk_size;
file_bytes.extend_from_slice(&chunk);
}
@@ -140,13 +159,16 @@ pub async fn upload_handler(
.await
{
Ok(_) => {
info!("File {} successfully uploaded to S3 ({} bytes)", filename, file_size);
info!(
"File {} successfully uploaded to S3 ({} bytes)",
filename, file_size
);
// Обновляем квоту пользователя
if let Err(e) = state.increment_uploaded_bytes(&user_id, file_size).await {
error!("Failed to increment quota for user {}: {}", user_id, e);
return Err(actix_web::error::ErrorInternalServerError(
"Failed to update user quota"
"Failed to update user quota",
));
}
@@ -156,21 +178,25 @@ pub async fn upload_handler(
error!("Failed to store file info in Redis: {}", e);
// Не прерываем процесс, файл уже загружен в S3
}
if let Err(e) = user_added_file(&mut redis, &user_id, &filename).await {
error!("Failed to record user file association: {}", e);
// Не прерываем процесс
}
// Сохраняем маппинг пути
let generated_key = generate_key_with_extension(filename.clone(), content_type.clone());
let generated_key =
generate_key_with_extension(filename.clone(), content_type.clone());
state.set_path(&filename, &generated_key).await;
// Логируем новую квоту
if let Ok(new_quota) = state.get_or_create_quota(&user_id).await {
info!("Updated quota for user {}: {} bytes ({:.1}% used)",
user_id, new_quota,
(new_quota as f64 / MAX_USER_QUOTA_BYTES as f64) * 100.0);
info!(
"Updated quota for user {}: {} bytes ({:.1}% used)",
user_id,
new_quota,
(new_quota as f64 / MAX_USER_QUOTA_BYTES as f64) * 100.0
);
}
uploaded_files.push(filename);
@@ -178,7 +204,7 @@ pub async fn upload_handler(
Err(e) => {
error!("Failed to upload file to S3: {}", e);
return Err(actix_web::error::ErrorInternalServerError(
"File upload failed"
"File upload failed",
));
}
}
@@ -188,7 +214,9 @@ pub async fn upload_handler(
match uploaded_files.len() {
0 => {
warn!("No files were uploaded");
Err(actix_web::error::ErrorBadRequest("No files provided or all files were empty"))
Err(actix_web::error::ErrorBadRequest(
"No files provided or all files were empty",
))
}
1 => {
info!("Successfully uploaded 1 file: {}", uploaded_files[0]);