clippy-fixes
Some checks failed
Deploy / deploy (push) Has been skipped
CI / lint (push) Failing after 1m53s
CI / test (push) Failing after 1m58s

This commit is contained in:
2025-08-12 14:13:35 +03:00
parent a4c2825f8a
commit 31053db4a2
10 changed files with 23 additions and 42 deletions

View File

@@ -67,12 +67,6 @@ jobs:
echo "total_coverage=$COVERAGE" >> $GITHUB_OUTPUT echo "total_coverage=$COVERAGE" >> $GITHUB_OUTPUT
echo "Coverage: $COVERAGE" echo "Coverage: $COVERAGE"
- name: Create Coverage Badge
run: |
COVERAGE=$(cargo llvm-cov --summary | grep -oP 'coverage: \K[0-9.]+' || echo "0")
echo "Покрытие тестами: $COVERAGE %" >> $GITHUB_OUTPUT
continue-on-error: true
- name: Upload coverage HTML - name: Upload coverage HTML
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:

View File

@@ -16,7 +16,6 @@ pub struct AppState {
const PATH_MAPPING_KEY: &str = "filepath_mapping"; // Ключ для хранения маппинга путей const PATH_MAPPING_KEY: &str = "filepath_mapping"; // Ключ для хранения маппинга путей
// Убираем TTL для квоты - она должна быть постоянной на пользователя // Убираем TTL для квоты - она должна быть постоянной на пользователя
const QUOTA_TTL: u64 = 0; // 0 означает отсутствие TTL
impl AppState { impl AppState {
/// Инициализация нового состояния приложения. /// Инициализация нового состояния приложения.
@@ -100,7 +99,7 @@ impl AppState {
let _: () = redis let _: () = redis
.hset(PATH_MAPPING_KEY, filename.clone(), filepath) .hset(PATH_MAPPING_KEY, filename.clone(), filepath)
.await .await
.expect(&format!("Failed to cache file {} in Redis", filename)); .unwrap();
} }
warn!("cached {} files", filelist.len()); warn!("cached {} files", filelist.len());
@@ -121,7 +120,7 @@ impl AppState {
let _: () = redis let _: () = redis
.hset(PATH_MAPPING_KEY, filename, filepath) .hset(PATH_MAPPING_KEY, filename, filepath)
.await .await
.expect(&format!("Failed to cache file {} in Redis", filename)); .unwrap_or_else(|_| panic!("Failed to cache file {} in Redis", filename));
} }
/// создает или получает текущее значение квоты пользователя /// создает или получает текущее значение квоты пользователя

View File

@@ -69,15 +69,12 @@ pub async fn get_id_by_token(token: &str) -> Result<String, Box<dyn Error>> {
} }
} }
} }
Err(Box::new(std::io::Error::new( Err(Box::new(std::io::Error::other("Invalid token response")))
std::io::ErrorKind::Other,
"Invalid token response",
)))
} else { } else {
Err(Box::new(std::io::Error::new( Err(Box::new(std::io::Error::other(format!(
std::io::ErrorKind::Other, "Request failed with status: {}",
format!("Request failed with status: {}", response.status()), response.status()
))) ))))
} }
} }

View File

@@ -52,13 +52,9 @@ pub async fn get_shout_by_id(shout_id: i32) -> Result<Shout, Box<dyn Error>> {
if let Some(shout) = core_response.data { if let Some(shout) = core_response.data {
return Ok(shout); return Ok(shout);
} }
Err(Box::new(std::io::Error::new( Err(Box::new(std::io::Error::other("Shout not found")))
std::io::ErrorKind::Other,
"Shout not found",
)))
} else { } else {
Err(Box::new(std::io::Error::new( Err(Box::new(std::io::Error::other(
std::io::ErrorKind::Other,
response.status().to_string(), response.status().to_string(),
))) )))
} }

View File

@@ -37,7 +37,7 @@ pub async fn proxy_handler(
let mut redis = state.redis.clone(); let mut redis = state.redis.clone();
match find_file_by_pattern(&mut redis, &base_filename).await { match find_file_by_pattern(&mut redis, &base_filename).await {
Ok(Some(found_file)) => { Ok(Some(found_file)) => {
if let Some(found_ext) = found_file.split('.').last() { if let Some(found_ext) = found_file.split('.').next_back() {
get_mime_type(found_ext) get_mime_type(found_ext)
.unwrap_or("application/octet-stream") .unwrap_or("application/octet-stream")
.to_string() .to_string()
@@ -80,7 +80,7 @@ pub async fn proxy_handler(
warn!("Serving original file without resizing"); warn!("Serving original file without resizing");
serve_file(&stored_path, &state, shout_id).await serve_file(&stored_path, &state, shout_id).await
} else { } else {
let closest: u32 = find_closest_width(requested_width as u32); let closest: u32 = find_closest_width(requested_width);
warn!( warn!(
"Calculated closest width: {} for requested: {}", "Calculated closest width: {} for requested: {}",
closest, requested_width closest, requested_width

View File

@@ -1,5 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse, Result}; use actix_web::{web, HttpRequest, HttpResponse, Result};
use log::{error, warn}; use log::warn;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::app_state::AppState; use crate::app_state::AppState;

View File

@@ -16,7 +16,7 @@ pub async fn serve_file(
} }
// Проверяем наличие файла в Storj S3 // Проверяем наличие файла в Storj S3
let exists = check_file_exists(&state.storj_client, &state.bucket, &filepath).await?; let exists = check_file_exists(&state.storj_client, &state.bucket, filepath).await?;
if !exists { if !exists {
return Err(ErrorInternalServerError(format!( return Err(ErrorInternalServerError(format!(
"File {} not found in Storj", "File {} not found in Storj",
@@ -47,7 +47,7 @@ pub async fn serve_file(
false => generate_overlay(shout_id, data.into_bytes()).await?, false => generate_overlay(shout_id, data.into_bytes()).await?,
}; };
let mime_type = MimeGuess::from_path(&filepath).first_or_octet_stream(); let mime_type = MimeGuess::from_path(filepath).first_or_octet_stream();
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type(mime_type.as_ref()) .content_type(mime_type.as_ref())

View File

@@ -14,7 +14,7 @@ use actix_web::{
web, App, HttpServer, web, App, HttpServer,
}; };
use app_state::AppState; use app_state::AppState;
use env_logger;
use handlers::{ use handlers::{
get_quota_handler, increase_quota_handler, proxy_handler, root_handler, set_quota_handler, get_quota_handler, increase_quota_handler, proxy_handler, root_handler, set_quota_handler,
upload_handler, upload_handler,

View File

@@ -8,10 +8,7 @@ use std::{error::Error, io::Cursor};
use crate::core::get_shout_by_id; use crate::core::get_shout_by_id;
pub async fn generate_overlay<'a>( pub async fn generate_overlay(shout_id: &str, filedata: Bytes) -> Result<Bytes, Box<dyn Error>> {
shout_id: &'a str,
filedata: Bytes,
) -> Result<Bytes, Box<dyn Error>> {
// Получаем shout из GraphQL // Получаем shout из GraphQL
let shout_id_int = shout_id.parse::<i32>().unwrap_or(0); let shout_id_int = shout_id.parse::<i32>().unwrap_or(0);
match get_shout_by_id(shout_id_int).await { match get_shout_by_id(shout_id_int).await {

View File

@@ -58,14 +58,12 @@ pub fn parse_file_path(requested_path: &str) -> (String, u32, String) {
} }
// Проверка на старую ширину в путях, начинающихся с "unsafe" // Проверка на старую ширину в путях, начинающихся с "unsafe"
if path.starts_with("unsafe") && width == 0 { if path.starts_with("unsafe") && width == 0 && path_parts.len() >= 2 {
if path_parts.len() >= 2 { if let Some(old_width_str) = path_parts.get(1) {
if let Some(old_width_str) = path_parts.get(1) { // Получаем второй элемент
// Получаем второй элемент let old_width_str = old_width_str.trim_end_matches('x');
let old_width_str = old_width_str.trim_end_matches('x'); if let Ok(w) = old_width_str.parse::<u32>() {
if let Ok(w) = old_width_str.parse::<u32>() { width = w;
width = w;
}
} }
} }
} }
@@ -129,7 +127,7 @@ pub async fn thumbdata_save(
) -> Result<(), actix_web::Error> { ) -> Result<(), actix_web::Error> {
if content_type.starts_with("image") { if content_type.starts_with("image") {
warn!("original file name: {}", original_filename); warn!("original file name: {}", original_filename);
let (base_filename, _, extension) = parse_file_path(&original_filename); let (base_filename, _, extension) = parse_file_path(original_filename);
warn!("detected file extension: {}", extension); warn!("detected file extension: {}", extension);
// Для HEIC файлов просто сохраняем оригинал как миниатюру // Для HEIC файлов просто сохраняем оригинал как миниатюру