This commit is contained in:
Andras Schmelczer 2025-03-16 15:38:13 +00:00
parent 7eb740cd4c
commit 9f09b07de9
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
16 changed files with 191 additions and 114 deletions

View file

@ -42,9 +42,12 @@ impl Config {
}
pub async fn load_from_file(path: &Path) -> Result<Self> {
let contents = fs::read_to_string(path)
.await
.with_context(|| format!("Cannot load configuration from disk from ({path:?})"))?;
let contents = fs::read_to_string(path).await.with_context(|| {
format!(
"Cannot load configuration from disk from ({})",
path.display()
)
})?;
let config = serde_yaml::from_str(&contents).context("Failed to parse configuration")?;

View file

@ -79,7 +79,7 @@ impl Database {
.test_before_acquire(true)
.connect_with(connection_options)
.await
.with_context(|| format!("Cannot open database at '{file_name:?}'"))?;
.with_context(|| format!("Cannot open database at '{}'", file_name.display()))?;
Self::run_migrations(&pool).await?;

View file

@ -33,12 +33,12 @@ pub enum SyncServerError {
impl SyncServerError {
pub fn serialize(&self) -> SerializedError {
match self {
Self::InitError(error) => error.into(),
Self::ClientError(error) => error.into(),
Self::ServerError(error) => error.into(),
Self::NotFound(error) => error.into(),
Self::Unauthorized(error) => error.into(),
Self::PermissionDeniedError(error) => error.into(),
Self::InitError(error)
| Self::ClientError(error)
| Self::ServerError(error)
| Self::NotFound(error)
| Self::Unauthorized(error)
| Self::PermissionDeniedError(error) => error.into(),
}
}
}
@ -48,9 +48,10 @@ impl IntoResponse for SyncServerError {
let body = Json(self.serialize());
match self {
Self::InitError(_) => (StatusCode::INTERNAL_SERVER_ERROR, body).into_response(),
Self::InitError(_) | Self::ServerError(_) => {
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
Self::ClientError(_) => (StatusCode::BAD_REQUEST, body).into_response(),
Self::ServerError(_) => (StatusCode::INTERNAL_SERVER_ERROR, body).into_response(),
Self::NotFound(_) => (StatusCode::NOT_FOUND, body).into_response(),
Self::Unauthorized(_) => (StatusCode::UNAUTHORIZED, body).into_response(),
Self::PermissionDeniedError(_) => (StatusCode::FORBIDDEN, body).into_response(),

View file

@ -16,6 +16,7 @@ use axum::{
extract::{DefaultBodyLimit, Request},
http::{self, HeaderValue, Method},
response::IntoResponse,
routing::IntoMakeService,
};
use log::{error, info};
use tokio::signal;
@ -30,7 +31,10 @@ use tower_http::{
};
use tracing::{Level, info_span};
use crate::errors::{SerializedError, not_found_error};
use crate::{
config::server_config::ServerConfig,
errors::{SerializedError, not_found_error},
};
mod app_state;
mod auth;
mod create_document;
@ -52,24 +56,9 @@ pub async fn create_server() -> Result<()> {
.await
.context("Failed to initialise app state")?;
let address = format!(
"{}:{}",
&app_state.config.server.host, &app_state.config.server.port
);
let mut api = OpenApi {
info: Info {
title: "VaultLink sync server".to_owned(),
summary: Some(
"Simple API for syncing documents between concurrent clients.".to_owned(),
),
description: Some(include_str!("../README.md").to_owned()),
version: env!("CARGO_PKG_VERSION").to_owned(),
..Info::default()
},
..OpenApi::default()
};
let server_config = app_state.config.server.clone();
let mut api = create_open_api();
let app = ApiRouter::new()
.api_route("/ping", get(ping::ping))
.api_route(
@ -140,11 +129,42 @@ pub async fn create_server() -> Result<()> {
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE]),
)
.with_state(app_state)
.finish_api_with(&mut api, api_docs)
.finish_api_with(&mut api, add_api_docs_error_example)
.layer(Extension(Arc::new(api))) // https://github.com/tamasfe/aide/blob/507f4a8822bc0c13cbda0f589da1e0f4cbcdb812/examples/example-axum/src/main.rs#L39
.fallback(handler_404)
.into_make_service();
start_server(app, &server_config).await
}
async fn serve_api(Extension(api): Extension<Arc<OpenApi>>) -> impl IntoResponse { Json(api) }
fn create_open_api() -> OpenApi {
OpenApi {
info: Info {
title: "VaultLink sync server".to_owned(),
summary: Some(
"Simple API for syncing documents between concurrent clients.".to_owned(),
),
description: Some(include_str!("../README.md").to_owned()),
version: env!("CARGO_PKG_VERSION").to_owned(),
..Info::default()
},
..OpenApi::default()
}
}
fn add_api_docs_error_example(api: TransformOpenApi<'_>) -> TransformOpenApi<'_> {
api.default_response_with::<Json<SerializedError>, _>(|res| {
res.example(SerializedError {
message: "An error has occurred".to_owned(),
causes: vec![],
})
})
}
async fn start_server(app: IntoMakeService<axum::Router>, config: &ServerConfig) -> Result<()> {
let address = format!("{}:{}", config.host, config.port);
let listener = tokio::net::TcpListener::bind(address.clone())
.await
.with_context(|| format!("Failed to bind to address: {address}"))?;
@ -163,17 +183,6 @@ pub async fn create_server() -> Result<()> {
.context("Failed to start server")
}
async fn serve_api(Extension(api): Extension<Arc<OpenApi>>) -> impl IntoResponse { Json(api) }
fn api_docs(api: TransformOpenApi<'_>) -> TransformOpenApi<'_> {
api.default_response_with::<Json<SerializedError>, _>(|res| {
res.example(SerializedError {
message: "An error has occurred".to_owned(),
causes: vec![],
})
})
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
@ -193,8 +202,8 @@ async fn shutdown_signal() {
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
() = ctrl_c => {},
() = terminate => {},
}
}

View file

@ -39,12 +39,14 @@ pub async fn fetch_document_version(
.get_document_version(&vault_id, vault_update_id, None)
.await
.map_err(server_error)?
.map(Ok)
.unwrap_or_else(|| {
Err(not_found_error(anyhow!(
"Document with vault update id `{vault_update_id}` not found",
)))
})?;
.map_or_else(
|| {
Err(not_found_error(anyhow!(
"Document with vault update id `{vault_update_id}` not found",
)))
},
Ok,
)?;
if result.document_id != document_id {
return Err(not_found_error(anyhow!(

View file

@ -41,12 +41,14 @@ pub async fn fetch_document_version_content(
.get_document_version(&vault_id, vault_update_id, None)
.await
.map_err(server_error)?
.map(Ok)
.unwrap_or_else(|| {
Err(not_found_error(anyhow!(
"Document with vault update id `{vault_update_id}` not found",
)))
})?;
.map_or_else(
|| {
Err(not_found_error(anyhow!(
"Document with vault update id `{vault_update_id}` not found",
)))
},
Ok,
)?;
if result.document_id != document_id {
return Err(not_found_error(anyhow!(

View file

@ -37,12 +37,14 @@ pub async fn fetch_latest_document_version(
.get_latest_document(&vault_id, &document_id, None)
.await
.map_err(server_error)?
.map(Ok)
.unwrap_or_else(|| {
Err(not_found_error(anyhow!(
"Document with id `{document_id}` not found",
)))
})?;
.map_or_else(
|| {
Err(not_found_error(anyhow!(
"Document with id `{document_id}` not found",
)))
},
Ok,
)?;
Ok(Json(latest_version.into()))
}

View file

@ -80,7 +80,7 @@ pub async fn update_document_json(
.await
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
async fn internal_update_document(
auth_header: Authorization<Bearer>,
mut state: AppState,
@ -176,7 +176,7 @@ async fn internal_update_document(
let new_relative_path = if parent_document.relative_path == latest_version.relative_path
&& latest_version.relative_path != sanitized_relative_path
{
let mut new_relative_path = Default::default();
let mut new_relative_path = String::default();
for candidate in deduped_file_paths(&sanitized_relative_path) {
if state
.database