refactor: file_info, rabbitmq, queue

This commit is contained in:
Per Stark
2024-12-10 16:02:40 +01:00
parent 6ad4071d63
commit 4803632f0a
10 changed files with 113 additions and 161 deletions

View File

@@ -1,21 +1,13 @@
use crate::{
server::AppState,
storage::types::file_info::{FileError, FileInfo},
};
use axum::{
extract::{Path, State},
response::IntoResponse,
Json,
};
use crate::{error::ApiError, server::AppState, storage::types::file_info::FileInfo};
use axum::{extract::State, response::IntoResponse, Json};
use axum_typed_multipart::{FieldData, TryFromMultipart, TypedMultipart};
use serde_json::json;
use tempfile::NamedTempFile;
use tracing::info;
use uuid::Uuid;
#[derive(Debug, TryFromMultipart)]
pub struct FileUploadRequest {
#[form_data(limit = "100000")] // Example limit: ~100 KB
#[form_data(limit = "1000000")] // Example limit: ~1000 KB
pub file: FieldData<NamedTempFile>,
}
@@ -25,7 +17,7 @@ pub struct FileUploadRequest {
pub async fn upload_handler(
State(state): State<AppState>,
TypedMultipart(input): TypedMultipart<FileUploadRequest>,
) -> Result<impl IntoResponse, FileError> {
) -> Result<impl IntoResponse, ApiError> {
info!("Received an upload request");
// Process the file upload
@@ -33,7 +25,7 @@ pub async fn upload_handler(
// Prepare the response JSON
let response = json!({
"uuid": file_info.uuid,
"id": file_info.id,
"sha256": file_info.sha256,
"path": file_info.path,
"mime_type": file_info.mime_type,
@@ -44,82 +36,3 @@ pub async fn upload_handler(
// Return the response with HTTP 200
Ok((axum::http::StatusCode::OK, Json(response)))
}
/// Handler to retrieve file information by UUID.
///
/// Route: GET /file/:uuid
pub async fn get_file_handler(
State(state): State<AppState>,
Path(uuid_str): Path<String>,
) -> Result<impl IntoResponse, FileError> {
// Parse UUID
let uuid = Uuid::parse_str(&uuid_str).map_err(|_| FileError::InvalidUuid(uuid_str.clone()))?;
// Retrieve FileInfo
let file_info = FileInfo::get_by_uuid(uuid, &state.surreal_db_client).await?;
// Prepare the response JSON
let response = json!({
"uuid": file_info.uuid,
"sha256": file_info.sha256,
"path": file_info.path,
"mime_type": file_info.mime_type,
});
info!("Retrieved FileInfo: {:?}", file_info);
// Return the response with HTTP 200
Ok((axum::http::StatusCode::OK, Json(response)))
}
/// Handler to update an existing file by UUID.
///
/// Route: PUT /file/:uuid
pub async fn update_file_handler(
State(state): State<AppState>,
Path(uuid_str): Path<String>,
TypedMultipart(input): TypedMultipart<FileUploadRequest>,
) -> Result<impl IntoResponse, FileError> {
// Parse UUID
let uuid = Uuid::parse_str(&uuid_str).map_err(|_| FileError::InvalidUuid(uuid_str.clone()))?;
// Update the file
let updated_file_info = FileInfo::update(uuid, input.file, &state.surreal_db_client).await?;
// Prepare the response JSON
let response = json!({
"uuid": updated_file_info.uuid,
"sha256": updated_file_info.sha256,
"path": updated_file_info.path,
"mime_type": updated_file_info.mime_type,
});
info!("File updated successfully: {:?}", updated_file_info);
// Return the response with HTTP 200
Ok((axum::http::StatusCode::OK, Json(response)))
}
/// Handler to delete a file by UUID.
///
/// Route: DELETE /file/:uuid
pub async fn delete_file_handler(
State(state): State<AppState>,
Path(uuid_str): Path<String>,
) -> Result<impl IntoResponse, FileError> {
// Parse UUID
let uuid = Uuid::parse_str(&uuid_str).map_err(|_| FileError::InvalidUuid(uuid_str.clone()))?;
// Delete the file
FileInfo::delete(uuid, &state.surreal_db_client).await?;
info!("Deleted file with UUID: {}", uuid);
// Prepare the response JSON
let response = json!({
"message": "File deleted successfully",
});
// Return the response with HTTP 204 No Content
Ok((axum::http::StatusCode::NO_CONTENT, Json(response)))
}

View File

@@ -8,7 +8,6 @@ use crate::{error::ApiError, server::AppState};
pub async fn index_handler(State(state): State<AppState>) -> Result<Html<String>, ApiError> {
info!("Displaying index page");
// Now you can access the consumer directly from the state
let queue_length = state.rabbitmq_consumer.queue.message_count();
let output = state

View File

@@ -1,42 +1,17 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use tracing::{error, info};
use axum::{extract::State, http::StatusCode, response::IntoResponse};
use tracing::info;
use crate::rabbitmq::{consumer::RabbitMQConsumer, RabbitMQConfig};
use crate::{error::ApiError, server::AppState};
pub async fn queue_length_handler() -> Response {
pub async fn queue_length_handler(
State(state): State<AppState>,
) -> Result<impl IntoResponse, ApiError> {
info!("Getting queue length");
// Set up RabbitMQ config
let config = RabbitMQConfig {
amqp_addr: "amqp://localhost".to_string(),
exchange: "my_exchange".to_string(),
queue: "my_queue".to_string(),
routing_key: "my_key".to_string(),
};
let queue_length = state.rabbitmq_consumer.get_queue_length().await?;
// Create a new consumer
match RabbitMQConsumer::new(&config).await {
Ok(consumer) => {
info!("Consumer connected to RabbitMQ");
info!("Queue length: {}", queue_length);
// Get the queue length
let queue_length = consumer.queue.message_count();
info!("Queue length: {}", queue_length);
// Return the queue length with a 200 OK status
(StatusCode::OK, queue_length.to_string()).into_response()
}
Err(e) => {
error!("Failed to create consumer: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to connect to RabbitMQ".to_string(),
)
.into_response()
}
}
// Return the queue length with a 200 OK status
Ok((StatusCode::OK, queue_length.to_string()))
}