This commit is contained in:
Andras Schmelczer 2025-12-14 23:30:04 +00:00
parent e103bba12c
commit c4f992c9d6
21 changed files with 233 additions and 193 deletions

View file

@ -20,4 +20,4 @@ pub const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Info;
pub const DEFAULT_MERGEABLE_FILE_EXTENSIONS: &[&str] = &["md", "txt"];
pub const SUPPORTED_API_VERSION: u32 = 2;
pub const SUPPORTED_API_VERSION: u32 = 3;

View file

@ -5,7 +5,7 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use log::{debug, error};
use log::debug;
use serde::Serialize;
use thiserror::Error;
use ts_rs::TS;

View file

@ -11,10 +11,11 @@ use super::{device_id_header::DeviceIdHeader, requests::CreateDocumentVersion};
use crate::{
app_state::{
AppState,
database::models::{DocumentVersionWithoutContent, StoredDocumentVersion, VaultId},
database::models::{StoredDocumentVersion, VaultId},
},
config::user_config::User,
errors::{SyncServerError, client_error, server_error},
errors::{SyncServerError, server_error},
server::{responses::DocumentUpdateResponse, update_document::merge_with_stored_version},
utils::{
find_first_available_path::find_first_available_path, normalize::normalize,
sanitize_path::sanitize_path,
@ -37,7 +38,7 @@ pub async fn create_document(
TypedHeader(device_id): TypedHeader<DeviceIdHeader>,
State(state): State<AppState>,
TypedMultipart(request): TypedMultipart<CreateDocumentVersion>,
) -> Result<Json<DocumentVersionWithoutContent>, SyncServerError> {
) -> Result<Json<DocumentUpdateResponse>, SyncServerError> {
debug!("Creating document in vault `{vault_id}`");
let mut transaction = state
@ -46,24 +47,39 @@ pub async fn create_document(
.await
.map_err(server_error)?;
let document_id = match request.document_id {
Some(document_id) => {
let existing_version = state
.database
.get_latest_document(&vault_id, &document_id, Some(&mut transaction))
.await
.map_err(server_error)?;
let sanitized_relative_path = sanitize_path(&request.relative_path);
if existing_version.is_some() {
return Err(client_error(anyhow::anyhow!(
"Document with the same ID `{document_id}` already exists"
)));
}
if request.force_merge.unwrap_or_default() {
let latest_version = state
.database
.get_latest_document_by_path(
&vault_id,
&sanitized_relative_path,
Some(&mut transaction),
)
.await
.map_err(server_error)?;
if let Some(latest_version) = latest_version {
info!(
"Document already exists at new location: `{sanitized_relative_path}` when trying to create it in vault `{vault_id}`, merging into existing document"
);
document_id
return merge_with_stored_version(
latest_version.clone(),
latest_version,
vault_id,
user,
device_id,
state,
&sanitized_relative_path,
request.content.contents.to_vec(),
transaction,
)
.await;
}
None => uuid::Uuid::new_v4(),
};
}
let document_id = uuid::Uuid::new_v4();
let last_update_id = state
.database
@ -71,7 +87,6 @@ pub async fn create_document(
.await
.map_err(server_error)?;
let sanitized_relative_path = sanitize_path(&request.relative_path);
let deduped_path = find_first_available_path(
&vault_id,
&sanitized_relative_path,
@ -105,5 +120,7 @@ pub async fn create_document(
.await
.map_err(server_error)?;
Ok(Json(new_version.into()))
Ok(Json(DocumentUpdateResponse::FastForwardUpdate(
new_version.into(),
)))
}

View file

@ -4,18 +4,16 @@ use reconcile_text::NumberOrText;
use serde::{self, Deserialize};
use ts_rs::TS;
use crate::app_state::database::models::{DocumentId, VaultUpdateId};
use crate::app_state::database::models::VaultUpdateId;
#[derive(TS, Debug, TryFromMultipart)]
#[ts(export)]
pub struct CreateDocumentVersion {
/// The client can decide the document id (if it wishes to) in order
/// to help with syncing. If the client does not provide a document id,
/// the server will generate one. If the client provides a document id
/// it must not already exist in the database.
pub document_id: Option<DocumentId>,
pub relative_path: String,
// whether to merge with existing document at the same path if it exists
pub force_merge: Option<bool>,
#[ts(as = "Vec<u8>")]
#[form_data(limit = "unlimited")]
pub content: FieldData<Bytes>,

View file

@ -16,7 +16,10 @@ use super::{
use crate::{
app_state::{
AppState,
database::models::{DocumentId, StoredDocumentVersion, VaultId, VaultUpdateId},
database::{
Transaction,
models::{DocumentId, StoredDocumentVersion, VaultId, VaultUpdateId},
},
},
config::user_config::User,
errors::{SyncServerError, client_error, not_found_error, server_error},
@ -141,12 +144,6 @@ async fn update_document(
.await
.map_err(server_error)?;
let last_update_id = state
.database
.get_max_update_id_in_vault(&vault_id, Some(&mut transaction))
.await
.map_err(server_error)?;
let latest_version = state
.database
.get_latest_document(&vault_id, &document_id, Some(&mut transaction))
@ -174,12 +171,39 @@ async fn update_document(
)));
}
merge_with_stored_version(
parent_document,
latest_version,
vault_id,
user,
device_id,
state,
&sanitized_relative_path,
content,
transaction,
)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn merge_with_stored_version(
parent_document: StoredDocumentVersion,
latest_version: StoredDocumentVersion,
vault_id: VaultId,
user: User,
device_id: DeviceIdHeader,
state: AppState,
sanitized_relative_path: &str,
content: Vec<u8>,
mut transaction: Transaction<'_>,
) -> Result<Json<DocumentUpdateResponse>, SyncServerError> {
// Return the latest version if the content and path are the same as the latest
// version
if content == latest_version.content && sanitized_relative_path == latest_version.relative_path
{
info!(
"Document content is the same as the latest version for `{document_id}`, skipping update"
"Document content is the same as the latest version for `{}`, skipping update",
parent_document.document_id
);
transaction
.rollback()
@ -193,14 +217,17 @@ async fn update_document(
}
let are_all_participants_mergable = is_file_type_mergable(
&sanitized_relative_path,
sanitized_relative_path,
&state.config.server.mergeable_file_extensions,
) && !is_binary(&parent_document.content)
&& !is_binary(&latest_version.content)
&& !is_binary(&content);
let merged_content = if are_all_participants_mergable {
info!("Merging changes for document `{document_id}` in vault `{vault_id}`");
info!(
"Merging changes for document `{}` in vault `{vault_id}`",
parent_document.document_id
);
reconcile(
str::from_utf8(&parent_document.content)
.expect("parent must be valid UTF-8 because it's not binary"),
@ -227,7 +254,7 @@ async fn update_document(
{
let new_path = find_first_available_path(
&vault_id,
&sanitized_relative_path,
sanitized_relative_path,
&state.database,
&mut transaction,
)
@ -245,8 +272,14 @@ async fn update_document(
latest_version.relative_path.clone()
};
let last_update_id = state
.database
.get_max_update_id_in_vault(&vault_id, Some(&mut transaction))
.await
.map_err(server_error)?;
let new_version = StoredDocumentVersion {
document_id,
document_id: parent_document.document_id,
vault_update_id: last_update_id + 1,
relative_path: new_relative_path,
content: merged_content,