Don't merge with existing document on create for correctness reasons

This commit is contained in:
Andras Schmelczer 2025-02-26 23:11:46 +00:00
commit e493b98a24
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
3 changed files with 24 additions and 83 deletions

View file

@ -7,19 +7,17 @@ use axum_extra::{
}; };
use axum_jsonschema::Json; use axum_jsonschema::Json;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use log::info;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::Deserialize; use serde::Deserialize;
use sync_lib::{base64_to_bytes, is_file_type_mergable, merge}; use sync_lib::base64_to_bytes;
use super::{ use super::{
app_state::AppState, app_state::AppState,
auth::auth, auth::auth,
requests::{CreateDocumentVersion, CreateDocumentVersionMultipart}, requests::{CreateDocumentVersion, CreateDocumentVersionMultipart},
responses::DocumentUpdateResponse,
}; };
use crate::{ use crate::{
database::models::{StoredDocumentVersion, VaultId}, database::models::{DocumentVersionWithoutContent, StoredDocumentVersion, VaultId},
errors::{SyncServerError, client_error, server_error}, errors::{SyncServerError, client_error, server_error},
utils::sanitize_path, utils::sanitize_path,
}; };
@ -41,7 +39,7 @@ pub async fn create_document_multipart(
TypedMultipart(axum_typed_multipart::TypedMultipart(request)): TypedMultipart< TypedMultipart(axum_typed_multipart::TypedMultipart(request)): TypedMultipart<
CreateDocumentVersionMultipart, CreateDocumentVersionMultipart,
>, >,
) -> Result<Json<DocumentUpdateResponse>, SyncServerError> { ) -> Result<Json<DocumentVersionWithoutContent>, SyncServerError> {
internal_create_document( internal_create_document(
auth_header, auth_header,
state, state,
@ -62,7 +60,7 @@ pub async fn create_document_json(
Path(PathParams { vault_id }): Path<PathParams>, Path(PathParams { vault_id }): Path<PathParams>,
State(state): State<AppState>, State(state): State<AppState>,
Json(request): Json<CreateDocumentVersion>, Json(request): Json<CreateDocumentVersion>,
) -> Result<Json<DocumentUpdateResponse>, SyncServerError> { ) -> Result<Json<DocumentVersionWithoutContent>, SyncServerError> {
let content_bytes = base64_to_bytes(&request.content_base64) let content_bytes = base64_to_bytes(&request.content_base64)
.context("Failed to decode base64 content in request") .context("Failed to decode base64 content in request")
.map_err(client_error)?; .map_err(client_error)?;
@ -85,7 +83,7 @@ async fn internal_create_document(
relative_path: String, relative_path: String,
created_date: DateTime<Utc>, created_date: DateTime<Utc>,
content: Vec<u8>, content: Vec<u8>,
) -> Result<Json<DocumentUpdateResponse>, SyncServerError> { ) -> Result<Json<DocumentVersionWithoutContent>, SyncServerError> {
auth(&state, auth_header.token())?; auth(&state, auth_header.token())?;
let mut transaction = state let mut transaction = state
@ -102,85 +100,28 @@ async fn internal_create_document(
let sanitized_relative_path = sanitize_path(&relative_path); let sanitized_relative_path = sanitize_path(&relative_path);
let maybe_existing_version = state let new_version = StoredDocumentVersion {
.database vault_id,
.get_latest_document_by_path(&vault_id, &sanitized_relative_path, Some(&mut transaction)) vault_update_id: last_update_id + 1,
.await document_id: uuid::Uuid::new_v4(),
.map_err(server_error)? relative_path: sanitized_relative_path,
.and_then(|doc| if doc.is_deleted { None } else { Some(doc) }); content,
created_date,
let response = if let Some(existing_version) = maybe_existing_version { updated_date: chrono::Utc::now(),
if content == existing_version.content { is_deleted: false,
info!(
"Content of the new version is the same as the existing version. Not creating a \
new version."
);
transaction
.rollback()
.await
.context("Failed to roll back unecceseary transaction")
.map_err(server_error)?;
return Ok(Json(DocumentUpdateResponse::FastForwardUpdate(
existing_version.into(),
)));
}
let merged_content = if is_file_type_mergable(&sanitized_relative_path) {
merge(
&[], // the empty string is the first common parent of the two documents,
&existing_version.content,
&content,
)
} else {
content
};
let new_version = StoredDocumentVersion {
vault_id,
vault_update_id: last_update_id + 1,
relative_path: sanitized_relative_path,
document_id: existing_version.document_id,
content: merged_content,
created_date,
updated_date: chrono::Utc::now(),
is_deleted: false,
};
state
.database
.insert_document_version(&new_version, Some(&mut transaction))
.await
.map_err(server_error)?;
DocumentUpdateResponse::MergingUpdate(new_version.into())
} else {
let new_version = StoredDocumentVersion {
vault_id,
vault_update_id: last_update_id + 1,
document_id: uuid::Uuid::new_v4(),
relative_path: sanitized_relative_path,
content,
created_date,
updated_date: chrono::Utc::now(),
is_deleted: false,
};
state
.database
.insert_document_version(&new_version, Some(&mut transaction))
.await
.map_err(server_error)?;
DocumentUpdateResponse::FastForwardUpdate(new_version.into())
}; };
state
.database
.insert_document_version(&new_version, Some(&mut transaction))
.await
.map_err(server_error)?;
transaction transaction
.commit() .commit()
.await .await
.context("Failed to commit successful transaction") .context("Failed to commit successful transaction")
.map_err(server_error)?; .map_err(server_error)?;
Ok(Json(response)) Ok(Json(new_version.into()))
} }

View file

@ -25,7 +25,7 @@ pub struct FetchLatestDocumentsResponse {
pub last_update_id: VaultUpdateId, pub last_update_id: VaultUpdateId,
} }
/// Response to a create/update document request. /// Response to an update document request.
#[derive(Debug, Clone, Serialize, JsonSchema)] #[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum DocumentUpdateResponse { pub enum DocumentUpdateResponse {

View file

@ -111,7 +111,7 @@ export interface paths {
[name: string]: unknown; [name: string]: unknown;
}; };
content: { content: {
"application/json": components["schemas"]["DocumentUpdateResponse"]; "application/json": components["schemas"]["DocumentVersionWithoutContent"];
}; };
}; };
default: { default: {
@ -161,7 +161,7 @@ export interface paths {
[name: string]: unknown; [name: string]: unknown;
}; };
content: { content: {
"application/json": components["schemas"]["DocumentUpdateResponse"]; "application/json": components["schemas"]["DocumentVersionWithoutContent"];
}; };
}; };
default: { default: {
@ -466,7 +466,7 @@ export interface components {
createdDate: string; createdDate: string;
relativePath: string; relativePath: string;
}; };
/** @description Response to a create/update document request. */ /** @description Response to a update document request. */
DocumentUpdateResponse: DocumentUpdateResponse:
| { | {
/** Format: date-time */ /** Format: date-time */